Debian Codegraph @

node/colorjs.io/dist/color-fn.legacy.cjs

raw
1 'use strict';
2
3 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
5 var es_error_cause = {};
6
7 var globalThis_1;
8 var hasRequiredGlobalThis;
9
10 function requireGlobalThis () {
11 if (hasRequiredGlobalThis) return globalThis_1;
12 hasRequiredGlobalThis = 1;
13 var check = function (it) {
14 return it && it.Math === Math && it;
15 };
16
17 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
18 globalThis_1 =
19 // eslint-disable-next-line es/no-global-this -- safe
20 check(typeof globalThis == 'object' && globalThis) ||
21 check(typeof window == 'object' && window) ||
22 // eslint-disable-next-line no-restricted-globals -- safe
23 check(typeof self == 'object' && self) ||
24 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
25 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
26 // eslint-disable-next-line no-new-func -- fallback
27 (function () { return this; })() || Function('return this')();
28 return globalThis_1;
29 }
30
31 var objectGetOwnPropertyDescriptor = {};
32
33 var fails;
34 var hasRequiredFails;
35
36 function requireFails () {
37 if (hasRequiredFails) return fails;
38 hasRequiredFails = 1;
39 fails = function (exec) {
40 try {
41 return !!exec();
42 } catch (error) {
43 return true;
44 }
45 };
46 return fails;
47 }
48
49 var descriptors;
50 var hasRequiredDescriptors;
51
52 function requireDescriptors () {
53 if (hasRequiredDescriptors) return descriptors;
54 hasRequiredDescriptors = 1;
55 var fails = requireFails();
56
57 // Detect IE8's incomplete defineProperty implementation
58 descriptors = !fails(function () {
59 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
60 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
61 });
62 return descriptors;
63 }
64
65 var functionBindNative;
66 var hasRequiredFunctionBindNative;
67
68 function requireFunctionBindNative () {
69 if (hasRequiredFunctionBindNative) return functionBindNative;
70 hasRequiredFunctionBindNative = 1;
71 var fails = requireFails();
72
73 functionBindNative = !fails(function () {
74 // eslint-disable-next-line es/no-function-prototype-bind -- safe
75 var test = (function () { /* empty */ }).bind();
76 // eslint-disable-next-line no-prototype-builtins -- safe
77 return typeof test != 'function' || test.hasOwnProperty('prototype');
78 });
79 return functionBindNative;
80 }
81
82 var functionCall;
83 var hasRequiredFunctionCall;
84
85 function requireFunctionCall () {
86 if (hasRequiredFunctionCall) return functionCall;
87 hasRequiredFunctionCall = 1;
88 var NATIVE_BIND = requireFunctionBindNative();
89
90 var call = Function.prototype.call;
91
92 functionCall = NATIVE_BIND ? call.bind(call) : function () {
93 return call.apply(call, arguments);
94 };
95 return functionCall;
96 }
97
98 var objectPropertyIsEnumerable = {};
99
100 var hasRequiredObjectPropertyIsEnumerable;
101
102 function requireObjectPropertyIsEnumerable () {
103 if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
104 hasRequiredObjectPropertyIsEnumerable = 1;
105 var $propertyIsEnumerable = {}.propertyIsEnumerable;
106 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
107 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
108
109 // Nashorn ~ JDK8 bug
110 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
111
112 // `Object.prototype.propertyIsEnumerable` method implementation
113 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
114 objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
115 var descriptor = getOwnPropertyDescriptor(this, V);
116 return !!descriptor && descriptor.enumerable;
117 } : $propertyIsEnumerable;
118 return objectPropertyIsEnumerable;
119 }
120
121 var createPropertyDescriptor;
122 var hasRequiredCreatePropertyDescriptor;
123
124 function requireCreatePropertyDescriptor () {
125 if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
126 hasRequiredCreatePropertyDescriptor = 1;
127 createPropertyDescriptor = function (bitmap, value) {
128 return {
129 enumerable: !(bitmap & 1),
130 configurable: !(bitmap & 2),
131 writable: !(bitmap & 4),
132 value: value
133 };
134 };
135 return createPropertyDescriptor;
136 }
137
138 var functionUncurryThis;
139 var hasRequiredFunctionUncurryThis;
140
141 function requireFunctionUncurryThis () {
142 if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
143 hasRequiredFunctionUncurryThis = 1;
144 var NATIVE_BIND = requireFunctionBindNative();
145
146 var FunctionPrototype = Function.prototype;
147 var call = FunctionPrototype.call;
148 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
149
150 functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
151 return function () {
152 return call.apply(fn, arguments);
153 };
154 };
155 return functionUncurryThis;
156 }
157
158 var classofRaw;
159 var hasRequiredClassofRaw;
160
161 function requireClassofRaw () {
162 if (hasRequiredClassofRaw) return classofRaw;
163 hasRequiredClassofRaw = 1;
164 var uncurryThis = requireFunctionUncurryThis();
165
166 var toString = uncurryThis({}.toString);
167 var stringSlice = uncurryThis(''.slice);
168
169 classofRaw = function (it) {
170 return stringSlice(toString(it), 8, -1);
171 };
172 return classofRaw;
173 }
174
175 var indexedObject;
176 var hasRequiredIndexedObject;
177
178 function requireIndexedObject () {
179 if (hasRequiredIndexedObject) return indexedObject;
180 hasRequiredIndexedObject = 1;
181 var uncurryThis = requireFunctionUncurryThis();
182 var fails = requireFails();
183 var classof = requireClassofRaw();
184
185 var $Object = Object;
186 var split = uncurryThis(''.split);
187
188 // fallback for non-array-like ES3 and non-enumerable old V8 strings
189 indexedObject = fails(function () {
190 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
191 // eslint-disable-next-line no-prototype-builtins -- safe
192 return !$Object('z').propertyIsEnumerable(0);
193 }) ? function (it) {
194 return classof(it) === 'String' ? split(it, '') : $Object(it);
195 } : $Object;
196 return indexedObject;
197 }
198
199 var isNullOrUndefined;
200 var hasRequiredIsNullOrUndefined;
201
202 function requireIsNullOrUndefined () {
203 if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
204 hasRequiredIsNullOrUndefined = 1;
205 // we can't use just `it == null` since of `document.all` special case
206 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
207 isNullOrUndefined = function (it) {
208 return it === null || it === undefined;
209 };
210 return isNullOrUndefined;
211 }
212
213 var requireObjectCoercible;
214 var hasRequiredRequireObjectCoercible;
215
216 function requireRequireObjectCoercible () {
217 if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
218 hasRequiredRequireObjectCoercible = 1;
219 var isNullOrUndefined = requireIsNullOrUndefined();
220
221 var $TypeError = TypeError;
222
223 // `RequireObjectCoercible` abstract operation
224 // https://tc39.es/ecma262/#sec-requireobjectcoercible
225 requireObjectCoercible = function (it) {
226 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
227 return it;
228 };
229 return requireObjectCoercible;
230 }
231
232 var toIndexedObject;
233 var hasRequiredToIndexedObject;
234
235 function requireToIndexedObject () {
236 if (hasRequiredToIndexedObject) return toIndexedObject;
237 hasRequiredToIndexedObject = 1;
238 // toObject with fallback for non-array-like ES3 strings
239 var IndexedObject = requireIndexedObject();
240 var requireObjectCoercible = requireRequireObjectCoercible();
241
242 toIndexedObject = function (it) {
243 return IndexedObject(requireObjectCoercible(it));
244 };
245 return toIndexedObject;
246 }
247
248 var isCallable;
249 var hasRequiredIsCallable;
250
251 function requireIsCallable () {
252 if (hasRequiredIsCallable) return isCallable;
253 hasRequiredIsCallable = 1;
254 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
255 var documentAll = typeof document == 'object' && document.all;
256
257 // `IsCallable` abstract operation
258 // https://tc39.es/ecma262/#sec-iscallable
259 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
260 isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
261 return typeof argument == 'function' || argument === documentAll;
262 } : function (argument) {
263 return typeof argument == 'function';
264 };
265 return isCallable;
266 }
267
268 var isObject;
269 var hasRequiredIsObject;
270
271 function requireIsObject () {
272 if (hasRequiredIsObject) return isObject;
273 hasRequiredIsObject = 1;
274 var isCallable = requireIsCallable();
275
276 isObject = function (it) {
277 return typeof it == 'object' ? it !== null : isCallable(it);
278 };
279 return isObject;
280 }
281
282 var getBuiltIn;
283 var hasRequiredGetBuiltIn;
284
285 function requireGetBuiltIn () {
286 if (hasRequiredGetBuiltIn) return getBuiltIn;
287 hasRequiredGetBuiltIn = 1;
288 var globalThis = requireGlobalThis();
289 var isCallable = requireIsCallable();
290
291 var aFunction = function (argument) {
292 return isCallable(argument) ? argument : undefined;
293 };
294
295 getBuiltIn = function (namespace, method) {
296 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
297 };
298 return getBuiltIn;
299 }
300
301 var objectIsPrototypeOf;
302 var hasRequiredObjectIsPrototypeOf;
303
304 function requireObjectIsPrototypeOf () {
305 if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
306 hasRequiredObjectIsPrototypeOf = 1;
307 var uncurryThis = requireFunctionUncurryThis();
308
309 objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
310 return objectIsPrototypeOf;
311 }
312
313 var environmentUserAgent;
314 var hasRequiredEnvironmentUserAgent;
315
316 function requireEnvironmentUserAgent () {
317 if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
318 hasRequiredEnvironmentUserAgent = 1;
319 var globalThis = requireGlobalThis();
320
321 var navigator = globalThis.navigator;
322 var userAgent = navigator && navigator.userAgent;
323
324 environmentUserAgent = userAgent ? String(userAgent) : '';
325 return environmentUserAgent;
326 }
327
328 var environmentV8Version;
329 var hasRequiredEnvironmentV8Version;
330
331 function requireEnvironmentV8Version () {
332 if (hasRequiredEnvironmentV8Version) return environmentV8Version;
333 hasRequiredEnvironmentV8Version = 1;
334 var globalThis = requireGlobalThis();
335 var userAgent = requireEnvironmentUserAgent();
336
337 var process = globalThis.process;
338 var Deno = globalThis.Deno;
339 var versions = process && process.versions || Deno && Deno.version;
340 var v8 = versions && versions.v8;
341 var match, version;
342
343 if (v8) {
344 match = v8.split('.');
345 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
346 // but their correct versions are not interesting for us
347 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
348 }
349
350 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
351 // so check `userAgent` even if `.v8` exists, but 0
352 if (!version && userAgent) {
353 match = userAgent.match(/Edge\/(\d+)/);
354 if (!match || match[1] >= 74) {
355 match = userAgent.match(/Chrome\/(\d+)/);
356 if (match) version = +match[1];
357 }
358 }
359
360 environmentV8Version = version;
361 return environmentV8Version;
362 }
363
364 var symbolConstructorDetection;
365 var hasRequiredSymbolConstructorDetection;
366
367 function requireSymbolConstructorDetection () {
368 if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
369 hasRequiredSymbolConstructorDetection = 1;
370 /* eslint-disable es/no-symbol -- required for testing */
371 var V8_VERSION = requireEnvironmentV8Version();
372 var fails = requireFails();
373 var globalThis = requireGlobalThis();
374
375 var $String = globalThis.String;
376
377 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
378 symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
379 var symbol = Symbol('symbol detection');
380 // Chrome 38 Symbol has incorrect toString conversion
381 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
382 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
383 // of course, fail.
384 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
385 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
386 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
387 });
388 return symbolConstructorDetection;
389 }
390
391 var useSymbolAsUid;
392 var hasRequiredUseSymbolAsUid;
393
394 function requireUseSymbolAsUid () {
395 if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
396 hasRequiredUseSymbolAsUid = 1;
397 /* eslint-disable es/no-symbol -- required for testing */
398 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
399
400 useSymbolAsUid = NATIVE_SYMBOL &&
401 !Symbol.sham &&
402 typeof Symbol.iterator == 'symbol';
403 return useSymbolAsUid;
404 }
405
406 var isSymbol;
407 var hasRequiredIsSymbol;
408
409 function requireIsSymbol () {
410 if (hasRequiredIsSymbol) return isSymbol;
411 hasRequiredIsSymbol = 1;
412 var getBuiltIn = requireGetBuiltIn();
413 var isCallable = requireIsCallable();
414 var isPrototypeOf = requireObjectIsPrototypeOf();
415 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
416
417 var $Object = Object;
418
419 isSymbol = USE_SYMBOL_AS_UID ? function (it) {
420 return typeof it == 'symbol';
421 } : function (it) {
422 var $Symbol = getBuiltIn('Symbol');
423 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
424 };
425 return isSymbol;
426 }
427
428 var tryToString;
429 var hasRequiredTryToString;
430
431 function requireTryToString () {
432 if (hasRequiredTryToString) return tryToString;
433 hasRequiredTryToString = 1;
434 var $String = String;
435
436 tryToString = function (argument) {
437 try {
438 return $String(argument);
439 } catch (error) {
440 return 'Object';
441 }
442 };
443 return tryToString;
444 }
445
446 var aCallable;
447 var hasRequiredACallable;
448
449 function requireACallable () {
450 if (hasRequiredACallable) return aCallable;
451 hasRequiredACallable = 1;
452 var isCallable = requireIsCallable();
453 var tryToString = requireTryToString();
454
455 var $TypeError = TypeError;
456
457 // `Assert: IsCallable(argument) is true`
458 aCallable = function (argument) {
459 if (isCallable(argument)) return argument;
460 throw new $TypeError(tryToString(argument) + ' is not a function');
461 };
462 return aCallable;
463 }
464
465 var getMethod;
466 var hasRequiredGetMethod;
467
468 function requireGetMethod () {
469 if (hasRequiredGetMethod) return getMethod;
470 hasRequiredGetMethod = 1;
471 var aCallable = requireACallable();
472 var isNullOrUndefined = requireIsNullOrUndefined();
473
474 // `GetMethod` abstract operation
475 // https://tc39.es/ecma262/#sec-getmethod
476 getMethod = function (V, P) {
477 var func = V[P];
478 return isNullOrUndefined(func) ? undefined : aCallable(func);
479 };
480 return getMethod;
481 }
482
483 var ordinaryToPrimitive;
484 var hasRequiredOrdinaryToPrimitive;
485
486 function requireOrdinaryToPrimitive () {
487 if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
488 hasRequiredOrdinaryToPrimitive = 1;
489 var call = requireFunctionCall();
490 var isCallable = requireIsCallable();
491 var isObject = requireIsObject();
492
493 var $TypeError = TypeError;
494
495 // `OrdinaryToPrimitive` abstract operation
496 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
497 ordinaryToPrimitive = function (input, pref) {
498 var fn, val;
499 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
500 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
501 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
502 throw new $TypeError("Can't convert object to primitive value");
503 };
504 return ordinaryToPrimitive;
505 }
506
507 var sharedStore = {exports: {}};
508
509 var isPure;
510 var hasRequiredIsPure;
511
512 function requireIsPure () {
513 if (hasRequiredIsPure) return isPure;
514 hasRequiredIsPure = 1;
515 isPure = false;
516 return isPure;
517 }
518
519 var defineGlobalProperty;
520 var hasRequiredDefineGlobalProperty;
521
522 function requireDefineGlobalProperty () {
523 if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
524 hasRequiredDefineGlobalProperty = 1;
525 var globalThis = requireGlobalThis();
526
527 // eslint-disable-next-line es/no-object-defineproperty -- safe
528 var defineProperty = Object.defineProperty;
529
530 defineGlobalProperty = function (key, value) {
531 try {
532 defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
533 } catch (error) {
534 globalThis[key] = value;
535 } return value;
536 };
537 return defineGlobalProperty;
538 }
539
540 var hasRequiredSharedStore;
541
542 function requireSharedStore () {
543 if (hasRequiredSharedStore) return sharedStore.exports;
544 hasRequiredSharedStore = 1;
545 var IS_PURE = requireIsPure();
546 var globalThis = requireGlobalThis();
547 var defineGlobalProperty = requireDefineGlobalProperty();
548
549 var SHARED = '__core-js_shared__';
550 var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
551
552 (store.versions || (store.versions = [])).push({
553 version: '3.39.0',
554 mode: IS_PURE ? 'pure' : 'global',
555 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
556 license: 'https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE',
557 source: 'https://github.com/zloirock/core-js'
558 });
559 return sharedStore.exports;
560 }
561
562 var shared;
563 var hasRequiredShared;
564
565 function requireShared () {
566 if (hasRequiredShared) return shared;
567 hasRequiredShared = 1;
568 var store = requireSharedStore();
569
570 shared = function (key, value) {
571 return store[key] || (store[key] = value || {});
572 };
573 return shared;
574 }
575
576 var toObject;
577 var hasRequiredToObject;
578
579 function requireToObject () {
580 if (hasRequiredToObject) return toObject;
581 hasRequiredToObject = 1;
582 var requireObjectCoercible = requireRequireObjectCoercible();
583
584 var $Object = Object;
585
586 // `ToObject` abstract operation
587 // https://tc39.es/ecma262/#sec-toobject
588 toObject = function (argument) {
589 return $Object(requireObjectCoercible(argument));
590 };
591 return toObject;
592 }
593
594 var hasOwnProperty_1;
595 var hasRequiredHasOwnProperty;
596
597 function requireHasOwnProperty () {
598 if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
599 hasRequiredHasOwnProperty = 1;
600 var uncurryThis = requireFunctionUncurryThis();
601 var toObject = requireToObject();
602
603 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
604
605 // `HasOwnProperty` abstract operation
606 // https://tc39.es/ecma262/#sec-hasownproperty
607 // eslint-disable-next-line es/no-object-hasown -- safe
608 hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
609 return hasOwnProperty(toObject(it), key);
610 };
611 return hasOwnProperty_1;
612 }
613
614 var uid;
615 var hasRequiredUid;
616
617 function requireUid () {
618 if (hasRequiredUid) return uid;
619 hasRequiredUid = 1;
620 var uncurryThis = requireFunctionUncurryThis();
621
622 var id = 0;
623 var postfix = Math.random();
624 var toString = uncurryThis(1.0.toString);
625
626 uid = function (key) {
627 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
628 };
629 return uid;
630 }
631
632 var wellKnownSymbol;
633 var hasRequiredWellKnownSymbol;
634
635 function requireWellKnownSymbol () {
636 if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
637 hasRequiredWellKnownSymbol = 1;
638 var globalThis = requireGlobalThis();
639 var shared = requireShared();
640 var hasOwn = requireHasOwnProperty();
641 var uid = requireUid();
642 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
643 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
644
645 var Symbol = globalThis.Symbol;
646 var WellKnownSymbolsStore = shared('wks');
647 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
648
649 wellKnownSymbol = function (name) {
650 if (!hasOwn(WellKnownSymbolsStore, name)) {
651 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
652 ? Symbol[name]
653 : createWellKnownSymbol('Symbol.' + name);
654 } return WellKnownSymbolsStore[name];
655 };
656 return wellKnownSymbol;
657 }
658
659 var toPrimitive;
660 var hasRequiredToPrimitive;
661
662 function requireToPrimitive () {
663 if (hasRequiredToPrimitive) return toPrimitive;
664 hasRequiredToPrimitive = 1;
665 var call = requireFunctionCall();
666 var isObject = requireIsObject();
667 var isSymbol = requireIsSymbol();
668 var getMethod = requireGetMethod();
669 var ordinaryToPrimitive = requireOrdinaryToPrimitive();
670 var wellKnownSymbol = requireWellKnownSymbol();
671
672 var $TypeError = TypeError;
673 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
674
675 // `ToPrimitive` abstract operation
676 // https://tc39.es/ecma262/#sec-toprimitive
677 toPrimitive = function (input, pref) {
678 if (!isObject(input) || isSymbol(input)) return input;
679 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
680 var result;
681 if (exoticToPrim) {
682 if (pref === undefined) pref = 'default';
683 result = call(exoticToPrim, input, pref);
684 if (!isObject(result) || isSymbol(result)) return result;
685 throw new $TypeError("Can't convert object to primitive value");
686 }
687 if (pref === undefined) pref = 'number';
688 return ordinaryToPrimitive(input, pref);
689 };
690 return toPrimitive;
691 }
692
693 var toPropertyKey;
694 var hasRequiredToPropertyKey;
695
696 function requireToPropertyKey () {
697 if (hasRequiredToPropertyKey) return toPropertyKey;
698 hasRequiredToPropertyKey = 1;
699 var toPrimitive = requireToPrimitive();
700 var isSymbol = requireIsSymbol();
701
702 // `ToPropertyKey` abstract operation
703 // https://tc39.es/ecma262/#sec-topropertykey
704 toPropertyKey = function (argument) {
705 var key = toPrimitive(argument, 'string');
706 return isSymbol(key) ? key : key + '';
707 };
708 return toPropertyKey;
709 }
710
711 var documentCreateElement;
712 var hasRequiredDocumentCreateElement;
713
714 function requireDocumentCreateElement () {
715 if (hasRequiredDocumentCreateElement) return documentCreateElement;
716 hasRequiredDocumentCreateElement = 1;
717 var globalThis = requireGlobalThis();
718 var isObject = requireIsObject();
719
720 var document = globalThis.document;
721 // typeof document.createElement is 'object' in old IE
722 var EXISTS = isObject(document) && isObject(document.createElement);
723
724 documentCreateElement = function (it) {
725 return EXISTS ? document.createElement(it) : {};
726 };
727 return documentCreateElement;
728 }
729
730 var ie8DomDefine;
731 var hasRequiredIe8DomDefine;
732
733 function requireIe8DomDefine () {
734 if (hasRequiredIe8DomDefine) return ie8DomDefine;
735 hasRequiredIe8DomDefine = 1;
736 var DESCRIPTORS = requireDescriptors();
737 var fails = requireFails();
738 var createElement = requireDocumentCreateElement();
739
740 // Thanks to IE8 for its funny defineProperty
741 ie8DomDefine = !DESCRIPTORS && !fails(function () {
742 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
743 return Object.defineProperty(createElement('div'), 'a', {
744 get: function () { return 7; }
745 }).a !== 7;
746 });
747 return ie8DomDefine;
748 }
749
750 var hasRequiredObjectGetOwnPropertyDescriptor;
751
752 function requireObjectGetOwnPropertyDescriptor () {
753 if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
754 hasRequiredObjectGetOwnPropertyDescriptor = 1;
755 var DESCRIPTORS = requireDescriptors();
756 var call = requireFunctionCall();
757 var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
758 var createPropertyDescriptor = requireCreatePropertyDescriptor();
759 var toIndexedObject = requireToIndexedObject();
760 var toPropertyKey = requireToPropertyKey();
761 var hasOwn = requireHasOwnProperty();
762 var IE8_DOM_DEFINE = requireIe8DomDefine();
763
764 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
765 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
766
767 // `Object.getOwnPropertyDescriptor` method
768 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
769 objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
770 O = toIndexedObject(O);
771 P = toPropertyKey(P);
772 if (IE8_DOM_DEFINE) try {
773 return $getOwnPropertyDescriptor(O, P);
774 } catch (error) { /* empty */ }
775 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
776 };
777 return objectGetOwnPropertyDescriptor;
778 }
779
780 var objectDefineProperty = {};
781
782 var v8PrototypeDefineBug;
783 var hasRequiredV8PrototypeDefineBug;
784
785 function requireV8PrototypeDefineBug () {
786 if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
787 hasRequiredV8PrototypeDefineBug = 1;
788 var DESCRIPTORS = requireDescriptors();
789 var fails = requireFails();
790
791 // V8 ~ Chrome 36-
792 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
793 v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
794 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
795 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
796 value: 42,
797 writable: false
798 }).prototype !== 42;
799 });
800 return v8PrototypeDefineBug;
801 }
802
803 var anObject;
804 var hasRequiredAnObject;
805
806 function requireAnObject () {
807 if (hasRequiredAnObject) return anObject;
808 hasRequiredAnObject = 1;
809 var isObject = requireIsObject();
810
811 var $String = String;
812 var $TypeError = TypeError;
813
814 // `Assert: Type(argument) is Object`
815 anObject = function (argument) {
816 if (isObject(argument)) return argument;
817 throw new $TypeError($String(argument) + ' is not an object');
818 };
819 return anObject;
820 }
821
822 var hasRequiredObjectDefineProperty;
823
824 function requireObjectDefineProperty () {
825 if (hasRequiredObjectDefineProperty) return objectDefineProperty;
826 hasRequiredObjectDefineProperty = 1;
827 var DESCRIPTORS = requireDescriptors();
828 var IE8_DOM_DEFINE = requireIe8DomDefine();
829 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
830 var anObject = requireAnObject();
831 var toPropertyKey = requireToPropertyKey();
832
833 var $TypeError = TypeError;
834 // eslint-disable-next-line es/no-object-defineproperty -- safe
835 var $defineProperty = Object.defineProperty;
836 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
837 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
838 var ENUMERABLE = 'enumerable';
839 var CONFIGURABLE = 'configurable';
840 var WRITABLE = 'writable';
841
842 // `Object.defineProperty` method
843 // https://tc39.es/ecma262/#sec-object.defineproperty
844 objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
845 anObject(O);
846 P = toPropertyKey(P);
847 anObject(Attributes);
848 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
849 var current = $getOwnPropertyDescriptor(O, P);
850 if (current && current[WRITABLE]) {
851 O[P] = Attributes.value;
852 Attributes = {
853 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
854 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
855 writable: false
856 };
857 }
858 } return $defineProperty(O, P, Attributes);
859 } : $defineProperty : function defineProperty(O, P, Attributes) {
860 anObject(O);
861 P = toPropertyKey(P);
862 anObject(Attributes);
863 if (IE8_DOM_DEFINE) try {
864 return $defineProperty(O, P, Attributes);
865 } catch (error) { /* empty */ }
866 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
867 if ('value' in Attributes) O[P] = Attributes.value;
868 return O;
869 };
870 return objectDefineProperty;
871 }
872
873 var createNonEnumerableProperty;
874 var hasRequiredCreateNonEnumerableProperty;
875
876 function requireCreateNonEnumerableProperty () {
877 if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
878 hasRequiredCreateNonEnumerableProperty = 1;
879 var DESCRIPTORS = requireDescriptors();
880 var definePropertyModule = requireObjectDefineProperty();
881 var createPropertyDescriptor = requireCreatePropertyDescriptor();
882
883 createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
884 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
885 } : function (object, key, value) {
886 object[key] = value;
887 return object;
888 };
889 return createNonEnumerableProperty;
890 }
891
892 var makeBuiltIn = {exports: {}};
893
894 var functionName;
895 var hasRequiredFunctionName;
896
897 function requireFunctionName () {
898 if (hasRequiredFunctionName) return functionName;
899 hasRequiredFunctionName = 1;
900 var DESCRIPTORS = requireDescriptors();
901 var hasOwn = requireHasOwnProperty();
902
903 var FunctionPrototype = Function.prototype;
904 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
905 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
906
907 var EXISTS = hasOwn(FunctionPrototype, 'name');
908 // additional protection from minified / mangled / dropped function names
909 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
910 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
911
912 functionName = {
913 EXISTS: EXISTS,
914 PROPER: PROPER,
915 CONFIGURABLE: CONFIGURABLE
916 };
917 return functionName;
918 }
919
920 var inspectSource;
921 var hasRequiredInspectSource;
922
923 function requireInspectSource () {
924 if (hasRequiredInspectSource) return inspectSource;
925 hasRequiredInspectSource = 1;
926 var uncurryThis = requireFunctionUncurryThis();
927 var isCallable = requireIsCallable();
928 var store = requireSharedStore();
929
930 var functionToString = uncurryThis(Function.toString);
931
932 // this helper broken in `[email protected]`, so we can't use `shared` helper
933 if (!isCallable(store.inspectSource)) {
934 store.inspectSource = function (it) {
935 return functionToString(it);
936 };
937 }
938
939 inspectSource = store.inspectSource;
940 return inspectSource;
941 }
942
943 var weakMapBasicDetection;
944 var hasRequiredWeakMapBasicDetection;
945
946 function requireWeakMapBasicDetection () {
947 if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
948 hasRequiredWeakMapBasicDetection = 1;
949 var globalThis = requireGlobalThis();
950 var isCallable = requireIsCallable();
951
952 var WeakMap = globalThis.WeakMap;
953
954 weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
955 return weakMapBasicDetection;
956 }
957
958 var sharedKey;
959 var hasRequiredSharedKey;
960
961 function requireSharedKey () {
962 if (hasRequiredSharedKey) return sharedKey;
963 hasRequiredSharedKey = 1;
964 var shared = requireShared();
965 var uid = requireUid();
966
967 var keys = shared('keys');
968
969 sharedKey = function (key) {
970 return keys[key] || (keys[key] = uid(key));
971 };
972 return sharedKey;
973 }
974
975 var hiddenKeys;
976 var hasRequiredHiddenKeys;
977
978 function requireHiddenKeys () {
979 if (hasRequiredHiddenKeys) return hiddenKeys;
980 hasRequiredHiddenKeys = 1;
981 hiddenKeys = {};
982 return hiddenKeys;
983 }
984
985 var internalState;
986 var hasRequiredInternalState;
987
988 function requireInternalState () {
989 if (hasRequiredInternalState) return internalState;
990 hasRequiredInternalState = 1;
991 var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
992 var globalThis = requireGlobalThis();
993 var isObject = requireIsObject();
994 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
995 var hasOwn = requireHasOwnProperty();
996 var shared = requireSharedStore();
997 var sharedKey = requireSharedKey();
998 var hiddenKeys = requireHiddenKeys();
999
1000 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
1001 var TypeError = globalThis.TypeError;
1002 var WeakMap = globalThis.WeakMap;
1003 var set, get, has;
1004
1005 var enforce = function (it) {
1006 return has(it) ? get(it) : set(it, {});
1007 };
1008
1009 var getterFor = function (TYPE) {
1010 return function (it) {
1011 var state;
1012 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1013 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1014 } return state;
1015 };
1016 };
1017
1018 if (NATIVE_WEAK_MAP || shared.state) {
1019 var store = shared.state || (shared.state = new WeakMap());
1020 /* eslint-disable no-self-assign -- prototype methods protection */
1021 store.get = store.get;
1022 store.has = store.has;
1023 store.set = store.set;
1024 /* eslint-enable no-self-assign -- prototype methods protection */
1025 set = function (it, metadata) {
1026 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1027 metadata.facade = it;
1028 store.set(it, metadata);
1029 return metadata;
1030 };
1031 get = function (it) {
1032 return store.get(it) || {};
1033 };
1034 has = function (it) {
1035 return store.has(it);
1036 };
1037 } else {
1038 var STATE = sharedKey('state');
1039 hiddenKeys[STATE] = true;
1040 set = function (it, metadata) {
1041 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1042 metadata.facade = it;
1043 createNonEnumerableProperty(it, STATE, metadata);
1044 return metadata;
1045 };
1046 get = function (it) {
1047 return hasOwn(it, STATE) ? it[STATE] : {};
1048 };
1049 has = function (it) {
1050 return hasOwn(it, STATE);
1051 };
1052 }
1053
1054 internalState = {
1055 set: set,
1056 get: get,
1057 has: has,
1058 enforce: enforce,
1059 getterFor: getterFor
1060 };
1061 return internalState;
1062 }
1063
1064 var hasRequiredMakeBuiltIn;
1065
1066 function requireMakeBuiltIn () {
1067 if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
1068 hasRequiredMakeBuiltIn = 1;
1069 var uncurryThis = requireFunctionUncurryThis();
1070 var fails = requireFails();
1071 var isCallable = requireIsCallable();
1072 var hasOwn = requireHasOwnProperty();
1073 var DESCRIPTORS = requireDescriptors();
1074 var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
1075 var inspectSource = requireInspectSource();
1076 var InternalStateModule = requireInternalState();
1077
1078 var enforceInternalState = InternalStateModule.enforce;
1079 var getInternalState = InternalStateModule.get;
1080 var $String = String;
1081 // eslint-disable-next-line es/no-object-defineproperty -- safe
1082 var defineProperty = Object.defineProperty;
1083 var stringSlice = uncurryThis(''.slice);
1084 var replace = uncurryThis(''.replace);
1085 var join = uncurryThis([].join);
1086
1087 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
1088 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
1089 });
1090
1091 var TEMPLATE = String(String).split('String');
1092
1093 var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
1094 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
1095 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
1096 }
1097 if (options && options.getter) name = 'get ' + name;
1098 if (options && options.setter) name = 'set ' + name;
1099 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
1100 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
1101 else value.name = name;
1102 }
1103 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
1104 defineProperty(value, 'length', { value: options.arity });
1105 }
1106 try {
1107 if (options && hasOwn(options, 'constructor') && options.constructor) {
1108 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
1109 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
1110 } else if (value.prototype) value.prototype = undefined;
1111 } catch (error) { /* empty */ }
1112 var state = enforceInternalState(value);
1113 if (!hasOwn(state, 'source')) {
1114 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
1115 } return value;
1116 };
1117
1118 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1119 // eslint-disable-next-line no-extend-native -- required
1120 Function.prototype.toString = makeBuiltIn$1(function toString() {
1121 return isCallable(this) && getInternalState(this).source || inspectSource(this);
1122 }, 'toString');
1123 return makeBuiltIn.exports;
1124 }
1125
1126 var defineBuiltIn;
1127 var hasRequiredDefineBuiltIn;
1128
1129 function requireDefineBuiltIn () {
1130 if (hasRequiredDefineBuiltIn) return defineBuiltIn;
1131 hasRequiredDefineBuiltIn = 1;
1132 var isCallable = requireIsCallable();
1133 var definePropertyModule = requireObjectDefineProperty();
1134 var makeBuiltIn = requireMakeBuiltIn();
1135 var defineGlobalProperty = requireDefineGlobalProperty();
1136
1137 defineBuiltIn = function (O, key, value, options) {
1138 if (!options) options = {};
1139 var simple = options.enumerable;
1140 var name = options.name !== undefined ? options.name : key;
1141 if (isCallable(value)) makeBuiltIn(value, name, options);
1142 if (options.global) {
1143 if (simple) O[key] = value;
1144 else defineGlobalProperty(key, value);
1145 } else {
1146 try {
1147 if (!options.unsafe) delete O[key];
1148 else if (O[key]) simple = true;
1149 } catch (error) { /* empty */ }
1150 if (simple) O[key] = value;
1151 else definePropertyModule.f(O, key, {
1152 value: value,
1153 enumerable: false,
1154 configurable: !options.nonConfigurable,
1155 writable: !options.nonWritable
1156 });
1157 } return O;
1158 };
1159 return defineBuiltIn;
1160 }
1161
1162 var objectGetOwnPropertyNames = {};
1163
1164 var mathTrunc;
1165 var hasRequiredMathTrunc;
1166
1167 function requireMathTrunc () {
1168 if (hasRequiredMathTrunc) return mathTrunc;
1169 hasRequiredMathTrunc = 1;
1170 var ceil = Math.ceil;
1171 var floor = Math.floor;
1172
1173 // `Math.trunc` method
1174 // https://tc39.es/ecma262/#sec-math.trunc
1175 // eslint-disable-next-line es/no-math-trunc -- safe
1176 mathTrunc = Math.trunc || function trunc(x) {
1177 var n = +x;
1178 return (n > 0 ? floor : ceil)(n);
1179 };
1180 return mathTrunc;
1181 }
1182
1183 var toIntegerOrInfinity;
1184 var hasRequiredToIntegerOrInfinity;
1185
1186 function requireToIntegerOrInfinity () {
1187 if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
1188 hasRequiredToIntegerOrInfinity = 1;
1189 var trunc = requireMathTrunc();
1190
1191 // `ToIntegerOrInfinity` abstract operation
1192 // https://tc39.es/ecma262/#sec-tointegerorinfinity
1193 toIntegerOrInfinity = function (argument) {
1194 var number = +argument;
1195 // eslint-disable-next-line no-self-compare -- NaN check
1196 return number !== number || number === 0 ? 0 : trunc(number);
1197 };
1198 return toIntegerOrInfinity;
1199 }
1200
1201 var toAbsoluteIndex;
1202 var hasRequiredToAbsoluteIndex;
1203
1204 function requireToAbsoluteIndex () {
1205 if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
1206 hasRequiredToAbsoluteIndex = 1;
1207 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1208
1209 var max = Math.max;
1210 var min = Math.min;
1211
1212 // Helper for a popular repeating case of the spec:
1213 // Let integer be ? ToInteger(index).
1214 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1215 toAbsoluteIndex = function (index, length) {
1216 var integer = toIntegerOrInfinity(index);
1217 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1218 };
1219 return toAbsoluteIndex;
1220 }
1221
1222 var toLength;
1223 var hasRequiredToLength;
1224
1225 function requireToLength () {
1226 if (hasRequiredToLength) return toLength;
1227 hasRequiredToLength = 1;
1228 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1229
1230 var min = Math.min;
1231
1232 // `ToLength` abstract operation
1233 // https://tc39.es/ecma262/#sec-tolength
1234 toLength = function (argument) {
1235 var len = toIntegerOrInfinity(argument);
1236 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1237 };
1238 return toLength;
1239 }
1240
1241 var lengthOfArrayLike;
1242 var hasRequiredLengthOfArrayLike;
1243
1244 function requireLengthOfArrayLike () {
1245 if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
1246 hasRequiredLengthOfArrayLike = 1;
1247 var toLength = requireToLength();
1248
1249 // `LengthOfArrayLike` abstract operation
1250 // https://tc39.es/ecma262/#sec-lengthofarraylike
1251 lengthOfArrayLike = function (obj) {
1252 return toLength(obj.length);
1253 };
1254 return lengthOfArrayLike;
1255 }
1256
1257 var arrayIncludes;
1258 var hasRequiredArrayIncludes;
1259
1260 function requireArrayIncludes () {
1261 if (hasRequiredArrayIncludes) return arrayIncludes;
1262 hasRequiredArrayIncludes = 1;
1263 var toIndexedObject = requireToIndexedObject();
1264 var toAbsoluteIndex = requireToAbsoluteIndex();
1265 var lengthOfArrayLike = requireLengthOfArrayLike();
1266
1267 // `Array.prototype.{ indexOf, includes }` methods implementation
1268 var createMethod = function (IS_INCLUDES) {
1269 return function ($this, el, fromIndex) {
1270 var O = toIndexedObject($this);
1271 var length = lengthOfArrayLike(O);
1272 if (length === 0) return !IS_INCLUDES && -1;
1273 var index = toAbsoluteIndex(fromIndex, length);
1274 var value;
1275 // Array#includes uses SameValueZero equality algorithm
1276 // eslint-disable-next-line no-self-compare -- NaN check
1277 if (IS_INCLUDES && el !== el) while (length > index) {
1278 value = O[index++];
1279 // eslint-disable-next-line no-self-compare -- NaN check
1280 if (value !== value) return true;
1281 // Array#indexOf ignores holes, Array#includes - not
1282 } else for (;length > index; index++) {
1283 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1284 } return !IS_INCLUDES && -1;
1285 };
1286 };
1287
1288 arrayIncludes = {
1289 // `Array.prototype.includes` method
1290 // https://tc39.es/ecma262/#sec-array.prototype.includes
1291 includes: createMethod(true),
1292 // `Array.prototype.indexOf` method
1293 // https://tc39.es/ecma262/#sec-array.prototype.indexof
1294 indexOf: createMethod(false)
1295 };
1296 return arrayIncludes;
1297 }
1298
1299 var objectKeysInternal;
1300 var hasRequiredObjectKeysInternal;
1301
1302 function requireObjectKeysInternal () {
1303 if (hasRequiredObjectKeysInternal) return objectKeysInternal;
1304 hasRequiredObjectKeysInternal = 1;
1305 var uncurryThis = requireFunctionUncurryThis();
1306 var hasOwn = requireHasOwnProperty();
1307 var toIndexedObject = requireToIndexedObject();
1308 var indexOf = requireArrayIncludes().indexOf;
1309 var hiddenKeys = requireHiddenKeys();
1310
1311 var push = uncurryThis([].push);
1312
1313 objectKeysInternal = function (object, names) {
1314 var O = toIndexedObject(object);
1315 var i = 0;
1316 var result = [];
1317 var key;
1318 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
1319 // Don't enum bug & hidden keys
1320 while (names.length > i) if (hasOwn(O, key = names[i++])) {
1321 ~indexOf(result, key) || push(result, key);
1322 }
1323 return result;
1324 };
1325 return objectKeysInternal;
1326 }
1327
1328 var enumBugKeys;
1329 var hasRequiredEnumBugKeys;
1330
1331 function requireEnumBugKeys () {
1332 if (hasRequiredEnumBugKeys) return enumBugKeys;
1333 hasRequiredEnumBugKeys = 1;
1334 // IE8- don't enum bug keys
1335 enumBugKeys = [
1336 'constructor',
1337 'hasOwnProperty',
1338 'isPrototypeOf',
1339 'propertyIsEnumerable',
1340 'toLocaleString',
1341 'toString',
1342 'valueOf'
1343 ];
1344 return enumBugKeys;
1345 }
1346
1347 var hasRequiredObjectGetOwnPropertyNames;
1348
1349 function requireObjectGetOwnPropertyNames () {
1350 if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
1351 hasRequiredObjectGetOwnPropertyNames = 1;
1352 var internalObjectKeys = requireObjectKeysInternal();
1353 var enumBugKeys = requireEnumBugKeys();
1354
1355 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
1356
1357 // `Object.getOwnPropertyNames` method
1358 // https://tc39.es/ecma262/#sec-object.getownpropertynames
1359 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
1360 objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1361 return internalObjectKeys(O, hiddenKeys);
1362 };
1363 return objectGetOwnPropertyNames;
1364 }
1365
1366 var objectGetOwnPropertySymbols = {};
1367
1368 var hasRequiredObjectGetOwnPropertySymbols;
1369
1370 function requireObjectGetOwnPropertySymbols () {
1371 if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
1372 hasRequiredObjectGetOwnPropertySymbols = 1;
1373 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
1374 objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
1375 return objectGetOwnPropertySymbols;
1376 }
1377
1378 var ownKeys;
1379 var hasRequiredOwnKeys;
1380
1381 function requireOwnKeys () {
1382 if (hasRequiredOwnKeys) return ownKeys;
1383 hasRequiredOwnKeys = 1;
1384 var getBuiltIn = requireGetBuiltIn();
1385 var uncurryThis = requireFunctionUncurryThis();
1386 var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
1387 var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
1388 var anObject = requireAnObject();
1389
1390 var concat = uncurryThis([].concat);
1391
1392 // all object keys, includes non-enumerable and symbols
1393 ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1394 var keys = getOwnPropertyNamesModule.f(anObject(it));
1395 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1396 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
1397 };
1398 return ownKeys;
1399 }
1400
1401 var copyConstructorProperties;
1402 var hasRequiredCopyConstructorProperties;
1403
1404 function requireCopyConstructorProperties () {
1405 if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
1406 hasRequiredCopyConstructorProperties = 1;
1407 var hasOwn = requireHasOwnProperty();
1408 var ownKeys = requireOwnKeys();
1409 var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
1410 var definePropertyModule = requireObjectDefineProperty();
1411
1412 copyConstructorProperties = function (target, source, exceptions) {
1413 var keys = ownKeys(source);
1414 var defineProperty = definePropertyModule.f;
1415 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1416 for (var i = 0; i < keys.length; i++) {
1417 var key = keys[i];
1418 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
1419 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1420 }
1421 }
1422 };
1423 return copyConstructorProperties;
1424 }
1425
1426 var isForced_1;
1427 var hasRequiredIsForced;
1428
1429 function requireIsForced () {
1430 if (hasRequiredIsForced) return isForced_1;
1431 hasRequiredIsForced = 1;
1432 var fails = requireFails();
1433 var isCallable = requireIsCallable();
1434
1435 var replacement = /#|\.prototype\./;
1436
1437 var isForced = function (feature, detection) {
1438 var value = data[normalize(feature)];
1439 return value === POLYFILL ? true
1440 : value === NATIVE ? false
1441 : isCallable(detection) ? fails(detection)
1442 : !!detection;
1443 };
1444
1445 var normalize = isForced.normalize = function (string) {
1446 return String(string).replace(replacement, '.').toLowerCase();
1447 };
1448
1449 var data = isForced.data = {};
1450 var NATIVE = isForced.NATIVE = 'N';
1451 var POLYFILL = isForced.POLYFILL = 'P';
1452
1453 isForced_1 = isForced;
1454 return isForced_1;
1455 }
1456
1457 var _export;
1458 var hasRequired_export;
1459
1460 function require_export () {
1461 if (hasRequired_export) return _export;
1462 hasRequired_export = 1;
1463 var globalThis = requireGlobalThis();
1464 var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
1465 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1466 var defineBuiltIn = requireDefineBuiltIn();
1467 var defineGlobalProperty = requireDefineGlobalProperty();
1468 var copyConstructorProperties = requireCopyConstructorProperties();
1469 var isForced = requireIsForced();
1470
1471 /*
1472 options.target - name of the target object
1473 options.global - target is the global object
1474 options.stat - export as static methods of target
1475 options.proto - export as prototype methods of target
1476 options.real - real prototype method for the `pure` version
1477 options.forced - export even if the native feature is available
1478 options.bind - bind methods to the target, required for the `pure` version
1479 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1480 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1481 options.sham - add a flag to not completely full polyfills
1482 options.enumerable - export as enumerable property
1483 options.dontCallGetSet - prevent calling a getter on target
1484 options.name - the .name of the function if it does not match the key
1485 */
1486 _export = function (options, source) {
1487 var TARGET = options.target;
1488 var GLOBAL = options.global;
1489 var STATIC = options.stat;
1490 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1491 if (GLOBAL) {
1492 target = globalThis;
1493 } else if (STATIC) {
1494 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
1495 } else {
1496 target = globalThis[TARGET] && globalThis[TARGET].prototype;
1497 }
1498 if (target) for (key in source) {
1499 sourceProperty = source[key];
1500 if (options.dontCallGetSet) {
1501 descriptor = getOwnPropertyDescriptor(target, key);
1502 targetProperty = descriptor && descriptor.value;
1503 } else targetProperty = target[key];
1504 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1505 // contained in target
1506 if (!FORCED && targetProperty !== undefined) {
1507 if (typeof sourceProperty == typeof targetProperty) continue;
1508 copyConstructorProperties(sourceProperty, targetProperty);
1509 }
1510 // add a flag to not completely full polyfills
1511 if (options.sham || (targetProperty && targetProperty.sham)) {
1512 createNonEnumerableProperty(sourceProperty, 'sham', true);
1513 }
1514 defineBuiltIn(target, key, sourceProperty, options);
1515 }
1516 };
1517 return _export;
1518 }
1519
1520 var functionApply;
1521 var hasRequiredFunctionApply;
1522
1523 function requireFunctionApply () {
1524 if (hasRequiredFunctionApply) return functionApply;
1525 hasRequiredFunctionApply = 1;
1526 var NATIVE_BIND = requireFunctionBindNative();
1527
1528 var FunctionPrototype = Function.prototype;
1529 var apply = FunctionPrototype.apply;
1530 var call = FunctionPrototype.call;
1531
1532 // eslint-disable-next-line es/no-reflect -- safe
1533 functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
1534 return call.apply(apply, arguments);
1535 });
1536 return functionApply;
1537 }
1538
1539 var functionUncurryThisAccessor;
1540 var hasRequiredFunctionUncurryThisAccessor;
1541
1542 function requireFunctionUncurryThisAccessor () {
1543 if (hasRequiredFunctionUncurryThisAccessor) return functionUncurryThisAccessor;
1544 hasRequiredFunctionUncurryThisAccessor = 1;
1545 var uncurryThis = requireFunctionUncurryThis();
1546 var aCallable = requireACallable();
1547
1548 functionUncurryThisAccessor = function (object, key, method) {
1549 try {
1550 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
1551 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
1552 } catch (error) { /* empty */ }
1553 };
1554 return functionUncurryThisAccessor;
1555 }
1556
1557 var isPossiblePrototype;
1558 var hasRequiredIsPossiblePrototype;
1559
1560 function requireIsPossiblePrototype () {
1561 if (hasRequiredIsPossiblePrototype) return isPossiblePrototype;
1562 hasRequiredIsPossiblePrototype = 1;
1563 var isObject = requireIsObject();
1564
1565 isPossiblePrototype = function (argument) {
1566 return isObject(argument) || argument === null;
1567 };
1568 return isPossiblePrototype;
1569 }
1570
1571 var aPossiblePrototype;
1572 var hasRequiredAPossiblePrototype;
1573
1574 function requireAPossiblePrototype () {
1575 if (hasRequiredAPossiblePrototype) return aPossiblePrototype;
1576 hasRequiredAPossiblePrototype = 1;
1577 var isPossiblePrototype = requireIsPossiblePrototype();
1578
1579 var $String = String;
1580 var $TypeError = TypeError;
1581
1582 aPossiblePrototype = function (argument) {
1583 if (isPossiblePrototype(argument)) return argument;
1584 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
1585 };
1586 return aPossiblePrototype;
1587 }
1588
1589 var objectSetPrototypeOf;
1590 var hasRequiredObjectSetPrototypeOf;
1591
1592 function requireObjectSetPrototypeOf () {
1593 if (hasRequiredObjectSetPrototypeOf) return objectSetPrototypeOf;
1594 hasRequiredObjectSetPrototypeOf = 1;
1595 /* eslint-disable no-proto -- safe */
1596 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
1597 var isObject = requireIsObject();
1598 var requireObjectCoercible = requireRequireObjectCoercible();
1599 var aPossiblePrototype = requireAPossiblePrototype();
1600
1601 // `Object.setPrototypeOf` method
1602 // https://tc39.es/ecma262/#sec-object.setprototypeof
1603 // Works with __proto__ only. Old v8 can't work with null proto objects.
1604 // eslint-disable-next-line es/no-object-setprototypeof -- safe
1605 objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
1606 var CORRECT_SETTER = false;
1607 var test = {};
1608 var setter;
1609 try {
1610 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
1611 setter(test, []);
1612 CORRECT_SETTER = test instanceof Array;
1613 } catch (error) { /* empty */ }
1614 return function setPrototypeOf(O, proto) {
1615 requireObjectCoercible(O);
1616 aPossiblePrototype(proto);
1617 if (!isObject(O)) return O;
1618 if (CORRECT_SETTER) setter(O, proto);
1619 else O.__proto__ = proto;
1620 return O;
1621 };
1622 }() : undefined);
1623 return objectSetPrototypeOf;
1624 }
1625
1626 var proxyAccessor;
1627 var hasRequiredProxyAccessor;
1628
1629 function requireProxyAccessor () {
1630 if (hasRequiredProxyAccessor) return proxyAccessor;
1631 hasRequiredProxyAccessor = 1;
1632 var defineProperty = requireObjectDefineProperty().f;
1633
1634 proxyAccessor = function (Target, Source, key) {
1635 key in Target || defineProperty(Target, key, {
1636 configurable: true,
1637 get: function () { return Source[key]; },
1638 set: function (it) { Source[key] = it; }
1639 });
1640 };
1641 return proxyAccessor;
1642 }
1643
1644 var inheritIfRequired;
1645 var hasRequiredInheritIfRequired;
1646
1647 function requireInheritIfRequired () {
1648 if (hasRequiredInheritIfRequired) return inheritIfRequired;
1649 hasRequiredInheritIfRequired = 1;
1650 var isCallable = requireIsCallable();
1651 var isObject = requireIsObject();
1652 var setPrototypeOf = requireObjectSetPrototypeOf();
1653
1654 // makes subclassing work correct for wrapped built-ins
1655 inheritIfRequired = function ($this, dummy, Wrapper) {
1656 var NewTarget, NewTargetPrototype;
1657 if (
1658 // it can work only with native `setPrototypeOf`
1659 setPrototypeOf &&
1660 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
1661 isCallable(NewTarget = dummy.constructor) &&
1662 NewTarget !== Wrapper &&
1663 isObject(NewTargetPrototype = NewTarget.prototype) &&
1664 NewTargetPrototype !== Wrapper.prototype
1665 ) setPrototypeOf($this, NewTargetPrototype);
1666 return $this;
1667 };
1668 return inheritIfRequired;
1669 }
1670
1671 var toStringTagSupport;
1672 var hasRequiredToStringTagSupport;
1673
1674 function requireToStringTagSupport () {
1675 if (hasRequiredToStringTagSupport) return toStringTagSupport;
1676 hasRequiredToStringTagSupport = 1;
1677 var wellKnownSymbol = requireWellKnownSymbol();
1678
1679 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1680 var test = {};
1681
1682 test[TO_STRING_TAG] = 'z';
1683
1684 toStringTagSupport = String(test) === '[object z]';
1685 return toStringTagSupport;
1686 }
1687
1688 var classof;
1689 var hasRequiredClassof;
1690
1691 function requireClassof () {
1692 if (hasRequiredClassof) return classof;
1693 hasRequiredClassof = 1;
1694 var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
1695 var isCallable = requireIsCallable();
1696 var classofRaw = requireClassofRaw();
1697 var wellKnownSymbol = requireWellKnownSymbol();
1698
1699 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1700 var $Object = Object;
1701
1702 // ES3 wrong here
1703 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
1704
1705 // fallback for IE11 Script Access Denied error
1706 var tryGet = function (it, key) {
1707 try {
1708 return it[key];
1709 } catch (error) { /* empty */ }
1710 };
1711
1712 // getting tag from ES6+ `Object.prototype.toString`
1713 classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
1714 var O, tag, result;
1715 return it === undefined ? 'Undefined' : it === null ? 'Null'
1716 // @@toStringTag case
1717 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
1718 // builtinTag case
1719 : CORRECT_ARGUMENTS ? classofRaw(O)
1720 // ES3 arguments fallback
1721 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
1722 };
1723 return classof;
1724 }
1725
1726 var toString;
1727 var hasRequiredToString;
1728
1729 function requireToString () {
1730 if (hasRequiredToString) return toString;
1731 hasRequiredToString = 1;
1732 var classof = requireClassof();
1733
1734 var $String = String;
1735
1736 toString = function (argument) {
1737 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
1738 return $String(argument);
1739 };
1740 return toString;
1741 }
1742
1743 var normalizeStringArgument;
1744 var hasRequiredNormalizeStringArgument;
1745
1746 function requireNormalizeStringArgument () {
1747 if (hasRequiredNormalizeStringArgument) return normalizeStringArgument;
1748 hasRequiredNormalizeStringArgument = 1;
1749 var toString = requireToString();
1750
1751 normalizeStringArgument = function (argument, $default) {
1752 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
1753 };
1754 return normalizeStringArgument;
1755 }
1756
1757 var installErrorCause;
1758 var hasRequiredInstallErrorCause;
1759
1760 function requireInstallErrorCause () {
1761 if (hasRequiredInstallErrorCause) return installErrorCause;
1762 hasRequiredInstallErrorCause = 1;
1763 var isObject = requireIsObject();
1764 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1765
1766 // `InstallErrorCause` abstract operation
1767 // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
1768 installErrorCause = function (O, options) {
1769 if (isObject(options) && 'cause' in options) {
1770 createNonEnumerableProperty(O, 'cause', options.cause);
1771 }
1772 };
1773 return installErrorCause;
1774 }
1775
1776 var errorStackClear;
1777 var hasRequiredErrorStackClear;
1778
1779 function requireErrorStackClear () {
1780 if (hasRequiredErrorStackClear) return errorStackClear;
1781 hasRequiredErrorStackClear = 1;
1782 var uncurryThis = requireFunctionUncurryThis();
1783
1784 var $Error = Error;
1785 var replace = uncurryThis(''.replace);
1786
1787 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
1788 // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
1789 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
1790 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
1791
1792 errorStackClear = function (stack, dropEntries) {
1793 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
1794 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
1795 } return stack;
1796 };
1797 return errorStackClear;
1798 }
1799
1800 var errorStackInstallable;
1801 var hasRequiredErrorStackInstallable;
1802
1803 function requireErrorStackInstallable () {
1804 if (hasRequiredErrorStackInstallable) return errorStackInstallable;
1805 hasRequiredErrorStackInstallable = 1;
1806 var fails = requireFails();
1807 var createPropertyDescriptor = requireCreatePropertyDescriptor();
1808
1809 errorStackInstallable = !fails(function () {
1810 var error = new Error('a');
1811 if (!('stack' in error)) return true;
1812 // eslint-disable-next-line es/no-object-defineproperty -- safe
1813 Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
1814 return error.stack !== 7;
1815 });
1816 return errorStackInstallable;
1817 }
1818
1819 var errorStackInstall;
1820 var hasRequiredErrorStackInstall;
1821
1822 function requireErrorStackInstall () {
1823 if (hasRequiredErrorStackInstall) return errorStackInstall;
1824 hasRequiredErrorStackInstall = 1;
1825 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1826 var clearErrorStack = requireErrorStackClear();
1827 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
1828
1829 // non-standard V8
1830 var captureStackTrace = Error.captureStackTrace;
1831
1832 errorStackInstall = function (error, C, stack, dropEntries) {
1833 if (ERROR_STACK_INSTALLABLE) {
1834 if (captureStackTrace) captureStackTrace(error, C);
1835 else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
1836 }
1837 };
1838 return errorStackInstall;
1839 }
1840
1841 var wrapErrorConstructorWithCause;
1842 var hasRequiredWrapErrorConstructorWithCause;
1843
1844 function requireWrapErrorConstructorWithCause () {
1845 if (hasRequiredWrapErrorConstructorWithCause) return wrapErrorConstructorWithCause;
1846 hasRequiredWrapErrorConstructorWithCause = 1;
1847 var getBuiltIn = requireGetBuiltIn();
1848 var hasOwn = requireHasOwnProperty();
1849 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1850 var isPrototypeOf = requireObjectIsPrototypeOf();
1851 var setPrototypeOf = requireObjectSetPrototypeOf();
1852 var copyConstructorProperties = requireCopyConstructorProperties();
1853 var proxyAccessor = requireProxyAccessor();
1854 var inheritIfRequired = requireInheritIfRequired();
1855 var normalizeStringArgument = requireNormalizeStringArgument();
1856 var installErrorCause = requireInstallErrorCause();
1857 var installErrorStack = requireErrorStackInstall();
1858 var DESCRIPTORS = requireDescriptors();
1859 var IS_PURE = requireIsPure();
1860
1861 wrapErrorConstructorWithCause = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
1862 var STACK_TRACE_LIMIT = 'stackTraceLimit';
1863 var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
1864 var path = FULL_NAME.split('.');
1865 var ERROR_NAME = path[path.length - 1];
1866 var OriginalError = getBuiltIn.apply(null, path);
1867
1868 if (!OriginalError) return;
1869
1870 var OriginalErrorPrototype = OriginalError.prototype;
1871
1872 // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
1873 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
1874
1875 if (!FORCED) return OriginalError;
1876
1877 var BaseError = getBuiltIn('Error');
1878
1879 var WrappedError = wrapper(function (a, b) {
1880 var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
1881 var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
1882 if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
1883 installErrorStack(result, WrappedError, result.stack, 2);
1884 if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
1885 if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
1886 return result;
1887 });
1888
1889 WrappedError.prototype = OriginalErrorPrototype;
1890
1891 if (ERROR_NAME !== 'Error') {
1892 if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
1893 else copyConstructorProperties(WrappedError, BaseError, { name: true });
1894 } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
1895 proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
1896 proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
1897 }
1898
1899 copyConstructorProperties(WrappedError, OriginalError);
1900
1901 if (!IS_PURE) try {
1902 // Safari 13- bug: WebAssembly errors does not have a proper `.name`
1903 if (OriginalErrorPrototype.name !== ERROR_NAME) {
1904 createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
1905 }
1906 OriginalErrorPrototype.constructor = WrappedError;
1907 } catch (error) { /* empty */ }
1908
1909 return WrappedError;
1910 };
1911 return wrapErrorConstructorWithCause;
1912 }
1913
1914 var hasRequiredEs_error_cause;
1915
1916 function requireEs_error_cause () {
1917 if (hasRequiredEs_error_cause) return es_error_cause;
1918 hasRequiredEs_error_cause = 1;
1919 /* eslint-disable no-unused-vars -- required for functions `.length` */
1920 var $ = require_export();
1921 var globalThis = requireGlobalThis();
1922 var apply = requireFunctionApply();
1923 var wrapErrorConstructorWithCause = requireWrapErrorConstructorWithCause();
1924
1925 var WEB_ASSEMBLY = 'WebAssembly';
1926 var WebAssembly = globalThis[WEB_ASSEMBLY];
1927
1928 // eslint-disable-next-line es/no-error-cause -- feature detection
1929 var FORCED = new Error('e', { cause: 7 }).cause !== 7;
1930
1931 var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
1932 var O = {};
1933 O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
1934 $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
1935 };
1936
1937 var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
1938 if (WebAssembly && WebAssembly[ERROR_NAME]) {
1939 var O = {};
1940 O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
1941 $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
1942 }
1943 };
1944
1945 // https://tc39.es/ecma262/#sec-nativeerror
1946 exportGlobalErrorCauseWrapper('Error', function (init) {
1947 return function Error(message) { return apply(init, this, arguments); };
1948 });
1949 exportGlobalErrorCauseWrapper('EvalError', function (init) {
1950 return function EvalError(message) { return apply(init, this, arguments); };
1951 });
1952 exportGlobalErrorCauseWrapper('RangeError', function (init) {
1953 return function RangeError(message) { return apply(init, this, arguments); };
1954 });
1955 exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
1956 return function ReferenceError(message) { return apply(init, this, arguments); };
1957 });
1958 exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
1959 return function SyntaxError(message) { return apply(init, this, arguments); };
1960 });
1961 exportGlobalErrorCauseWrapper('TypeError', function (init) {
1962 return function TypeError(message) { return apply(init, this, arguments); };
1963 });
1964 exportGlobalErrorCauseWrapper('URIError', function (init) {
1965 return function URIError(message) { return apply(init, this, arguments); };
1966 });
1967 exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
1968 return function CompileError(message) { return apply(init, this, arguments); };
1969 });
1970 exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
1971 return function LinkError(message) { return apply(init, this, arguments); };
1972 });
1973 exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
1974 return function RuntimeError(message) { return apply(init, this, arguments); };
1975 });
1976 return es_error_cause;
1977 }
1978
1979 requireEs_error_cause();
1980
1981 var es_array_push = {};
1982
1983 var isArray;
1984 var hasRequiredIsArray;
1985
1986 function requireIsArray () {
1987 if (hasRequiredIsArray) return isArray;
1988 hasRequiredIsArray = 1;
1989 var classof = requireClassofRaw();
1990
1991 // `IsArray` abstract operation
1992 // https://tc39.es/ecma262/#sec-isarray
1993 // eslint-disable-next-line es/no-array-isarray -- safe
1994 isArray = Array.isArray || function isArray(argument) {
1995 return classof(argument) === 'Array';
1996 };
1997 return isArray;
1998 }
1999
2000 var arraySetLength;
2001 var hasRequiredArraySetLength;
2002
2003 function requireArraySetLength () {
2004 if (hasRequiredArraySetLength) return arraySetLength;
2005 hasRequiredArraySetLength = 1;
2006 var DESCRIPTORS = requireDescriptors();
2007 var isArray = requireIsArray();
2008
2009 var $TypeError = TypeError;
2010 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2011 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2012
2013 // Safari < 13 does not throw an error in this case
2014 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
2015 // makes no sense without proper strict mode support
2016 if (this !== undefined) return true;
2017 try {
2018 // eslint-disable-next-line es/no-object-defineproperty -- safe
2019 Object.defineProperty([], 'length', { writable: false }).length = 1;
2020 } catch (error) {
2021 return error instanceof TypeError;
2022 }
2023 }();
2024
2025 arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
2026 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
2027 throw new $TypeError('Cannot set read only .length');
2028 } return O.length = length;
2029 } : function (O, length) {
2030 return O.length = length;
2031 };
2032 return arraySetLength;
2033 }
2034
2035 var doesNotExceedSafeInteger;
2036 var hasRequiredDoesNotExceedSafeInteger;
2037
2038 function requireDoesNotExceedSafeInteger () {
2039 if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
2040 hasRequiredDoesNotExceedSafeInteger = 1;
2041 var $TypeError = TypeError;
2042 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
2043
2044 doesNotExceedSafeInteger = function (it) {
2045 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
2046 return it;
2047 };
2048 return doesNotExceedSafeInteger;
2049 }
2050
2051 var hasRequiredEs_array_push;
2052
2053 function requireEs_array_push () {
2054 if (hasRequiredEs_array_push) return es_array_push;
2055 hasRequiredEs_array_push = 1;
2056 var $ = require_export();
2057 var toObject = requireToObject();
2058 var lengthOfArrayLike = requireLengthOfArrayLike();
2059 var setArrayLength = requireArraySetLength();
2060 var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
2061 var fails = requireFails();
2062
2063 var INCORRECT_TO_LENGTH = fails(function () {
2064 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
2065 });
2066
2067 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
2068 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
2069 var properErrorOnNonWritableLength = function () {
2070 try {
2071 // eslint-disable-next-line es/no-object-defineproperty -- safe
2072 Object.defineProperty([], 'length', { writable: false }).push();
2073 } catch (error) {
2074 return error instanceof TypeError;
2075 }
2076 };
2077
2078 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
2079
2080 // `Array.prototype.push` method
2081 // https://tc39.es/ecma262/#sec-array.prototype.push
2082 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
2083 // eslint-disable-next-line no-unused-vars -- required for `.length`
2084 push: function push(item) {
2085 var O = toObject(this);
2086 var len = lengthOfArrayLike(O);
2087 var argCount = arguments.length;
2088 doesNotExceedSafeInteger(len + argCount);
2089 for (var i = 0; i < argCount; i++) {
2090 O[len] = arguments[i];
2091 len++;
2092 }
2093 setArrayLength(O, len);
2094 return len;
2095 }
2096 });
2097 return es_array_push;
2098 }
2099
2100 requireEs_array_push();
2101
2102 var esnext_iterator_constructor = {};
2103
2104 var es_iterator_constructor = {};
2105
2106 var anInstance;
2107 var hasRequiredAnInstance;
2108
2109 function requireAnInstance () {
2110 if (hasRequiredAnInstance) return anInstance;
2111 hasRequiredAnInstance = 1;
2112 var isPrototypeOf = requireObjectIsPrototypeOf();
2113
2114 var $TypeError = TypeError;
2115
2116 anInstance = function (it, Prototype) {
2117 if (isPrototypeOf(Prototype, it)) return it;
2118 throw new $TypeError('Incorrect invocation');
2119 };
2120 return anInstance;
2121 }
2122
2123 var correctPrototypeGetter;
2124 var hasRequiredCorrectPrototypeGetter;
2125
2126 function requireCorrectPrototypeGetter () {
2127 if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
2128 hasRequiredCorrectPrototypeGetter = 1;
2129 var fails = requireFails();
2130
2131 correctPrototypeGetter = !fails(function () {
2132 function F() { /* empty */ }
2133 F.prototype.constructor = null;
2134 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
2135 return Object.getPrototypeOf(new F()) !== F.prototype;
2136 });
2137 return correctPrototypeGetter;
2138 }
2139
2140 var objectGetPrototypeOf;
2141 var hasRequiredObjectGetPrototypeOf;
2142
2143 function requireObjectGetPrototypeOf () {
2144 if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
2145 hasRequiredObjectGetPrototypeOf = 1;
2146 var hasOwn = requireHasOwnProperty();
2147 var isCallable = requireIsCallable();
2148 var toObject = requireToObject();
2149 var sharedKey = requireSharedKey();
2150 var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
2151
2152 var IE_PROTO = sharedKey('IE_PROTO');
2153 var $Object = Object;
2154 var ObjectPrototype = $Object.prototype;
2155
2156 // `Object.getPrototypeOf` method
2157 // https://tc39.es/ecma262/#sec-object.getprototypeof
2158 // eslint-disable-next-line es/no-object-getprototypeof -- safe
2159 objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
2160 var object = toObject(O);
2161 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
2162 var constructor = object.constructor;
2163 if (isCallable(constructor) && object instanceof constructor) {
2164 return constructor.prototype;
2165 } return object instanceof $Object ? ObjectPrototype : null;
2166 };
2167 return objectGetPrototypeOf;
2168 }
2169
2170 var defineBuiltInAccessor;
2171 var hasRequiredDefineBuiltInAccessor;
2172
2173 function requireDefineBuiltInAccessor () {
2174 if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
2175 hasRequiredDefineBuiltInAccessor = 1;
2176 var makeBuiltIn = requireMakeBuiltIn();
2177 var defineProperty = requireObjectDefineProperty();
2178
2179 defineBuiltInAccessor = function (target, name, descriptor) {
2180 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
2181 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
2182 return defineProperty.f(target, name, descriptor);
2183 };
2184 return defineBuiltInAccessor;
2185 }
2186
2187 var createProperty;
2188 var hasRequiredCreateProperty;
2189
2190 function requireCreateProperty () {
2191 if (hasRequiredCreateProperty) return createProperty;
2192 hasRequiredCreateProperty = 1;
2193 var DESCRIPTORS = requireDescriptors();
2194 var definePropertyModule = requireObjectDefineProperty();
2195 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2196
2197 createProperty = function (object, key, value) {
2198 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
2199 else object[key] = value;
2200 };
2201 return createProperty;
2202 }
2203
2204 var objectDefineProperties = {};
2205
2206 var objectKeys;
2207 var hasRequiredObjectKeys;
2208
2209 function requireObjectKeys () {
2210 if (hasRequiredObjectKeys) return objectKeys;
2211 hasRequiredObjectKeys = 1;
2212 var internalObjectKeys = requireObjectKeysInternal();
2213 var enumBugKeys = requireEnumBugKeys();
2214
2215 // `Object.keys` method
2216 // https://tc39.es/ecma262/#sec-object.keys
2217 // eslint-disable-next-line es/no-object-keys -- safe
2218 objectKeys = Object.keys || function keys(O) {
2219 return internalObjectKeys(O, enumBugKeys);
2220 };
2221 return objectKeys;
2222 }
2223
2224 var hasRequiredObjectDefineProperties;
2225
2226 function requireObjectDefineProperties () {
2227 if (hasRequiredObjectDefineProperties) return objectDefineProperties;
2228 hasRequiredObjectDefineProperties = 1;
2229 var DESCRIPTORS = requireDescriptors();
2230 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
2231 var definePropertyModule = requireObjectDefineProperty();
2232 var anObject = requireAnObject();
2233 var toIndexedObject = requireToIndexedObject();
2234 var objectKeys = requireObjectKeys();
2235
2236 // `Object.defineProperties` method
2237 // https://tc39.es/ecma262/#sec-object.defineproperties
2238 // eslint-disable-next-line es/no-object-defineproperties -- safe
2239 objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
2240 anObject(O);
2241 var props = toIndexedObject(Properties);
2242 var keys = objectKeys(Properties);
2243 var length = keys.length;
2244 var index = 0;
2245 var key;
2246 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
2247 return O;
2248 };
2249 return objectDefineProperties;
2250 }
2251
2252 var html;
2253 var hasRequiredHtml;
2254
2255 function requireHtml () {
2256 if (hasRequiredHtml) return html;
2257 hasRequiredHtml = 1;
2258 var getBuiltIn = requireGetBuiltIn();
2259
2260 html = getBuiltIn('document', 'documentElement');
2261 return html;
2262 }
2263
2264 var objectCreate;
2265 var hasRequiredObjectCreate;
2266
2267 function requireObjectCreate () {
2268 if (hasRequiredObjectCreate) return objectCreate;
2269 hasRequiredObjectCreate = 1;
2270 /* global ActiveXObject -- old IE, WSH */
2271 var anObject = requireAnObject();
2272 var definePropertiesModule = requireObjectDefineProperties();
2273 var enumBugKeys = requireEnumBugKeys();
2274 var hiddenKeys = requireHiddenKeys();
2275 var html = requireHtml();
2276 var documentCreateElement = requireDocumentCreateElement();
2277 var sharedKey = requireSharedKey();
2278
2279 var GT = '>';
2280 var LT = '<';
2281 var PROTOTYPE = 'prototype';
2282 var SCRIPT = 'script';
2283 var IE_PROTO = sharedKey('IE_PROTO');
2284
2285 var EmptyConstructor = function () { /* empty */ };
2286
2287 var scriptTag = function (content) {
2288 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
2289 };
2290
2291 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
2292 var NullProtoObjectViaActiveX = function (activeXDocument) {
2293 activeXDocument.write(scriptTag(''));
2294 activeXDocument.close();
2295 var temp = activeXDocument.parentWindow.Object;
2296 // eslint-disable-next-line no-useless-assignment -- avoid memory leak
2297 activeXDocument = null;
2298 return temp;
2299 };
2300
2301 // Create object with fake `null` prototype: use iframe Object with cleared prototype
2302 var NullProtoObjectViaIFrame = function () {
2303 // Thrash, waste and sodomy: IE GC bug
2304 var iframe = documentCreateElement('iframe');
2305 var JS = 'java' + SCRIPT + ':';
2306 var iframeDocument;
2307 iframe.style.display = 'none';
2308 html.appendChild(iframe);
2309 // https://github.com/zloirock/core-js/issues/475
2310 iframe.src = String(JS);
2311 iframeDocument = iframe.contentWindow.document;
2312 iframeDocument.open();
2313 iframeDocument.write(scriptTag('document.F=Object'));
2314 iframeDocument.close();
2315 return iframeDocument.F;
2316 };
2317
2318 // Check for document.domain and active x support
2319 // No need to use active x approach when document.domain is not set
2320 // see https://github.com/es-shims/es5-shim/issues/150
2321 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
2322 // avoid IE GC bug
2323 var activeXDocument;
2324 var NullProtoObject = function () {
2325 try {
2326 activeXDocument = new ActiveXObject('htmlfile');
2327 } catch (error) { /* ignore */ }
2328 NullProtoObject = typeof document != 'undefined'
2329 ? document.domain && activeXDocument
2330 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
2331 : NullProtoObjectViaIFrame()
2332 : NullProtoObjectViaActiveX(activeXDocument); // WSH
2333 var length = enumBugKeys.length;
2334 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
2335 return NullProtoObject();
2336 };
2337
2338 hiddenKeys[IE_PROTO] = true;
2339
2340 // `Object.create` method
2341 // https://tc39.es/ecma262/#sec-object.create
2342 // eslint-disable-next-line es/no-object-create -- safe
2343 objectCreate = Object.create || function create(O, Properties) {
2344 var result;
2345 if (O !== null) {
2346 EmptyConstructor[PROTOTYPE] = anObject(O);
2347 result = new EmptyConstructor();
2348 EmptyConstructor[PROTOTYPE] = null;
2349 // add "__proto__" for Object.getPrototypeOf polyfill
2350 result[IE_PROTO] = O;
2351 } else result = NullProtoObject();
2352 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
2353 };
2354 return objectCreate;
2355 }
2356
2357 var iteratorsCore;
2358 var hasRequiredIteratorsCore;
2359
2360 function requireIteratorsCore () {
2361 if (hasRequiredIteratorsCore) return iteratorsCore;
2362 hasRequiredIteratorsCore = 1;
2363 var fails = requireFails();
2364 var isCallable = requireIsCallable();
2365 var isObject = requireIsObject();
2366 var create = requireObjectCreate();
2367 var getPrototypeOf = requireObjectGetPrototypeOf();
2368 var defineBuiltIn = requireDefineBuiltIn();
2369 var wellKnownSymbol = requireWellKnownSymbol();
2370 var IS_PURE = requireIsPure();
2371
2372 var ITERATOR = wellKnownSymbol('iterator');
2373 var BUGGY_SAFARI_ITERATORS = false;
2374
2375 // `%IteratorPrototype%` object
2376 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
2377 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
2378
2379 /* eslint-disable es/no-array-prototype-keys -- safe */
2380 if ([].keys) {
2381 arrayIterator = [].keys();
2382 // Safari 8 has buggy iterators w/o `next`
2383 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
2384 else {
2385 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
2386 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
2387 }
2388 }
2389
2390 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
2391 var test = {};
2392 // FF44- legacy iterators case
2393 return IteratorPrototype[ITERATOR].call(test) !== test;
2394 });
2395
2396 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
2397 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
2398
2399 // `%IteratorPrototype%[@@iterator]()` method
2400 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
2401 if (!isCallable(IteratorPrototype[ITERATOR])) {
2402 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
2403 return this;
2404 });
2405 }
2406
2407 iteratorsCore = {
2408 IteratorPrototype: IteratorPrototype,
2409 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
2410 };
2411 return iteratorsCore;
2412 }
2413
2414 var hasRequiredEs_iterator_constructor;
2415
2416 function requireEs_iterator_constructor () {
2417 if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
2418 hasRequiredEs_iterator_constructor = 1;
2419 var $ = require_export();
2420 var globalThis = requireGlobalThis();
2421 var anInstance = requireAnInstance();
2422 var anObject = requireAnObject();
2423 var isCallable = requireIsCallable();
2424 var getPrototypeOf = requireObjectGetPrototypeOf();
2425 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
2426 var createProperty = requireCreateProperty();
2427 var fails = requireFails();
2428 var hasOwn = requireHasOwnProperty();
2429 var wellKnownSymbol = requireWellKnownSymbol();
2430 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2431 var DESCRIPTORS = requireDescriptors();
2432 var IS_PURE = requireIsPure();
2433
2434 var CONSTRUCTOR = 'constructor';
2435 var ITERATOR = 'Iterator';
2436 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2437
2438 var $TypeError = TypeError;
2439 var NativeIterator = globalThis[ITERATOR];
2440
2441 // FF56- have non-standard global helper `Iterator`
2442 var FORCED = IS_PURE
2443 || !isCallable(NativeIterator)
2444 || NativeIterator.prototype !== IteratorPrototype
2445 // FF44- non-standard `Iterator` passes previous tests
2446 || !fails(function () { NativeIterator({}); });
2447
2448 var IteratorConstructor = function Iterator() {
2449 anInstance(this, IteratorPrototype);
2450 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
2451 };
2452
2453 var defineIteratorPrototypeAccessor = function (key, value) {
2454 if (DESCRIPTORS) {
2455 defineBuiltInAccessor(IteratorPrototype, key, {
2456 configurable: true,
2457 get: function () {
2458 return value;
2459 },
2460 set: function (replacement) {
2461 anObject(this);
2462 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
2463 if (hasOwn(this, key)) this[key] = replacement;
2464 else createProperty(this, key, replacement);
2465 }
2466 });
2467 } else IteratorPrototype[key] = value;
2468 };
2469
2470 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
2471
2472 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
2473 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
2474 }
2475
2476 IteratorConstructor.prototype = IteratorPrototype;
2477
2478 // `Iterator` constructor
2479 // https://tc39.es/ecma262/#sec-iterator
2480 $({ global: true, constructor: true, forced: FORCED }, {
2481 Iterator: IteratorConstructor
2482 });
2483 return es_iterator_constructor;
2484 }
2485
2486 var hasRequiredEsnext_iterator_constructor;
2487
2488 function requireEsnext_iterator_constructor () {
2489 if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
2490 hasRequiredEsnext_iterator_constructor = 1;
2491 // TODO: Remove from `core-js@4`
2492 requireEs_iterator_constructor();
2493 return esnext_iterator_constructor;
2494 }
2495
2496 requireEsnext_iterator_constructor();
2497
2498 var esnext_iterator_every = {};
2499
2500 var es_iterator_every = {};
2501
2502 var functionUncurryThisClause;
2503 var hasRequiredFunctionUncurryThisClause;
2504
2505 function requireFunctionUncurryThisClause () {
2506 if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
2507 hasRequiredFunctionUncurryThisClause = 1;
2508 var classofRaw = requireClassofRaw();
2509 var uncurryThis = requireFunctionUncurryThis();
2510
2511 functionUncurryThisClause = function (fn) {
2512 // Nashorn bug:
2513 // https://github.com/zloirock/core-js/issues/1128
2514 // https://github.com/zloirock/core-js/issues/1130
2515 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
2516 };
2517 return functionUncurryThisClause;
2518 }
2519
2520 var functionBindContext;
2521 var hasRequiredFunctionBindContext;
2522
2523 function requireFunctionBindContext () {
2524 if (hasRequiredFunctionBindContext) return functionBindContext;
2525 hasRequiredFunctionBindContext = 1;
2526 var uncurryThis = requireFunctionUncurryThisClause();
2527 var aCallable = requireACallable();
2528 var NATIVE_BIND = requireFunctionBindNative();
2529
2530 var bind = uncurryThis(uncurryThis.bind);
2531
2532 // optional / simple context binding
2533 functionBindContext = function (fn, that) {
2534 aCallable(fn);
2535 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
2536 return fn.apply(that, arguments);
2537 };
2538 };
2539 return functionBindContext;
2540 }
2541
2542 var iterators;
2543 var hasRequiredIterators;
2544
2545 function requireIterators () {
2546 if (hasRequiredIterators) return iterators;
2547 hasRequiredIterators = 1;
2548 iterators = {};
2549 return iterators;
2550 }
2551
2552 var isArrayIteratorMethod;
2553 var hasRequiredIsArrayIteratorMethod;
2554
2555 function requireIsArrayIteratorMethod () {
2556 if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
2557 hasRequiredIsArrayIteratorMethod = 1;
2558 var wellKnownSymbol = requireWellKnownSymbol();
2559 var Iterators = requireIterators();
2560
2561 var ITERATOR = wellKnownSymbol('iterator');
2562 var ArrayPrototype = Array.prototype;
2563
2564 // check on default Array iterator
2565 isArrayIteratorMethod = function (it) {
2566 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2567 };
2568 return isArrayIteratorMethod;
2569 }
2570
2571 var getIteratorMethod;
2572 var hasRequiredGetIteratorMethod;
2573
2574 function requireGetIteratorMethod () {
2575 if (hasRequiredGetIteratorMethod) return getIteratorMethod;
2576 hasRequiredGetIteratorMethod = 1;
2577 var classof = requireClassof();
2578 var getMethod = requireGetMethod();
2579 var isNullOrUndefined = requireIsNullOrUndefined();
2580 var Iterators = requireIterators();
2581 var wellKnownSymbol = requireWellKnownSymbol();
2582
2583 var ITERATOR = wellKnownSymbol('iterator');
2584
2585 getIteratorMethod = function (it) {
2586 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
2587 || getMethod(it, '@@iterator')
2588 || Iterators[classof(it)];
2589 };
2590 return getIteratorMethod;
2591 }
2592
2593 var getIterator;
2594 var hasRequiredGetIterator;
2595
2596 function requireGetIterator () {
2597 if (hasRequiredGetIterator) return getIterator;
2598 hasRequiredGetIterator = 1;
2599 var call = requireFunctionCall();
2600 var aCallable = requireACallable();
2601 var anObject = requireAnObject();
2602 var tryToString = requireTryToString();
2603 var getIteratorMethod = requireGetIteratorMethod();
2604
2605 var $TypeError = TypeError;
2606
2607 getIterator = function (argument, usingIterator) {
2608 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
2609 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
2610 throw new $TypeError(tryToString(argument) + ' is not iterable');
2611 };
2612 return getIterator;
2613 }
2614
2615 var iteratorClose;
2616 var hasRequiredIteratorClose;
2617
2618 function requireIteratorClose () {
2619 if (hasRequiredIteratorClose) return iteratorClose;
2620 hasRequiredIteratorClose = 1;
2621 var call = requireFunctionCall();
2622 var anObject = requireAnObject();
2623 var getMethod = requireGetMethod();
2624
2625 iteratorClose = function (iterator, kind, value) {
2626 var innerResult, innerError;
2627 anObject(iterator);
2628 try {
2629 innerResult = getMethod(iterator, 'return');
2630 if (!innerResult) {
2631 if (kind === 'throw') throw value;
2632 return value;
2633 }
2634 innerResult = call(innerResult, iterator);
2635 } catch (error) {
2636 innerError = true;
2637 innerResult = error;
2638 }
2639 if (kind === 'throw') throw value;
2640 if (innerError) throw innerResult;
2641 anObject(innerResult);
2642 return value;
2643 };
2644 return iteratorClose;
2645 }
2646
2647 var iterate;
2648 var hasRequiredIterate;
2649
2650 function requireIterate () {
2651 if (hasRequiredIterate) return iterate;
2652 hasRequiredIterate = 1;
2653 var bind = requireFunctionBindContext();
2654 var call = requireFunctionCall();
2655 var anObject = requireAnObject();
2656 var tryToString = requireTryToString();
2657 var isArrayIteratorMethod = requireIsArrayIteratorMethod();
2658 var lengthOfArrayLike = requireLengthOfArrayLike();
2659 var isPrototypeOf = requireObjectIsPrototypeOf();
2660 var getIterator = requireGetIterator();
2661 var getIteratorMethod = requireGetIteratorMethod();
2662 var iteratorClose = requireIteratorClose();
2663
2664 var $TypeError = TypeError;
2665
2666 var Result = function (stopped, result) {
2667 this.stopped = stopped;
2668 this.result = result;
2669 };
2670
2671 var ResultPrototype = Result.prototype;
2672
2673 iterate = function (iterable, unboundFunction, options) {
2674 var that = options && options.that;
2675 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
2676 var IS_RECORD = !!(options && options.IS_RECORD);
2677 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
2678 var INTERRUPTED = !!(options && options.INTERRUPTED);
2679 var fn = bind(unboundFunction, that);
2680 var iterator, iterFn, index, length, result, next, step;
2681
2682 var stop = function (condition) {
2683 if (iterator) iteratorClose(iterator, 'normal', condition);
2684 return new Result(true, condition);
2685 };
2686
2687 var callFn = function (value) {
2688 if (AS_ENTRIES) {
2689 anObject(value);
2690 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
2691 } return INTERRUPTED ? fn(value, stop) : fn(value);
2692 };
2693
2694 if (IS_RECORD) {
2695 iterator = iterable.iterator;
2696 } else if (IS_ITERATOR) {
2697 iterator = iterable;
2698 } else {
2699 iterFn = getIteratorMethod(iterable);
2700 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
2701 // optimisation for array iterators
2702 if (isArrayIteratorMethod(iterFn)) {
2703 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
2704 result = callFn(iterable[index]);
2705 if (result && isPrototypeOf(ResultPrototype, result)) return result;
2706 } return new Result(false);
2707 }
2708 iterator = getIterator(iterable, iterFn);
2709 }
2710
2711 next = IS_RECORD ? iterable.next : iterator.next;
2712 while (!(step = call(next, iterator)).done) {
2713 try {
2714 result = callFn(step.value);
2715 } catch (error) {
2716 iteratorClose(iterator, 'throw', error);
2717 }
2718 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
2719 } return new Result(false);
2720 };
2721 return iterate;
2722 }
2723
2724 var getIteratorDirect;
2725 var hasRequiredGetIteratorDirect;
2726
2727 function requireGetIteratorDirect () {
2728 if (hasRequiredGetIteratorDirect) return getIteratorDirect;
2729 hasRequiredGetIteratorDirect = 1;
2730 // `GetIteratorDirect(obj)` abstract operation
2731 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
2732 getIteratorDirect = function (obj) {
2733 return {
2734 iterator: obj,
2735 next: obj.next,
2736 done: false
2737 };
2738 };
2739 return getIteratorDirect;
2740 }
2741
2742 var hasRequiredEs_iterator_every;
2743
2744 function requireEs_iterator_every () {
2745 if (hasRequiredEs_iterator_every) return es_iterator_every;
2746 hasRequiredEs_iterator_every = 1;
2747 var $ = require_export();
2748 var iterate = requireIterate();
2749 var aCallable = requireACallable();
2750 var anObject = requireAnObject();
2751 var getIteratorDirect = requireGetIteratorDirect();
2752
2753 // `Iterator.prototype.every` method
2754 // https://tc39.es/ecma262/#sec-iterator.prototype.every
2755 $({ target: 'Iterator', proto: true, real: true }, {
2756 every: function every(predicate) {
2757 anObject(this);
2758 aCallable(predicate);
2759 var record = getIteratorDirect(this);
2760 var counter = 0;
2761 return !iterate(record, function (value, stop) {
2762 if (!predicate(value, counter++)) return stop();
2763 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
2764 }
2765 });
2766 return es_iterator_every;
2767 }
2768
2769 var hasRequiredEsnext_iterator_every;
2770
2771 function requireEsnext_iterator_every () {
2772 if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
2773 hasRequiredEsnext_iterator_every = 1;
2774 // TODO: Remove from `core-js@4`
2775 requireEs_iterator_every();
2776 return esnext_iterator_every;
2777 }
2778
2779 requireEsnext_iterator_every();
2780
2781 var esnext_iterator_map = {};
2782
2783 var es_iterator_map = {};
2784
2785 var defineBuiltIns;
2786 var hasRequiredDefineBuiltIns;
2787
2788 function requireDefineBuiltIns () {
2789 if (hasRequiredDefineBuiltIns) return defineBuiltIns;
2790 hasRequiredDefineBuiltIns = 1;
2791 var defineBuiltIn = requireDefineBuiltIn();
2792
2793 defineBuiltIns = function (target, src, options) {
2794 for (var key in src) defineBuiltIn(target, key, src[key], options);
2795 return target;
2796 };
2797 return defineBuiltIns;
2798 }
2799
2800 var createIterResultObject;
2801 var hasRequiredCreateIterResultObject;
2802
2803 function requireCreateIterResultObject () {
2804 if (hasRequiredCreateIterResultObject) return createIterResultObject;
2805 hasRequiredCreateIterResultObject = 1;
2806 // `CreateIterResultObject` abstract operation
2807 // https://tc39.es/ecma262/#sec-createiterresultobject
2808 createIterResultObject = function (value, done) {
2809 return { value: value, done: done };
2810 };
2811 return createIterResultObject;
2812 }
2813
2814 var iteratorCreateProxy;
2815 var hasRequiredIteratorCreateProxy;
2816
2817 function requireIteratorCreateProxy () {
2818 if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
2819 hasRequiredIteratorCreateProxy = 1;
2820 var call = requireFunctionCall();
2821 var create = requireObjectCreate();
2822 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2823 var defineBuiltIns = requireDefineBuiltIns();
2824 var wellKnownSymbol = requireWellKnownSymbol();
2825 var InternalStateModule = requireInternalState();
2826 var getMethod = requireGetMethod();
2827 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2828 var createIterResultObject = requireCreateIterResultObject();
2829 var iteratorClose = requireIteratorClose();
2830
2831 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2832 var ITERATOR_HELPER = 'IteratorHelper';
2833 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
2834 var setInternalState = InternalStateModule.set;
2835
2836 var createIteratorProxyPrototype = function (IS_ITERATOR) {
2837 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
2838
2839 return defineBuiltIns(create(IteratorPrototype), {
2840 next: function next() {
2841 var state = getInternalState(this);
2842 // for simplification:
2843 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
2844 // for `%IteratorHelperPrototype%.next` - just a value
2845 if (IS_ITERATOR) return state.nextHandler();
2846 try {
2847 var result = state.done ? undefined : state.nextHandler();
2848 return createIterResultObject(result, state.done);
2849 } catch (error) {
2850 state.done = true;
2851 throw error;
2852 }
2853 },
2854 'return': function () {
2855 var state = getInternalState(this);
2856 var iterator = state.iterator;
2857 state.done = true;
2858 if (IS_ITERATOR) {
2859 var returnMethod = getMethod(iterator, 'return');
2860 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
2861 }
2862 if (state.inner) try {
2863 iteratorClose(state.inner.iterator, 'normal');
2864 } catch (error) {
2865 return iteratorClose(iterator, 'throw', error);
2866 }
2867 if (iterator) iteratorClose(iterator, 'normal');
2868 return createIterResultObject(undefined, true);
2869 }
2870 });
2871 };
2872
2873 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
2874 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
2875
2876 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
2877
2878 iteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
2879 var IteratorProxy = function Iterator(record, state) {
2880 if (state) {
2881 state.iterator = record.iterator;
2882 state.next = record.next;
2883 } else state = record;
2884 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
2885 state.nextHandler = nextHandler;
2886 state.counter = 0;
2887 state.done = false;
2888 setInternalState(this, state);
2889 };
2890
2891 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
2892
2893 return IteratorProxy;
2894 };
2895 return iteratorCreateProxy;
2896 }
2897
2898 var callWithSafeIterationClosing;
2899 var hasRequiredCallWithSafeIterationClosing;
2900
2901 function requireCallWithSafeIterationClosing () {
2902 if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
2903 hasRequiredCallWithSafeIterationClosing = 1;
2904 var anObject = requireAnObject();
2905 var iteratorClose = requireIteratorClose();
2906
2907 // call something on iterator step with safe closing on error
2908 callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
2909 try {
2910 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
2911 } catch (error) {
2912 iteratorClose(iterator, 'throw', error);
2913 }
2914 };
2915 return callWithSafeIterationClosing;
2916 }
2917
2918 var iteratorMap;
2919 var hasRequiredIteratorMap;
2920
2921 function requireIteratorMap () {
2922 if (hasRequiredIteratorMap) return iteratorMap;
2923 hasRequiredIteratorMap = 1;
2924 var call = requireFunctionCall();
2925 var aCallable = requireACallable();
2926 var anObject = requireAnObject();
2927 var getIteratorDirect = requireGetIteratorDirect();
2928 var createIteratorProxy = requireIteratorCreateProxy();
2929 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
2930
2931 var IteratorProxy = createIteratorProxy(function () {
2932 var iterator = this.iterator;
2933 var result = anObject(call(this.next, iterator));
2934 var done = this.done = !!result.done;
2935 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
2936 });
2937
2938 // `Iterator.prototype.map` method
2939 // https://github.com/tc39/proposal-iterator-helpers
2940 iteratorMap = function map(mapper) {
2941 anObject(this);
2942 aCallable(mapper);
2943 return new IteratorProxy(getIteratorDirect(this), {
2944 mapper: mapper
2945 });
2946 };
2947 return iteratorMap;
2948 }
2949
2950 var hasRequiredEs_iterator_map;
2951
2952 function requireEs_iterator_map () {
2953 if (hasRequiredEs_iterator_map) return es_iterator_map;
2954 hasRequiredEs_iterator_map = 1;
2955 var $ = require_export();
2956 var map = requireIteratorMap();
2957 var IS_PURE = requireIsPure();
2958
2959 // `Iterator.prototype.map` method
2960 // https://tc39.es/ecma262/#sec-iterator.prototype.map
2961 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
2962 map: map
2963 });
2964 return es_iterator_map;
2965 }
2966
2967 var hasRequiredEsnext_iterator_map;
2968
2969 function requireEsnext_iterator_map () {
2970 if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
2971 hasRequiredEsnext_iterator_map = 1;
2972 // TODO: Remove from `core-js@4`
2973 requireEs_iterator_map();
2974 return esnext_iterator_map;
2975 }
2976
2977 requireEsnext_iterator_map();
2978
2979 var esnext_iterator_some = {};
2980
2981 var es_iterator_some = {};
2982
2983 var hasRequiredEs_iterator_some;
2984
2985 function requireEs_iterator_some () {
2986 if (hasRequiredEs_iterator_some) return es_iterator_some;
2987 hasRequiredEs_iterator_some = 1;
2988 var $ = require_export();
2989 var iterate = requireIterate();
2990 var aCallable = requireACallable();
2991 var anObject = requireAnObject();
2992 var getIteratorDirect = requireGetIteratorDirect();
2993
2994 // `Iterator.prototype.some` method
2995 // https://tc39.es/ecma262/#sec-iterator.prototype.some
2996 $({ target: 'Iterator', proto: true, real: true }, {
2997 some: function some(predicate) {
2998 anObject(this);
2999 aCallable(predicate);
3000 var record = getIteratorDirect(this);
3001 var counter = 0;
3002 return iterate(record, function (value, stop) {
3003 if (predicate(value, counter++)) return stop();
3004 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
3005 }
3006 });
3007 return es_iterator_some;
3008 }
3009
3010 var hasRequiredEsnext_iterator_some;
3011
3012 function requireEsnext_iterator_some () {
3013 if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
3014 hasRequiredEsnext_iterator_some = 1;
3015 // TODO: Remove from `core-js@4`
3016 requireEs_iterator_some();
3017 return esnext_iterator_some;
3018 }
3019
3020 requireEsnext_iterator_some();
3021
3022 var esnext_set_difference_v2 = {};
3023
3024 var es_set_difference_v2 = {};
3025
3026 var setHelpers;
3027 var hasRequiredSetHelpers;
3028
3029 function requireSetHelpers () {
3030 if (hasRequiredSetHelpers) return setHelpers;
3031 hasRequiredSetHelpers = 1;
3032 var uncurryThis = requireFunctionUncurryThis();
3033
3034 // eslint-disable-next-line es/no-set -- safe
3035 var SetPrototype = Set.prototype;
3036
3037 setHelpers = {
3038 // eslint-disable-next-line es/no-set -- safe
3039 Set: Set,
3040 add: uncurryThis(SetPrototype.add),
3041 has: uncurryThis(SetPrototype.has),
3042 remove: uncurryThis(SetPrototype['delete']),
3043 proto: SetPrototype
3044 };
3045 return setHelpers;
3046 }
3047
3048 var aSet;
3049 var hasRequiredASet;
3050
3051 function requireASet () {
3052 if (hasRequiredASet) return aSet;
3053 hasRequiredASet = 1;
3054 var has = requireSetHelpers().has;
3055
3056 // Perform ? RequireInternalSlot(M, [[SetData]])
3057 aSet = function (it) {
3058 has(it);
3059 return it;
3060 };
3061 return aSet;
3062 }
3063
3064 var iterateSimple;
3065 var hasRequiredIterateSimple;
3066
3067 function requireIterateSimple () {
3068 if (hasRequiredIterateSimple) return iterateSimple;
3069 hasRequiredIterateSimple = 1;
3070 var call = requireFunctionCall();
3071
3072 iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
3073 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
3074 var next = record.next;
3075 var step, result;
3076 while (!(step = call(next, iterator)).done) {
3077 result = fn(step.value);
3078 if (result !== undefined) return result;
3079 }
3080 };
3081 return iterateSimple;
3082 }
3083
3084 var setIterate;
3085 var hasRequiredSetIterate;
3086
3087 function requireSetIterate () {
3088 if (hasRequiredSetIterate) return setIterate;
3089 hasRequiredSetIterate = 1;
3090 var uncurryThis = requireFunctionUncurryThis();
3091 var iterateSimple = requireIterateSimple();
3092 var SetHelpers = requireSetHelpers();
3093
3094 var Set = SetHelpers.Set;
3095 var SetPrototype = SetHelpers.proto;
3096 var forEach = uncurryThis(SetPrototype.forEach);
3097 var keys = uncurryThis(SetPrototype.keys);
3098 var next = keys(new Set()).next;
3099
3100 setIterate = function (set, fn, interruptible) {
3101 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
3102 };
3103 return setIterate;
3104 }
3105
3106 var setClone;
3107 var hasRequiredSetClone;
3108
3109 function requireSetClone () {
3110 if (hasRequiredSetClone) return setClone;
3111 hasRequiredSetClone = 1;
3112 var SetHelpers = requireSetHelpers();
3113 var iterate = requireSetIterate();
3114
3115 var Set = SetHelpers.Set;
3116 var add = SetHelpers.add;
3117
3118 setClone = function (set) {
3119 var result = new Set();
3120 iterate(set, function (it) {
3121 add(result, it);
3122 });
3123 return result;
3124 };
3125 return setClone;
3126 }
3127
3128 var setSize;
3129 var hasRequiredSetSize;
3130
3131 function requireSetSize () {
3132 if (hasRequiredSetSize) return setSize;
3133 hasRequiredSetSize = 1;
3134 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
3135 var SetHelpers = requireSetHelpers();
3136
3137 setSize = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
3138 return set.size;
3139 };
3140 return setSize;
3141 }
3142
3143 var getSetRecord;
3144 var hasRequiredGetSetRecord;
3145
3146 function requireGetSetRecord () {
3147 if (hasRequiredGetSetRecord) return getSetRecord;
3148 hasRequiredGetSetRecord = 1;
3149 var aCallable = requireACallable();
3150 var anObject = requireAnObject();
3151 var call = requireFunctionCall();
3152 var toIntegerOrInfinity = requireToIntegerOrInfinity();
3153 var getIteratorDirect = requireGetIteratorDirect();
3154
3155 var INVALID_SIZE = 'Invalid size';
3156 var $RangeError = RangeError;
3157 var $TypeError = TypeError;
3158 var max = Math.max;
3159
3160 var SetRecord = function (set, intSize) {
3161 this.set = set;
3162 this.size = max(intSize, 0);
3163 this.has = aCallable(set.has);
3164 this.keys = aCallable(set.keys);
3165 };
3166
3167 SetRecord.prototype = {
3168 getIterator: function () {
3169 return getIteratorDirect(anObject(call(this.keys, this.set)));
3170 },
3171 includes: function (it) {
3172 return call(this.has, this.set, it);
3173 }
3174 };
3175
3176 // `GetSetRecord` abstract operation
3177 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
3178 getSetRecord = function (obj) {
3179 anObject(obj);
3180 var numSize = +obj.size;
3181 // NOTE: If size is undefined, then numSize will be NaN
3182 // eslint-disable-next-line no-self-compare -- NaN check
3183 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
3184 var intSize = toIntegerOrInfinity(numSize);
3185 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
3186 return new SetRecord(obj, intSize);
3187 };
3188 return getSetRecord;
3189 }
3190
3191 var setDifference;
3192 var hasRequiredSetDifference;
3193
3194 function requireSetDifference () {
3195 if (hasRequiredSetDifference) return setDifference;
3196 hasRequiredSetDifference = 1;
3197 var aSet = requireASet();
3198 var SetHelpers = requireSetHelpers();
3199 var clone = requireSetClone();
3200 var size = requireSetSize();
3201 var getSetRecord = requireGetSetRecord();
3202 var iterateSet = requireSetIterate();
3203 var iterateSimple = requireIterateSimple();
3204
3205 var has = SetHelpers.has;
3206 var remove = SetHelpers.remove;
3207
3208 // `Set.prototype.difference` method
3209 // https://github.com/tc39/proposal-set-methods
3210 setDifference = function difference(other) {
3211 var O = aSet(this);
3212 var otherRec = getSetRecord(other);
3213 var result = clone(O);
3214 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
3215 if (otherRec.includes(e)) remove(result, e);
3216 });
3217 else iterateSimple(otherRec.getIterator(), function (e) {
3218 if (has(O, e)) remove(result, e);
3219 });
3220 return result;
3221 };
3222 return setDifference;
3223 }
3224
3225 var setMethodAcceptSetLike;
3226 var hasRequiredSetMethodAcceptSetLike;
3227
3228 function requireSetMethodAcceptSetLike () {
3229 if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
3230 hasRequiredSetMethodAcceptSetLike = 1;
3231 var getBuiltIn = requireGetBuiltIn();
3232
3233 var createSetLike = function (size) {
3234 return {
3235 size: size,
3236 has: function () {
3237 return false;
3238 },
3239 keys: function () {
3240 return {
3241 next: function () {
3242 return { done: true };
3243 }
3244 };
3245 }
3246 };
3247 };
3248
3249 setMethodAcceptSetLike = function (name) {
3250 var Set = getBuiltIn('Set');
3251 try {
3252 new Set()[name](createSetLike(0));
3253 try {
3254 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
3255 // https://github.com/tc39/proposal-set-methods/pull/88
3256 new Set()[name](createSetLike(-1));
3257 return false;
3258 } catch (error2) {
3259 return true;
3260 }
3261 } catch (error) {
3262 return false;
3263 }
3264 };
3265 return setMethodAcceptSetLike;
3266 }
3267
3268 var hasRequiredEs_set_difference_v2;
3269
3270 function requireEs_set_difference_v2 () {
3271 if (hasRequiredEs_set_difference_v2) return es_set_difference_v2;
3272 hasRequiredEs_set_difference_v2 = 1;
3273 var $ = require_export();
3274 var difference = requireSetDifference();
3275 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3276
3277 // `Set.prototype.difference` method
3278 // https://tc39.es/ecma262/#sec-set.prototype.difference
3279 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
3280 difference: difference
3281 });
3282 return es_set_difference_v2;
3283 }
3284
3285 var hasRequiredEsnext_set_difference_v2;
3286
3287 function requireEsnext_set_difference_v2 () {
3288 if (hasRequiredEsnext_set_difference_v2) return esnext_set_difference_v2;
3289 hasRequiredEsnext_set_difference_v2 = 1;
3290 // TODO: Remove from `core-js@4`
3291 requireEs_set_difference_v2();
3292 return esnext_set_difference_v2;
3293 }
3294
3295 requireEsnext_set_difference_v2();
3296
3297 var esnext_set_intersection_v2 = {};
3298
3299 var es_set_intersection_v2 = {};
3300
3301 var setIntersection;
3302 var hasRequiredSetIntersection;
3303
3304 function requireSetIntersection () {
3305 if (hasRequiredSetIntersection) return setIntersection;
3306 hasRequiredSetIntersection = 1;
3307 var aSet = requireASet();
3308 var SetHelpers = requireSetHelpers();
3309 var size = requireSetSize();
3310 var getSetRecord = requireGetSetRecord();
3311 var iterateSet = requireSetIterate();
3312 var iterateSimple = requireIterateSimple();
3313
3314 var Set = SetHelpers.Set;
3315 var add = SetHelpers.add;
3316 var has = SetHelpers.has;
3317
3318 // `Set.prototype.intersection` method
3319 // https://github.com/tc39/proposal-set-methods
3320 setIntersection = function intersection(other) {
3321 var O = aSet(this);
3322 var otherRec = getSetRecord(other);
3323 var result = new Set();
3324
3325 if (size(O) > otherRec.size) {
3326 iterateSimple(otherRec.getIterator(), function (e) {
3327 if (has(O, e)) add(result, e);
3328 });
3329 } else {
3330 iterateSet(O, function (e) {
3331 if (otherRec.includes(e)) add(result, e);
3332 });
3333 }
3334
3335 return result;
3336 };
3337 return setIntersection;
3338 }
3339
3340 var hasRequiredEs_set_intersection_v2;
3341
3342 function requireEs_set_intersection_v2 () {
3343 if (hasRequiredEs_set_intersection_v2) return es_set_intersection_v2;
3344 hasRequiredEs_set_intersection_v2 = 1;
3345 var $ = require_export();
3346 var fails = requireFails();
3347 var intersection = requireSetIntersection();
3348 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3349
3350 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
3351 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
3352 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
3353 });
3354
3355 // `Set.prototype.intersection` method
3356 // https://tc39.es/ecma262/#sec-set.prototype.intersection
3357 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
3358 intersection: intersection
3359 });
3360 return es_set_intersection_v2;
3361 }
3362
3363 var hasRequiredEsnext_set_intersection_v2;
3364
3365 function requireEsnext_set_intersection_v2 () {
3366 if (hasRequiredEsnext_set_intersection_v2) return esnext_set_intersection_v2;
3367 hasRequiredEsnext_set_intersection_v2 = 1;
3368 // TODO: Remove from `core-js@4`
3369 requireEs_set_intersection_v2();
3370 return esnext_set_intersection_v2;
3371 }
3372
3373 requireEsnext_set_intersection_v2();
3374
3375 var esnext_set_isDisjointFrom_v2 = {};
3376
3377 var es_set_isDisjointFrom_v2 = {};
3378
3379 var setIsDisjointFrom;
3380 var hasRequiredSetIsDisjointFrom;
3381
3382 function requireSetIsDisjointFrom () {
3383 if (hasRequiredSetIsDisjointFrom) return setIsDisjointFrom;
3384 hasRequiredSetIsDisjointFrom = 1;
3385 var aSet = requireASet();
3386 var has = requireSetHelpers().has;
3387 var size = requireSetSize();
3388 var getSetRecord = requireGetSetRecord();
3389 var iterateSet = requireSetIterate();
3390 var iterateSimple = requireIterateSimple();
3391 var iteratorClose = requireIteratorClose();
3392
3393 // `Set.prototype.isDisjointFrom` method
3394 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
3395 setIsDisjointFrom = function isDisjointFrom(other) {
3396 var O = aSet(this);
3397 var otherRec = getSetRecord(other);
3398 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
3399 if (otherRec.includes(e)) return false;
3400 }, true) !== false;
3401 var iterator = otherRec.getIterator();
3402 return iterateSimple(iterator, function (e) {
3403 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
3404 }) !== false;
3405 };
3406 return setIsDisjointFrom;
3407 }
3408
3409 var hasRequiredEs_set_isDisjointFrom_v2;
3410
3411 function requireEs_set_isDisjointFrom_v2 () {
3412 if (hasRequiredEs_set_isDisjointFrom_v2) return es_set_isDisjointFrom_v2;
3413 hasRequiredEs_set_isDisjointFrom_v2 = 1;
3414 var $ = require_export();
3415 var isDisjointFrom = requireSetIsDisjointFrom();
3416 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3417
3418 // `Set.prototype.isDisjointFrom` method
3419 // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
3420 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
3421 isDisjointFrom: isDisjointFrom
3422 });
3423 return es_set_isDisjointFrom_v2;
3424 }
3425
3426 var hasRequiredEsnext_set_isDisjointFrom_v2;
3427
3428 function requireEsnext_set_isDisjointFrom_v2 () {
3429 if (hasRequiredEsnext_set_isDisjointFrom_v2) return esnext_set_isDisjointFrom_v2;
3430 hasRequiredEsnext_set_isDisjointFrom_v2 = 1;
3431 // TODO: Remove from `core-js@4`
3432 requireEs_set_isDisjointFrom_v2();
3433 return esnext_set_isDisjointFrom_v2;
3434 }
3435
3436 requireEsnext_set_isDisjointFrom_v2();
3437
3438 var esnext_set_isSubsetOf_v2 = {};
3439
3440 var es_set_isSubsetOf_v2 = {};
3441
3442 var setIsSubsetOf;
3443 var hasRequiredSetIsSubsetOf;
3444
3445 function requireSetIsSubsetOf () {
3446 if (hasRequiredSetIsSubsetOf) return setIsSubsetOf;
3447 hasRequiredSetIsSubsetOf = 1;
3448 var aSet = requireASet();
3449 var size = requireSetSize();
3450 var iterate = requireSetIterate();
3451 var getSetRecord = requireGetSetRecord();
3452
3453 // `Set.prototype.isSubsetOf` method
3454 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
3455 setIsSubsetOf = function isSubsetOf(other) {
3456 var O = aSet(this);
3457 var otherRec = getSetRecord(other);
3458 if (size(O) > otherRec.size) return false;
3459 return iterate(O, function (e) {
3460 if (!otherRec.includes(e)) return false;
3461 }, true) !== false;
3462 };
3463 return setIsSubsetOf;
3464 }
3465
3466 var hasRequiredEs_set_isSubsetOf_v2;
3467
3468 function requireEs_set_isSubsetOf_v2 () {
3469 if (hasRequiredEs_set_isSubsetOf_v2) return es_set_isSubsetOf_v2;
3470 hasRequiredEs_set_isSubsetOf_v2 = 1;
3471 var $ = require_export();
3472 var isSubsetOf = requireSetIsSubsetOf();
3473 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3474
3475 // `Set.prototype.isSubsetOf` method
3476 // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
3477 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
3478 isSubsetOf: isSubsetOf
3479 });
3480 return es_set_isSubsetOf_v2;
3481 }
3482
3483 var hasRequiredEsnext_set_isSubsetOf_v2;
3484
3485 function requireEsnext_set_isSubsetOf_v2 () {
3486 if (hasRequiredEsnext_set_isSubsetOf_v2) return esnext_set_isSubsetOf_v2;
3487 hasRequiredEsnext_set_isSubsetOf_v2 = 1;
3488 // TODO: Remove from `core-js@4`
3489 requireEs_set_isSubsetOf_v2();
3490 return esnext_set_isSubsetOf_v2;
3491 }
3492
3493 requireEsnext_set_isSubsetOf_v2();
3494
3495 var esnext_set_isSupersetOf_v2 = {};
3496
3497 var es_set_isSupersetOf_v2 = {};
3498
3499 var setIsSupersetOf;
3500 var hasRequiredSetIsSupersetOf;
3501
3502 function requireSetIsSupersetOf () {
3503 if (hasRequiredSetIsSupersetOf) return setIsSupersetOf;
3504 hasRequiredSetIsSupersetOf = 1;
3505 var aSet = requireASet();
3506 var has = requireSetHelpers().has;
3507 var size = requireSetSize();
3508 var getSetRecord = requireGetSetRecord();
3509 var iterateSimple = requireIterateSimple();
3510 var iteratorClose = requireIteratorClose();
3511
3512 // `Set.prototype.isSupersetOf` method
3513 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
3514 setIsSupersetOf = function isSupersetOf(other) {
3515 var O = aSet(this);
3516 var otherRec = getSetRecord(other);
3517 if (size(O) < otherRec.size) return false;
3518 var iterator = otherRec.getIterator();
3519 return iterateSimple(iterator, function (e) {
3520 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
3521 }) !== false;
3522 };
3523 return setIsSupersetOf;
3524 }
3525
3526 var hasRequiredEs_set_isSupersetOf_v2;
3527
3528 function requireEs_set_isSupersetOf_v2 () {
3529 if (hasRequiredEs_set_isSupersetOf_v2) return es_set_isSupersetOf_v2;
3530 hasRequiredEs_set_isSupersetOf_v2 = 1;
3531 var $ = require_export();
3532 var isSupersetOf = requireSetIsSupersetOf();
3533 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3534
3535 // `Set.prototype.isSupersetOf` method
3536 // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
3537 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
3538 isSupersetOf: isSupersetOf
3539 });
3540 return es_set_isSupersetOf_v2;
3541 }
3542
3543 var hasRequiredEsnext_set_isSupersetOf_v2;
3544
3545 function requireEsnext_set_isSupersetOf_v2 () {
3546 if (hasRequiredEsnext_set_isSupersetOf_v2) return esnext_set_isSupersetOf_v2;
3547 hasRequiredEsnext_set_isSupersetOf_v2 = 1;
3548 // TODO: Remove from `core-js@4`
3549 requireEs_set_isSupersetOf_v2();
3550 return esnext_set_isSupersetOf_v2;
3551 }
3552
3553 requireEsnext_set_isSupersetOf_v2();
3554
3555 var esnext_set_symmetricDifference_v2 = {};
3556
3557 var es_set_symmetricDifference_v2 = {};
3558
3559 var setSymmetricDifference;
3560 var hasRequiredSetSymmetricDifference;
3561
3562 function requireSetSymmetricDifference () {
3563 if (hasRequiredSetSymmetricDifference) return setSymmetricDifference;
3564 hasRequiredSetSymmetricDifference = 1;
3565 var aSet = requireASet();
3566 var SetHelpers = requireSetHelpers();
3567 var clone = requireSetClone();
3568 var getSetRecord = requireGetSetRecord();
3569 var iterateSimple = requireIterateSimple();
3570
3571 var add = SetHelpers.add;
3572 var has = SetHelpers.has;
3573 var remove = SetHelpers.remove;
3574
3575 // `Set.prototype.symmetricDifference` method
3576 // https://github.com/tc39/proposal-set-methods
3577 setSymmetricDifference = function symmetricDifference(other) {
3578 var O = aSet(this);
3579 var keysIter = getSetRecord(other).getIterator();
3580 var result = clone(O);
3581 iterateSimple(keysIter, function (e) {
3582 if (has(O, e)) remove(result, e);
3583 else add(result, e);
3584 });
3585 return result;
3586 };
3587 return setSymmetricDifference;
3588 }
3589
3590 var hasRequiredEs_set_symmetricDifference_v2;
3591
3592 function requireEs_set_symmetricDifference_v2 () {
3593 if (hasRequiredEs_set_symmetricDifference_v2) return es_set_symmetricDifference_v2;
3594 hasRequiredEs_set_symmetricDifference_v2 = 1;
3595 var $ = require_export();
3596 var symmetricDifference = requireSetSymmetricDifference();
3597 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3598
3599 // `Set.prototype.symmetricDifference` method
3600 // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
3601 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
3602 symmetricDifference: symmetricDifference
3603 });
3604 return es_set_symmetricDifference_v2;
3605 }
3606
3607 var hasRequiredEsnext_set_symmetricDifference_v2;
3608
3609 function requireEsnext_set_symmetricDifference_v2 () {
3610 if (hasRequiredEsnext_set_symmetricDifference_v2) return esnext_set_symmetricDifference_v2;
3611 hasRequiredEsnext_set_symmetricDifference_v2 = 1;
3612 // TODO: Remove from `core-js@4`
3613 requireEs_set_symmetricDifference_v2();
3614 return esnext_set_symmetricDifference_v2;
3615 }
3616
3617 requireEsnext_set_symmetricDifference_v2();
3618
3619 var esnext_set_union_v2 = {};
3620
3621 var es_set_union_v2 = {};
3622
3623 var setUnion;
3624 var hasRequiredSetUnion;
3625
3626 function requireSetUnion () {
3627 if (hasRequiredSetUnion) return setUnion;
3628 hasRequiredSetUnion = 1;
3629 var aSet = requireASet();
3630 var add = requireSetHelpers().add;
3631 var clone = requireSetClone();
3632 var getSetRecord = requireGetSetRecord();
3633 var iterateSimple = requireIterateSimple();
3634
3635 // `Set.prototype.union` method
3636 // https://github.com/tc39/proposal-set-methods
3637 setUnion = function union(other) {
3638 var O = aSet(this);
3639 var keysIter = getSetRecord(other).getIterator();
3640 var result = clone(O);
3641 iterateSimple(keysIter, function (it) {
3642 add(result, it);
3643 });
3644 return result;
3645 };
3646 return setUnion;
3647 }
3648
3649 var hasRequiredEs_set_union_v2;
3650
3651 function requireEs_set_union_v2 () {
3652 if (hasRequiredEs_set_union_v2) return es_set_union_v2;
3653 hasRequiredEs_set_union_v2 = 1;
3654 var $ = require_export();
3655 var union = requireSetUnion();
3656 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3657
3658 // `Set.prototype.union` method
3659 // https://tc39.es/ecma262/#sec-set.prototype.union
3660 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
3661 union: union
3662 });
3663 return es_set_union_v2;
3664 }
3665
3666 var hasRequiredEsnext_set_union_v2;
3667
3668 function requireEsnext_set_union_v2 () {
3669 if (hasRequiredEsnext_set_union_v2) return esnext_set_union_v2;
3670 hasRequiredEsnext_set_union_v2 = 1;
3671 // TODO: Remove from `core-js@4`
3672 requireEs_set_union_v2();
3673 return esnext_set_union_v2;
3674 }
3675
3676 requireEsnext_set_union_v2();
3677
3678 var esnext_iterator_reduce = {};
3679
3680 var es_iterator_reduce = {};
3681
3682 var hasRequiredEs_iterator_reduce;
3683
3684 function requireEs_iterator_reduce () {
3685 if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
3686 hasRequiredEs_iterator_reduce = 1;
3687 var $ = require_export();
3688 var iterate = requireIterate();
3689 var aCallable = requireACallable();
3690 var anObject = requireAnObject();
3691 var getIteratorDirect = requireGetIteratorDirect();
3692
3693 var $TypeError = TypeError;
3694
3695 // `Iterator.prototype.reduce` method
3696 // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
3697 $({ target: 'Iterator', proto: true, real: true }, {
3698 reduce: function reduce(reducer /* , initialValue */) {
3699 anObject(this);
3700 aCallable(reducer);
3701 var record = getIteratorDirect(this);
3702 var noInitial = arguments.length < 2;
3703 var accumulator = noInitial ? undefined : arguments[1];
3704 var counter = 0;
3705 iterate(record, function (value) {
3706 if (noInitial) {
3707 noInitial = false;
3708 accumulator = value;
3709 } else {
3710 accumulator = reducer(accumulator, value, counter);
3711 }
3712 counter++;
3713 }, { IS_RECORD: true });
3714 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
3715 return accumulator;
3716 }
3717 });
3718 return es_iterator_reduce;
3719 }
3720
3721 var hasRequiredEsnext_iterator_reduce;
3722
3723 function requireEsnext_iterator_reduce () {
3724 if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
3725 hasRequiredEsnext_iterator_reduce = 1;
3726 // TODO: Remove from `core-js@4`
3727 requireEs_iterator_reduce();
3728 return esnext_iterator_reduce;
3729 }
3730
3731 requireEsnext_iterator_reduce();
3732
3733 var web_domException_constructor = {};
3734
3735 var environment$1;
3736 var hasRequiredEnvironment;
3737
3738 function requireEnvironment () {
3739 if (hasRequiredEnvironment) return environment$1;
3740 hasRequiredEnvironment = 1;
3741 /* global Bun, Deno -- detection */
3742 var globalThis = requireGlobalThis();
3743 var userAgent = requireEnvironmentUserAgent();
3744 var classof = requireClassofRaw();
3745
3746 var userAgentStartsWith = function (string) {
3747 return userAgent.slice(0, string.length) === string;
3748 };
3749
3750 environment$1 = (function () {
3751 if (userAgentStartsWith('Bun/')) return 'BUN';
3752 if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
3753 if (userAgentStartsWith('Deno/')) return 'DENO';
3754 if (userAgentStartsWith('Node.js/')) return 'NODE';
3755 if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
3756 if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
3757 if (classof(globalThis.process) === 'process') return 'NODE';
3758 if (globalThis.window && globalThis.document) return 'BROWSER';
3759 return 'REST';
3760 })();
3761 return environment$1;
3762 }
3763
3764 var environmentIsNode;
3765 var hasRequiredEnvironmentIsNode;
3766
3767 function requireEnvironmentIsNode () {
3768 if (hasRequiredEnvironmentIsNode) return environmentIsNode;
3769 hasRequiredEnvironmentIsNode = 1;
3770 var ENVIRONMENT = requireEnvironment();
3771
3772 environmentIsNode = ENVIRONMENT === 'NODE';
3773 return environmentIsNode;
3774 }
3775
3776 var getBuiltInNodeModule;
3777 var hasRequiredGetBuiltInNodeModule;
3778
3779 function requireGetBuiltInNodeModule () {
3780 if (hasRequiredGetBuiltInNodeModule) return getBuiltInNodeModule;
3781 hasRequiredGetBuiltInNodeModule = 1;
3782 var globalThis = requireGlobalThis();
3783 var IS_NODE = requireEnvironmentIsNode();
3784
3785 getBuiltInNodeModule = function (name) {
3786 if (IS_NODE) {
3787 try {
3788 return globalThis.process.getBuiltinModule(name);
3789 } catch (error) { /* empty */ }
3790 try {
3791 // eslint-disable-next-line no-new-func -- safe
3792 return Function('return require("' + name + '")')();
3793 } catch (error) { /* empty */ }
3794 }
3795 };
3796 return getBuiltInNodeModule;
3797 }
3798
3799 var errorToString;
3800 var hasRequiredErrorToString;
3801
3802 function requireErrorToString () {
3803 if (hasRequiredErrorToString) return errorToString;
3804 hasRequiredErrorToString = 1;
3805 var DESCRIPTORS = requireDescriptors();
3806 var fails = requireFails();
3807 var anObject = requireAnObject();
3808 var normalizeStringArgument = requireNormalizeStringArgument();
3809
3810 var nativeErrorToString = Error.prototype.toString;
3811
3812 var INCORRECT_TO_STRING = fails(function () {
3813 if (DESCRIPTORS) {
3814 // Chrome 32- incorrectly call accessor
3815 // eslint-disable-next-line es/no-object-create, es/no-object-defineproperty -- safe
3816 var object = Object.create(Object.defineProperty({}, 'name', { get: function () {
3817 return this === object;
3818 } }));
3819 if (nativeErrorToString.call(object) !== 'true') return true;
3820 }
3821 // FF10- does not properly handle non-strings
3822 return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1'
3823 // IE8 does not properly handle defaults
3824 || nativeErrorToString.call({}) !== 'Error';
3825 });
3826
3827 errorToString = INCORRECT_TO_STRING ? function toString() {
3828 var O = anObject(this);
3829 var name = normalizeStringArgument(O.name, 'Error');
3830 var message = normalizeStringArgument(O.message);
3831 return !name ? message : !message ? name : name + ': ' + message;
3832 } : nativeErrorToString;
3833 return errorToString;
3834 }
3835
3836 var domExceptionConstants;
3837 var hasRequiredDomExceptionConstants;
3838
3839 function requireDomExceptionConstants () {
3840 if (hasRequiredDomExceptionConstants) return domExceptionConstants;
3841 hasRequiredDomExceptionConstants = 1;
3842 domExceptionConstants = {
3843 IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
3844 DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
3845 HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
3846 WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
3847 InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
3848 NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
3849 NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
3850 NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
3851 NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
3852 InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
3853 InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
3854 SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
3855 InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
3856 NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
3857 InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
3858 ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
3859 TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
3860 SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
3861 NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
3862 AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
3863 URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
3864 QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
3865 TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
3866 InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
3867 DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
3868 };
3869 return domExceptionConstants;
3870 }
3871
3872 var hasRequiredWeb_domException_constructor;
3873
3874 function requireWeb_domException_constructor () {
3875 if (hasRequiredWeb_domException_constructor) return web_domException_constructor;
3876 hasRequiredWeb_domException_constructor = 1;
3877 var $ = require_export();
3878 var getBuiltIn = requireGetBuiltIn();
3879 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
3880 var fails = requireFails();
3881 var create = requireObjectCreate();
3882 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3883 var defineProperty = requireObjectDefineProperty().f;
3884 var defineBuiltIn = requireDefineBuiltIn();
3885 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
3886 var hasOwn = requireHasOwnProperty();
3887 var anInstance = requireAnInstance();
3888 var anObject = requireAnObject();
3889 var errorToString = requireErrorToString();
3890 var normalizeStringArgument = requireNormalizeStringArgument();
3891 var DOMExceptionConstants = requireDomExceptionConstants();
3892 var clearErrorStack = requireErrorStackClear();
3893 var InternalStateModule = requireInternalState();
3894 var DESCRIPTORS = requireDescriptors();
3895 var IS_PURE = requireIsPure();
3896
3897 var DOM_EXCEPTION = 'DOMException';
3898 var DATA_CLONE_ERR = 'DATA_CLONE_ERR';
3899 var Error = getBuiltIn('Error');
3900 // NodeJS < 17.0 does not expose `DOMException` to global
3901 var NativeDOMException = getBuiltIn(DOM_EXCEPTION) || (function () {
3902 try {
3903 // NodeJS < 15.0 does not expose `MessageChannel` to global
3904 var MessageChannel = getBuiltIn('MessageChannel') || getBuiltInNodeModule('worker_threads').MessageChannel;
3905 // eslint-disable-next-line es/no-weak-map, unicorn/require-post-message-target-origin -- safe
3906 new MessageChannel().port1.postMessage(new WeakMap());
3907 } catch (error) {
3908 if (error.name === DATA_CLONE_ERR && error.code === 25) return error.constructor;
3909 }
3910 })();
3911 var NativeDOMExceptionPrototype = NativeDOMException && NativeDOMException.prototype;
3912 var ErrorPrototype = Error.prototype;
3913 var setInternalState = InternalStateModule.set;
3914 var getInternalState = InternalStateModule.getterFor(DOM_EXCEPTION);
3915 var HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
3916
3917 var codeFor = function (name) {
3918 return hasOwn(DOMExceptionConstants, name) && DOMExceptionConstants[name].m ? DOMExceptionConstants[name].c : 0;
3919 };
3920
3921 var $DOMException = function DOMException() {
3922 anInstance(this, DOMExceptionPrototype);
3923 var argumentsLength = arguments.length;
3924 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
3925 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
3926 var code = codeFor(name);
3927 setInternalState(this, {
3928 type: DOM_EXCEPTION,
3929 name: name,
3930 message: message,
3931 code: code
3932 });
3933 if (!DESCRIPTORS) {
3934 this.name = name;
3935 this.message = message;
3936 this.code = code;
3937 }
3938 if (HAS_STACK) {
3939 var error = new Error(message);
3940 error.name = DOM_EXCEPTION;
3941 defineProperty(this, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
3942 }
3943 };
3944
3945 var DOMExceptionPrototype = $DOMException.prototype = create(ErrorPrototype);
3946
3947 var createGetterDescriptor = function (get) {
3948 return { enumerable: true, configurable: true, get: get };
3949 };
3950
3951 var getterFor = function (key) {
3952 return createGetterDescriptor(function () {
3953 return getInternalState(this)[key];
3954 });
3955 };
3956
3957 if (DESCRIPTORS) {
3958 // `DOMException.prototype.code` getter
3959 defineBuiltInAccessor(DOMExceptionPrototype, 'code', getterFor('code'));
3960 // `DOMException.prototype.message` getter
3961 defineBuiltInAccessor(DOMExceptionPrototype, 'message', getterFor('message'));
3962 // `DOMException.prototype.name` getter
3963 defineBuiltInAccessor(DOMExceptionPrototype, 'name', getterFor('name'));
3964 }
3965
3966 defineProperty(DOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, $DOMException));
3967
3968 // FF36- DOMException is a function, but can't be constructed
3969 var INCORRECT_CONSTRUCTOR = fails(function () {
3970 return !(new NativeDOMException() instanceof Error);
3971 });
3972
3973 // Safari 10.1 / Chrome 32- / IE8- DOMException.prototype.toString bugs
3974 var INCORRECT_TO_STRING = INCORRECT_CONSTRUCTOR || fails(function () {
3975 return ErrorPrototype.toString !== errorToString || String(new NativeDOMException(1, 2)) !== '2: 1';
3976 });
3977
3978 // Deno 1.6.3- DOMException.prototype.code just missed
3979 var INCORRECT_CODE = INCORRECT_CONSTRUCTOR || fails(function () {
3980 return new NativeDOMException(1, 'DataCloneError').code !== 25;
3981 });
3982
3983 // Deno 1.6.3- DOMException constants just missed
3984 var MISSED_CONSTANTS = INCORRECT_CONSTRUCTOR
3985 || NativeDOMException[DATA_CLONE_ERR] !== 25
3986 || NativeDOMExceptionPrototype[DATA_CLONE_ERR] !== 25;
3987
3988 var FORCED_CONSTRUCTOR = IS_PURE ? INCORRECT_TO_STRING || INCORRECT_CODE || MISSED_CONSTANTS : INCORRECT_CONSTRUCTOR;
3989
3990 // `DOMException` constructor
3991 // https://webidl.spec.whatwg.org/#idl-DOMException
3992 $({ global: true, constructor: true, forced: FORCED_CONSTRUCTOR }, {
3993 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
3994 });
3995
3996 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
3997 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
3998
3999 if (INCORRECT_TO_STRING && (IS_PURE || NativeDOMException === PolyfilledDOMException)) {
4000 defineBuiltIn(PolyfilledDOMExceptionPrototype, 'toString', errorToString);
4001 }
4002
4003 if (INCORRECT_CODE && DESCRIPTORS && NativeDOMException === PolyfilledDOMException) {
4004 defineBuiltInAccessor(PolyfilledDOMExceptionPrototype, 'code', createGetterDescriptor(function () {
4005 return codeFor(anObject(this).name);
4006 }));
4007 }
4008
4009 // `DOMException` constants
4010 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
4011 var constant = DOMExceptionConstants[key];
4012 var constantName = constant.s;
4013 var descriptor = createPropertyDescriptor(6, constant.c);
4014 if (!hasOwn(PolyfilledDOMException, constantName)) {
4015 defineProperty(PolyfilledDOMException, constantName, descriptor);
4016 }
4017 if (!hasOwn(PolyfilledDOMExceptionPrototype, constantName)) {
4018 defineProperty(PolyfilledDOMExceptionPrototype, constantName, descriptor);
4019 }
4020 }
4021 return web_domException_constructor;
4022 }
4023
4024 requireWeb_domException_constructor();
4025
4026 var web_domException_stack = {};
4027
4028 var hasRequiredWeb_domException_stack;
4029
4030 function requireWeb_domException_stack () {
4031 if (hasRequiredWeb_domException_stack) return web_domException_stack;
4032 hasRequiredWeb_domException_stack = 1;
4033 var $ = require_export();
4034 var globalThis = requireGlobalThis();
4035 var getBuiltIn = requireGetBuiltIn();
4036 var createPropertyDescriptor = requireCreatePropertyDescriptor();
4037 var defineProperty = requireObjectDefineProperty().f;
4038 var hasOwn = requireHasOwnProperty();
4039 var anInstance = requireAnInstance();
4040 var inheritIfRequired = requireInheritIfRequired();
4041 var normalizeStringArgument = requireNormalizeStringArgument();
4042 var DOMExceptionConstants = requireDomExceptionConstants();
4043 var clearErrorStack = requireErrorStackClear();
4044 var DESCRIPTORS = requireDescriptors();
4045 var IS_PURE = requireIsPure();
4046
4047 var DOM_EXCEPTION = 'DOMException';
4048 var Error = getBuiltIn('Error');
4049 var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
4050
4051 var $DOMException = function DOMException() {
4052 anInstance(this, DOMExceptionPrototype);
4053 var argumentsLength = arguments.length;
4054 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
4055 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
4056 var that = new NativeDOMException(message, name);
4057 var error = new Error(message);
4058 error.name = DOM_EXCEPTION;
4059 defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
4060 inheritIfRequired(that, this, $DOMException);
4061 return that;
4062 };
4063
4064 var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
4065
4066 var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
4067 var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
4068
4069 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4070 var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);
4071
4072 // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
4073 // https://github.com/Jarred-Sumner/bun/issues/399
4074 var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
4075
4076 var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
4077
4078 // `DOMException` constructor patch for `.stack` where it's required
4079 // https://webidl.spec.whatwg.org/#es-DOMException-specialness
4080 $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
4081 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
4082 });
4083
4084 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
4085 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
4086
4087 if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
4088 if (!IS_PURE) {
4089 defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
4090 }
4091
4092 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
4093 var constant = DOMExceptionConstants[key];
4094 var constantName = constant.s;
4095 if (!hasOwn(PolyfilledDOMException, constantName)) {
4096 defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
4097 }
4098 }
4099 }
4100 return web_domException_stack;
4101 }
4102
4103 requireWeb_domException_stack();
4104
4105 var web_domException_toStringTag = {};
4106
4107 var setToStringTag;
4108 var hasRequiredSetToStringTag;
4109
4110 function requireSetToStringTag () {
4111 if (hasRequiredSetToStringTag) return setToStringTag;
4112 hasRequiredSetToStringTag = 1;
4113 var defineProperty = requireObjectDefineProperty().f;
4114 var hasOwn = requireHasOwnProperty();
4115 var wellKnownSymbol = requireWellKnownSymbol();
4116
4117 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
4118
4119 setToStringTag = function (target, TAG, STATIC) {
4120 if (target && !STATIC) target = target.prototype;
4121 if (target && !hasOwn(target, TO_STRING_TAG)) {
4122 defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
4123 }
4124 };
4125 return setToStringTag;
4126 }
4127
4128 var hasRequiredWeb_domException_toStringTag;
4129
4130 function requireWeb_domException_toStringTag () {
4131 if (hasRequiredWeb_domException_toStringTag) return web_domException_toStringTag;
4132 hasRequiredWeb_domException_toStringTag = 1;
4133 var getBuiltIn = requireGetBuiltIn();
4134 var setToStringTag = requireSetToStringTag();
4135
4136 var DOM_EXCEPTION = 'DOMException';
4137
4138 // `DOMException.prototype[@@toStringTag]` property
4139 setToStringTag(getBuiltIn(DOM_EXCEPTION), DOM_EXCEPTION);
4140 return web_domException_toStringTag;
4141 }
4142
4143 requireWeb_domException_toStringTag();
4144
4145 var web_structuredClone = {};
4146
4147 var isConstructor;
4148 var hasRequiredIsConstructor;
4149
4150 function requireIsConstructor () {
4151 if (hasRequiredIsConstructor) return isConstructor;
4152 hasRequiredIsConstructor = 1;
4153 var uncurryThis = requireFunctionUncurryThis();
4154 var fails = requireFails();
4155 var isCallable = requireIsCallable();
4156 var classof = requireClassof();
4157 var getBuiltIn = requireGetBuiltIn();
4158 var inspectSource = requireInspectSource();
4159
4160 var noop = function () { /* empty */ };
4161 var construct = getBuiltIn('Reflect', 'construct');
4162 var constructorRegExp = /^\s*(?:class|function)\b/;
4163 var exec = uncurryThis(constructorRegExp.exec);
4164 var INCORRECT_TO_STRING = !constructorRegExp.test(noop);
4165
4166 var isConstructorModern = function isConstructor(argument) {
4167 if (!isCallable(argument)) return false;
4168 try {
4169 construct(noop, [], argument);
4170 return true;
4171 } catch (error) {
4172 return false;
4173 }
4174 };
4175
4176 var isConstructorLegacy = function isConstructor(argument) {
4177 if (!isCallable(argument)) return false;
4178 switch (classof(argument)) {
4179 case 'AsyncFunction':
4180 case 'GeneratorFunction':
4181 case 'AsyncGeneratorFunction': return false;
4182 }
4183 try {
4184 // we can't check .prototype since constructors produced by .bind haven't it
4185 // `Function#toString` throws on some built-it function in some legacy engines
4186 // (for example, `DOMQuad` and similar in FF41-)
4187 return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
4188 } catch (error) {
4189 return true;
4190 }
4191 };
4192
4193 isConstructorLegacy.sham = true;
4194
4195 // `IsConstructor` abstract operation
4196 // https://tc39.es/ecma262/#sec-isconstructor
4197 isConstructor = !construct || fails(function () {
4198 var called;
4199 return isConstructorModern(isConstructorModern.call)
4200 || !isConstructorModern(Object)
4201 || !isConstructorModern(function () { called = true; })
4202 || called;
4203 }) ? isConstructorLegacy : isConstructorModern;
4204 return isConstructor;
4205 }
4206
4207 var validateArgumentsLength;
4208 var hasRequiredValidateArgumentsLength;
4209
4210 function requireValidateArgumentsLength () {
4211 if (hasRequiredValidateArgumentsLength) return validateArgumentsLength;
4212 hasRequiredValidateArgumentsLength = 1;
4213 var $TypeError = TypeError;
4214
4215 validateArgumentsLength = function (passed, required) {
4216 if (passed < required) throw new $TypeError('Not enough arguments');
4217 return passed;
4218 };
4219 return validateArgumentsLength;
4220 }
4221
4222 var regexpFlags;
4223 var hasRequiredRegexpFlags;
4224
4225 function requireRegexpFlags () {
4226 if (hasRequiredRegexpFlags) return regexpFlags;
4227 hasRequiredRegexpFlags = 1;
4228 var anObject = requireAnObject();
4229
4230 // `RegExp.prototype.flags` getter implementation
4231 // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
4232 regexpFlags = function () {
4233 var that = anObject(this);
4234 var result = '';
4235 if (that.hasIndices) result += 'd';
4236 if (that.global) result += 'g';
4237 if (that.ignoreCase) result += 'i';
4238 if (that.multiline) result += 'm';
4239 if (that.dotAll) result += 's';
4240 if (that.unicode) result += 'u';
4241 if (that.unicodeSets) result += 'v';
4242 if (that.sticky) result += 'y';
4243 return result;
4244 };
4245 return regexpFlags;
4246 }
4247
4248 var regexpGetFlags;
4249 var hasRequiredRegexpGetFlags;
4250
4251 function requireRegexpGetFlags () {
4252 if (hasRequiredRegexpGetFlags) return regexpGetFlags;
4253 hasRequiredRegexpGetFlags = 1;
4254 var call = requireFunctionCall();
4255 var hasOwn = requireHasOwnProperty();
4256 var isPrototypeOf = requireObjectIsPrototypeOf();
4257 var regExpFlags = requireRegexpFlags();
4258
4259 var RegExpPrototype = RegExp.prototype;
4260
4261 regexpGetFlags = function (R) {
4262 var flags = R.flags;
4263 return flags === undefined && !('flags' in RegExpPrototype) && !hasOwn(R, 'flags') && isPrototypeOf(RegExpPrototype, R)
4264 ? call(regExpFlags, R) : flags;
4265 };
4266 return regexpGetFlags;
4267 }
4268
4269 var mapHelpers;
4270 var hasRequiredMapHelpers;
4271
4272 function requireMapHelpers () {
4273 if (hasRequiredMapHelpers) return mapHelpers;
4274 hasRequiredMapHelpers = 1;
4275 var uncurryThis = requireFunctionUncurryThis();
4276
4277 // eslint-disable-next-line es/no-map -- safe
4278 var MapPrototype = Map.prototype;
4279
4280 mapHelpers = {
4281 // eslint-disable-next-line es/no-map -- safe
4282 Map: Map,
4283 set: uncurryThis(MapPrototype.set),
4284 get: uncurryThis(MapPrototype.get),
4285 has: uncurryThis(MapPrototype.has),
4286 remove: uncurryThis(MapPrototype['delete']),
4287 proto: MapPrototype
4288 };
4289 return mapHelpers;
4290 }
4291
4292 var structuredCloneProperTransfer;
4293 var hasRequiredStructuredCloneProperTransfer;
4294
4295 function requireStructuredCloneProperTransfer () {
4296 if (hasRequiredStructuredCloneProperTransfer) return structuredCloneProperTransfer;
4297 hasRequiredStructuredCloneProperTransfer = 1;
4298 var globalThis = requireGlobalThis();
4299 var fails = requireFails();
4300 var V8 = requireEnvironmentV8Version();
4301 var ENVIRONMENT = requireEnvironment();
4302
4303 var structuredClone = globalThis.structuredClone;
4304
4305 structuredCloneProperTransfer = !!structuredClone && !fails(function () {
4306 // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
4307 // https://github.com/zloirock/core-js/issues/679
4308 if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false;
4309 var buffer = new ArrayBuffer(8);
4310 var clone = structuredClone(buffer, { transfer: [buffer] });
4311 return buffer.byteLength !== 0 || clone.byteLength !== 8;
4312 });
4313 return structuredCloneProperTransfer;
4314 }
4315
4316 var detachTransferable;
4317 var hasRequiredDetachTransferable;
4318
4319 function requireDetachTransferable () {
4320 if (hasRequiredDetachTransferable) return detachTransferable;
4321 hasRequiredDetachTransferable = 1;
4322 var globalThis = requireGlobalThis();
4323 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
4324 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
4325
4326 var structuredClone = globalThis.structuredClone;
4327 var $ArrayBuffer = globalThis.ArrayBuffer;
4328 var $MessageChannel = globalThis.MessageChannel;
4329 var detach = false;
4330 var WorkerThreads, channel, buffer, $detach;
4331
4332 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4333 detach = function (transferable) {
4334 structuredClone(transferable, { transfer: [transferable] });
4335 };
4336 } else if ($ArrayBuffer) try {
4337 if (!$MessageChannel) {
4338 WorkerThreads = getBuiltInNodeModule('worker_threads');
4339 if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
4340 }
4341
4342 if ($MessageChannel) {
4343 channel = new $MessageChannel();
4344 buffer = new $ArrayBuffer(2);
4345
4346 $detach = function (transferable) {
4347 channel.port1.postMessage(null, [transferable]);
4348 };
4349
4350 if (buffer.byteLength === 2) {
4351 $detach(buffer);
4352 if (buffer.byteLength === 0) detach = $detach;
4353 }
4354 }
4355 } catch (error) { /* empty */ }
4356
4357 detachTransferable = detach;
4358 return detachTransferable;
4359 }
4360
4361 var hasRequiredWeb_structuredClone;
4362
4363 function requireWeb_structuredClone () {
4364 if (hasRequiredWeb_structuredClone) return web_structuredClone;
4365 hasRequiredWeb_structuredClone = 1;
4366 var IS_PURE = requireIsPure();
4367 var $ = require_export();
4368 var globalThis = requireGlobalThis();
4369 var getBuiltIn = requireGetBuiltIn();
4370 var uncurryThis = requireFunctionUncurryThis();
4371 var fails = requireFails();
4372 var uid = requireUid();
4373 var isCallable = requireIsCallable();
4374 var isConstructor = requireIsConstructor();
4375 var isNullOrUndefined = requireIsNullOrUndefined();
4376 var isObject = requireIsObject();
4377 var isSymbol = requireIsSymbol();
4378 var iterate = requireIterate();
4379 var anObject = requireAnObject();
4380 var classof = requireClassof();
4381 var hasOwn = requireHasOwnProperty();
4382 var createProperty = requireCreateProperty();
4383 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
4384 var lengthOfArrayLike = requireLengthOfArrayLike();
4385 var validateArgumentsLength = requireValidateArgumentsLength();
4386 var getRegExpFlags = requireRegexpGetFlags();
4387 var MapHelpers = requireMapHelpers();
4388 var SetHelpers = requireSetHelpers();
4389 var setIterate = requireSetIterate();
4390 var detachTransferable = requireDetachTransferable();
4391 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
4392 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
4393
4394 var Object = globalThis.Object;
4395 var Array = globalThis.Array;
4396 var Date = globalThis.Date;
4397 var Error = globalThis.Error;
4398 var TypeError = globalThis.TypeError;
4399 var PerformanceMark = globalThis.PerformanceMark;
4400 var DOMException = getBuiltIn('DOMException');
4401 var Map = MapHelpers.Map;
4402 var mapHas = MapHelpers.has;
4403 var mapGet = MapHelpers.get;
4404 var mapSet = MapHelpers.set;
4405 var Set = SetHelpers.Set;
4406 var setAdd = SetHelpers.add;
4407 var setHas = SetHelpers.has;
4408 var objectKeys = getBuiltIn('Object', 'keys');
4409 var push = uncurryThis([].push);
4410 var thisBooleanValue = uncurryThis(true.valueOf);
4411 var thisNumberValue = uncurryThis(1.0.valueOf);
4412 var thisStringValue = uncurryThis(''.valueOf);
4413 var thisTimeValue = uncurryThis(Date.prototype.getTime);
4414 var PERFORMANCE_MARK = uid('structuredClone');
4415 var DATA_CLONE_ERROR = 'DataCloneError';
4416 var TRANSFERRING = 'Transferring';
4417
4418 var checkBasicSemantic = function (structuredCloneImplementation) {
4419 return !fails(function () {
4420 var set1 = new globalThis.Set([7]);
4421 var set2 = structuredCloneImplementation(set1);
4422 var number = structuredCloneImplementation(Object(7));
4423 return set2 === set1 || !set2.has(7) || !isObject(number) || +number !== 7;
4424 }) && structuredCloneImplementation;
4425 };
4426
4427 var checkErrorsCloning = function (structuredCloneImplementation, $Error) {
4428 return !fails(function () {
4429 var error = new $Error();
4430 var test = structuredCloneImplementation({ a: error, b: error });
4431 return !(test && test.a === test.b && test.a instanceof $Error && test.a.stack === error.stack);
4432 });
4433 };
4434
4435 // https://github.com/whatwg/html/pull/5749
4436 var checkNewErrorsCloningSemantic = function (structuredCloneImplementation) {
4437 return !fails(function () {
4438 var test = structuredCloneImplementation(new globalThis.AggregateError([1], PERFORMANCE_MARK, { cause: 3 }));
4439 return test.name !== 'AggregateError' || test.errors[0] !== 1 || test.message !== PERFORMANCE_MARK || test.cause !== 3;
4440 });
4441 };
4442
4443 // FF94+, Safari 15.4+, Chrome 98+, NodeJS 17.0+, Deno 1.13+
4444 // FF<103 and Safari implementations can't clone errors
4445 // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604
4446 // FF103 can clone errors, but `.stack` of clone is an empty string
4447 // https://bugzilla.mozilla.org/show_bug.cgi?id=1778762
4448 // FF104+ fixed it on usual errors, but not on DOMExceptions
4449 // https://bugzilla.mozilla.org/show_bug.cgi?id=1777321
4450 // Chrome <102 returns `null` if cloned object contains multiple references to one error
4451 // https://bugs.chromium.org/p/v8/issues/detail?id=12542
4452 // NodeJS implementation can't clone DOMExceptions
4453 // https://github.com/nodejs/node/issues/41038
4454 // only FF103+ supports new (html/5749) error cloning semantic
4455 var nativeStructuredClone = globalThis.structuredClone;
4456
4457 var FORCED_REPLACEMENT = IS_PURE
4458 || !checkErrorsCloning(nativeStructuredClone, Error)
4459 || !checkErrorsCloning(nativeStructuredClone, DOMException)
4460 || !checkNewErrorsCloningSemantic(nativeStructuredClone);
4461
4462 // Chrome 82+, Safari 14.1+, Deno 1.11+
4463 // Chrome 78-81 implementation swaps `.name` and `.message` of cloned `DOMException`
4464 // Chrome returns `null` if cloned object contains multiple references to one error
4465 // Safari 14.1 implementation doesn't clone some `RegExp` flags, so requires a workaround
4466 // Safari implementation can't clone errors
4467 // Deno 1.2-1.10 implementations too naive
4468 // NodeJS 16.0+ does not have `PerformanceMark` constructor
4469 // NodeJS <17.2 structured cloning implementation from `performance.mark` is too naive
4470 // and can't clone, for example, `RegExp` or some boxed primitives
4471 // https://github.com/nodejs/node/issues/40840
4472 // no one of those implementations supports new (html/5749) error cloning semantic
4473 var structuredCloneFromMark = !nativeStructuredClone && checkBasicSemantic(function (value) {
4474 return new PerformanceMark(PERFORMANCE_MARK, { detail: value }).detail;
4475 });
4476
4477 var nativeRestrictedStructuredClone = checkBasicSemantic(nativeStructuredClone) || structuredCloneFromMark;
4478
4479 var throwUncloneable = function (type) {
4480 throw new DOMException('Uncloneable type: ' + type, DATA_CLONE_ERROR);
4481 };
4482
4483 var throwUnpolyfillable = function (type, action) {
4484 throw new DOMException((action || 'Cloning') + ' of ' + type + ' cannot be properly polyfilled in this engine', DATA_CLONE_ERROR);
4485 };
4486
4487 var tryNativeRestrictedStructuredClone = function (value, type) {
4488 if (!nativeRestrictedStructuredClone) throwUnpolyfillable(type);
4489 return nativeRestrictedStructuredClone(value);
4490 };
4491
4492 var createDataTransfer = function () {
4493 var dataTransfer;
4494 try {
4495 dataTransfer = new globalThis.DataTransfer();
4496 } catch (error) {
4497 try {
4498 dataTransfer = new globalThis.ClipboardEvent('').clipboardData;
4499 } catch (error2) { /* empty */ }
4500 }
4501 return dataTransfer && dataTransfer.items && dataTransfer.files ? dataTransfer : null;
4502 };
4503
4504 var cloneBuffer = function (value, map, $type) {
4505 if (mapHas(map, value)) return mapGet(map, value);
4506
4507 var type = $type || classof(value);
4508 var clone, length, options, source, target, i;
4509
4510 if (type === 'SharedArrayBuffer') {
4511 if (nativeRestrictedStructuredClone) clone = nativeRestrictedStructuredClone(value);
4512 // SharedArrayBuffer should use shared memory, we can't polyfill it, so return the original
4513 else clone = value;
4514 } else {
4515 var DataView = globalThis.DataView;
4516
4517 // `ArrayBuffer#slice` is not available in IE10
4518 // `ArrayBuffer#slice` and `DataView` are not available in old FF
4519 if (!DataView && !isCallable(value.slice)) throwUnpolyfillable('ArrayBuffer');
4520 // detached buffers throws in `DataView` and `.slice`
4521 try {
4522 if (isCallable(value.slice) && !value.resizable) {
4523 clone = value.slice(0);
4524 } else {
4525 length = value.byteLength;
4526 options = 'maxByteLength' in value ? { maxByteLength: value.maxByteLength } : undefined;
4527 // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- safe
4528 clone = new ArrayBuffer(length, options);
4529 source = new DataView(value);
4530 target = new DataView(clone);
4531 for (i = 0; i < length; i++) {
4532 target.setUint8(i, source.getUint8(i));
4533 }
4534 }
4535 } catch (error) {
4536 throw new DOMException('ArrayBuffer is detached', DATA_CLONE_ERROR);
4537 }
4538 }
4539
4540 mapSet(map, value, clone);
4541
4542 return clone;
4543 };
4544
4545 var cloneView = function (value, type, offset, length, map) {
4546 var C = globalThis[type];
4547 // in some old engines like Safari 9, typeof C is 'object'
4548 // on Uint8ClampedArray or some other constructors
4549 if (!isObject(C)) throwUnpolyfillable(type);
4550 return new C(cloneBuffer(value.buffer, map), offset, length);
4551 };
4552
4553 var structuredCloneInternal = function (value, map) {
4554 if (isSymbol(value)) throwUncloneable('Symbol');
4555 if (!isObject(value)) return value;
4556 // effectively preserves circular references
4557 if (map) {
4558 if (mapHas(map, value)) return mapGet(map, value);
4559 } else map = new Map();
4560
4561 var type = classof(value);
4562 var C, name, cloned, dataTransfer, i, length, keys, key;
4563
4564 switch (type) {
4565 case 'Array':
4566 cloned = Array(lengthOfArrayLike(value));
4567 break;
4568 case 'Object':
4569 cloned = {};
4570 break;
4571 case 'Map':
4572 cloned = new Map();
4573 break;
4574 case 'Set':
4575 cloned = new Set();
4576 break;
4577 case 'RegExp':
4578 // in this block because of a Safari 14.1 bug
4579 // old FF does not clone regexes passed to the constructor, so get the source and flags directly
4580 cloned = new RegExp(value.source, getRegExpFlags(value));
4581 break;
4582 case 'Error':
4583 name = value.name;
4584 switch (name) {
4585 case 'AggregateError':
4586 cloned = new (getBuiltIn(name))([]);
4587 break;
4588 case 'EvalError':
4589 case 'RangeError':
4590 case 'ReferenceError':
4591 case 'SuppressedError':
4592 case 'SyntaxError':
4593 case 'TypeError':
4594 case 'URIError':
4595 cloned = new (getBuiltIn(name))();
4596 break;
4597 case 'CompileError':
4598 case 'LinkError':
4599 case 'RuntimeError':
4600 cloned = new (getBuiltIn('WebAssembly', name))();
4601 break;
4602 default:
4603 cloned = new Error();
4604 }
4605 break;
4606 case 'DOMException':
4607 cloned = new DOMException(value.message, value.name);
4608 break;
4609 case 'ArrayBuffer':
4610 case 'SharedArrayBuffer':
4611 cloned = cloneBuffer(value, map, type);
4612 break;
4613 case 'DataView':
4614 case 'Int8Array':
4615 case 'Uint8Array':
4616 case 'Uint8ClampedArray':
4617 case 'Int16Array':
4618 case 'Uint16Array':
4619 case 'Int32Array':
4620 case 'Uint32Array':
4621 case 'Float16Array':
4622 case 'Float32Array':
4623 case 'Float64Array':
4624 case 'BigInt64Array':
4625 case 'BigUint64Array':
4626 length = type === 'DataView' ? value.byteLength : value.length;
4627 cloned = cloneView(value, type, value.byteOffset, length, map);
4628 break;
4629 case 'DOMQuad':
4630 try {
4631 cloned = new DOMQuad(
4632 structuredCloneInternal(value.p1, map),
4633 structuredCloneInternal(value.p2, map),
4634 structuredCloneInternal(value.p3, map),
4635 structuredCloneInternal(value.p4, map)
4636 );
4637 } catch (error) {
4638 cloned = tryNativeRestrictedStructuredClone(value, type);
4639 }
4640 break;
4641 case 'File':
4642 if (nativeRestrictedStructuredClone) try {
4643 cloned = nativeRestrictedStructuredClone(value);
4644 // NodeJS 20.0.0 bug, https://github.com/nodejs/node/issues/47612
4645 if (classof(cloned) !== type) cloned = undefined;
4646 } catch (error) { /* empty */ }
4647 if (!cloned) try {
4648 cloned = new File([value], value.name, value);
4649 } catch (error) { /* empty */ }
4650 if (!cloned) throwUnpolyfillable(type);
4651 break;
4652 case 'FileList':
4653 dataTransfer = createDataTransfer();
4654 if (dataTransfer) {
4655 for (i = 0, length = lengthOfArrayLike(value); i < length; i++) {
4656 dataTransfer.items.add(structuredCloneInternal(value[i], map));
4657 }
4658 cloned = dataTransfer.files;
4659 } else cloned = tryNativeRestrictedStructuredClone(value, type);
4660 break;
4661 case 'ImageData':
4662 // Safari 9 ImageData is a constructor, but typeof ImageData is 'object'
4663 try {
4664 cloned = new ImageData(
4665 structuredCloneInternal(value.data, map),
4666 value.width,
4667 value.height,
4668 { colorSpace: value.colorSpace }
4669 );
4670 } catch (error) {
4671 cloned = tryNativeRestrictedStructuredClone(value, type);
4672 } break;
4673 default:
4674 if (nativeRestrictedStructuredClone) {
4675 cloned = nativeRestrictedStructuredClone(value);
4676 } else switch (type) {
4677 case 'BigInt':
4678 // can be a 3rd party polyfill
4679 cloned = Object(value.valueOf());
4680 break;
4681 case 'Boolean':
4682 cloned = Object(thisBooleanValue(value));
4683 break;
4684 case 'Number':
4685 cloned = Object(thisNumberValue(value));
4686 break;
4687 case 'String':
4688 cloned = Object(thisStringValue(value));
4689 break;
4690 case 'Date':
4691 cloned = new Date(thisTimeValue(value));
4692 break;
4693 case 'Blob':
4694 try {
4695 cloned = value.slice(0, value.size, value.type);
4696 } catch (error) {
4697 throwUnpolyfillable(type);
4698 } break;
4699 case 'DOMPoint':
4700 case 'DOMPointReadOnly':
4701 C = globalThis[type];
4702 try {
4703 cloned = C.fromPoint
4704 ? C.fromPoint(value)
4705 : new C(value.x, value.y, value.z, value.w);
4706 } catch (error) {
4707 throwUnpolyfillable(type);
4708 } break;
4709 case 'DOMRect':
4710 case 'DOMRectReadOnly':
4711 C = globalThis[type];
4712 try {
4713 cloned = C.fromRect
4714 ? C.fromRect(value)
4715 : new C(value.x, value.y, value.width, value.height);
4716 } catch (error) {
4717 throwUnpolyfillable(type);
4718 } break;
4719 case 'DOMMatrix':
4720 case 'DOMMatrixReadOnly':
4721 C = globalThis[type];
4722 try {
4723 cloned = C.fromMatrix
4724 ? C.fromMatrix(value)
4725 : new C(value);
4726 } catch (error) {
4727 throwUnpolyfillable(type);
4728 } break;
4729 case 'AudioData':
4730 case 'VideoFrame':
4731 if (!isCallable(value.clone)) throwUnpolyfillable(type);
4732 try {
4733 cloned = value.clone();
4734 } catch (error) {
4735 throwUncloneable(type);
4736 } break;
4737 case 'CropTarget':
4738 case 'CryptoKey':
4739 case 'FileSystemDirectoryHandle':
4740 case 'FileSystemFileHandle':
4741 case 'FileSystemHandle':
4742 case 'GPUCompilationInfo':
4743 case 'GPUCompilationMessage':
4744 case 'ImageBitmap':
4745 case 'RTCCertificate':
4746 case 'WebAssembly.Module':
4747 throwUnpolyfillable(type);
4748 // break omitted
4749 default:
4750 throwUncloneable(type);
4751 }
4752 }
4753
4754 mapSet(map, value, cloned);
4755
4756 switch (type) {
4757 case 'Array':
4758 case 'Object':
4759 keys = objectKeys(value);
4760 for (i = 0, length = lengthOfArrayLike(keys); i < length; i++) {
4761 key = keys[i];
4762 createProperty(cloned, key, structuredCloneInternal(value[key], map));
4763 } break;
4764 case 'Map':
4765 value.forEach(function (v, k) {
4766 mapSet(cloned, structuredCloneInternal(k, map), structuredCloneInternal(v, map));
4767 });
4768 break;
4769 case 'Set':
4770 value.forEach(function (v) {
4771 setAdd(cloned, structuredCloneInternal(v, map));
4772 });
4773 break;
4774 case 'Error':
4775 createNonEnumerableProperty(cloned, 'message', structuredCloneInternal(value.message, map));
4776 if (hasOwn(value, 'cause')) {
4777 createNonEnumerableProperty(cloned, 'cause', structuredCloneInternal(value.cause, map));
4778 }
4779 if (name === 'AggregateError') {
4780 cloned.errors = structuredCloneInternal(value.errors, map);
4781 } else if (name === 'SuppressedError') {
4782 cloned.error = structuredCloneInternal(value.error, map);
4783 cloned.suppressed = structuredCloneInternal(value.suppressed, map);
4784 } // break omitted
4785 case 'DOMException':
4786 if (ERROR_STACK_INSTALLABLE) {
4787 createNonEnumerableProperty(cloned, 'stack', structuredCloneInternal(value.stack, map));
4788 }
4789 }
4790
4791 return cloned;
4792 };
4793
4794 var tryToTransfer = function (rawTransfer, map) {
4795 if (!isObject(rawTransfer)) throw new TypeError('Transfer option cannot be converted to a sequence');
4796
4797 var transfer = [];
4798
4799 iterate(rawTransfer, function (value) {
4800 push(transfer, anObject(value));
4801 });
4802
4803 var i = 0;
4804 var length = lengthOfArrayLike(transfer);
4805 var buffers = new Set();
4806 var value, type, C, transferred, canvas, context;
4807
4808 while (i < length) {
4809 value = transfer[i++];
4810
4811 type = classof(value);
4812
4813 if (type === 'ArrayBuffer' ? setHas(buffers, value) : mapHas(map, value)) {
4814 throw new DOMException('Duplicate transferable', DATA_CLONE_ERROR);
4815 }
4816
4817 if (type === 'ArrayBuffer') {
4818 setAdd(buffers, value);
4819 continue;
4820 }
4821
4822 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4823 transferred = nativeStructuredClone(value, { transfer: [value] });
4824 } else switch (type) {
4825 case 'ImageBitmap':
4826 C = globalThis.OffscreenCanvas;
4827 if (!isConstructor(C)) throwUnpolyfillable(type, TRANSFERRING);
4828 try {
4829 canvas = new C(value.width, value.height);
4830 context = canvas.getContext('bitmaprenderer');
4831 context.transferFromImageBitmap(value);
4832 transferred = canvas.transferToImageBitmap();
4833 } catch (error) { /* empty */ }
4834 break;
4835 case 'AudioData':
4836 case 'VideoFrame':
4837 if (!isCallable(value.clone) || !isCallable(value.close)) throwUnpolyfillable(type, TRANSFERRING);
4838 try {
4839 transferred = value.clone();
4840 value.close();
4841 } catch (error) { /* empty */ }
4842 break;
4843 case 'MediaSourceHandle':
4844 case 'MessagePort':
4845 case 'MIDIAccess':
4846 case 'OffscreenCanvas':
4847 case 'ReadableStream':
4848 case 'RTCDataChannel':
4849 case 'TransformStream':
4850 case 'WebTransportReceiveStream':
4851 case 'WebTransportSendStream':
4852 case 'WritableStream':
4853 throwUnpolyfillable(type, TRANSFERRING);
4854 }
4855
4856 if (transferred === undefined) throw new DOMException('This object cannot be transferred: ' + type, DATA_CLONE_ERROR);
4857
4858 mapSet(map, value, transferred);
4859 }
4860
4861 return buffers;
4862 };
4863
4864 var detachBuffers = function (buffers) {
4865 setIterate(buffers, function (buffer) {
4866 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4867 nativeRestrictedStructuredClone(buffer, { transfer: [buffer] });
4868 } else if (isCallable(buffer.transfer)) {
4869 buffer.transfer();
4870 } else if (detachTransferable) {
4871 detachTransferable(buffer);
4872 } else {
4873 throwUnpolyfillable('ArrayBuffer', TRANSFERRING);
4874 }
4875 });
4876 };
4877
4878 // `structuredClone` method
4879 // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
4880 $({ global: true, enumerable: true, sham: !PROPER_STRUCTURED_CLONE_TRANSFER, forced: FORCED_REPLACEMENT }, {
4881 structuredClone: function structuredClone(value /* , { transfer } */) {
4882 var options = validateArgumentsLength(arguments.length, 1) > 1 && !isNullOrUndefined(arguments[1]) ? anObject(arguments[1]) : undefined;
4883 var transfer = options ? options.transfer : undefined;
4884 var map, buffers;
4885
4886 if (transfer !== undefined) {
4887 map = new Map();
4888 buffers = tryToTransfer(transfer, map);
4889 }
4890
4891 var clone = structuredCloneInternal(value, map);
4892
4893 // since of an issue with cloning views of transferred buffers, we a forced to detach them later
4894 // https://github.com/zloirock/core-js/issues/1265
4895 if (buffers) detachBuffers(buffers);
4896
4897 return clone;
4898 }
4899 });
4900 return web_structuredClone;
4901 }
4902
4903 requireWeb_structuredClone();
4904
4905 /** @import { Matrix3x3, Vector3 } from "./types.js" */
4906
4907 /**
4908 * A is m x n. B is n x p. product is m x p.
4909 *
4910 * Array arguments are treated like vectors:
4911 * - A becomes 1 x n
4912 * - B becomes n x 1
4913 *
4914 * Returns Matrix m x p or equivalent array or number
4915 *
4916 * @overload
4917 * @param {number[]} A Vector 1 x n
4918 * @param {number[]} B Vector n x 1
4919 * @returns {number} Scalar number
4920 *
4921 * @overload
4922 * @param {number[][]} A Matrix m x n
4923 * @param {number[]} B Vector n x 1
4924 * @returns {number[]} Array with length m
4925 *
4926 * @overload
4927 * @param {number[]} A Vector 1 x n
4928 * @param {number[][]} B Matrix n x p
4929 * @returns {number[]} Array with length p
4930 *
4931 * @overload
4932 * @param {number[][]} A Matrix m x n
4933 * @param {number[][]} B Matrix n x p
4934 * @returns {number[][]} Matrix m x p
4935 *
4936 * @param {number[] | number[][]} A Matrix m x n or a vector
4937 * @param {number[] | number[][]} B Matrix n x p or a vector
4938 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
4939 */
4940 function multiplyMatrices(A, B) {
4941 let m = A.length;
4942 /** @type {number[][]} */
4943 let AM;
4944 /** @type {number[][]} */
4945 let BM;
4946 let aVec = false;
4947 let bVec = false;
4948 if (!Array.isArray(A[0])) {
4949 // A is vector, convert to [[a, b, c, ...]]
4950 AM = [(/** @type {number[]} */A)];
4951 m = AM.length;
4952 aVec = true;
4953 } else {
4954 AM = /** @type {number[][]} */A;
4955 }
4956 if (!Array.isArray(B[0])) {
4957 // B is vector, convert to [[a], [b], [c], ...]]
4958 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
4959 bVec = true;
4960 } else {
4961 BM = /** @type {number[][]} */B;
4962 }
4963 let p = BM[0].length;
4964 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
4965 /** @type {number[] | number[][]} */
4966 let product = AM.map(row => BM_cols.map(col => {
4967 let ret = 0;
4968 if (!Array.isArray(row)) {
4969 for (let c of col) {
4970 ret += row * c;
4971 }
4972 return ret;
4973 }
4974 for (let i = 0; i < row.length; i++) {
4975 ret += row[i] * (col[i] || 0);
4976 }
4977 return ret;
4978 }));
4979 if (m === 1 && aVec) {
4980 product = product[0]; // Avoid [[a, b, c, ...]]
4981 }
4982 if (p === 1 && bVec) {
4983 if (m === 1 && aVec) {
4984 return product[0]; // Avoid [[a]], return a number
4985 } else {
4986 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
4987 }
4988 }
4989 return product;
4990 }
4991
4992 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
4993 //
4994 // The MIT License (MIT)
4995 // Copyright (c) 2024 Matt DesLauriers
4996
4997 // Permission is hereby granted, free of charge, to any person obtaining a copy
4998 // of this software and associated documentation files (the "Software"), to deal
4999 // in the Software without restriction, including without limitation the rights
5000 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
5001 // copies of the Software, and to permit persons to whom the Software is
5002 // furnished to do so, subject to the following conditions:
5003
5004 // The above copyright notice and this permission notice shall be included in all
5005 // copies or substantial portions of the Software.
5006
5007 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
5008 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5009 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
5010 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5011 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5012 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
5013 // OR OTHER DEALINGS IN THE SOFTWARE.
5014
5015 /**
5016 * Returns the dot product of two vectors each with a length of 3.
5017 *
5018 * @param {Vector3} a
5019 * @param {Vector3} b
5020 * @returns {number}
5021 */
5022 function dot3(a, b) {
5023 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
5024 }
5025
5026 /**
5027 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
5028 * vector to transform in place.
5029 *
5030 * @param {Vector3} input
5031 * @param {Matrix3x3} matrix
5032 * @param {Vector3} [out]
5033 * @returns {Vector3}
5034 */
5035 function multiply_v3_m3x3(input, matrix, out = [0, 0, 0]) {
5036 const x = dot3(input, matrix[0]);
5037 const y = dot3(input, matrix[1]);
5038 const z = dot3(input, matrix[2]);
5039 out[0] = x;
5040 out[1] = y;
5041 out[2] = z;
5042 return out;
5043 }
5044
5045 /**
5046 * Check if a value is a string (including a String object)
5047 * @param {any} str - Value to check
5048 * @returns {str is string}
5049 */
5050 function isString(str) {
5051 return type(str) === "string";
5052 }
5053
5054 /**
5055 * Determine the internal JavaScript [[Class]] of an object.
5056 * @param {any} o - Value to check
5057 * @returns {string}
5058 */
5059 function type(o) {
5060 let str = Object.prototype.toString.call(o);
5061 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
5062 }
5063
5064 /**
5065 * @param {number} n
5066 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
5067 * @returns {string}
5068 */
5069 function serializeNumber(n, {
5070 precision = 16,
5071 unit
5072 }) {
5073 if (isNone(n)) {
5074 return "none";
5075 }
5076 n = +toPrecision(n, precision);
5077 return n + (unit !== null && unit !== void 0 ? unit : "");
5078 }
5079
5080 /**
5081 * Check if a value corresponds to a none argument
5082 * @param {any} n - Value to check
5083 * @returns {n is null}
5084 */
5085 function isNone(n) {
5086 return n === null;
5087 }
5088
5089 /**
5090 * Replace none values with 0
5091 * @param {number | null} n
5092 * @returns {number}
5093 */
5094 function skipNone(n) {
5095 return isNone(n) ? 0 : n;
5096 }
5097
5098 /**
5099 * Round a number to a certain number of significant digits
5100 * @param {number} n - The number to round
5101 * @param {number} precision - Number of significant digits
5102 */
5103 function toPrecision(n, precision) {
5104 if (n === 0) {
5105 return 0;
5106 }
5107 let integer = ~~n;
5108 let digits = 0;
5109 if (integer && precision) {
5110 digits = ~~Math.log10(Math.abs(integer)) + 1;
5111 }
5112 const multiplier = 10.0 ** (precision - digits);
5113 return Math.floor(n * multiplier + 0.5) / multiplier;
5114 }
5115
5116 /**
5117 * Interpolate between two values, either of which may be a `none` value.
5118 * A `none` endpoint is treated as having the other endpoint's value;
5119 * if both are `none`, the result is `none` as well.
5120 * @param {number | null} start
5121 * @param {number | null} end
5122 * @param {number} p
5123 * @returns {number | null}
5124 */
5125 function interpolate(start, end, p) {
5126 if (isNone(start) || isNaN(start)) {
5127 return end;
5128 }
5129 if (isNone(end) || isNaN(end)) {
5130 return start;
5131 }
5132 return start + (end - start) * p;
5133 }
5134
5135 /**
5136 * @param {number} start
5137 * @param {number} end
5138 * @param {number} value
5139 */
5140 function interpolateInv(start, end, value) {
5141 return (value - start) / (end - start);
5142 }
5143
5144 /**
5145 * @param {[number, number]} from
5146 * @param {[number, number]} to
5147 * @param {number} value
5148 */
5149 function mapRange(from, to, value) {
5150 if (!from || !to || from === to || from[0] === to[0] && from[1] === to[1] || isNaN(value) || value === null) {
5151 // Ranges missing or the same
5152 return value;
5153 }
5154 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
5155 }
5156
5157 /**
5158 * Clamp value between the minimum and maximum
5159 * @param {number} min minimum value to return
5160 * @param {number} val the value to return if it is between min and max
5161 * @param {number} max maximum value to return
5162 */
5163 function clamp(min, val, max) {
5164 return Math.max(Math.min(max, val), min);
5165 }
5166
5167 /**
5168 * Copy sign of one value to another.
5169 * @param {number} to - Number to copy sign to
5170 * @param {number} from - Number to copy sign from
5171 */
5172 function copySign(to, from) {
5173 return Math.sign(to) === Math.sign(from) ? to : -to;
5174 }
5175
5176 /**
5177 * Perform pow on a signed number and copy sign to result
5178 * @param {number} base The base number
5179 * @param {number} exp The exponent
5180 */
5181 function spow(base, exp) {
5182 return copySign(Math.abs(base) ** exp, base);
5183 }
5184
5185 /**
5186 * Perform a divide, but return zero if the denominator is zero
5187 * @param {number} n The numerator
5188 * @param {number} d The denominator
5189 */
5190 function zdiv(n, d) {
5191 return d === 0 ? 0 : n / d;
5192 }
5193
5194 /**
5195 * Perform a bisect on a sorted list and locate the insertion point for
5196 * a value in arr to maintain sorted order.
5197 * @param {number[]} arr - array of sorted numbers
5198 * @param {number} value - value to find insertion point for
5199 * @param {number} lo - used to specify a the low end of a subset of the list
5200 * @param {number} hi - used to specify a the high end of a subset of the list
5201 */
5202 function bisectLeft(arr, value, lo = 0, hi = arr.length) {
5203 while (lo < hi) {
5204 const mid = lo + hi >> 1;
5205 if (arr[mid] < value) {
5206 lo = mid + 1;
5207 } else {
5208 hi = mid;
5209 }
5210 }
5211 return lo;
5212 }
5213
5214 /**
5215 * Determines whether an argument is an instance of a constructor, including subclasses.
5216 * This is done by first just checking `instanceof`,
5217 * and then comparing the string names of the constructors if that fails.
5218 * @param {any} arg
5219 * @param {C} constructor
5220 * @template {new (...args: any) => any} C
5221 * @returns {arg is InstanceType<C>}
5222 */
5223 function isInstance(arg, constructor) {
5224 if (arg instanceof constructor) {
5225 return true;
5226 }
5227 const targetName = constructor.name;
5228 while (arg) {
5229 var _proto$constructor;
5230 const proto = Object.getPrototypeOf(arg);
5231 const constructorName = proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.name;
5232 if (constructorName === targetName) {
5233 return true;
5234 }
5235 if (!constructorName || constructorName === "Object") {
5236 return false;
5237 }
5238 arg = proto;
5239 }
5240 return false;
5241 }
5242
5243 var esnext_iterator_find = {};
5244
5245 var es_iterator_find = {};
5246
5247 var hasRequiredEs_iterator_find;
5248
5249 function requireEs_iterator_find () {
5250 if (hasRequiredEs_iterator_find) return es_iterator_find;
5251 hasRequiredEs_iterator_find = 1;
5252 var $ = require_export();
5253 var iterate = requireIterate();
5254 var aCallable = requireACallable();
5255 var anObject = requireAnObject();
5256 var getIteratorDirect = requireGetIteratorDirect();
5257
5258 // `Iterator.prototype.find` method
5259 // https://tc39.es/ecma262/#sec-iterator.prototype.find
5260 $({ target: 'Iterator', proto: true, real: true }, {
5261 find: function find(predicate) {
5262 anObject(this);
5263 aCallable(predicate);
5264 var record = getIteratorDirect(this);
5265 var counter = 0;
5266 return iterate(record, function (value, stop) {
5267 if (predicate(value, counter++)) return stop(value);
5268 }, { IS_RECORD: true, INTERRUPTED: true }).result;
5269 }
5270 });
5271 return es_iterator_find;
5272 }
5273
5274 var hasRequiredEsnext_iterator_find;
5275
5276 function requireEsnext_iterator_find () {
5277 if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
5278 hasRequiredEsnext_iterator_find = 1;
5279 // TODO: Remove from `core-js@4`
5280 requireEs_iterator_find();
5281 return esnext_iterator_find;
5282 }
5283
5284 requireEsnext_iterator_find();
5285
5286 class Type {
5287 // Class properties - declared here so that type inference works
5288 type;
5289 coordMeta;
5290 coordRange;
5291 /** @type {[number, number]} */
5292 range;
5293
5294 /**
5295 * @param {any} type
5296 * @param {import("./types.js").CoordMeta} coordMeta
5297 */
5298 constructor(type, coordMeta) {
5299 if (typeof type === "object") {
5300 this.coordMeta = type;
5301 }
5302 if (coordMeta) {
5303 var _coordMeta$range;
5304 this.coordMeta = coordMeta;
5305 this.coordRange = (_coordMeta$range = coordMeta.range) !== null && _coordMeta$range !== void 0 ? _coordMeta$range : coordMeta.refRange;
5306 }
5307 if (typeof type === "string") {
5308 let params = type.trim().match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
5309 if (!params) {
5310 throw new TypeError(`Cannot parse ${type} as a type definition.`);
5311 }
5312 this.type = params.groups.type;
5313 let {
5314 min,
5315 max
5316 } = params.groups;
5317 if (min || max) {
5318 this.range = [+min, +max];
5319 }
5320 }
5321 }
5322
5323 /** @returns {[number, number]} */
5324 get computedRange() {
5325 if (this.range) {
5326 return this.range;
5327 }
5328 if (this.type === "<percentage>") {
5329 return this.percentageRange();
5330 } else if (this.type === "<angle>") {
5331 return [0, 360];
5332 }
5333 return null;
5334 }
5335 get unit() {
5336 if (this.type === "<percentage>") {
5337 return "%";
5338 } else if (this.type === "<angle>") {
5339 return "deg";
5340 }
5341 return "";
5342 }
5343
5344 /**
5345 * Map a number to the internal representation
5346 * @param {number} number
5347 */
5348 resolve(number) {
5349 if (this.type === "<angle>") {
5350 return number;
5351 }
5352 let fromRange = this.computedRange;
5353 let toRange = this.coordRange;
5354 if (this.type === "<percentage>") {
5355 var _toRange;
5356 (_toRange = toRange) !== null && _toRange !== void 0 ? _toRange : toRange = this.percentageRange();
5357 }
5358 return mapRange(fromRange, toRange, number);
5359 }
5360
5361 /**
5362 * Serialize a number from the internal representation to a string
5363 * @param {number} number
5364 * @param {number} [precision]
5365 */
5366 serialize(number, precision) {
5367 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
5368 let unit = this.unit;
5369 number = mapRange(this.coordRange, toRange, number);
5370 return serializeNumber(number, {
5371 unit,
5372 precision
5373 });
5374 }
5375 toString() {
5376 let ret = this.type;
5377 if (this.range) {
5378 let [min = "", max = ""] = this.range;
5379 ret += `[${min},${max}]`;
5380 }
5381 return ret;
5382 }
5383
5384 /**
5385 * Returns a percentage range for values of this type
5386 * @param {number} scale
5387 * @returns {[number, number]}
5388 */
5389 percentageRange(scale = 1) {
5390 let range;
5391 if (this.coordMeta && this.coordMeta.range || this.coordRange && this.coordRange[0] >= 0) {
5392 range = [0, 1];
5393 } else {
5394 range = [-1, 1];
5395 }
5396 return [range[0] * scale, range[1] * scale];
5397 }
5398 static get(type, coordMeta) {
5399 if (isInstance(type, this)) {
5400 return type;
5401 }
5402 return new this(type, coordMeta);
5403 }
5404 }
5405
5406 /** @import { ColorSpace, Coords } from "./types.js" */
5407
5408 // Type re-exports
5409 /** @typedef {import("./types.js").Format} FormatInterface */
5410
5411 /**
5412 * @internal
5413 * Used to index {@link FormatInterface Format} objects and store an instance.
5414 * Not meant for external use
5415 */
5416 const instance = Symbol("instance");
5417
5418 /**
5419 * Remove the first element of an array type
5420 * @template {any[]} T
5421 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
5422 */
5423
5424 /**
5425 * @class Format
5426 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
5427 * Class to hold a color serialization format
5428 */
5429 class Format {
5430 // Class properties - declared here so that type inference works
5431 type;
5432 name;
5433 spaceCoords;
5434 /** @type {Type[][]} */
5435 coords;
5436 /** @type {string | undefined} */
5437 id;
5438 /** @type {boolean | undefined} */
5439 alpha;
5440
5441 /**
5442 * @param {FormatInterface} format
5443 * @param {ColorSpace} space
5444 */
5445 constructor(format, space = format.space) {
5446 format[instance] = this;
5447 this.type = "function";
5448 this.name = "color";
5449 Object.assign(this, format);
5450 this.space = space;
5451 if (this.type === "custom") {
5452 // Nothing else to do here
5453 return;
5454 }
5455 this.spaceCoords = Object.values(space.coords);
5456 if (!this.coords) {
5457 // @ts-expect-error Strings are converted to the correct type later
5458 this.coords = this.spaceCoords.map(coordMeta => {
5459 let ret = ["<number>", "<percentage>"];
5460 if (coordMeta.type === "angle") {
5461 ret.push("<angle>");
5462 }
5463 return ret;
5464 });
5465 }
5466 this.coords = this.coords.map(/** @param {string | string[] | Type[]} types */(types, i) => {
5467 let coordMeta = this.spaceCoords[i];
5468 if (typeof types === "string") {
5469 types = types.trim().split(/\s*\|\s*/);
5470 }
5471 return types.map(type => Type.get(type, coordMeta));
5472 });
5473 }
5474
5475 /**
5476 * @param {Coords} coords
5477 * @param {number} precision
5478 * @param {Type[]} types
5479 */
5480 serializeCoords(coords, precision, types) {
5481 types = coords.map((_, i) => {
5482 var _types$i, _types;
5483 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]);
5484 });
5485 return coords.map((c, i) => types[i].serialize(c, precision));
5486 }
5487
5488 /**
5489 * Validates the coordinates of a color against a format's coord grammar and
5490 * maps the coordinates to the range or refRange of the coordinates.
5491 * @param {Coords} coords
5492 * @param {[string, string, string]} types
5493 */
5494 coerceCoords(coords, types) {
5495 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
5496 let arg = coords[i];
5497 if (isNone(arg) || isNaN(arg)) {
5498 // Nothing to do here
5499 return arg;
5500 }
5501
5502 // Find grammar alternative that matches the provided type
5503 // Non-strict equals is intentional because we are comparing w/ string objects
5504 let providedType = types[i];
5505 let type = this.coords[i].find(c => c.type == providedType);
5506
5507 // Check that each coord conforms to its grammar
5508 if (!type) {
5509 var _ref, _arg;
5510 // Type does not exist in the grammar, throw
5511 let coordName = coordMeta.name || id;
5512 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}()`);
5513 }
5514 arg = type.resolve(arg);
5515 if (type.range) {
5516 // Adjust type to include range
5517 types[i] = type.toString();
5518 }
5519 return arg;
5520 });
5521 }
5522
5523 /**
5524 * @returns {boolean | Required<FormatInterface>["serialize"]}
5525 */
5526 canSerialize() {
5527 return this.type === "function" || /** @type {any} */this.serialize;
5528 }
5529
5530 /**
5531 * @param {string} str
5532 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
5533 */
5534 parse(str) {
5535 return null;
5536 }
5537
5538 /**
5539 * @param {Format | FormatInterface} format
5540 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
5541 * @returns {Format}
5542 */
5543 static get(format, ...args) {
5544 if (!format || isInstance(format, this)) {
5545 return /** @type {Format} */format;
5546 }
5547 if (format[instance]) {
5548 return format[instance];
5549 }
5550 return new Format(format, ...args);
5551 }
5552 }
5553
5554 var esnext_iterator_forEach = {};
5555
5556 var es_iterator_forEach = {};
5557
5558 var hasRequiredEs_iterator_forEach;
5559
5560 function requireEs_iterator_forEach () {
5561 if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
5562 hasRequiredEs_iterator_forEach = 1;
5563 var $ = require_export();
5564 var iterate = requireIterate();
5565 var aCallable = requireACallable();
5566 var anObject = requireAnObject();
5567 var getIteratorDirect = requireGetIteratorDirect();
5568
5569 // `Iterator.prototype.forEach` method
5570 // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
5571 $({ target: 'Iterator', proto: true, real: true }, {
5572 forEach: function forEach(fn) {
5573 anObject(this);
5574 aCallable(fn);
5575 var record = getIteratorDirect(this);
5576 var counter = 0;
5577 iterate(record, function (value) {
5578 fn(value, counter++);
5579 }, { IS_RECORD: true });
5580 }
5581 });
5582 return es_iterator_forEach;
5583 }
5584
5585 var hasRequiredEsnext_iterator_forEach;
5586
5587 function requireEsnext_iterator_forEach () {
5588 if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
5589 hasRequiredEsnext_iterator_forEach = 1;
5590 // TODO: Remove from `core-js@4`
5591 requireEs_iterator_forEach();
5592 return esnext_iterator_forEach;
5593 }
5594
5595 requireEsnext_iterator_forEach();
5596
5597 /**
5598 * A class for adding deep extensibility to any piece of JS code
5599 */
5600 class Hooks {
5601 add(name, callback, first) {
5602 if (typeof arguments[0] != "string") {
5603 // Multiple hooks
5604 for (var name in arguments[0]) {
5605 this.add(name, arguments[0][name], arguments[1]);
5606 }
5607 return;
5608 }
5609 (Array.isArray(name) ? name : [name]).forEach(function (name) {
5610 this[name] = this[name] || [];
5611 if (callback) {
5612 this[name][first ? "unshift" : "push"](callback);
5613 }
5614 }, this);
5615 }
5616 run(name, env) {
5617 this[name] = this[name] || [];
5618 this[name].forEach(function (callback) {
5619 callback.call(env && env.context ? env.context : env, env);
5620 });
5621 }
5622 }
5623
5624 /**
5625 * The instance of {@link Hooks} used throughout Color.js
5626 */
5627 const hooks = new Hooks();
5628
5629 // Type re-exports
5630 /** @typedef {import("./types.js").White} White */
5631
5632 /** @type {Record<string, White>} */
5633 // prettier-ignore
5634 const WHITES = {
5635 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
5636 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
5637 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]
5638 };
5639
5640 /**
5641 *
5642 * @param {string | White} name
5643 * @returns {White}
5644 */
5645 function getWhite(name) {
5646 if (Array.isArray(name)) {
5647 return name;
5648 }
5649 return WHITES[name];
5650 }
5651
5652 /**
5653 * Adapt XYZ from white point W1 to W2
5654 * @param {White | string} W1
5655 * @param {White | string} W2
5656 * @param {[number, number, number]} XYZ
5657 * @param {{ method?: string | undefined }} options
5658 * @returns {[number, number, number]}
5659 */
5660 function adapt$2(W1, W2, XYZ, options = {}) {
5661 W1 = getWhite(W1);
5662 W2 = getWhite(W2);
5663 if (!W1 || !W2) {
5664 throw new TypeError(`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`);
5665 }
5666 if (W1 === W2) {
5667 // Same whitepoints, no conversion needed
5668 return XYZ;
5669 }
5670 let env = {
5671 W1,
5672 W2,
5673 XYZ,
5674 options
5675 };
5676 hooks.run("chromatic-adaptation-start", env);
5677 if (!env.M) {
5678 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
5679 // prettier-ignore
5680 env.M = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
5681 } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
5682 // prettier-ignore
5683 env.M = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
5684 }
5685 }
5686 hooks.run("chromatic-adaptation-end", env);
5687 if (env.M) {
5688 return multiply_v3_m3x3(env.XYZ, env.M);
5689 } else {
5690 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
5691 }
5692 }
5693
5694 var _globalThis$process;
5695 // Global defaults one may want to configure
5696 var defaults = {
5697 gamut_mapping: "css",
5698 precision: 5,
5699 deltaE: "76",
5700 // Default deltaE method
5701 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",
5702 warn: function warn(msg) {
5703 if (this.verbose) {
5704 var _globalThis$console, _globalThis$console$w;
5705 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);
5706 }
5707 }
5708 };
5709
5710 /** @import { ColorConstructor } from "./types.js" */
5711
5712 // Type re-exports
5713 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
5714 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
5715 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
5716
5717 /**
5718 * Convert a CSS Color string to a color object
5719 * @param {string} str
5720 * @param {ParseOptions} [options]
5721 * @returns {ColorConstructor}
5722 */
5723 function parse(str, options) {
5724 var _String, _env$options$parseMet;
5725 let env = {
5726 str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim(),
5727 options
5728 };
5729 hooks.run("parse-start", env);
5730 if (env.color) {
5731 return env.color;
5732 }
5733 env.parsed = parseFunction(env.str);
5734 let ret;
5735 let meta = env.options ? (_env$options$parseMet = env.options.parseMeta) !== null && _env$options$parseMet !== void 0 ? _env$options$parseMet : env.options.meta : null;
5736 if (env.parsed) {
5737 // Is a functional syntax
5738 let name = env.parsed.name;
5739 let format;
5740 let space;
5741 let coords = env.parsed.args;
5742 let types = coords.map((c, i) => {
5743 var _env$parsed$argMeta$i;
5744 return (_env$parsed$argMeta$i = env.parsed.argMeta[i]) === null || _env$parsed$argMeta$i === void 0 ? void 0 : _env$parsed$argMeta$i.type;
5745 });
5746 if (name === "color") {
5747 // color() function
5748 let id = coords.shift();
5749 types.shift();
5750 // Check against both <dashed-ident> and <ident> versions
5751 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
5752 let ids = [id, alternateId];
5753 format = ColorSpace.findFormat({
5754 name,
5755 id: ids,
5756 type: "function"
5757 });
5758 if (!format) {
5759 var _didYouMean;
5760 // Not found
5761 let didYouMean;
5762 let registryId = id in ColorSpace.registry ? id : alternateId;
5763 if (registryId in ColorSpace.registry) {
5764 var _ColorSpace$registry$;
5765 // Used color space id instead of color() id, these are often different
5766 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;
5767 if (cssId) {
5768 let altColor = str.replace("color(" + id, "color(" + cssId);
5769 didYouMean = `Did you mean ${altColor}?`;
5770 }
5771 }
5772 throw new TypeError(`Cannot parse ${env.str}. ` + ((_didYouMean = didYouMean) !== null && _didYouMean !== void 0 ? _didYouMean : "Missing a plugin?"));
5773 }
5774 space = format.space;
5775 if (format.id.startsWith("--") && !id.startsWith("--")) {
5776 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}).`);
5777 }
5778 if (id.startsWith("--") && !format.id.startsWith("--")) {
5779 defaults.warn(`${space.name} is a standard space and supported in the CSS spec. ` + `Use color(${format.id}) instead of prefixed color(${id}).`);
5780 }
5781 } else {
5782 format = ColorSpace.findFormat({
5783 name,
5784 type: "function"
5785 });
5786 space = format.space;
5787 }
5788 if (meta) {
5789 Object.assign(meta, {
5790 format,
5791 formatId: format.name,
5792 types,
5793 commas: env.parsed.commas
5794 });
5795 }
5796 let alpha = 1;
5797 if (env.parsed.lastAlpha) {
5798 alpha = env.parsed.args.pop();
5799 if (meta) {
5800 meta.alphaType = types.pop();
5801 }
5802 }
5803 let coordCount = format.coords.length;
5804 if (coords.length !== coordCount) {
5805 throw new TypeError(`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`);
5806 }
5807 coords = format.coerceCoords(coords, types);
5808 ret = {
5809 spaceId: space.id,
5810 coords,
5811 alpha
5812 };
5813 } else {
5814 // Custom, colorspace-specific format
5815 spaceloop: for (let space of ColorSpace.all) {
5816 for (let formatId in space.formats) {
5817 let format = space.formats[formatId];
5818 if (format.type !== "custom") {
5819 continue;
5820 }
5821 if (format.test && !format.test(env.str)) {
5822 continue;
5823 }
5824
5825 // Convert to Format object
5826 let formatObject = space.getFormat(format);
5827 let color = formatObject.parse(env.str);
5828 if (color) {
5829 if (meta) {
5830 Object.assign(meta, {
5831 format: formatObject,
5832 formatId
5833 });
5834 }
5835 ret = color;
5836 break spaceloop;
5837 }
5838 }
5839 }
5840 }
5841 if (!ret) {
5842 // If we're here, we couldn't parse
5843 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
5844 }
5845
5846 // Clamp alpha to [0, 1]
5847 ret.alpha = isNone(ret.alpha) ? ret.alpha : ret.alpha === undefined ? 1 : clamp(0, ret.alpha, 1);
5848 return ret;
5849 }
5850
5851 /**
5852 * Units and multiplication factors for the internally stored numbers
5853 */
5854 const units = {
5855 "%": 0.01,
5856 deg: 1,
5857 grad: 0.9,
5858 rad: 180 / Math.PI,
5859 turn: 360
5860 };
5861 const regex = {
5862 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
5863 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
5864 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
5865 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
5866 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
5867 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g
5868 };
5869
5870 /**
5871 * Parse a single function argument
5872 * @param {string} rawArg
5873 * @returns {{value: number, meta: ArgumentMeta}}
5874 */
5875 function parseArgument(rawArg) {
5876 var _rawArg$match;
5877 /** @type {Partial<ArgumentMeta>} */
5878 let meta = {};
5879 let unit = (_rawArg$match = rawArg.match(regex.unitValue)) === null || _rawArg$match === void 0 ? void 0 : _rawArg$match[0];
5880 /** @type {string | number} */
5881 let value = meta.raw = rawArg;
5882 if (unit) {
5883 // It’s a dimension token
5884 meta.type = unit === "%" ? "<percentage>" : "<angle>";
5885 meta.unit = unit;
5886 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
5887
5888 value = meta.unitless * units[unit];
5889 } else if (regex.number.test(value)) {
5890 // It's a number
5891 // Convert numerical args to numbers
5892 value = Number(value);
5893 meta.type = "<number>";
5894 } else if (value === "none") {
5895 value = null;
5896 } else if (value === "NaN" || value === "calc(NaN)") {
5897 value = NaN;
5898 meta.type = "<number>";
5899 } else {
5900 meta.type = "<ident>";
5901 }
5902 return {
5903 value: (/** @type {number} */value),
5904 meta: (/** @type {ArgumentMeta} */meta)
5905 };
5906 }
5907
5908 /**
5909 * Parse a CSS function, regardless of its name and arguments
5910 * @param {string} str String to parse
5911 * @return {ParseFunctionReturn | void}
5912 */
5913 function parseFunction(str) {
5914 if (!str) {
5915 return;
5916 }
5917 str = str.trim();
5918 let parts = str.match(regex.function);
5919 if (parts) {
5920 // It is a function, parse args
5921 let args = [];
5922 let argMeta = [];
5923 let lastAlpha = false;
5924 let name = parts[1].toLowerCase();
5925 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
5926 let {
5927 value,
5928 meta
5929 } = parseArgument(rawArg);
5930 if (
5931 // If there's a slash here, it's modern syntax
5932 $0.startsWith("/") ||
5933 // 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)"
5934 name !== "color" && args.length === 3) {
5935 // It's alpha
5936 lastAlpha = true;
5937 }
5938 args.push(value);
5939 argMeta.push(meta);
5940 return "";
5941 });
5942 return {
5943 name,
5944 args,
5945 argMeta,
5946 lastAlpha,
5947 commas: separators.includes(","),
5948 rawName: parts[1],
5949 rawArgs: parts[2]
5950 };
5951 }
5952 }
5953
5954 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
5955
5956 /**
5957 * Resolves a color reference (object or string) to a plain color object
5958 * @overload
5959 * @param {ColorTypes} color
5960 * @param {GetColorOptions} [options]
5961 * @returns {PlainColorObject}
5962 */
5963 /**
5964 * @overload
5965 * @param {ColorTypes[]} color
5966 * @param {GetColorOptions} [options]
5967 * @returns {PlainColorObject[]}
5968 */
5969 function getColor(color, options) {
5970 if (Array.isArray(color)) {
5971 return color.map(c => getColor(c, options));
5972 }
5973 if (!color) {
5974 throw new TypeError("Empty color reference");
5975 }
5976 if (isString(color)) {
5977 color = parse(color, options);
5978 }
5979
5980 // Object fixup
5981 let space = color.space || color.spaceId;
5982 if (typeof space === "string") {
5983 // Convert string id to color space object
5984 color.space = ColorSpace.get(space);
5985 }
5986 if (color.alpha === undefined) {
5987 color.alpha = 1;
5988 }
5989 return color;
5990 }
5991
5992 const ε$7 = 0.000075;
5993
5994 /**
5995 * Class to represent a color space
5996 */
5997 class ColorSpace {
5998 constructor(options) {
5999 var _options$displaySpace, _options$coords, _ref, _options$white, _options$formats, _this$formats$color, _options$M;
6000 this.id = options.id;
6001 this.name = options.name;
6002 this.base = options.base ? ColorSpace.get(options.base) : null;
6003 this.aliases = options.aliases;
6004 this.displaySpaces = (_options$displaySpace = options.displaySpaces) === null || _options$displaySpace === void 0 ? void 0 : _options$displaySpace.map(space => ColorSpace.get(space));
6005
6006 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
6007 this.bases = [];
6008 for (let base = this.base; base; base = base.base) {
6009 this.bases.push(base);
6010 }
6011 if (options.rgbGamut) {
6012 this.rgbGamut = options.rgbGamut;
6013 }
6014 if (options.linearGamut) {
6015 this.linearGamut = options.linearGamut;
6016 }
6017 if (this.base) {
6018 // Keep a subclass's own methods if the options don't override them
6019 if (options.fromBase) {
6020 this.fromBase = options.fromBase;
6021 }
6022 if (options.toBase) {
6023 this.toBase = options.toBase;
6024 }
6025 }
6026
6027 // Coordinate metadata
6028
6029 let coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords;
6030 for (let name in coords) {
6031 if (!("name" in coords[name])) {
6032 coords[name].name = name;
6033 }
6034 }
6035 this.coords = coords;
6036
6037 // White point
6038
6039 let white = (_ref = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref !== void 0 ? _ref : "D65";
6040 this.white = getWhite(white);
6041
6042 // Sort out formats
6043
6044 this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {};
6045 for (let name in this.formats) {
6046 let format = this.formats[name];
6047 format.type || (format.type = "function");
6048 format.name || (format.name = name);
6049 }
6050 if (!((_this$formats$color = this.formats.color) !== null && _this$formats$color !== void 0 && _this$formats$color.id)) {
6051 var _this$formats$color2;
6052 this.formats.color = {
6053 ...((_this$formats$color2 = this.formats.color) !== null && _this$formats$color2 !== void 0 ? _this$formats$color2 : {}),
6054 id: options.cssId || this.id
6055 };
6056 }
6057
6058 // Gamut space
6059
6060 if (options.gamutSpace) {
6061 // Gamut space explicitly specified
6062 this.gamutSpace = options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
6063 } else {
6064 // No gamut space specified, calculate a sensible default
6065 if (this.isPolar) {
6066 // Do not check gamut through polar coordinates
6067 this.gamutSpace = this.base;
6068 } else {
6069 this.gamutSpace = this;
6070 }
6071 }
6072
6073 // Optimize inGamut for unbounded spaces
6074 if (this.gamutSpace.isUnbounded) {
6075 this.inGamut = (coords, options) => {
6076 return true;
6077 };
6078 }
6079
6080 // Matrices used by this color space, exposed so that consumer code
6081 // can reuse them instead of duplicating the data. E.g. `this.M.toXYZ`.
6082 this.M = (_options$M = options.M) !== null && _options$M !== void 0 ? _options$M : {};
6083
6084 // Other stuff
6085 this.referred = options.referred;
6086
6087 // Compute ancestors and store them, since they will never change
6088 Object.defineProperty(this, "path", {
6089 value: getPath(this).reverse(),
6090 writable: false,
6091 enumerable: true,
6092 configurable: true
6093 });
6094 hooks.run("colorspace-init-end", this);
6095 }
6096 inGamut(coords, {
6097 epsilon = ε$7
6098 } = {}) {
6099 if (!this.equals(this.gamutSpace)) {
6100 coords = this.to(this.gamutSpace, coords);
6101 return this.gamutSpace.inGamut(coords, {
6102 epsilon
6103 });
6104 }
6105 let coordMeta = Object.values(this.coords);
6106 return coords.every((c, i) => {
6107 let meta = coordMeta[i];
6108 if (meta.type !== "angle" && meta.range) {
6109 if (isNone(c)) {
6110 // NaN is always in gamut
6111 return true;
6112 }
6113 let [min, max] = meta.range;
6114 return (min === undefined || c >= min - epsilon) && (max === undefined || c <= max + epsilon);
6115 }
6116 return true;
6117 });
6118 }
6119 get isUnbounded() {
6120 return Object.values(this.coords).every(coord => !("range" in coord));
6121 }
6122 get cssId() {
6123 var _this$formats;
6124 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;
6125 }
6126
6127 /**
6128 * The id of this space's hue coordinate, or null if the space is not polar
6129 * @returns {string | null}
6130 */
6131 get hueId() {
6132 for (let id in this.coords) {
6133 if (this.coords[id].type === "angle") {
6134 return id;
6135 }
6136 }
6137 return null;
6138 }
6139
6140 /**
6141 * The index of this space's hue coordinate within its coords array, or -1 if the space is not polar
6142 * @returns {number}
6143 */
6144 get hueIndex() {
6145 return Object.keys(this.coords).findIndex(id => this.coords[id].type === "angle");
6146 }
6147 get isPolar() {
6148 return this.hueId !== null;
6149 }
6150
6151 /**
6152 * Lookup a format in this color space
6153 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
6154 * @returns {Format}
6155 */
6156 getFormat(format) {
6157 if (!format) {
6158 return null;
6159 }
6160 if (format === "default") {
6161 format = Object.values(this.formats)[0];
6162 } else if (typeof format === "string") {
6163 format = this.formats[format];
6164 }
6165 let ret = Format.get(format, this);
6166 if (ret !== format && format.name in this.formats) {
6167 // Update the format we have on file so we can find it more quickly next time
6168 this.formats[format.name] = ret;
6169 }
6170 return ret;
6171 }
6172
6173 /**
6174 * Check if this color space is the same as another color space reference.
6175 * Allows proxying color space objects and comparing color spaces with ids.
6176 * @param {string | ColorSpace} space ColorSpace object or id to compare to
6177 * @returns {boolean}
6178 */
6179 equals(space) {
6180 if (!space) {
6181 return false;
6182 }
6183 return this === space || this.id === space || this.id === space.id;
6184 }
6185 to(space, coords) {
6186 if (arguments.length === 1) {
6187 const color = getColor(space);
6188 [space, coords] = [color.space, color.coords];
6189 }
6190 space = ColorSpace.get(space);
6191 if (this.equals(space)) {
6192 // Same space, no change needed
6193 return coords;
6194 }
6195
6196 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
6197 coords = coords.map(c => isNone(c) ? 0 : c);
6198
6199 // Find connection space = lowest common ancestor in the base tree
6200 let myPath = this.path;
6201 let otherPath = space.path;
6202 let connectionSpace, connectionSpaceIndex;
6203 for (let i = 0; i < myPath.length; i++) {
6204 if (myPath[i].equals(otherPath[i])) {
6205 connectionSpace = myPath[i];
6206 connectionSpaceIndex = i;
6207 } else {
6208 break;
6209 }
6210 }
6211 if (!connectionSpace) {
6212 // This should never happen
6213 throw new Error(`Cannot convert between color spaces ${this} and ${space}: no connection space was found`);
6214 }
6215
6216 // Go up from current space to connection space
6217 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
6218 coords = myPath[i].toBase(coords);
6219 }
6220
6221 // Go down from connection space to target space
6222 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
6223 coords = otherPath[i].fromBase(coords);
6224 }
6225 return coords;
6226 }
6227 from(space, coords) {
6228 if (arguments.length === 1) {
6229 const color = getColor(space);
6230 [space, coords] = [color.space, color.coords];
6231 }
6232 space = ColorSpace.get(space);
6233 return space.to(this, coords);
6234 }
6235 toString() {
6236 return `${this.name} (${this.id})`;
6237 }
6238 getMinCoords() {
6239 let ret = [];
6240 for (let id in this.coords) {
6241 var _range$min;
6242 let meta = this.coords[id];
6243 let range = meta.range || meta.refRange;
6244 ret.push((_range$min = range === null || range === void 0 ? void 0 : range.min) !== null && _range$min !== void 0 ? _range$min : 0);
6245 }
6246 return ret;
6247 }
6248 static registry = {};
6249
6250 // Returns array of unique color spaces
6251 static get all() {
6252 return [...new Set(Object.values(ColorSpace.registry))];
6253 }
6254 static register(id, space) {
6255 if (arguments.length === 1) {
6256 space = arguments[0];
6257 id = space.id;
6258 }
6259 space = this.get(space);
6260 if (this.registry[id] && this.registry[id] !== space) {
6261 throw new Error(`Duplicate color space registration: '${id}'`);
6262 }
6263 this.registry[id] = space;
6264
6265 // Register aliases when called without an explicit ID.
6266 if (arguments.length === 1 && space.aliases) {
6267 for (let alias of space.aliases) {
6268 this.register(alias, space);
6269 }
6270 }
6271 return space;
6272 }
6273
6274 /**
6275 * Lookup ColorSpace object by name
6276 * @param {ColorSpace | string} name
6277 */
6278 static get(space, ...alternatives) {
6279 if (!space || isInstance(space, this)) {
6280 return space;
6281 }
6282 let argType = type(space);
6283 if (argType === "string") {
6284 // It's a color space id
6285 let ret = ColorSpace.registry[space.toLowerCase()];
6286 if (!ret) {
6287 throw new TypeError(`No color space found with id = "${space}"`);
6288 }
6289 return ret;
6290 }
6291 if (alternatives.length) {
6292 return ColorSpace.get(...alternatives);
6293 }
6294 throw new TypeError(`${space} is not a valid color space`);
6295 }
6296
6297 /**
6298 * Look up all color spaces for a format that matches certain criteria
6299 * @param {object | string} filters
6300 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
6301 * @returns {Format | null}
6302 */
6303 static findFormat(filters, spaces = ColorSpace.all) {
6304 if (!filters) {
6305 return null;
6306 }
6307 if (typeof filters === "string") {
6308 filters = {
6309 name: filters
6310 };
6311 }
6312 for (let space of spaces) {
6313 for (let [name, format] of Object.entries(space.formats)) {
6314 var _format$name, _format$type;
6315 (_format$name = format.name) !== null && _format$name !== void 0 ? _format$name : format.name = name;
6316 (_format$type = format.type) !== null && _format$type !== void 0 ? _format$type : format.type = "function";
6317 let matches = (!filters.name || format.name === filters.name) && (!filters.type || format.type === filters.type);
6318 if (filters.id) {
6319 let ids = format.ids || [format.id];
6320 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
6321 matches && (matches = filterIds.some(id => ids.includes(id)));
6322 }
6323 if (matches) {
6324 let ret = Format.get(format, space);
6325 if (ret !== format) {
6326 space.formats[format.name] = ret;
6327 }
6328 return ret;
6329 }
6330 }
6331 }
6332 return null;
6333 }
6334
6335 /**
6336 * Get metadata about a coordinate of a color space
6337 *
6338 * @static
6339 * @param {Array | string} ref
6340 * @param {ColorSpace | string} [workingSpace]
6341 * @return {Object}
6342 */
6343 static resolveCoord(ref, workingSpace) {
6344 let coordType = type(ref);
6345 let space, coord;
6346 if (coordType === "string") {
6347 if (ref.includes(".")) {
6348 // Absolute coordinate
6349 [space, coord] = ref.split(".");
6350 } else {
6351 // Relative coordinate
6352 [space, coord] = [, ref];
6353 }
6354 } else if (Array.isArray(ref)) {
6355 [space, coord] = ref;
6356 } else {
6357 // Object
6358 space = ref.space;
6359 coord = ref.coordId;
6360 }
6361 space = ColorSpace.get(space);
6362 if (!space) {
6363 space = workingSpace;
6364 }
6365 if (!space) {
6366 throw new TypeError(`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`);
6367 }
6368 coordType = type(coord);
6369 if (coordType === "number" || coordType === "string" && coord >= 0) {
6370 // Resolve numerical coord
6371 let meta = Object.entries(space.coords)[coord];
6372 if (meta) {
6373 return {
6374 space,
6375 id: meta[0],
6376 index: coord,
6377 ...meta[1]
6378 };
6379 }
6380 }
6381 space = ColorSpace.get(space);
6382 let normalizedCoord = coord.toLowerCase();
6383 let i = 0;
6384 for (let id in space.coords) {
6385 var _meta$name;
6386 let meta = space.coords[id];
6387 if (id.toLowerCase() === normalizedCoord || ((_meta$name = meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) {
6388 return {
6389 space,
6390 id,
6391 index: i,
6392 ...meta
6393 };
6394 }
6395 i++;
6396 }
6397 throw new TypeError(`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`);
6398 }
6399 static DEFAULT_FORMAT = {
6400 type: "functions",
6401 name: "color"
6402 };
6403 }
6404 function getPath(space) {
6405 let ret = [space];
6406 for (let s = space; s = s.base;) {
6407 ret.push(s);
6408 }
6409 return ret;
6410 }
6411
6412 var XYZ_D65 = new ColorSpace({
6413 id: "xyz-d65",
6414 name: "XYZ D65",
6415 coords: {
6416 x: {
6417 refRange: [0, 1],
6418 name: "X"
6419 },
6420 y: {
6421 refRange: [0, 1],
6422 name: "Y"
6423 },
6424 z: {
6425 refRange: [0, 1],
6426 name: "Z"
6427 }
6428 },
6429 white: "D65",
6430 formats: {
6431 color: {
6432 ids: ["xyz-d65", "xyz"]
6433 }
6434 },
6435 aliases: ["xyz"]
6436 });
6437
6438 // Type re-exports
6439 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
6440
6441 /** Convenience class for RGB color spaces */
6442 class RGBColorSpace extends ColorSpace {
6443 /**
6444 * Creates a new RGB ColorSpace.
6445 * If coords are not specified, they will use the default RGB coords.
6446 * Instead of `fromBase()` and `toBase()` functions,
6447 * you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()`
6448 * methods use them via `this.M.toXYZ` and `this.M.fromXYZ`.
6449 * @param {RGBOptions} options
6450 */
6451 constructor(options) {
6452 var _options$toXYZ_M, _options$M, _options$fromXYZ_M, _options$M2, _options$referred;
6453 if (!options.coords) {
6454 options.coords = {
6455 r: {
6456 range: [0, 1],
6457 name: "Red"
6458 },
6459 g: {
6460 range: [0, 1],
6461 name: "Green"
6462 },
6463 b: {
6464 range: [0, 1],
6465 name: "Blue"
6466 }
6467 };
6468 }
6469 if (!options.base) {
6470 options.base = XYZ_D65;
6471 }
6472
6473 // Accept matrices either as dedicated options or via the generic `M` object
6474 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;
6475 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;
6476 (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = "display";
6477 super(options);
6478
6479 // Expose the matrices on the color space (via `this.M`) so consumers can reuse them.
6480 if (toXYZ && fromXYZ) {
6481 this.M.toXYZ = toXYZ;
6482 this.M.fromXYZ = fromXYZ;
6483 }
6484 }
6485 toBase(rgb) {
6486 let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ);
6487 if (this.white !== this.base.white) {
6488 // Perform chromatic adaptation
6489 xyz = adapt$2(this.white, this.base.white, xyz);
6490 }
6491 return xyz;
6492 }
6493 fromBase(xyz) {
6494 xyz = adapt$2(this.base.white, this.white, xyz);
6495 return multiply_v3_m3x3(xyz, this.M.fromXYZ);
6496 }
6497 }
6498
6499 var XYZ_D50 = new ColorSpace({
6500 id: "xyz-d50",
6501 name: "XYZ D50",
6502 white: "D50",
6503 base: XYZ_D65,
6504 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
6505 toBase: coords => adapt$2("D50", XYZ_D65.white, coords)
6506 });
6507
6508 // κ * ε = 2^3 = 8
6509 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6510 const ε3$1 = 24 / 116;
6511 const κ$4 = 24389 / 27; // 29^3/3^3
6512
6513 let white$4 = WHITES.D50;
6514 var lab = new ColorSpace({
6515 id: "lab",
6516 name: "Lab",
6517 coords: {
6518 l: {
6519 refRange: [0, 100],
6520 name: "Lightness"
6521 },
6522 a: {
6523 refRange: [-125, 125]
6524 },
6525 b: {
6526 refRange: [-125, 125]
6527 }
6528 },
6529 // Assuming XYZ is relative to D50, convert to CIE Lab
6530 // from CIE standard, which now defines these as a rational fraction
6531 white: white$4,
6532 base: XYZ_D50,
6533 // Convert D50-adapted XYX to Lab
6534 // CIE 15.3:2004 section 8.2.1.1
6535 fromBase(XYZ) {
6536 // XYZ scaled relative to reference white
6537 let xyz = XYZ.map((value, i) => value / white$4[i]);
6538 let f = xyz.map(value => value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116);
6539 let L = 116 * f[1] - 16;
6540 let a = 500 * (f[0] - f[1]);
6541 let b = 200 * (f[1] - f[2]);
6542 return [L, a, b];
6543 },
6544 // Convert Lab to D50-adapted XYZ
6545 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
6546 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
6547 toBase(Lab) {
6548 // compute f, starting with the luminance-related term
6549 let [L, a, b] = Lab;
6550 let f = [];
6551 f[1] = (L + 16) / 116;
6552 f[0] = a / 500 + f[1];
6553 f[2] = f[1] - b / 200;
6554
6555 // compute xyz
6556 // prettier-ignore
6557 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];
6558
6559 // Compute XYZ by scaling xyz by reference white
6560 return xyz.map((value, i) => value * white$4[i]);
6561 },
6562 formats: {
6563 lab: {
6564 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6565 }
6566 }
6567 });
6568
6569 /**
6570 * Constrain an angle to 360 degrees
6571 * @param {number} angle
6572 * @returns {number}
6573 */
6574 function constrain(angle) {
6575 if (typeof angle !== "number") {
6576 return angle;
6577 }
6578 return (angle % 360 + 360) % 360;
6579 }
6580
6581 /**
6582 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
6583 * @param {[number, number]} angles
6584 * @returns {[number, number]}
6585 */
6586 function adjust(arc, angles) {
6587 let [a1, a2] = angles;
6588 let none1 = isNone(a1);
6589 let none2 = isNone(a2);
6590 if (none1 && none2) {
6591 return [a1, a2];
6592 } else if (none1) {
6593 a1 = a2;
6594 } else if (none2) {
6595 a2 = a1;
6596 }
6597 if (arc === "raw") {
6598 return angles;
6599 }
6600 a1 = constrain(a1);
6601 a2 = constrain(a2);
6602 let angleDiff = a2 - a1;
6603 if (arc === "increasing") {
6604 if (angleDiff < 0) {
6605 a2 += 360;
6606 }
6607 } else if (arc === "decreasing") {
6608 if (angleDiff > 0) {
6609 a1 += 360;
6610 }
6611 } else if (arc === "longer") {
6612 if (-180 < angleDiff && angleDiff < 180) {
6613 if (angleDiff > 0) {
6614 a1 += 360;
6615 } else {
6616 a2 += 360;
6617 }
6618 }
6619 } else if (arc === "shorter") {
6620 if (angleDiff > 180) {
6621 a1 += 360;
6622 } else if (angleDiff < -180) {
6623 a2 += 360;
6624 }
6625 }
6626 return [a1, a2];
6627 }
6628
6629 var lch = new ColorSpace({
6630 id: "lch",
6631 name: "LCH",
6632 coords: {
6633 l: {
6634 refRange: [0, 100],
6635 name: "Lightness"
6636 },
6637 c: {
6638 refRange: [0, 150],
6639 name: "Chroma"
6640 },
6641 h: {
6642 refRange: [0, 360],
6643 type: "angle",
6644 name: "Hue"
6645 }
6646 },
6647 base: lab,
6648 fromBase(Lab) {
6649 // These methods are used for other polar forms as well, so we can't hardcode the ε
6650 if (this.ε === undefined) {
6651 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
6652 let range = Object.values(this.base.coords)[1].refRange;
6653 let extent = range[1] - range[0];
6654 this.ε = extent / 100000;
6655 }
6656
6657 // Convert to polar form
6658 let [L, a, b] = Lab;
6659 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
6660 let h = isAchromatic ? null : constrain(Math.atan2(b, a) * 180 / Math.PI);
6661 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
6662 return [L, C, h];
6663 },
6664 toBase(lch) {
6665 // Convert from polar form
6666 let [L, C, h] = lch;
6667 let a = null,
6668 b = null;
6669 if (!isNone(h)) {
6670 C = C < 0 ? 0 : C; // Clamp negative Chroma
6671 a = C * Math.cos(h * Math.PI / 180);
6672 b = C * Math.sin(h * Math.PI / 180);
6673 }
6674 return [L, a, b];
6675 },
6676 formats: {
6677 lch: {
6678 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
6679 }
6680 }
6681 });
6682
6683 // deltaE2000 is a statistically significant improvement
6684 // and is recommended by the CIE and Idealliance
6685 // especially for color differences less than 10 deltaE76
6686 // but is wicked complicated
6687 // and many implementations have small errors!
6688 // DeltaE2000 is also discontinuous; in case this
6689 // matters to you, use deltaECMC instead.
6690
6691 const Gfactor = 25 ** 7;
6692 const π$1 = Math.PI;
6693 const r2d = 180 / π$1;
6694 const d2r$1 = π$1 / 180;
6695 function pow7(x) {
6696 // Faster than x ** 7 or Math.pow(x, 7)
6697
6698 const x2 = x * x;
6699 const x7 = x2 * x2 * x2 * x;
6700 return x7;
6701 }
6702
6703 /**
6704 * @param {import("../types.js").ColorTypes} color
6705 * @param {import("../types.js").ColorTypes} sample
6706 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
6707 * @returns {number}
6708 */
6709 function deltaE2000 (color, sample, {
6710 kL = 1,
6711 kC = 1,
6712 kH = 1
6713 } = {}) {
6714 [color, sample] = getColor([color, sample]);
6715
6716 // Given this color as the reference
6717 // and the function parameter as the sample,
6718 // calculate deltaE 2000.
6719
6720 // This implementation assumes the parametric
6721 // weighting factors kL, kC and kH
6722 // for the influence of viewing conditions
6723 // are all 1, as sadly seems typical.
6724 // kL should be increased for lightness texture or noise
6725 // and kC increased for chroma noise
6726
6727 let [L1, a1, b1] = lab.from(color);
6728 let C1 = lch.from(lab, [L1, a1, b1])[1];
6729 let [L2, a2, b2] = lab.from(sample);
6730 let C2 = lch.from(lab, [L2, a2, b2])[1];
6731
6732 // Check for negative Chroma,
6733 // which might happen through
6734 // direct user input of LCH values
6735
6736 if (C1 < 0) {
6737 C1 = 0;
6738 }
6739 if (C2 < 0) {
6740 C2 = 0;
6741 }
6742 let Cbar = (C1 + C2) / 2; // mean Chroma
6743
6744 // calculate a-axis asymmetry factor from mean Chroma
6745 // this turns JND ellipses for near-neutral colors back into circles
6746 let C7 = pow7(Cbar);
6747 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
6748
6749 // scale a axes by asymmetry factor
6750 // this by the way is why there is no Lab2000 colorspace
6751 let adash1 = (1 + G) * a1;
6752 let adash2 = (1 + G) * a2;
6753
6754 // calculate new Chroma from scaled a and original b axes
6755 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
6756 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
6757
6758 // calculate new hues, with zero hue for true neutrals
6759 // and in degrees, not radians
6760
6761 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
6762 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
6763 if (h1 < 0) {
6764 h1 += 2 * π$1;
6765 }
6766 if (h2 < 0) {
6767 h2 += 2 * π$1;
6768 }
6769 h1 *= r2d;
6770 h2 *= r2d;
6771
6772 // Lightness and Chroma differences; sign matters
6773 let ΔL = L2 - L1;
6774 let ΔC = Cdash2 - Cdash1;
6775
6776 // Hue difference, getting the sign correct
6777 let hdiff = h2 - h1;
6778 let hsum = h1 + h2;
6779 let habs = Math.abs(hdiff);
6780 let Δh;
6781 if (Cdash1 * Cdash2 === 0) {
6782 Δh = 0;
6783 } else if (habs <= 180) {
6784 Δh = hdiff;
6785 } else if (hdiff > 180) {
6786 Δh = hdiff - 360;
6787 } else if (hdiff < -180) {
6788 Δh = hdiff + 360;
6789 } else {
6790 defaults.warn("the unthinkable has happened");
6791 }
6792
6793 // weighted Hue difference, more for larger Chroma
6794 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(Δh * d2r$1 / 2);
6795
6796 // calculate mean Lightness and Chroma
6797 let Ldash = (L1 + L2) / 2;
6798 let Cdash = (Cdash1 + Cdash2) / 2;
6799 let Cdash7 = pow7(Cdash);
6800
6801 // Compensate for non-linearity in the blue region of Lab.
6802 // Four possibilities for hue weighting factor,
6803 // depending on the angles, to get the correct sign
6804 let hdash;
6805 if (Cdash1 * Cdash2 === 0) {
6806 hdash = hsum; // which should be zero
6807 } else if (habs <= 180) {
6808 hdash = hsum / 2;
6809 } else if (hsum < 360) {
6810 hdash = (hsum + 360) / 2;
6811 } else {
6812 hdash = (hsum - 360) / 2;
6813 }
6814
6815 // positional corrections to the lack of uniformity of CIELAB
6816 // These are all trying to make JND ellipsoids more like spheres
6817
6818 // SL Lightness crispening factor
6819 // a background with L=50 is assumed
6820 let lsq = (Ldash - 50) ** 2;
6821 let SL = 1 + 0.015 * lsq / Math.sqrt(20 + lsq);
6822
6823 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
6824 let SC = 1 + 0.045 * Cdash;
6825
6826 // Cross term T for blue non-linearity
6827 let T = 1;
6828 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
6829 T += 0.24 * Math.cos(2 * hdash * d2r$1);
6830 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
6831 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
6832
6833 // SH Hue factor depends on Chroma,
6834 // as well as adjusted hue angle like deltaE94.
6835 let SH = 1 + 0.015 * Cdash * T;
6836
6837 // RT Hue rotation term compensates for rotation of JND ellipses
6838 // and Munsell constant hue lines
6839 // in the medium-high Chroma blue region
6840 // (Hue 225 to 315)
6841 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
6842 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
6843 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
6844
6845 // Finally calculate the deltaE, term by term as root sume of squares
6846 let dE = (ΔL / (kL * SL)) ** 2;
6847 dE += (ΔC / (kC * SC)) ** 2;
6848 dE += (ΔH / (kH * SH)) ** 2;
6849 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
6850 return Math.sqrt(dE);
6851 // Yay!!!
6852 }
6853
6854 /** @import { Matrix3x3 } from "../types.js" */
6855
6856 /**
6857 * Matrices used by this color space, also available as `Oklab.M`.
6858 * Recalculated for consistent reference white,
6859 * see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
6860 * @type {Record<string, Matrix3x3>}
6861 */
6862 // prettier-ignore
6863 const M$d = {
6864 XYZtoLMS: [[0.8190224379967030, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]],
6865 // inverse of XYZtoLMS
6866 LMStoXYZ: [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]],
6867 LMStoLab: [[0.2104542683093140, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]],
6868 // LMStoLab inverted
6869 LabtoLMS: [[1.0000000000000000, 0.3963377773761749, 0.2158037573099136], [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], [1.0000000000000000, -0.0894841775298119, -1.2914855480194092]]
6870 };
6871 var Oklab = new ColorSpace({
6872 id: "oklab",
6873 name: "Oklab",
6874 coords: {
6875 l: {
6876 refRange: [0, 1],
6877 name: "Lightness"
6878 },
6879 a: {
6880 refRange: [-0.4, 0.4]
6881 },
6882 b: {
6883 refRange: [-0.4, 0.4]
6884 }
6885 },
6886 // Note that XYZ is relative to D65
6887 white: "D65",
6888 base: XYZ_D65,
6889 M: M$d,
6890 fromBase(XYZ) {
6891 // move to LMS cone domain
6892 let LMS = multiply_v3_m3x3(XYZ, M$d.XYZtoLMS);
6893
6894 // non-linearity
6895 LMS[0] = Math.cbrt(LMS[0]);
6896 LMS[1] = Math.cbrt(LMS[1]);
6897 LMS[2] = Math.cbrt(LMS[2]);
6898 return multiply_v3_m3x3(LMS, M$d.LMStoLab, LMS);
6899 },
6900 toBase(OKLab) {
6901 // move to LMS cone domain
6902 let LMSg = multiply_v3_m3x3(OKLab, M$d.LabtoLMS);
6903
6904 // restore linearity
6905 LMSg[0] = LMSg[0] ** 3;
6906 LMSg[1] = LMSg[1] ** 3;
6907 LMSg[2] = LMSg[2] ** 3;
6908 return multiply_v3_m3x3(LMSg, M$d.LMStoXYZ, LMSg);
6909 },
6910 formats: {
6911 oklab: {
6912 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6913 }
6914 }
6915 });
6916
6917 /**
6918 * More accurate color-difference formulae
6919 * than the simple 1976 Euclidean distance in CIE Lab
6920 * @param {import("../types.js").ColorTypes} color
6921 * @param {import("../types.js").ColorTypes} sample
6922 * @returns {number}
6923 */
6924 function deltaEOK (color, sample) {
6925 [color, sample] = getColor([color, sample]);
6926
6927 // Given this color as the reference
6928 // and a sample,
6929 // calculate deltaEOK, term by term as root sum of squares
6930 let [L1, a1, b1] = Oklab.from(color);
6931 let [L2, a2, b2] = Oklab.from(sample);
6932 let ΔL = L1 - L2;
6933 let Δa = a1 - a2;
6934 let Δb = b1 - b2;
6935 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
6936 }
6937
6938 /** @import { ColorTypes } from "./types.js" */
6939
6940 const ε$5 = 0.000075;
6941
6942 /**
6943 * Check if a color is in gamut of either its own or another color space
6944 * @param {ColorTypes} color
6945 * @param {string | ColorSpace} [space]
6946 * @param {{ epsilon?: number | undefined }} [param2]
6947 * @returns {boolean}
6948 */
6949 function inGamut(color, space, {
6950 epsilon = ε$5
6951 } = {}) {
6952 color = getColor(color);
6953 if (!space) {
6954 space = color.space;
6955 }
6956 space = ColorSpace.get(space);
6957 let coords = color.coords;
6958 if (space !== color.space) {
6959 coords = space.from(color);
6960 }
6961 return space.inGamut(coords, {
6962 epsilon
6963 });
6964 }
6965
6966 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
6967
6968 /**
6969 * Convert to color space and return a new color
6970 * @param {ColorTypes} color
6971 * @param {string | ColorSpace} space
6972 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
6973 * @returns {PlainColorObject}
6974 */
6975 function to(color, space, {
6976 inGamut
6977 } = {}) {
6978 color = getColor(color);
6979 space = ColorSpace.get(space);
6980 let coords = space.from(color);
6981 let ret = {
6982 space,
6983 coords,
6984 alpha: color.alpha
6985 };
6986 if (inGamut) {
6987 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
6988 }
6989 return ret;
6990 }
6991
6992 /** @type {"color"} */
6993 to.returns = "color";
6994
6995 /** @import { ColorTypes, Coords } from "./types.js" */
6996
6997 /**
6998 * Options for {@link getAll}
6999 * @typedef GetAllOptions
7000 * @property {string | ColorSpace | undefined} [space]
7001 * The color space to convert to. Defaults to the color's current space
7002 * @property {number | undefined} [precision]
7003 * The number of significant digits to round the coordinates to
7004 */
7005
7006 /**
7007 * Get the coordinates of a color in any color space
7008 * @overload
7009 * @param {ColorTypes} color
7010 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
7011 * @returns {Coords} The color coordinates in the given color space
7012 */
7013 /**
7014 * @overload
7015 * @param {ColorTypes} color
7016 * @param {GetAllOptions} [options]
7017 * @returns {Coords} The color coordinates in the given color space
7018 */
7019 function getAll(color, options) {
7020 color = getColor(color);
7021 let space = ColorSpace.get(options, options === null || options === void 0 ? void 0 : options.space);
7022 let precision = options === null || options === void 0 ? void 0 : options.precision;
7023 let coords;
7024 if (!space || color.space.equals(space)) {
7025 // No conversion needed
7026 coords = color.coords.slice();
7027 } else {
7028 coords = space.from(color);
7029 }
7030 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
7031 }
7032
7033 /** @import { ColorTypes, Ref } from "./types.js" */
7034
7035 /**
7036 * @param {ColorTypes} color
7037 * @param {Ref} prop
7038 * @returns {number}
7039 */
7040 function get(color, prop) {
7041 color = getColor(color);
7042 if (prop === "alpha") {
7043 var _color$alpha;
7044 return (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : 1;
7045 }
7046 let {
7047 space,
7048 index
7049 } = ColorSpace.resolveCoord(prop, color.space);
7050 let coords = getAll(color, space);
7051 return coords[index];
7052 }
7053
7054 var OKLCH = new ColorSpace({
7055 id: "oklch",
7056 name: "OkLCh",
7057 coords: {
7058 l: {
7059 refRange: [0, 1],
7060 name: "Lightness"
7061 },
7062 c: {
7063 refRange: [0, 0.4],
7064 name: "Chroma"
7065 },
7066 h: {
7067 refRange: [0, 360],
7068 type: "angle",
7069 name: "Hue"
7070 }
7071 },
7072 white: "D65",
7073 base: Oklab,
7074 fromBase: lch.fromBase,
7075 toBase: lch.toBase,
7076 formats: {
7077 oklch: {
7078 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7079 }
7080 }
7081 });
7082
7083 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
7084
7085 /**
7086 * Set all coordinates of a color at once, in its own color space or another.
7087 * Modifies the color in place.
7088 * @overload
7089 * @param {ColorTypes} color
7090 * @param {Coords} coords Array of coordinates
7091 * @param {number} [alpha]
7092 * @returns {PlainColorObject}
7093 */
7094 /**
7095 * @overload
7096 * @param {ColorTypes} color
7097 * @param {string | ColorSpace} space The color space of the provided coordinates.
7098 * @param {Coords} coords Array of coordinates
7099 * @param {number} [alpha]
7100 * @returns {PlainColorObject}
7101 */
7102 function setAll(color, space, coords, alpha) {
7103 color = getColor(color);
7104 if (Array.isArray(space)) {
7105 // Space is omitted
7106 [space, coords, alpha] = [color.space, space, coords];
7107 }
7108 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
7109 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
7110 if (alpha !== undefined) {
7111 color.alpha = alpha;
7112 }
7113 return color;
7114 }
7115
7116 /** @type {"color"} */
7117 setAll.returns = "color";
7118
7119 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
7120
7121 /**
7122 * Set properties and return current instance
7123 * @overload
7124 * @param {ColorTypes} color
7125 * @param {Ref} prop
7126 * @param {number | ((coord: number) => number)} value
7127 * @returns {PlainColorObject}
7128 */
7129 /**
7130 * @overload
7131 * @param {ColorTypes} color
7132 * @param {Record<string, number | ((coord: number) => number)>} props
7133 * @returns {PlainColorObject}
7134 */
7135 function set(color, prop, value) {
7136 color = getColor(color);
7137 if (arguments.length === 2 && type(arguments[1]) === "object") {
7138 // Argument is an object literal
7139 let object = arguments[1];
7140 for (let p in object) {
7141 set(color, p, object[p]);
7142 }
7143 } else {
7144 if (typeof value === "function") {
7145 value = value(get(color, prop));
7146 }
7147 if (prop === "alpha") {
7148 color.alpha = value;
7149 } else {
7150 let {
7151 space,
7152 index
7153 } = ColorSpace.resolveCoord(prop, color.space);
7154 let coords = getAll(color, space);
7155 coords[index] = value;
7156 setAll(color, space, coords);
7157 }
7158 }
7159 return color;
7160 }
7161
7162 /** @type {"color"} */
7163 set.returns = "color";
7164
7165 /** @import { Coords, PlainColorObject } from "./types.js" */
7166
7167 /**
7168 * @param {PlainColorObject} color
7169 * @returns {PlainColorObject}
7170 */
7171 function clone(color) {
7172 return {
7173 space: color.space,
7174 coords: (/** @type {Coords} */color.coords.slice()),
7175 alpha: color.alpha
7176 };
7177 }
7178
7179 /** @import { ColorTypes } from "./types.js" */
7180
7181 /**
7182 * Euclidean distance of colors in an arbitrary color space
7183 * @param {ColorTypes} color1
7184 * @param {ColorTypes} color2
7185 * @param {string | ColorSpace} space
7186 * @returns {number}
7187 */
7188 function distance(color1, color2, space = "lab") {
7189 space = ColorSpace.get(space);
7190
7191 // Assume getColor() is called on color in space.from()
7192 let coords1 = space.from(color1);
7193 let coords2 = space.from(color2);
7194 return Math.sqrt(coords1.reduce((acc, c1, i) => {
7195 let c2 = coords2[i];
7196 if (isNone(c1) || isNone(c2)) {
7197 return acc;
7198 }
7199 return acc + (c2 - c1) ** 2;
7200 }, 0));
7201 }
7202
7203 /**
7204 * @param {import("../types.js").ColorTypes} color
7205 * @param {import("../types.js").ColorTypes} sample
7206 * @returns {number}
7207 */
7208 function deltaE76(color, sample) {
7209 // Assume getColor() is called in the distance function
7210 return distance(color, sample, "lab");
7211 }
7212
7213 // More accurate color-difference formulae
7214 // than the simple 1976 Euclidean distance in Lab
7215
7216 // CMC by the Color Measurement Committee of the
7217 // Bradford Society of Dyeists and Colorsts, 1994.
7218 // Uses LCH rather than Lab,
7219 // with different weights for L, C and H differences
7220 // A nice increase in accuracy for modest increase in complexity
7221 const π = Math.PI;
7222 const d2r = π / 180;
7223
7224 /**
7225 * @param {import("../types.js").ColorTypes} color
7226 * @param {import("../types.js").ColorTypes} sample
7227 * @param {{ l?: number | undefined; c?: number | undefined }} options
7228 * @returns {number}
7229 */
7230 function deltaECMC (color, sample, {
7231 l = 2,
7232 c = 1
7233 } = {}) {
7234 [color, sample] = getColor([color, sample]);
7235
7236 // Given this color as the reference
7237 // and a sample,
7238 // calculate deltaE CMC.
7239
7240 // This implementation assumes the parametric
7241 // weighting factors l:c are 2:1
7242 // which is typical for non-textile uses.
7243
7244 let [L1, a1, b1] = lab.from(color);
7245 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
7246 let [L2, a2, b2] = lab.from(sample);
7247 let C2 = lch.from(lab, [L2, a2, b2])[1];
7248
7249 // let [L1, a1, b1] = color.getAll(lab);
7250 // let C1 = color.get("lch.c");
7251 // let H1 = color.get("lch.h");
7252 // let [L2, a2, b2] = sample.getAll(lab);
7253 // let C2 = sample.get("lch.c");
7254
7255 // Check for negative Chroma,
7256 // which might happen through
7257 // direct user input of LCH values
7258
7259 if (C1 < 0) {
7260 C1 = 0;
7261 }
7262 if (C2 < 0) {
7263 C2 = 0;
7264 }
7265
7266 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
7267
7268 // Lightness and Chroma differences
7269 // These are (color - sample), unlike deltaE2000
7270 let ΔL = L1 - L2;
7271 let ΔC = C1 - C2;
7272 let Δa = a1 - a2;
7273 let Δb = b1 - b2;
7274
7275 // weighted Hue difference, less for larger Chroma difference
7276
7277 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
7278 // due to roundoff error it is possible that, for zero a and b,
7279 // ΔC > Δa + Δb is 0, resulting in attempting
7280 // to take the square root of a negative number
7281
7282 // trying instead the equation from Industrial Color Physics
7283 // By Georg A. Klein
7284
7285 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
7286 // console.log({ΔH});
7287 // This gives the same result to 12 decimal places
7288 // except it sometimes NaNs when trying to root a negative number
7289
7290 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
7291
7292 // positional corrections to the lack of uniformity of CIELAB
7293 // These are all trying to make JND ellipsoids more like spheres
7294
7295 // SL Lightness crispening factor, depends entirely on L1 not L2
7296 let SL = 0.511; // linear portion of the Y to L transfer function
7297 if (L1 >= 16) {
7298 // cubic portion
7299 SL = 0.040975 * L1 / (1 + 0.01765 * L1);
7300 }
7301
7302 // SC Chroma factor
7303 let SC = 0.0638 * C1 / (1 + 0.0131 * C1) + 0.638;
7304
7305 // Cross term T for blue non-linearity
7306 let T;
7307 if (isNone(H1)) {
7308 H1 = 0;
7309 }
7310 if (H1 >= 164 && H1 <= 345) {
7311 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
7312 } else {
7313 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
7314 }
7315 // console.log({T});
7316
7317 // SH Hue factor also depends on C1,
7318 let C4 = Math.pow(C1, 4);
7319 let F = Math.sqrt(C4 / (C4 + 1900));
7320 let SH = SC * (F * T + 1 - F);
7321
7322 // Finally calculate the deltaE, term by term as root sume of squares
7323 let dE = (ΔL / (l * SL)) ** 2;
7324 dE += (ΔC / (c * SC)) ** 2;
7325 dE += H2 / SH ** 2;
7326 // dE += (ΔH / SH) ** 2;
7327 return Math.sqrt(dE);
7328 // Yay!!!
7329 }
7330
7331 const Yw$1 = 203; // absolute luminance of media white
7332
7333 var XYZ_Abs_D65 = new ColorSpace({
7334 // Absolute CIE XYZ, with a D65 whitepoint,
7335 // as used in most HDR colorspaces as a starting point.
7336 // SDR spaces are converted per BT.2048
7337 // so that diffuse, media white is 203 cd/m²
7338 id: "xyz-abs-d65",
7339 cssId: "--xyz-abs-d65",
7340 name: "Absolute XYZ D65",
7341 coords: {
7342 x: {
7343 refRange: [0, 9504.7],
7344 name: "Xa"
7345 },
7346 y: {
7347 refRange: [0, 10000],
7348 name: "Ya"
7349 },
7350 z: {
7351 refRange: [0, 10888.3],
7352 name: "Za"
7353 }
7354 },
7355 base: XYZ_D65,
7356 fromBase(XYZ) {
7357 // Make XYZ absolute, not relative to media white
7358 // Maximum luminance in PQ is 10,000 cd/m²
7359 // Relative XYZ has Y=1 for media white
7360 return XYZ.map(v => v * Yw$1);
7361 },
7362 toBase(AbsXYZ) {
7363 // Convert to media-white relative XYZ
7364 return AbsXYZ.map(v => v / Yw$1);
7365 }
7366 });
7367
7368 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7369
7370 const b$1 = 1.15;
7371 const g = 0.66;
7372 const n$1 = 2610 / 2 ** 14;
7373 const ninv$1 = 2 ** 14 / 2610;
7374 const c1$2 = 3424 / 2 ** 12;
7375 const c2$2 = 2413 / 2 ** 7;
7376 const c3$2 = 2392 / 2 ** 7;
7377 const p$1 = 1.7 * 2523 / 2 ** 5;
7378 const pinv = 2 ** 5 / (1.7 * 2523);
7379 const d = -0.56;
7380 const d0 = 1.6295499532821566e-11;
7381
7382 /**
7383 * Matrices used by this color space, also available as `Jzazbz.M`
7384 * @type {Record<string, Matrix3x3>}
7385 */
7386 // prettier-ignore
7387 const M$c = {
7388 XYZtoCone: [[0.41478972, 0.579999, 0.0146480], [-0.2015100, 1.120649, 0.0531008], [-0.0166008, 0.264800, 0.6684799]],
7389 // XYZtoCone inverted
7390 ConetoXYZ: [[1.9242264357876067, -1.0047923125953657, 0.037651404030618], [0.35031676209499907, 0.7264811939316552, -0.06538442294808501], [-0.09098281098284752, -0.3127282905230739, 1.5227665613052603]],
7391 ConetoIab: [[0.5, 0.5, 0], [3.524000, -4.066708, 0.542708], [0.199076, 1.096799, -1.295875]],
7392 // ConetoIab inverted
7393 IabtoCone: [[1, 0.13860504327153927, 0.05804731615611883], [1, -0.1386050432715393, -0.058047316156118904], [1, -0.09601924202631895, -0.81189189605603900]]
7394 };
7395 var Jzazbz = new ColorSpace({
7396 id: "jzazbz",
7397 name: "Jzazbz",
7398 coords: {
7399 jz: {
7400 refRange: [0, 1],
7401 name: "Jz"
7402 },
7403 az: {
7404 refRange: [-0.21, 0.21]
7405 },
7406 bz: {
7407 refRange: [-0.21, 0.21]
7408 }
7409 },
7410 base: XYZ_Abs_D65,
7411 M: M$c,
7412 fromBase(XYZ) {
7413 // First make XYZ absolute, not relative to media white
7414 // Maximum luminance in PQ is 10,000 cd/m²
7415 // Relative XYZ has Y=1 for media white
7416 // BT.2048 says media white Y=203 at PQ 58
7417
7418 let [Xa, Ya, Za] = XYZ;
7419
7420 // modify X and Y to minimize blue curvature
7421 let Xm = b$1 * Xa - (b$1 - 1) * Za;
7422 let Ym = g * Ya - (g - 1) * Xa;
7423
7424 // move to LMS cone domain
7425 let LMS = multiply_v3_m3x3([Xm, Ym, Za], M$c.XYZtoCone);
7426
7427 // PQ-encode LMS
7428 let PQLMS = /** @type {Vector3} } */
7429 LMS.map(function (val) {
7430 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
7431 let denom = 1 + c3$2 * spow(val / 10000, n$1);
7432 return spow(num / denom, p$1);
7433 });
7434
7435 // almost there, calculate Iz az bz
7436 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, M$c.ConetoIab);
7437 // console.log({Iz, az, bz});
7438
7439 let Jz = (1 + d) * Iz / (1 + d * Iz) - d0;
7440 return [Jz, az, bz];
7441 },
7442 toBase(Jzazbz) {
7443 let [Jz, az, bz] = Jzazbz;
7444 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
7445
7446 // bring into LMS cone domain
7447 let PQLMS = multiply_v3_m3x3([Iz, az, bz], M$c.IabtoCone);
7448
7449 // convert from PQ-coded to linear-light
7450 let LMS = /** @type {Vector3} } */
7451 PQLMS.map(function (val) {
7452 let num = c1$2 - spow(val, pinv);
7453 let denom = c3$2 * spow(val, pinv) - c2$2;
7454 let x = 10000 * spow(num / denom, ninv$1);
7455 return x; // luminance relative to diffuse white, [0, 70 or so].
7456 });
7457
7458 // modified abs XYZ
7459 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, M$c.ConetoXYZ);
7460
7461 // un-modify X and Y to get D65 XYZ, relative to media white
7462 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
7463 let Ya = (Ym + (g - 1) * Xa) / g;
7464 return [Xa, Ya, Za];
7465 },
7466 formats: {
7467 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
7468 jzazbz: {
7469 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7470 }
7471 }
7472 });
7473
7474 var jzczhz = new ColorSpace({
7475 id: "jzczhz",
7476 name: "JzCzHz",
7477 coords: {
7478 jz: {
7479 refRange: [0, 1],
7480 name: "Jz"
7481 },
7482 cz: {
7483 refRange: [0, 0.26],
7484 name: "Chroma"
7485 },
7486 hz: {
7487 refRange: [0, 360],
7488 type: "angle",
7489 name: "Hue"
7490 }
7491 },
7492 base: Jzazbz,
7493 fromBase: lch.fromBase,
7494 toBase: lch.toBase,
7495 formats: {
7496 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
7497 jzczhz: {
7498 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7499 }
7500 }
7501 });
7502
7503 /**
7504 * More accurate color-difference formulae
7505 * than the simple 1976 Euclidean distance in Lab
7506 *
7507 * Uses JzCzHz, which has improved perceptual uniformity
7508 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
7509 * gives good results.
7510 * @param {import("../types.js").ColorTypes} color
7511 * @param {import("../types.js").ColorTypes} sample
7512 * @returns {number}
7513 */
7514 function deltaEJz (color, sample) {
7515 [color, sample] = getColor([color, sample]);
7516
7517 // Given this color as the reference
7518 // and a sample,
7519 // calculate deltaE in JzCzHz.
7520 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
7521 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
7522
7523 // Lightness and Chroma differences
7524 // sign does not matter as they are squared.
7525 let ΔJ = Jz1 - Jz2;
7526 let ΔC = Cz1 - Cz2;
7527
7528 // length of chord for ΔH
7529 if (isNone(Hz1) && isNone(Hz2)) {
7530 // both undefined hues
7531 Hz1 = 0;
7532 Hz2 = 0;
7533 } else if (isNone(Hz1)) {
7534 // one undefined, set to the defined hue
7535 Hz1 = Hz2;
7536 } else if (isNone(Hz2)) {
7537 Hz2 = Hz1;
7538 }
7539 let Δh = Hz1 - Hz2;
7540 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(Δh / 2 * (Math.PI / 180));
7541 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
7542 }
7543
7544 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7545
7546 const c1$1 = 3424 / 4096;
7547 const c2$1 = 2413 / 128;
7548 const c3$1 = 2392 / 128;
7549 const m1 = 2610 / 16384;
7550 const m2 = 2523 / 32;
7551 const im1 = 16384 / 2610;
7552 const im2 = 32 / 2523;
7553
7554 // Reference (rational-form) matrices, kept for documentation but not used directly:
7555 // linear-light Rec.2020 to LMS (with crosstalk) and its inverse
7556 // rational terms from Jan Fröhlich, Encoding High Dynamic Range
7557 // and Wide Color Gamut Imagery, p.97 and ITU-R BT.2124-0 pp.2-3
7558 /*
7559 const Rec2020toLMS = [
7560 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
7561 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
7562 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
7563 ];
7564 const LMStoRec2020 = [
7565 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
7566 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
7567 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
7568 ];
7569 */
7570
7571 /**
7572 * Matrices used by this color space, also available as `ICTCP.M`
7573 * @type {Record<string, Matrix3x3>}
7574 */
7575 // prettier-ignore
7576 const M$b = {
7577 // includes the 4% crosstalk components, from the Dolby "What is ICtCp" paper
7578 XYZtoLMS: [[0.3592832590121217, 0.6976051147779502, -0.0358915932320290], [-0.1920808463704993, 1.1004767970374321, 0.0753748658519118], [0.0070797844607479, 0.0748396662186362, 0.8433265453898765]],
7579 // includes the Ebner LMS coefficients, the rotation,
7580 // and the scaling to the [-0.5,0.5] range
7581 LMStoIPT: [[2048 / 4096, 2048 / 4096, 0], [6610 / 4096, -13613 / 4096, 7003 / 4096], [17933 / 4096, -17390 / 4096, -543 / 4096]],
7582 // inverted matrices, calculated from the above
7583 IPTtoLMS: [[0.9999999999999998, 0.0086090370379328, 0.1110296250030260], [0.9999999999999998, -0.0086090370379328, -0.1110296250030259], [0.9999999999999998, 0.5600313357106791, -0.3206271749873188]],
7584 LMStoXYZ: [[2.0701522183894223, -1.3263473389671563, 0.2066510476294053], [0.3647385209748072, 0.6805660249472273, -0.0453045459220347], [-0.0497472075358123, -0.0492609666966131, 1.1880659249923042]]
7585 };
7586
7587 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
7588 // from Dolby, "WHAT IS ICTCP?"
7589 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
7590 // and
7591 // Dolby, "Perceptual Color Volume
7592 // Measuring the Distinguishable Colors of HDR and WCG Displays"
7593 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
7594 var ictcp = new ColorSpace({
7595 id: "ictcp",
7596 name: "ICTCP",
7597 // From BT.2100-2 page 7:
7598 // During production, signal values are expected to exceed the
7599 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
7600 // signal degradation during cascaded processing. Such values of E′,
7601 // below 0.0 or exceeding 1.0, should not be clipped during production
7602 // and exchange.
7603 // Values below 0.0 should not be clipped in reference displays (even
7604 // though they represent “negative” light) to allow the black level of
7605 // the signal (LB) to be properly set using test signals known as “PLUGE”
7606 coords: {
7607 i: {
7608 refRange: [0, 1],
7609 // Constant luminance,
7610 name: "I"
7611 },
7612 ct: {
7613 refRange: [-0.5, 0.5],
7614 // Full BT.2020 gamut in range [-0.5, 0.5]
7615 name: "CT"
7616 },
7617 cp: {
7618 refRange: [-0.5, 0.5],
7619 name: "CP"
7620 }
7621 },
7622 base: XYZ_Abs_D65,
7623 M: M$b,
7624 fromBase(XYZ) {
7625 // move to LMS cone domain
7626 let LMS = multiply_v3_m3x3(XYZ, M$b.XYZtoLMS);
7627 return LMStoICtCp(LMS);
7628 },
7629 toBase(ICtCp) {
7630 let LMS = ICtCptoLMS(ICtCp);
7631 return multiply_v3_m3x3(LMS, M$b.LMStoXYZ);
7632 },
7633 formats: {
7634 ictcp: {
7635 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7636 }
7637 }
7638 });
7639
7640 /**
7641 *
7642 * @param {Vector3} LMS
7643 * @returns {Vector3}
7644 */
7645 function LMStoICtCp(LMS) {
7646 // apply the PQ EOTF
7647 // we can't ever be dividing by zero because of the "1 +" in the denominator
7648 let PQLMS = /** @type {Vector3} */
7649 LMS.map(function (val) {
7650 let num = c1$1 + c2$1 * (val / 10000) ** m1;
7651 let denom = 1 + c3$1 * (val / 10000) ** m1;
7652 return (num / denom) ** m2;
7653 });
7654
7655 // LMS to IPT, with rotation for Y'C'bC'r compatibility
7656 return multiply_v3_m3x3(PQLMS, M$b.LMStoIPT);
7657 }
7658
7659 /**
7660 *
7661 * @param {Vector3} ICtCp
7662 * @returns {Vector3}
7663 */
7664 function ICtCptoLMS(ICtCp) {
7665 let PQLMS = multiply_v3_m3x3(ICtCp, M$b.IPTtoLMS);
7666
7667 // From BT.2124-0 Annex 2 Conversion 3
7668 let LMS = /** @type {Vector3} */
7669 PQLMS.map(function (val) {
7670 let num = Math.max(val ** im2 - c1$1, 0);
7671 let denom = c2$1 - c3$1 * val ** im2;
7672 return 10000 * (num / denom) ** im1;
7673 });
7674 return LMS;
7675 }
7676
7677 /**
7678 * Delta E in ICtCp space,
7679 * which the ITU calls Delta E ITP, which is shorter.
7680 * Formulae from ITU Rec. ITU-R BT.2124-0
7681 * @param {import("../types.js").ColorTypes} color
7682 * @param {import("../types.js").ColorTypes} sample
7683 * @returns {number}
7684 */
7685 function deltaEITP (color, sample) {
7686 [color, sample] = getColor([color, sample]);
7687
7688 // Given this color as the reference
7689 // and a sample,
7690 // calculate deltaE in ICtCp
7691 // which is simply the Euclidean distance
7692
7693 let [I1, T1, P1] = ictcp.from(color);
7694 let [I2, T2, P2] = ictcp.from(sample);
7695
7696 // the 0.25 factor is to undo the encoding scaling in Ct
7697 // the 720 is so that 1 deltaE = 1 JND
7698 // per ITU-R BT.2124-0 p.3
7699
7700 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
7701 }
7702
7703 /**
7704 * More accurate color-difference formulae
7705 * than the simple 1976 Euclidean distance in CIE Lab
7706 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
7707 * Björn Ottosson said:
7708 * "I've recently done some tests with color distance datasets as implemented
7709 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
7710 * scale factor of slightly more than 2 for a and b would give the best results
7711 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
7712 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
7713 * @param {import("../types.js").ColorTypes} color
7714 * @param {import("../types.js").ColorTypes} sample
7715 * @returns {number}
7716 */
7717 function deltaEOK2 (color, sample) {
7718 [color, sample] = getColor([color, sample]);
7719
7720 // Given this color as the reference
7721 // and a sample,
7722 // calculate deltaEOK2, term by term as root sum of squares
7723 let abscale = 2;
7724 let [L1, a1, b1] = Oklab.from(color);
7725 let [L2, a2, b2] = Oklab.from(sample);
7726 let ΔL = L1 - L2;
7727 let Δa = abscale * (a1 - a2);
7728 let Δb = abscale * (b1 - b2);
7729 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
7730 }
7731
7732 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
7733
7734 // Type re-exports
7735 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
7736 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
7737 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
7738
7739 const white$3 = WHITES.D65;
7740 const adaptedCoef = 0.42;
7741 const adaptedCoefInv = 1 / adaptedCoef;
7742 const tau$1 = 2 * Math.PI;
7743
7744 /**
7745 * Matrices used by this color space, also available as `CAM16_JMh.M`
7746 * @type {Record<string, Matrix3x3>}
7747 */
7748 // prettier-ignore
7749 const M$a = {
7750 cat16: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
7751 cat16Inv: [[1.8620678550872327, -1.0112546305316843, 0.14918677544445175], [0.38752654323613717, 0.6214474419314753, -0.008973985167612518], [-0.015841498849333856, -0.03412293802851557, 1.0499644368778496]],
7752 m1: [[460.0, 451.0, 288.0], [460.0, -891.0, -261.0], [460.0, -220.0, -6300.0]]
7753 };
7754 const surroundMap = {
7755 dark: [0.8, 0.525, 0.8],
7756 dim: [0.9, 0.59, 0.9],
7757 average: [1, 0.69, 1]
7758 };
7759 const hueQuadMap = {
7760 // Red, Yellow, Green, Blue, Red
7761 h: [20.14, 90.0, 164.25, 237.53, 380.14],
7762 e: [0.8, 0.7, 1.0, 1.2, 0.8],
7763 H: [0.0, 100.0, 200.0, 300.0, 400.0]
7764 };
7765 const rad2deg = 180 / Math.PI;
7766 const deg2rad$1 = Math.PI / 180;
7767
7768 /**
7769 * @param {Coords} coords
7770 * @param {number} fl
7771 * @returns {[number, number, number]}
7772 */
7773 function adapt$1(coords, fl) {
7774 const temp = /** @type {[number, number, number]} */
7775 coords.map(c => {
7776 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
7777 return 400 * copySign(x, c) / (x + 27.13);
7778 });
7779 return temp;
7780 }
7781
7782 /**
7783 * @param {Coords} adapted
7784 * @param {number} fl
7785 * @returns {[number, number, number]}
7786 */
7787 function unadapt(adapted, fl) {
7788 const constant = 100 / fl * 27.13 ** adaptedCoefInv;
7789 return /** @type {[number, number, number]} */adapted.map(c => {
7790 const cabs = Math.abs(c);
7791 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
7792 });
7793 }
7794
7795 /**
7796 * @param {number} h
7797 */
7798 function hueQuadrature(h) {
7799 let hp = constrain(h);
7800 if (hp <= hueQuadMap.h[0]) {
7801 hp += 360;
7802 }
7803 const i = bisectLeft(hueQuadMap.h, hp) - 1;
7804 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
7805 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
7806 const Hi = hueQuadMap.H[i];
7807 const t = (hp - hi) / ei;
7808 return Hi + 100 * t / (t + (hii - hp) / eii);
7809 }
7810
7811 /**
7812 * @param {number} H
7813 */
7814 function invHueQuadrature(H) {
7815 let Hp = (H % 400 + 400) % 400;
7816 const i = Math.floor(0.01 * Hp);
7817 Hp = Hp % 100;
7818 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
7819 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
7820 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
7821 }
7822
7823 /**
7824 * @param {[number, number, number]} refWhite
7825 * @param {number} adaptingLuminance
7826 * @param {number} backgroundLuminance
7827 * @param {keyof typeof surroundMap} surround
7828 * @param {boolean} discounting
7829 * @returns {Cam16Environment}
7830 */
7831 function environment(refWhite, adaptingLuminance, backgroundLuminance, surround, discounting) {
7832 const env = {};
7833 env.discounting = discounting;
7834 env.refWhite = refWhite;
7835 env.surround = surround;
7836 const xyzW = /** @type {Vector3} */
7837 refWhite.map(c => {
7838 return c * 100;
7839 });
7840
7841 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
7842 env.la = adaptingLuminance;
7843 // The relative luminance of the nearby background
7844 env.yb = backgroundLuminance;
7845 // Absolute luminance of the reference white.
7846 const yw = xyzW[1];
7847
7848 // Cone response for reference white
7849 const rgbW = multiply_v3_m3x3(xyzW, M$a.cat16);
7850
7851 // Surround: dark, dim, and average
7852 let values = surroundMap[env.surround];
7853 const f = values[0];
7854 env.c = values[1];
7855 env.nc = values[2];
7856 const k = 1 / (5 * env.la + 1);
7857 const k4 = k ** 4;
7858
7859 // Factor of luminance level adaptation
7860 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
7861 env.flRoot = env.fl ** 0.25;
7862 env.n = env.yb / yw;
7863 env.z = 1.48 + Math.sqrt(env.n);
7864 env.nbb = 0.725 * env.n ** -0.2;
7865 env.ncb = env.nbb;
7866
7867 // Degree of adaptation calculating if not discounting
7868 // illuminant (assumed eye is fully adapted)
7869 const d = Math.max(Math.min(f * (1 - 1 / 3.6 * Math.exp((-env.la - 42) / 92)), 1), 0);
7870 env.dRgb = /** @type {[number, number, number]} */
7871 rgbW.map(c => {
7872 return interpolate(1, yw / c, d);
7873 });
7874 env.dRgbInv = /** @type {[number, number, number]} */
7875 env.dRgb.map(c => {
7876 return 1 / c;
7877 });
7878
7879 // Achromatic response
7880 const rgbCW = /** @type {[number, number, number]} */
7881 rgbW.map((c, i) => {
7882 return c * env.dRgb[i];
7883 });
7884 const rgbAW = adapt$1(rgbCW, env.fl);
7885 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
7886
7887 // console.log(env);
7888
7889 return env;
7890 }
7891
7892 // Pre-calculate everything we can with the viewing conditions
7893 const viewingConditions$1 = environment(white$3, 64 / Math.PI * 0.2, 20, "average", false);
7894
7895 /**
7896 * @param {Cam16Input} cam16
7897 * @param {Cam16Environment} env
7898 * @returns {[number, number, number]}
7899 */
7900 function fromCam16(cam16, env) {
7901 // These check ensure one, and only one attribute for a
7902 // given category is provided.
7903 // @ts-expect-error The '^` operator is not allowed for boolean types
7904 if (!(cam16.J !== undefined ^ cam16.Q !== undefined)) {
7905 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
7906 }
7907
7908 // @ts-expect-error - The '^` operator is not allowed for boolean types
7909 if (!(cam16.C !== undefined ^ cam16.M !== undefined ^ cam16.s !== undefined)) {
7910 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
7911 }
7912
7913 // Hue is absolutely required
7914 // @ts-expect-error - The '^` operator is not allowed for boolean types
7915 if (!(cam16.h !== undefined ^ cam16.H !== undefined)) {
7916 throw new Error("Conversion requires one and only one: 'h' or 'H'");
7917 }
7918
7919 // Black
7920 if (cam16.J === 0.0 || cam16.Q === 0.0) {
7921 return [0.0, 0.0, 0.0];
7922 }
7923
7924 // Break hue into Cartesian components
7925 let hRad = 0.0;
7926 if (cam16.h !== undefined) {
7927 hRad = constrain(cam16.h) * deg2rad$1;
7928 } else {
7929 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
7930 }
7931 const cosh = Math.cos(hRad);
7932 const sinh = Math.sin(hRad);
7933
7934 // Calculate `Jroot` from one of the lightness derived coordinates.
7935 let Jroot = 0.0;
7936 if (cam16.J !== undefined) {
7937 Jroot = spow(cam16.J, 1 / 2) * 0.1;
7938 } else if (cam16.Q !== undefined) {
7939 Jroot = 0.25 * env.c * cam16.Q / ((env.aW + 4) * env.flRoot);
7940 }
7941
7942 // Calculate the `t` value from one of the chroma derived coordinates
7943 let alpha = 0.0;
7944 if (cam16.C !== undefined) {
7945 alpha = cam16.C / Jroot;
7946 } else if (cam16.M !== undefined) {
7947 alpha = cam16.M / env.flRoot / Jroot;
7948 } else if (cam16.s !== undefined) {
7949 alpha = 0.0004 * cam16.s ** 2 * (env.aW + 4) / env.c;
7950 }
7951 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
7952
7953 // Eccentricity
7954 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
7955
7956 // Achromatic response
7957 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
7958
7959 // Calculate red-green and yellow-blue components
7960 const p1 = 5e4 / 13 * env.nc * env.ncb * et;
7961 const p2 = A / env.nbb;
7962 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
7963 const a = r * cosh;
7964 const b = r * sinh;
7965
7966 // Calculate back from cone response to XYZ
7967 const rgb_c = unadapt(/** @type {Vector3} */
7968
7969 multiply_v3_m3x3([p2, a, b], M$a.m1).map(c => {
7970 return c * 1 / 1403;
7971 }), env.fl);
7972 return /** @type {Vector3} */multiply_v3_m3x3(/** @type {Vector3} */
7973 rgb_c.map((c, i) => {
7974 return c * env.dRgbInv[i];
7975 }), M$a.cat16Inv).map(c => {
7976 return c / 100;
7977 });
7978 }
7979
7980 /**
7981 * @param {[number, number, number]} xyzd65
7982 * @param {Cam16Environment} env
7983 * @returns {Cam16Object}
7984 */
7985 function toCam16(xyzd65, env) {
7986 // Cone response
7987 const xyz100 = /** @type {Vector3} */
7988 xyzd65.map(c => {
7989 return c * 100;
7990 });
7991 const rgbA = adapt$1(/** @type {[number, number, number]} */
7992
7993 multiply_v3_m3x3(xyz100, M$a.cat16).map((c, i) => {
7994 return c * env.dRgb[i];
7995 }), env.fl);
7996
7997 // Calculate hue from red-green and yellow-blue components
7998 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
7999 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
8000 const hRad = (Math.atan2(b, a) % tau$1 + tau$1) % tau$1;
8001
8002 // Eccentricity
8003 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
8004 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);
8005 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
8006
8007 // Achromatic response
8008 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
8009 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
8010
8011 // Lightness
8012 const J = 100 * spow(Jroot, 2);
8013
8014 // Brightness
8015 const Q = 4 / env.c * Jroot * (env.aW + 4) * env.flRoot;
8016
8017 // Chroma
8018 const C = alpha * Jroot;
8019
8020 // Colorfulness
8021 const colorfulness = C * env.flRoot;
8022
8023 // Hue
8024 const h = constrain(hRad * rad2deg);
8025
8026 // Hue quadrature
8027 const H = hueQuadrature(h);
8028
8029 // Saturation
8030 const s = 50 * spow(env.c * alpha / (env.aW + 4), 1 / 2);
8031
8032 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H});
8033
8034 return {
8035 J: J,
8036 C: C,
8037 h: h,
8038 s: s,
8039 Q: Q,
8040 M: colorfulness,
8041 H: H
8042 };
8043 }
8044
8045 // Provided as a way to directly evaluate the CAM16 model
8046 // https://observablehq.com/@jrus/cam16: reference implementation
8047 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
8048 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
8049 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
8050 // Results compared against: https://github.com/colour-science/colour
8051 var cam16 = new ColorSpace({
8052 id: "cam16-jmh",
8053 cssId: "--cam16-jmh",
8054 name: "CAM16-JMh",
8055 coords: {
8056 j: {
8057 refRange: [0, 100],
8058 name: "J"
8059 },
8060 m: {
8061 refRange: [0, 105.0],
8062 name: "Colorfulness"
8063 },
8064 h: {
8065 refRange: [0, 360],
8066 type: "angle",
8067 name: "Hue"
8068 }
8069 },
8070 base: XYZ_D65,
8071 M: M$a,
8072 fromBase(xyz) {
8073 // If another derivation is created, ε could vary, so we can't hardcode
8074 if (this.ε === undefined) {
8075 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8076 }
8077 const cam16 = toCam16(xyz, viewingConditions$1);
8078 const isAchromatic = Math.abs(cam16.M) < this.ε;
8079 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
8080 },
8081 toBase(cam16) {
8082 return fromCam16({
8083 J: cam16[0],
8084 M: cam16[1],
8085 h: cam16[2]
8086 }, viewingConditions$1);
8087 }
8088 });
8089
8090 const white$2 = WHITES.D65;
8091 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
8092 const κ$3 = 24389 / 27; // 29^3/3^3
8093
8094 function toLstar(y) {
8095 // Convert XYZ Y to L*
8096
8097 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
8098 return 116.0 * fy - 16.0;
8099 }
8100 function fromLstar(lstar) {
8101 // Convert L* back to XYZ Y
8102
8103 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
8104 }
8105 function fromHct(coords, env) {
8106 // Use Newton's method to try and converge as quick as possible or
8107 // converge as close as we can. While the requested precision is achieved
8108 // most of the time, it may not always be achievable. Especially past the
8109 // visible spectrum, the algorithm will likely struggle to get the same
8110 // precision. If, for whatever reason, we cannot achieve the accuracy we
8111 // seek in the allotted iterations, just return the closest we were able to
8112 // get.
8113
8114 let [h, c, t] = coords;
8115 let xyz = [];
8116 let j = 0;
8117
8118 // Shortcut out for black
8119 if (t === 0) {
8120 return [0.0, 0.0, 0.0];
8121 }
8122
8123 // Calculate the Y we need to target
8124 let y = fromLstar(t);
8125
8126 // A better initial guess yields better results. Polynomials come from
8127 // curve fitting the T vs J response.
8128 if (t > 0) {
8129 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
8130 } else {
8131 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
8132 }
8133
8134 // Threshold of how close is close enough, and max number of attempts.
8135 // More precision and more attempts means more time spent iterating. Higher
8136 // required precision gives more accuracy but also increases the chance of
8137 // not hitting the goal. 2e-12 allows us to convert round trip with
8138 // reasonable accuracy of six decimal places or more.
8139 const threshold = 2e-12;
8140 const max_attempts = 15;
8141 let attempt = 0;
8142 let last = Infinity;
8143 let best = [0, 0, 0];
8144
8145 // Try to find a J such that the returned y matches the returned y of the L*
8146 while (attempt <= max_attempts) {
8147 xyz = fromCam16({
8148 J: j,
8149 C: c,
8150 h: h
8151 }, env);
8152
8153 // If we are within range, return XYZ
8154 // If we are closer than last time, save the values
8155 const delta = Math.abs(xyz[1] - y);
8156 if (delta < last) {
8157 if (delta <= threshold) {
8158 return xyz;
8159 }
8160 best = xyz;
8161 last = delta;
8162 }
8163
8164 // f(j_root) = (j ** (1 / 2)) * 0.1
8165 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
8166 // f(j_root) = Y = y / 100
8167 // f(j) = (y ** 2) / j - 1
8168 // f'(j) = (2 * y) / j
8169 j = j - (xyz[1] - y) * j / (2 * xyz[1]);
8170 attempt += 1;
8171 }
8172
8173 // We could not acquire the precision we desired,
8174 // return our closest attempt.
8175 return best;
8176 }
8177 function toHct(xyz, env) {
8178 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
8179
8180 const t = toLstar(xyz[1]);
8181 if (t === 0.0) {
8182 return [0.0, 0.0, 0.0];
8183 }
8184 const cam16 = toCam16(xyz, viewingConditions);
8185 return [constrain(cam16.h), cam16.C, t];
8186 }
8187
8188 // Pre-calculate everything we can with the viewing conditions
8189 const viewingConditions = environment(white$2, 200 / Math.PI * fromLstar(50.0), fromLstar(50.0) * 100, "average", false);
8190
8191 // https://material.io/blog/science-of-color-design
8192 // This is not a port of the material-color-utilities,
8193 // but instead implements the full color space as described,
8194 // combining CAM16 JCh and Lab D65. This does not clamp conversion
8195 // to HCT to specific chroma bands and provides support for wider
8196 // gamuts than Google currently supports and does so at a greater
8197 // precision (> 8 bits back to sRGB).
8198 // This implementation comes from https://github.com/facelessuser/coloraide
8199 // which is licensed under MIT.
8200 var hct = new ColorSpace({
8201 id: "hct",
8202 name: "HCT",
8203 coords: {
8204 h: {
8205 refRange: [0, 360],
8206 type: "angle",
8207 name: "Hue"
8208 },
8209 c: {
8210 refRange: [0, 145],
8211 name: "Colorfulness"
8212 },
8213 t: {
8214 refRange: [0, 100],
8215 name: "Tone"
8216 }
8217 },
8218 base: XYZ_D65,
8219 fromBase(xyz) {
8220 if (this.ε === undefined) {
8221 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8222 }
8223 let hct = toHct(xyz);
8224 if (hct[1] < this.ε) {
8225 hct[1] = 0.0;
8226 hct[0] = null;
8227 }
8228 return hct;
8229 },
8230 toBase(hct) {
8231 return fromHct(hct, viewingConditions);
8232 },
8233 formats: {
8234 color: {
8235 id: "--hct",
8236 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
8237 }
8238 }
8239 });
8240
8241 const deg2rad = Math.PI / 180;
8242 const ucsCoeff = [1.0, 0.007, 0.0228];
8243
8244 /**
8245 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
8246 * @param {Coords} coords - HCT coordinates.
8247 * @return {number[]}
8248 */
8249 function convertUcsAb(coords) {
8250 // We want the distance between the actual color.
8251 // If chroma is negative, it will throw off our calculations.
8252 // Normally, converting back to the base and forward will correct it.
8253 // If we have a negative chroma after this, then we have a color that
8254 // cannot resolve to positive chroma.
8255 if (coords[1] < 0) {
8256 coords = hct.fromBase(hct.toBase(coords));
8257 }
8258
8259 // Only in extreme cases (usually outside the visible spectrum)
8260 // can the input value for log become negative.
8261 // Avoid domain error by forcing a zero result via "max" if necessary.
8262 const M = Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / ucsCoeff[2];
8263 const hrad = coords[0] * deg2rad;
8264 const a = M * Math.cos(hrad);
8265 const b = M * Math.sin(hrad);
8266 return [coords[2], a, b];
8267 }
8268
8269 /**
8270 * Color distance using HCT.
8271 * @param {import("../types.js").ColorTypes} color
8272 * @param {import("../types.js").ColorTypes} sample
8273 * @returns {number}
8274 */
8275 function deltaEHCT (color, sample) {
8276 [color, sample] = getColor([color, sample]);
8277 let [t1, a1, b1] = convertUcsAb(hct.from(color));
8278 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
8279
8280 // Use simple euclidean distance with a and b using UCS conversion
8281 // and LCh lightness (HCT tone).
8282 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
8283 }
8284
8285 /**
8286 * Helmlab MetricSpace — 13-stage perceptual color space.
8287 *
8288 * A data-driven analytical color space fit on COMBVD (3,813 paired human
8289 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
8290 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
8291 * color space `helmlab-metric` for inspectability. Its coordinate system
8292 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
8293 * from origin) is shaped for ΔE accuracy rather than author-facing
8294 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
8295 *
8296 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
8297 *
8298 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
8299 * → hue-dep chroma scale → chroma power → L-dep chroma scale
8300 * → HLC interaction → hue-dep lightness → rotation
8301 *
8302 * Reference: arXiv:2602.23010
8303 * @see https://github.com/Grkmyldz148/helmlab
8304 */
8305
8306 /** @import { Matrix3x3 } from "../types.js" */
8307
8308 const {
8309 cos,
8310 sin,
8311 sqrt,
8312 atan2,
8313 exp,
8314 abs,
8315 pow,
8316 PI
8317 } = Math;
8318
8319 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
8320 /** @type {Matrix3x3} */
8321 // prettier-ignore
8322 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]];
8323
8324 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
8325 /** @type {Matrix3x3} */
8326 // prettier-ignore
8327 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]];
8328
8329 // ── Utility functions ──────────────────────────────────────────────
8330
8331 // ── Core parameters (v21, 72 params) ──────────────────────────────
8332
8333 /** @type {Matrix3x3} */
8334 // prettier-ignore
8335 const M1 = [[0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], [-0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], [-0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842]];
8336 /** @type {Matrix3x3} */
8337 // prettier-ignore
8338 const M1_INV = [[1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], [0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], [-0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399]];
8339 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
8340 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
8341
8342 /** @type {Matrix3x3} */
8343 // prettier-ignore
8344 const M2 = [[-0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], [1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], [0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967]];
8345 /** @type {Matrix3x3} */
8346 // prettier-ignore
8347 const M2_INV = [[0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], [1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], [1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097]];
8348
8349 /** Matrices used by this color space, also available as `Helmlab.M` */
8350 const M$9 = {
8351 CAT_TO_HELM,
8352 CAT_FROM_HELM,
8353 M1,
8354 M1_INV,
8355 M2,
8356 M2_INV
8357 };
8358
8359 // Enrichment parameters
8360 const hue_cos1 = -0.02833024015436984,
8361 hue_sin1 = -0.21131429516166544;
8362 const hue_cos2 = 0.2189784817615645,
8363 hue_sin2 = -0.06871898981942523;
8364 const hue_cos3 = 0.005506053349515315,
8365 hue_sin3 = -0.0641329861299175;
8366 const hue_cos4 = -0.053592461436994296,
8367 hue_sin4 = -0.00954137464208059;
8368 const hk_weight = 0.2676231133101982,
8369 hk_power = 0.8934892185255707;
8370 const hk_hue_mod = 0.7173169828841472;
8371 const hk_sin1 = 0.6915224124600773,
8372 hk_cos2 = 0.48647127559605596,
8373 hk_sin2 = 0.9853124591201782;
8374 const L_corr_p1 = 0.5385456675962418,
8375 L_corr_p2 = 0.12508858146241716,
8376 L_corr_p3 = 0.6768950256217603;
8377 const Lh_cos1 = -0.4963251525324449,
8378 Lh_sin1 = -0.09564696283240552;
8379 const lp_dark = -0.029053748937210654,
8380 lp_dark_hcos = 1.3346761652952872,
8381 lp_dark_hsin = -0.1698908144723919;
8382 const cs_cos1 = -0.195370576218515,
8383 cs_sin1 = 0.5330819227283227;
8384 const cs_cos2 = 0.08863325582067766,
8385 cs_sin2 = 0.9365540137751136;
8386 const cs_cos3 = 0.13789738139719568,
8387 cs_sin3 = 0.061650260197979936;
8388 const cs_cos4 = 0.0641970862504494,
8389 cs_sin4 = -0.027401052793571013;
8390 const cp_cos1 = -0.09900209889026965,
8391 cp_sin1 = 0.059635520647228726;
8392 const cp_cos2 = -0.013586499967803128,
8393 cp_sin2 = 0.2253393118474472;
8394 const lc1 = -1.5239477450767043,
8395 lc2 = -1.751157310240011;
8396 const hlc_cos1 = -0.43576378069144767,
8397 hlc_sin1 = 1.060094063845983;
8398 const hlc_cos2 = 0.47931193034584496,
8399 hlc_sin2 = -0.2622579649434462;
8400 const hl_cos1 = 0.13610794232685908,
8401 hl_sin1 = 0.1168702235362288;
8402 const hl_cos2 = -0.01617739641422492,
8403 hl_sin2 = 0.038145638815030566;
8404
8405 // Rigid rotation φ = −28.2°
8406 const PHI = -28.2 * PI / 180;
8407 const ROT_COS = cos(PHI);
8408 const ROT_SIN = sin(PHI);
8409
8410 // ── Pipeline helper functions ──────────────────────────────────────
8411
8412 function hueDelta(h) {
8413 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);
8414 }
8415 function hueDeltaDeriv(h) {
8416 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);
8417 }
8418 function chromaScaleH(h) {
8419 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);
8420 return exp(logS);
8421 }
8422 function lChromaScale(L) {
8423 let dL = L - 0.5;
8424 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
8425 }
8426 function hlcScale(h, L) {
8427 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
8428 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
8429 }
8430 function hueLightnessScale(h) {
8431 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
8432 return exp(logS);
8433 }
8434 function chromaPowerH(h) {
8435 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
8436 }
8437 function lCorrectFwd(L, h) {
8438 let t = L * (1 - L);
8439 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
8440 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
8441 return result;
8442 }
8443 function lCorrectInv(L1, h) {
8444 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
8445 let L = L1;
8446 for (let i = 0; i < 15; i++) {
8447 let t = L * (1 - L);
8448 let dt = 1 - 2 * L;
8449 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t - L1;
8450 let dfdL = 1 + (L_corr_p1 + Lh) * dt + L_corr_p2 * (dt * (0.5 - L) - t) + L_corr_p3 * 2 * t * dt;
8451 if (abs(dfdL) < 1e-10) {
8452 dfdL = 1;
8453 }
8454 L -= f / dfdL;
8455 }
8456 return L;
8457 }
8458 function darkLFwd(L, h) {
8459 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8460 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
8461 let g = coeff * L * oml * oml;
8462 return L * exp(clamp(-30, g, 30));
8463 }
8464 function darkLInv(Ln, h) {
8465 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8466 let L = Ln;
8467 for (let i = 0; i < 12; i++) {
8468 let oml = L < 1 ? 1 - L : 0;
8469 let g = coeff * L * oml * oml;
8470 let eg = exp(clamp(-30, g, 30));
8471 let f = L * eg - Ln;
8472 let gp = coeff * oml * (1 - 3 * L);
8473 let fp = eg * (1 + L * gp);
8474 if (abs(fp) < 1e-10) {
8475 fp = 1;
8476 }
8477 L -= f / fp;
8478 }
8479 return L;
8480 }
8481
8482 // ── Color space definition ─────────────────────────────────────────
8483 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
8484 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
8485 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
8486 // not author convenience. As a result:
8487 // - the ab plane is asymmetric (the metric was fit to directionally
8488 // asymmetric human discrimination thresholds);
8489 // - the L axis exceeds 1 for highly chromatic colors because the
8490 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
8491 // appear brighter than equiluminant neutrals);
8492 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
8493 // slightly off-origin in this coordinate system. Distance is
8494 // translation-invariant, so this does not affect ΔE quality.
8495 //
8496 // For CSS-author-facing color authoring (palettes, gradients, gamut
8497 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
8498 // is exposed primarily so the metric forward is inspectable for
8499 // debugging, color-science exploration, and as the internal forward used
8500 // by `deltaEHelmlab`.
8501
8502 const fromXYZ = function (xyz) {
8503 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
8504 let adapted = multiply_v3_m3x3(xyz, M$9.CAT_TO_HELM);
8505
8506 // Stage 1: XYZ → LMS (M1)
8507 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M$9.M1);
8508
8509 // Stage 2: Power compression (signed)
8510 let c0 = spow(lms0, GAMMA[0]);
8511 let c1 = spow(lms1, GAMMA[1]);
8512 let c2 = spow(lms2, GAMMA[2]);
8513
8514 // Stage 3: LMS_c → Lab_raw (M2)
8515 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$9.M2);
8516
8517 // Stage 3.5: Hue correction (4-harmonic Fourier)
8518 let h = atan2(b, a);
8519 let C = sqrt(a * a + b * b);
8520 let delta = hueDelta(h);
8521 let hNew = h + delta;
8522 a = C * cos(hNew);
8523 b = C * sin(hNew);
8524
8525 // Stage 3.7: Helmholtz-Kohlrausch correction
8526 let Cr = sqrt(a * a + b * b);
8527 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8528 let hr = atan2(b, a);
8529 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8530 L += hkBoost * factor;
8531
8532 // Stage 4: Cubic L correction (with hue modulation)
8533 h = atan2(b, a);
8534 L = lCorrectFwd(L, h);
8535
8536 // Stage 4.5: Dark L compression
8537 h = atan2(b, a);
8538 L = darkLFwd(L, h);
8539
8540 // Stage 5: Hue-dependent chroma scaling
8541 h = atan2(b, a);
8542 let cs = chromaScaleH(h);
8543 a *= cs;
8544 b *= cs;
8545
8546 // Stage 5.5: Nonlinear chroma power
8547 h = atan2(b, a);
8548 C = sqrt(a * a + b * b);
8549 let p = chromaPowerH(h);
8550 let Cn = C > 0 ? pow(C, p) : 0;
8551 a = Cn * cos(h);
8552 b = Cn * sin(h);
8553
8554 // Stage 6: L-dependent chroma scaling
8555 let T = lChromaScale(L);
8556 a *= T;
8557 b *= T;
8558
8559 // Stage 6.5: HLC interaction
8560 h = atan2(b, a);
8561 let hlcS = hlcScale(h, L);
8562 a *= hlcS;
8563 b *= hlcS;
8564
8565 // Stage 8: Hue-dependent lightness scaling
8566 h = atan2(b, a);
8567 L *= hueLightnessScale(h);
8568
8569 // Stage 11: Rigid rotation (φ = −28.2°)
8570 let aRot = a * ROT_COS - b * ROT_SIN;
8571 let bRot = a * ROT_SIN + b * ROT_COS;
8572 return [L, aRot, bRot];
8573 };
8574 const toXYZ = function (lab) {
8575 let [L, a, b] = lab;
8576
8577 // Undo Stage 11: rotation
8578 let aUn = a * ROT_COS + b * ROT_SIN;
8579 let bUn = -a * ROT_SIN + b * ROT_COS;
8580 a = aUn;
8581 b = bUn;
8582
8583 // Undo Stage 8: hue-dep lightness
8584 let h = atan2(b, a);
8585 L /= hueLightnessScale(h);
8586
8587 // Undo Stage 6.5: HLC
8588 h = atan2(b, a);
8589 let hlcS = hlcScale(h, L);
8590 a /= hlcS;
8591 b /= hlcS;
8592
8593 // Undo Stage 6: L-dep chroma
8594 let T = lChromaScale(L);
8595 a /= T;
8596 b /= T;
8597
8598 // Undo Stage 5.5: chroma power
8599 h = atan2(b, a);
8600 let C = sqrt(a * a + b * b);
8601 let p = chromaPowerH(h);
8602 let Co = C > 0 ? pow(C, 1 / p) : 0;
8603 a = Co * cos(h);
8604 b = Co * sin(h);
8605
8606 // Undo Stage 5: chroma scaling
8607 h = atan2(b, a);
8608 let cs = chromaScaleH(h);
8609 a /= cs;
8610 b /= cs;
8611
8612 // Undo Stage 4.5: dark L
8613 h = atan2(b, a);
8614 L = darkLInv(L, h);
8615
8616 // Undo Stage 4: cubic L
8617 h = atan2(b, a);
8618 L = lCorrectInv(L, h);
8619
8620 // Undo Stage 3.7: H-K
8621 let Cr = sqrt(a * a + b * b);
8622 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8623 let hr = atan2(b, a);
8624 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8625 L -= hkBoost * factor;
8626
8627 // Undo Stage 3.5: hue correction (Newton iteration)
8628 let hOut = atan2(b, a);
8629 C = sqrt(a * a + b * b);
8630 let hRaw = hOut;
8631 for (let i = 0; i < 8; i++) {
8632 let f = hRaw + hueDelta(hRaw) - hOut;
8633 let fp = 1 + hueDeltaDeriv(hRaw);
8634 if (abs(fp) < 1e-10) {
8635 fp = 1;
8636 }
8637 hRaw -= f / fp;
8638 }
8639 a = C * cos(hRaw);
8640 b = C * sin(hRaw);
8641
8642 // Undo Stage 3: Lab → LMS_c (M2_inv)
8643 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$9.M2_INV);
8644
8645 // Undo Stage 2: power compression
8646 let l0 = spow(lc0, INV_GAMMA[0]);
8647 let l1 = spow(lc1, INV_GAMMA[1]);
8648 let l2 = spow(lc2, INV_GAMMA[2]);
8649
8650 // Undo Stage 1: LMS → XYZ (M1_inv)
8651 let xyz = multiply_v3_m3x3([l0, l1, l2], M$9.M1_INV);
8652
8653 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
8654 return multiply_v3_m3x3(xyz, M$9.CAT_FROM_HELM);
8655 };
8656 var helmlab = new ColorSpace({
8657 id: "helmlab-metric",
8658 name: "Helmlab MetricSpace",
8659 cssId: "--helmlab-metric",
8660 coords: {
8661 l: {
8662 refRange: [0, 1.6],
8663 name: "Lightness"
8664 },
8665 a: {
8666 refRange: [-1.5, 1.5]
8667 },
8668 b: {
8669 refRange: [-1.5, 1.5]
8670 }
8671 },
8672 white: "D65",
8673 base: XYZ_D65,
8674 M: M$9,
8675 fromBase(xyz) {
8676 return fromXYZ(xyz);
8677 },
8678 toBase(lab) {
8679 return toXYZ(lab);
8680 }
8681 });
8682
8683 // Helmlab MetricSpace weighted distance (v21, 72 params).
8684 // Optimized on COMBVD human color-difference judgments.
8685 //
8686 // Formula:
8687 // SL = 1 + sl * (L_avg - 0.5)²
8688 // SC = 1 + sc * C_avg
8689 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
8690 // compressed = raw / (1 + c * raw)
8691 // ΔE = compressed ^ q
8692
8693 const sl = -0.9155125151657894;
8694 const sc = 2.9268353744941558;
8695 const wC = 3.966003089807536;
8696 const p = 1.9737081170404969;
8697 const compress = 52.473130649294724;
8698 const q = 0.47897301074925214;
8699
8700 /**
8701 * @param {import("../types.js").ColorTypes} color
8702 * @param {import("../types.js").ColorTypes} sample
8703 * @returns {number}
8704 */
8705 function deltaEHelmlab (color, sample) {
8706 [color, sample] = getColor([color, sample]);
8707 let [L1, a1, b1] = helmlab.from(color);
8708 let [L2, a2, b2] = helmlab.from(sample);
8709 let ΔL = L1 - L2;
8710 let Δa = a1 - a2;
8711 let Δb = b1 - b2;
8712
8713 // Pair-dependent weighting
8714 let Lavg = (L1 + L2) * 0.5;
8715 let SL = 1 + sl * (Lavg - 0.5) ** 2;
8716 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
8717 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
8718 let Cavg = (C1 + C2) * 0.5;
8719 let SC = 1 + sc * Cavg;
8720
8721 // Weighted Minkowski distance
8722 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
8723
8724 // Monotonic compression
8725 let compressed = raw / (1 + compress * raw);
8726 return compressed ** q;
8727 }
8728
8729 /**
8730 * @packageDocumentation
8731 * This module defines all the builtin deltaE methods.
8732 */
8733 var deltaEMethods = {
8734 deltaE76,
8735 deltaECMC,
8736 deltaE2000,
8737 deltaEJz,
8738 deltaEITP,
8739 deltaEOK,
8740 deltaEOK2,
8741 deltaEHCT,
8742 deltaEHelmlab
8743 };
8744
8745 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
8746
8747 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
8748
8749 // Type re-exports
8750 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
8751
8752 /**
8753 * Calculate the epsilon to 2 degrees smaller than the specified JND.
8754 * @param {number} jnd The target "just noticeable difference".
8755 * @returns {number}
8756 */
8757 function calcEpsilon(jnd) {
8758 // Calculate the epsilon to 2 degrees smaller than the specified JND.
8759
8760 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
8761 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
8762 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
8763 }
8764 const GMAPPRESET = {
8765 hct: {
8766 method: "hct.c",
8767 jnd: 2,
8768 deltaEMethod: "hct",
8769 blackWhiteClamp: {}
8770 },
8771 "hct-tonal": {
8772 method: "hct.c",
8773 jnd: 0,
8774 deltaEMethod: "hct",
8775 blackWhiteClamp: {
8776 channel: "hct.t",
8777 min: 0,
8778 max: 100
8779 }
8780 }
8781 };
8782
8783 /**
8784 * Force coordinates to be in gamut of a certain color space.
8785 * Mutates the color it is passed.
8786 * @overload
8787 * @param {ColorTypes} color
8788 * @param {ToGamutOptions} [options]
8789 * @returns {PlainColorObject}
8790 */
8791 /**
8792 * @overload
8793 * @param {ColorTypes} color
8794 * @param {string} [space]
8795 * @returns {PlainColorObject}
8796 */
8797 /**
8798 * @param {ColorTypes} color
8799 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
8800 * @returns {PlainColorObject}
8801 */
8802 function toGamut(color, {
8803 method = defaults.gamut_mapping,
8804 space = undefined,
8805 deltaEMethod = "",
8806 jnd = 2,
8807 blackWhiteClamp = undefined
8808 } = {}) {
8809 color = getColor(color);
8810 if (isString(arguments[1])) {
8811 space = arguments[1];
8812 } else if (!space) {
8813 space = color.space;
8814 }
8815 space = ColorSpace.get(space);
8816
8817 // 3 spaces:
8818 // color.space: current color space
8819 // space: space whose gamut we are mapping to
8820 // mapSpace: space with the coord we're reducing
8821
8822 if (inGamut(color, space, {
8823 epsilon: 0
8824 })) {
8825 return /** @type {PlainColorObject} */color;
8826 }
8827 let spaceColor;
8828 if (method === "css") {
8829 spaceColor = toGamutCSS(color, {
8830 space
8831 });
8832 } else if (method === "raytrace") {
8833 spaceColor = toGamutRayTrace(color, {
8834 space
8835 });
8836 } else {
8837 if (method !== "clip") {
8838 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
8839 ({
8840 method,
8841 jnd,
8842 deltaEMethod,
8843 blackWhiteClamp
8844 } = GMAPPRESET[method]);
8845 }
8846
8847 // Get the correct delta E method
8848 let de = deltaE2000;
8849 if (deltaEMethod !== "") {
8850 for (let m in deltaEMethods) {
8851 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
8852 de = deltaEMethods[m];
8853 break;
8854 }
8855 }
8856 }
8857 if (jnd === 0) {
8858 jnd = 1e-16;
8859 }
8860 let clipped = toGamut(to(color, space), {
8861 method: "clip",
8862 space
8863 });
8864 if (de(color, clipped) > jnd) {
8865 // Clamp to SDR white and black if required
8866 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
8867 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
8868 let channel = get(to(color, channelMeta.space), channelMeta.id);
8869 if (isNone(channel)) {
8870 channel = 0;
8871 }
8872 if (channel >= blackWhiteClamp.max) {
8873 return to({
8874 space: "xyz-d65",
8875 coords: WHITES["D65"]
8876 }, color.space);
8877 } else if (channel <= blackWhiteClamp.min) {
8878 return to({
8879 space: "xyz-d65",
8880 coords: [0, 0, 0]
8881 }, color.space);
8882 }
8883 }
8884
8885 // Reduce a coordinate of a certain color space until the color is in gamut
8886 let coordMeta = ColorSpace.resolveCoord(method);
8887 let mapSpace = coordMeta.space;
8888 let coordId = coordMeta.id;
8889 let mappedColor = to(color, mapSpace);
8890 // If we were already in the mapped color space, we need to resolve undefined channels
8891 mappedColor.coords.forEach((c, i) => {
8892 if (isNone(c)) {
8893 mappedColor.coords[i] = 0;
8894 }
8895 });
8896 let bounds = coordMeta.range || coordMeta.refRange;
8897 let min = bounds[0];
8898 let ε = calcEpsilon(jnd);
8899 let low = min;
8900 let high = get(mappedColor, coordId);
8901 while (high - low > ε) {
8902 let clipped = clone(mappedColor);
8903 clipped = toGamut(clipped, {
8904 space,
8905 method: "clip"
8906 });
8907 let deltaE = de(mappedColor, clipped);
8908 if (deltaE - jnd < ε) {
8909 low = get(mappedColor, coordId);
8910 } else {
8911 high = get(mappedColor, coordId);
8912 }
8913 set(mappedColor, coordId, (low + high) / 2);
8914 }
8915 spaceColor = to(mappedColor, space);
8916 } else {
8917 spaceColor = clipped;
8918 }
8919 } else {
8920 spaceColor = to(color, space);
8921 }
8922 if (method === "clip" ||
8923 // Dumb coord clipping
8924 // finish off smarter gamut mapping with clip to get rid of ε, see #17
8925 !inGamut(spaceColor, space, {
8926 epsilon: 0
8927 })) {
8928 let bounds = Object.values(space.coords).map(c => c.range || []);
8929 spaceColor.coords = /** @type {[number, number, number]} */
8930 spaceColor.coords.map((c, i) => {
8931 let [min, max] = bounds[i];
8932 if (min !== undefined) {
8933 c = Math.max(min, c);
8934 }
8935 if (max !== undefined) {
8936 c = Math.min(c, max);
8937 }
8938 return c;
8939 });
8940 }
8941 }
8942 if (space !== color.space) {
8943 spaceColor = to(spaceColor, color.space);
8944 }
8945 color.coords = spaceColor.coords;
8946 return /** @type {PlainColorObject} */color;
8947 }
8948
8949 /** @type {"color"} */
8950 toGamut.returns = "color";
8951
8952 /**
8953 * The reference colors to be used if lightness is out of the range 0-1 in the
8954 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
8955 * DeltaEOK calculation, so it is guaranteed to be imported.
8956 * @satisfies {Record<string, ColorTypes>}
8957 */
8958 const COLORS = {
8959 WHITE: {
8960 space: Oklab,
8961 coords: [1, 0, 0],
8962 alpha: 1
8963 },
8964 BLACK: {
8965 space: Oklab,
8966 coords: [0, 0, 0],
8967 alpha: 1
8968 }
8969 };
8970
8971 /**
8972 * Given a color `origin`, returns a new color that is in gamut using
8973 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
8974 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
8975 * returned in the color space of `origin`.
8976 * @param {ColorTypes} origin
8977 * @param {{ space?: string | ColorSpace | undefined }} options
8978 * @returns {PlainColorObject}
8979 */
8980 function toGamutCSS(origin, {
8981 space
8982 } = {}) {
8983 const JND = 0.02;
8984 const ε = 0.0001;
8985 origin = getColor(origin);
8986 if (!space) {
8987 space = origin.space;
8988 }
8989 space = ColorSpace.get(space);
8990 if (space.isUnbounded) {
8991 return to(origin, space);
8992 }
8993 const origin_OKLCH = to(origin, OKLCH);
8994 let L = origin_OKLCH.coords[0];
8995
8996 // return media white or black, if lightness is out of range
8997 if (L >= 1) {
8998 const white = to(COLORS.WHITE, space);
8999 white.alpha = origin.alpha;
9000 return to(white, space);
9001 }
9002 if (L <= 0) {
9003 const black = to(COLORS.BLACK, space);
9004 black.alpha = origin.alpha;
9005 return to(black, space);
9006 }
9007 if (inGamut(origin_OKLCH, space, {
9008 epsilon: 0
9009 })) {
9010 return to(origin_OKLCH, space);
9011 }
9012 function clip(_color) {
9013 const destColor = to(_color, space);
9014 const spaceCoords = Object.values(/** @type {ColorSpace} */space.coords);
9015 destColor.coords = /** @type {[number, number, number]} */
9016 destColor.coords.map((coord, index) => {
9017 if ("range" in spaceCoords[index]) {
9018 const [min, max] = spaceCoords[index].range;
9019 return clamp(min, coord, max);
9020 }
9021 return coord;
9022 });
9023 return destColor;
9024 }
9025 let min = 0;
9026 let max = origin_OKLCH.coords[1];
9027 let min_inGamut = true;
9028 let current = clone(origin_OKLCH);
9029 let clipped = clip(current);
9030 let E = deltaEOK(clipped, current);
9031 if (E < JND) {
9032 return clipped;
9033 }
9034 while (max - min > ε) {
9035 const chroma = (min + max) / 2;
9036 current.coords[1] = chroma;
9037 if (min_inGamut && inGamut(current, space, {
9038 epsilon: 0
9039 })) {
9040 min = chroma;
9041 } else {
9042 clipped = clip(current);
9043 E = deltaEOK(clipped, current);
9044 if (E < JND) {
9045 if (JND - E < ε) {
9046 break;
9047 } else {
9048 min_inGamut = false;
9049 min = chroma;
9050 }
9051 } else {
9052 max = chroma;
9053 }
9054 }
9055 }
9056 return clipped;
9057 }
9058
9059 /**
9060 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
9061 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
9062 * @param {[number, number, number]} start
9063 * @param {[number, number, number]} end
9064 * @param {[number, number, number]} bmin
9065 * @param {[number, number, number]} bmax
9066 * @returns {[number, number, number] | []}
9067 */
9068 function raytrace_box(start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
9069 // Use slab method to detect intersection of ray and box and return intersect.
9070 // https://en.wikipedia.org/wiki/Slab_method
9071
9072 // Calculate whether there was a hit
9073 let tfar = Infinity;
9074 let tnear = -Infinity;
9075 let direction = [];
9076 for (let i = 0; i < 3; i++) {
9077 const a = start[i];
9078 const b = end[i];
9079 const d = b - a;
9080 const bn = bmin[i];
9081 const bx = bmax[i];
9082 direction.push(d);
9083
9084 // Non parallel cases
9085 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types
9086 if (Math.abs(d) > 1e-12) {
9087 const inv_d = 1 / d;
9088 const t1 = (bn - a) * inv_d;
9089 const t2 = (bx - a) * inv_d;
9090 tnear = Math.max(Math.min(t1, t2), tnear);
9091 tfar = Math.min(Math.max(t1, t2), tfar);
9092 }
9093
9094 // Impossible parallel case
9095 else if (a < bn || a > bx) {
9096 return [];
9097 }
9098 }
9099
9100 // No hit
9101 if (tnear > tfar || tfar < 0) {
9102 return [];
9103 }
9104
9105 // Favor the intersection first in the direction start -> end
9106 if (tnear < 0) {
9107 tnear = tfar;
9108 }
9109
9110 // A point, or something approaching a single point where start and end are the same.
9111 if (!isFinite(tnear)) {
9112 return [];
9113 }
9114
9115 // Calculate nearest intersection via interpolation
9116 return [start[0] + direction[0] * tnear, start[1] + direction[1] * tnear, start[2] + direction[2] * tnear];
9117 }
9118
9119 /**
9120 * Given a color `origin`, returns a new color that is in gamut using
9121 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
9122 * it will be in gamut `space`, and returned in `space`. Otherwise,
9123 * it will be in gamut and returned in the color space of `origin`.
9124 * @param {ColorTypes} origin
9125 * @param {{ space?: string | ColorSpace | undefined }} options
9126 * @returns {PlainColorObject}
9127 */
9128 function toGamutRayTrace(origin, {
9129 space
9130 } = {}) {
9131 origin = getColor(origin);
9132 if (!space) {
9133 space = origin.space;
9134 }
9135 space = ColorSpace.get(space);
9136
9137 // If the space is already in gamut, stop.
9138 if (space.isUnbounded) {
9139 return to(origin, space);
9140 }
9141
9142 // Get the OkLCh coordinates.
9143 let oklchOrigin = to(origin, OKLCH);
9144 let [lightness, chroma, hue] = oklchOrigin.coords;
9145
9146 // Return white or black if color's lightness exceeds the SDR range.
9147 if (lightness >= 1) {
9148 const white = to(COLORS.WHITE, space);
9149 white.alpha = origin.alpha;
9150 return to(white, space);
9151 } else if (lightness <= 0) {
9152 const black = to(COLORS.BLACK, space);
9153 black.alpha = origin.alpha;
9154 return to(black, space);
9155 }
9156
9157 // Get a copy of the origin color as the RGB target space.
9158 const originSpace = space;
9159 const rGamut = space.rgbGamut;
9160 if (rGamut !== undefined) {
9161 space = rGamut;
9162 }
9163 if (!isInstance(space, RGBColorSpace)) {
9164 throw Error('An RGB gamut is required');
9165 }
9166
9167 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
9168 let [mn, mx] = Object.values(space.coords)[0].range;
9169 let max = /** @type {[number, number, number]} */[mx, mx, mx];
9170
9171 // See if we have a linear version of the color space
9172 const lGamut = space.linearGamut;
9173 if (lGamut !== undefined) {
9174 // Recalculate minimum and maximum relative to the linear space
9175 let temp = to({
9176 space: space,
9177 coords: max,
9178 alpha: origin.alpha
9179 }, lGamut);
9180 mx = temp.coords[0];
9181 max = /** @type {[number, number, number]} */[mx, mx, mx];
9182 space = lGamut;
9183 mn = Object.values(space.coords)[0].range[0];
9184 }
9185 let min = /** @type {[number, number, number]} */[mn, mn, mn];
9186 let rgbOrigin = to(oklchOrigin, space);
9187 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
9188 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
9189 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
9190 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
9191 let anchor = to({
9192 space: OKLCH,
9193 coords: [lightness, 0, hue]
9194 }, space).coords;
9195
9196 // Calculate bounds to adjust the anchor closer to the gamut surface.
9197 // We don't want to make the ray too short, so offset some amount from the low and high range.
9198 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types.
9199 const low = mn + 1e-12;
9200 const high = mx - 1e-12;
9201
9202 // Cast a ray from the zero chroma color to the target color.
9203 // Trace the line to the RGB cube edge and find where it intersects.
9204 // Correct L and h within the perceptual OkLCh after each attempt.
9205 let last = rgbOrigin.coords;
9206 for (let i = 0; i < 4; i++) {
9207 if (i) {
9208 // For constant luminance, we correct the color by simply setting lightness and hue to
9209 // match the original color. In a non constant luminance reduction, it is better to
9210 // project the color onto the reduction path vector.
9211 const oklchColor = to(rgbOrigin, OKLCH);
9212 oklchColor.coords[0] = lightness;
9213 oklchColor.coords[2] = hue;
9214 rgbOrigin = to(oklchColor, space);
9215 }
9216 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
9217 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
9218
9219 // If we cannot find an intersection, reset to last successful iteration of the color.
9220 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
9221 if (intersection.length === 0) {
9222 rgbOrigin.coords = [...last];
9223 break;
9224 }
9225
9226 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
9227 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
9228 anchor = [...rgbOrigin.coords];
9229 }
9230
9231 // If we have an intersection, update the color.
9232 last = /** @type {[number, number, number]} */intersection;
9233 rgbOrigin.coords = [...intersection];
9234 }
9235 }
9236
9237 // Convert to the original, specified gamut
9238 rgbOrigin = to(rgbOrigin, originSpace);
9239 const spaceCoords = Object.values(/** @type {ColorSpace} */originSpace.coords);
9240
9241 // Remove noise from floating point math by clipping
9242 rgbOrigin.coords = /** @type {[number, number, number]} */
9243 rgbOrigin.coords.map((coord, index) => {
9244 if ("range" in spaceCoords[index]) {
9245 const [lower, upper] = spaceCoords[index].range;
9246 return clamp(lower, coord, upper);
9247 }
9248 return coord;
9249 });
9250 return rgbOrigin;
9251 }
9252
9253 /** @import { SpaceOptions } from "./ColorSpace.js" */
9254
9255 /**
9256 * A color space whose chroma-like coordinate is expressed relative to an RGB gamut: chroma = 1 is
9257 * the most colorful in-gamut color for the rest of the coordinates, so any chroma in [0, 1] stays
9258 * in gamut. The reduced coordinate (`chroma`, default `"c"`) is rescaled against `gamutSpace`; every
9259 * other coordinate is inherited unchanged from `base`. Works for any base whose chroma coordinate
9260 * brings the color into gamut as it is reduced (e.g. OKLCh, LCH).
9261 */
9262 class GamutRelativeColorSpace extends ColorSpace {
9263 /**
9264 * @param {SpaceOptions & { gamutSpace: string | ColorSpace, chroma?: string }} options
9265 * Requires `base` (the source space) and `gamutSpace` (the RGB gamut). `chroma` names the
9266 * coordinate to rescale (default `"c"`).
9267 */
9268 constructor(options) {
9269 var _options$chroma, _options$coords, _options$formats;
9270 let base = ColorSpace.get(options.base);
9271 let chroma = (_options$chroma = options.chroma) !== null && _options$chroma !== void 0 ? _options$chroma : "c";
9272 let ids = Object.keys(base.coords);
9273 let chromaIndex = ids.indexOf(chroma);
9274 if (chromaIndex === -1) {
9275 throw new TypeError(`GamutRelativeColorSpace needs a "${chroma}" coordinate, got ${base.id}`);
9276 }
9277
9278 // Inherit the base's coords; the reduced coordinate becomes a 0–1 fraction of its gamut maximum
9279 let coords = Object.fromEntries(Object.entries(base.coords).map(([id, meta]) => [id, {
9280 ...meta
9281 }]));
9282 coords[chroma].range = [0, 1];
9283 delete coords[chroma].refRange;
9284 (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : options.coords = coords;
9285
9286 // Serialize the reduced coordinate and any other 0–1 coordinate as percentages; angles as angles
9287 (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : options.formats = {
9288 color: {
9289 coords: ids.map(id => {
9290 var _ref, _base$coords$id$range;
9291 if (base.coords[id].type === "angle") {
9292 return "<number> | <angle>";
9293 }
9294 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 : [];
9295 let pctFirst = id === chroma || min === 0 && max === 1;
9296 return pctFirst ? "<percentage> | <number>" : "<number> | <percentage>";
9297 })
9298 }
9299 };
9300 super(options);
9301 this.chromaIndex = chromaIndex;
9302 this.method = `${base.id}.${chroma}`;
9303
9304 // A chroma that is out of gamut at every lightness and hue: the gamut's most saturated corner
9305 // (its primaries/secondaries are its chroma maxima) plus headroom. Seeding the gamut search
9306 // from here lands on the first in-gamut crossing — the highest contiguous in-gamut chroma —
9307 // and avoids clamping wide gamuts (e.g. Rec.2020 exceeds OKLCh's nominal 0.4 chroma).
9308 // prettier-ignore
9309 let corners = /** @type {[number, number, number][]} */
9310 [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]];
9311 this.oogChroma = 1.01 * Math.max(...corners.map(rgb => base.from(this.gamutSpace, rgb)[this.chromaIndex] || 0));
9312 }
9313
9314 /**
9315 * The highest in-gamut value of the reduced coordinate for the given coordinates. The reduced
9316 * coordinate's own value is ignored; the others determine the result.
9317 * @param {number[]} coords
9318 * @returns {number}
9319 */
9320 maxChroma(coords) {
9321 let seed = /** @type {[number, number, number]} */[...coords];
9322 seed[this.chromaIndex] = this.oogChroma;
9323 return toGamut({
9324 space: this.base,
9325 coords: seed
9326 },
9327 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
9328 {
9329 space: this.gamutSpace,
9330 method: this.method,
9331 deltaEMethod: "OK",
9332 jnd: 0
9333 }).coords[this.chromaIndex];
9334 }
9335 toBase(coords) {
9336 coords = [...coords];
9337 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9338 // chroma is a fraction of maxChroma(the other coords); without them all it is undefined
9339 if (coords[this.chromaIndex] !== 0) {
9340 coords[this.chromaIndex] = null;
9341 }
9342 } else if (!isNone(coords[this.chromaIndex])) {
9343 coords[this.chromaIndex] *= this.maxChroma(coords);
9344 }
9345 return coords;
9346 }
9347 fromBase(coords) {
9348 coords = [...coords];
9349 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9350 if (coords[this.chromaIndex] !== 0) {
9351 coords[this.chromaIndex] = null;
9352 }
9353 } else if (!isNone(coords[this.chromaIndex])) {
9354 let cMax = this.maxChroma(coords);
9355 coords[this.chromaIndex] = cMax ? coords[this.chromaIndex] / cMax : 0;
9356 }
9357 return coords;
9358 }
9359 }
9360
9361 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
9362
9363 // Type re-exports
9364 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
9365
9366 /**
9367 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
9368 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
9369 *
9370 * @overload
9371 * @param {ColorTypes} color
9372 * @param {TryColorOptions} [options]
9373 * @returns {PlainColorObject | null}
9374 */
9375 /**
9376 * @overload
9377 * @param {ColorTypes[]} color
9378 * @param {TryColorOptions} [options]
9379 * @returns {(PlainColorObject | null)[]}
9380 */
9381 function tryColor(color, options = {}) {
9382 if (Array.isArray(color)) {
9383 return color.map(c => tryColor(c, options));
9384 }
9385 let {
9386 cssProperty = "background-color",
9387 element,
9388 ...getColorOptions
9389 } = options;
9390 let error = null;
9391 try {
9392 return getColor(color, getColorOptions);
9393 } catch (e) {
9394 error = e;
9395 }
9396 let {
9397 CSS,
9398 getComputedStyle
9399 } = globalThis;
9400 if (isString(color) && element && CSS && getComputedStyle) {
9401 // Try resolving the color using the DOM, if supported in CSS
9402 if (CSS.supports(cssProperty, color)) {
9403 let previousValue = element.style[cssProperty];
9404 if (color !== previousValue) {
9405 element.style[cssProperty] = color;
9406 }
9407 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
9408 if (color !== previousValue) {
9409 element.style[cssProperty] = previousValue;
9410 }
9411 if (computedColor !== color) {
9412 // getComputedStyle() changed the color, try again
9413 try {
9414 return getColor(computedColor, getColorOptions);
9415 } catch (e) {
9416 error = e;
9417 }
9418 } else {
9419 // Still not resolved
9420 error = {
9421 message: "Color value is a valid CSS color, but it could not be resolved :("
9422 };
9423 }
9424 }
9425 }
9426
9427 // If we're here, we failed to resolve the color
9428 if (options.errorMeta) {
9429 options.errorMeta.error = error;
9430 }
9431 return null;
9432 }
9433
9434 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
9435
9436 // Type re-exports
9437 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
9438
9439 /**
9440 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
9441 * @param {ColorTypes} color
9442 * @param {SerializeOptions & Record<string, any>} options
9443 * @returns {string}
9444 */
9445 function serialize(color, options = {}) {
9446 let {
9447 precision = defaults.precision,
9448 format,
9449 inGamut: inGamut$1 = true,
9450 coords: coordFormat,
9451 alpha: alphaFormat,
9452 commas
9453 } = options;
9454 let ret;
9455 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */getColor(color);
9456 let formatId = format;
9457 let parseMeta = colorWithMeta.parseMeta;
9458 if (parseMeta && !format) {
9459 var _coordFormat, _alphaFormat, _commas;
9460 if (parseMeta.format.canSerialize()) {
9461 format = parseMeta.format;
9462 formatId = parseMeta.formatId;
9463 }
9464 (_coordFormat = coordFormat) !== null && _coordFormat !== void 0 ? _coordFormat : coordFormat = parseMeta.types;
9465 (_alphaFormat = alphaFormat) !== null && _alphaFormat !== void 0 ? _alphaFormat : alphaFormat = parseMeta.alphaType;
9466 (_commas = commas) !== null && _commas !== void 0 ? _commas : commas = parseMeta.commas;
9467 }
9468 if (formatId) {
9469 var _colorWithMeta$space$;
9470 // A format is explicitly specified
9471 format = (_colorWithMeta$space$ = colorWithMeta.space.getFormat(format)) !== null && _colorWithMeta$space$ !== void 0 ? _colorWithMeta$space$ : ColorSpace.findFormat(formatId);
9472 }
9473 if (!format) {
9474 var _colorWithMeta$space$2;
9475 // No format specified, or format not found
9476 format = (_colorWithMeta$space$2 = colorWithMeta.space.getFormat("default")) !== null && _colorWithMeta$space$2 !== void 0 ? _colorWithMeta$space$2 : ColorSpace.DEFAULT_FORMAT;
9477 formatId = format.name;
9478 }
9479 if (format && format.space && format.space !== colorWithMeta.space) {
9480 // Format specified belongs to a different color space,
9481 // need to convert to it first
9482 colorWithMeta = to(colorWithMeta, format.space);
9483 }
9484
9485 // The assignment to coords and inGamut needs to stay in the order they are now
9486 // The order of the assignment was changed as a workaround for a bug in Next.js
9487 // See this issue for details: https://github.com/color-js/color.js/issues/260
9488
9489 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
9490
9491 inGamut$1 || (inGamut$1 = format.toGamut);
9492 if (inGamut$1 && !inGamut(colorWithMeta)) {
9493 // FIXME what happens if the color contains none values?
9494 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
9495 }
9496 if (format.type === "custom") {
9497 if (format.serialize) {
9498 ret = format.serialize(coords, colorWithMeta.alpha, options);
9499 } else {
9500 throw new TypeError(`format ${formatId} can only be used to parse colors, not for serialization`);
9501 }
9502 } else {
9503 var _alphaFormat$type, _alphaFormat2, _alphaFormat3, _alphaFormat4, _commas2;
9504 // Functional syntax
9505 let name = format.name || "color";
9506 let args = format.serializeCoords(coords, precision, coordFormat);
9507 if (name === "color") {
9508 var _format$ids;
9509 // If output is a color() function, add colorspace id as first argument
9510 let cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || colorWithMeta.space.cssId || colorWithMeta.space.id;
9511 args.unshift(cssId);
9512 }
9513
9514 // Serialize alpha?
9515 /** @type {string | number} */
9516 let alpha = colorWithMeta.alpha;
9517 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
9518 alphaFormat = typeof alphaFormat === "string" ? {
9519 type: alphaFormat
9520 } : {
9521 include: alphaFormat
9522 };
9523 }
9524 let alphaType = (_alphaFormat$type = (_alphaFormat2 = alphaFormat) === null || _alphaFormat2 === void 0 ? void 0 : _alphaFormat2.type) !== null && _alphaFormat$type !== void 0 ? _alphaFormat$type : "<number>";
9525 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;
9526 let strAlpha = "";
9527 (_commas2 = commas) !== null && _commas2 !== void 0 ? _commas2 : commas = format.commas;
9528 if (serializeAlpha) {
9529 if (precision !== null) {
9530 let unit;
9531 if (alphaType === "<percentage>") {
9532 unit = "%";
9533 alpha *= 100;
9534 }
9535 alpha = serializeNumber(alpha, {
9536 precision,
9537 unit
9538 });
9539 }
9540 strAlpha = `${commas ? "," : " /"} ${alpha}`;
9541 }
9542 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
9543 }
9544 return ret;
9545 }
9546
9547 var esnext_iterator_filter = {};
9548
9549 var es_iterator_filter = {};
9550
9551 var hasRequiredEs_iterator_filter;
9552
9553 function requireEs_iterator_filter () {
9554 if (hasRequiredEs_iterator_filter) return es_iterator_filter;
9555 hasRequiredEs_iterator_filter = 1;
9556 var $ = require_export();
9557 var call = requireFunctionCall();
9558 var aCallable = requireACallable();
9559 var anObject = requireAnObject();
9560 var getIteratorDirect = requireGetIteratorDirect();
9561 var createIteratorProxy = requireIteratorCreateProxy();
9562 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
9563 var IS_PURE = requireIsPure();
9564
9565 var IteratorProxy = createIteratorProxy(function () {
9566 var iterator = this.iterator;
9567 var predicate = this.predicate;
9568 var next = this.next;
9569 var result, done, value;
9570 while (true) {
9571 result = anObject(call(next, iterator));
9572 done = this.done = !!result.done;
9573 if (done) return;
9574 value = result.value;
9575 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
9576 }
9577 });
9578
9579 // `Iterator.prototype.filter` method
9580 // https://tc39.es/ecma262/#sec-iterator.prototype.filter
9581 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
9582 filter: function filter(predicate) {
9583 anObject(this);
9584 aCallable(predicate);
9585 return new IteratorProxy(getIteratorDirect(this), {
9586 predicate: predicate
9587 });
9588 }
9589 });
9590 return es_iterator_filter;
9591 }
9592
9593 var hasRequiredEsnext_iterator_filter;
9594
9595 function requireEsnext_iterator_filter () {
9596 if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
9597 hasRequiredEsnext_iterator_filter = 1;
9598 // TODO: Remove from `core-js@4`
9599 requireEs_iterator_filter();
9600 return esnext_iterator_filter;
9601 }
9602
9603 requireEsnext_iterator_filter();
9604
9605 /** @import { Matrix3x3 } from "../types.js" */
9606
9607 /**
9608 * Matrices used by this color space, also available as `REC_2020_Linear.M`.
9609 * Uses D65 (no chromatic adaptation).
9610 * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9611 * @type {Record<string, Matrix3x3>}
9612 */
9613 // prettier-ignore
9614 const M$8 = {
9615 // 0 is actually calculated as 4.994106574466076e-17
9616 toXYZ: [[0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0.000000000000000, 0.028072693049087428, 1.060985057710791]],
9617 // from ITU-R BT.2124-0 Annex 2 p.3
9618 fromXYZ: [[1.716651187971268, -0.355670783776392, -0.253366281373660], [-0.666684351832489, 1.616481236634939, 0.0157685458139111], [0.017639857445311, -0.042770613257809, 0.942103121235474]]
9619 };
9620 var REC2020Linear = new RGBColorSpace({
9621 id: "rec2020-linear",
9622 cssId: "--rec2020-linear",
9623 name: "Linear REC.2020",
9624 white: "D65",
9625 M: M$8
9626 });
9627
9628 // import sRGB from "./srgb.js";
9629
9630 var REC2020 = new RGBColorSpace({
9631 id: "rec2020",
9632 name: "REC.2020",
9633 base: REC2020Linear,
9634 linearGamut: REC2020Linear,
9635 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
9636 // with b (black lift) = 0 and a (user gain) = 1
9637 // defined over the extended range, not clamped
9638 toBase(RGB) {
9639 return RGB.map(function (val) {
9640 let sign = val < 0 ? -1 : 1;
9641 let abs = val * sign;
9642 return sign * Math.pow(abs, 2.4);
9643 });
9644 },
9645 fromBase(RGB) {
9646 return RGB.map(function (val) {
9647 let sign = val < 0 ? -1 : 1;
9648 let abs = val * sign;
9649 return sign * Math.pow(abs, 1 / 2.4);
9650 });
9651 }
9652 });
9653
9654 /** @import { Matrix3x3 } from "../types.js" */
9655
9656 /**
9657 * Matrices used by this color space, also available as `P3_Linear.M`
9658 * @type {Record<string, Matrix3x3>}
9659 */
9660 // prettier-ignore
9661 const M$7 = {
9662 toXYZ: [[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0.0000000000000000, 0.04511338185890264, 1.043944368900976]],
9663 fromXYZ: [[2.493496911941425, -0.9313836179191239, -0.40271078445071684], [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], [0.03584583024378447, -0.07617238926804182, 0.9568845240076872]]
9664 };
9665 var P3Linear = new RGBColorSpace({
9666 id: "p3-linear",
9667 cssId: "display-p3-linear",
9668 name: "Linear P3",
9669 white: "D65",
9670 M: M$7
9671 });
9672
9673 /** @import { Matrix3x3 } from "../types.js" */
9674
9675 // This is the linear-light version of sRGB
9676 // as used for example in SVG filters
9677 // or in Canvas
9678
9679 /**
9680 * Matrices used by this color space, also available as `sRGB_Linear.M`
9681 * @type {Record<string, Matrix3x3>}
9682 */
9683 // prettier-ignore
9684 const M$6 = {
9685 // calculated directly from the RGB and white chromaticities; when rounded to
9686 // 8 decimal places, agrees completely with the official matrix
9687 // see https://github.com/w3c/csswg-drafts/issues/5922
9688 toXYZ: [[0.41239079926595934, 0.357584339383878, 0.1804807884018343], [0.21263900587151027, 0.715168678767756, 0.07219231536073371], [0.01933081871559182, 0.11919477979462598, 0.9505321522496607]],
9689 // the inverse of the above; again agrees with the official definition
9690 // when rounded to 8 decimal places
9691 fromXYZ: [[3.2409699419045226, -1.537383177570094, -0.4986107602930034], [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559], [0.05563007969699366, -0.20397695888897652, 1.0569715142428786]]
9692 };
9693 var sRGBLinear = new RGBColorSpace({
9694 id: "srgb-linear",
9695 name: "Linear sRGB",
9696 white: "D65",
9697 M: M$6
9698 });
9699
9700 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
9701 // and run in the console:
9702 // 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"))
9703
9704 /** List of CSS color keywords
9705 * Note that this does not include currentColor, transparent,
9706 * or system colors
9707 *
9708 * @type {Record<string, [number, number, number]>}
9709 */
9710 var KEYWORDS = {
9711 aliceblue: [240 / 255, 248 / 255, 1],
9712 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
9713 aqua: [0, 1, 1],
9714 aquamarine: [127 / 255, 1, 212 / 255],
9715 azure: [240 / 255, 1, 1],
9716 beige: [245 / 255, 245 / 255, 220 / 255],
9717 bisque: [1, 228 / 255, 196 / 255],
9718 black: [0, 0, 0],
9719 blanchedalmond: [1, 235 / 255, 205 / 255],
9720 blue: [0, 0, 1],
9721 blueviolet: [138 / 255, 43 / 255, 226 / 255],
9722 brown: [165 / 255, 42 / 255, 42 / 255],
9723 burlywood: [222 / 255, 184 / 255, 135 / 255],
9724 cadetblue: [95 / 255, 158 / 255, 160 / 255],
9725 chartreuse: [127 / 255, 1, 0],
9726 chocolate: [210 / 255, 105 / 255, 30 / 255],
9727 coral: [1, 127 / 255, 80 / 255],
9728 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
9729 cornsilk: [1, 248 / 255, 220 / 255],
9730 crimson: [220 / 255, 20 / 255, 60 / 255],
9731 cyan: [0, 1, 1],
9732 darkblue: [0, 0, 139 / 255],
9733 darkcyan: [0, 139 / 255, 139 / 255],
9734 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
9735 darkgray: [169 / 255, 169 / 255, 169 / 255],
9736 darkgreen: [0, 100 / 255, 0],
9737 darkgrey: [169 / 255, 169 / 255, 169 / 255],
9738 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
9739 darkmagenta: [139 / 255, 0, 139 / 255],
9740 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
9741 darkorange: [1, 140 / 255, 0],
9742 darkorchid: [153 / 255, 50 / 255, 204 / 255],
9743 darkred: [139 / 255, 0, 0],
9744 darksalmon: [233 / 255, 150 / 255, 122 / 255],
9745 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
9746 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
9747 darkslategray: [47 / 255, 79 / 255, 79 / 255],
9748 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
9749 darkturquoise: [0, 206 / 255, 209 / 255],
9750 darkviolet: [148 / 255, 0, 211 / 255],
9751 deeppink: [1, 20 / 255, 147 / 255],
9752 deepskyblue: [0, 191 / 255, 1],
9753 dimgray: [105 / 255, 105 / 255, 105 / 255],
9754 dimgrey: [105 / 255, 105 / 255, 105 / 255],
9755 dodgerblue: [30 / 255, 144 / 255, 1],
9756 firebrick: [178 / 255, 34 / 255, 34 / 255],
9757 floralwhite: [1, 250 / 255, 240 / 255],
9758 forestgreen: [34 / 255, 139 / 255, 34 / 255],
9759 fuchsia: [1, 0, 1],
9760 gainsboro: [220 / 255, 220 / 255, 220 / 255],
9761 ghostwhite: [248 / 255, 248 / 255, 1],
9762 gold: [1, 215 / 255, 0],
9763 goldenrod: [218 / 255, 165 / 255, 32 / 255],
9764 gray: [128 / 255, 128 / 255, 128 / 255],
9765 green: [0, 128 / 255, 0],
9766 greenyellow: [173 / 255, 1, 47 / 255],
9767 grey: [128 / 255, 128 / 255, 128 / 255],
9768 honeydew: [240 / 255, 1, 240 / 255],
9769 hotpink: [1, 105 / 255, 180 / 255],
9770 indianred: [205 / 255, 92 / 255, 92 / 255],
9771 indigo: [75 / 255, 0, 130 / 255],
9772 ivory: [1, 1, 240 / 255],
9773 khaki: [240 / 255, 230 / 255, 140 / 255],
9774 lavender: [230 / 255, 230 / 255, 250 / 255],
9775 lavenderblush: [1, 240 / 255, 245 / 255],
9776 lawngreen: [124 / 255, 252 / 255, 0],
9777 lemonchiffon: [1, 250 / 255, 205 / 255],
9778 lightblue: [173 / 255, 216 / 255, 230 / 255],
9779 lightcoral: [240 / 255, 128 / 255, 128 / 255],
9780 lightcyan: [224 / 255, 1, 1],
9781 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
9782 lightgray: [211 / 255, 211 / 255, 211 / 255],
9783 lightgreen: [144 / 255, 238 / 255, 144 / 255],
9784 lightgrey: [211 / 255, 211 / 255, 211 / 255],
9785 lightpink: [1, 182 / 255, 193 / 255],
9786 lightsalmon: [1, 160 / 255, 122 / 255],
9787 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
9788 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
9789 lightslategray: [119 / 255, 136 / 255, 153 / 255],
9790 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
9791 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
9792 lightyellow: [1, 1, 224 / 255],
9793 lime: [0, 1, 0],
9794 limegreen: [50 / 255, 205 / 255, 50 / 255],
9795 linen: [250 / 255, 240 / 255, 230 / 255],
9796 magenta: [1, 0, 1],
9797 maroon: [128 / 255, 0, 0],
9798 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
9799 mediumblue: [0, 0, 205 / 255],
9800 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
9801 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
9802 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
9803 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
9804 mediumspringgreen: [0, 250 / 255, 154 / 255],
9805 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
9806 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
9807 midnightblue: [25 / 255, 25 / 255, 112 / 255],
9808 mintcream: [245 / 255, 1, 250 / 255],
9809 mistyrose: [1, 228 / 255, 225 / 255],
9810 moccasin: [1, 228 / 255, 181 / 255],
9811 navajowhite: [1, 222 / 255, 173 / 255],
9812 navy: [0, 0, 128 / 255],
9813 oldlace: [253 / 255, 245 / 255, 230 / 255],
9814 olive: [128 / 255, 128 / 255, 0],
9815 olivedrab: [107 / 255, 142 / 255, 35 / 255],
9816 orange: [1, 165 / 255, 0],
9817 orangered: [1, 69 / 255, 0],
9818 orchid: [218 / 255, 112 / 255, 214 / 255],
9819 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
9820 palegreen: [152 / 255, 251 / 255, 152 / 255],
9821 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
9822 palevioletred: [219 / 255, 112 / 255, 147 / 255],
9823 papayawhip: [1, 239 / 255, 213 / 255],
9824 peachpuff: [1, 218 / 255, 185 / 255],
9825 peru: [205 / 255, 133 / 255, 63 / 255],
9826 pink: [1, 192 / 255, 203 / 255],
9827 plum: [221 / 255, 160 / 255, 221 / 255],
9828 powderblue: [176 / 255, 224 / 255, 230 / 255],
9829 purple: [128 / 255, 0, 128 / 255],
9830 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
9831 red: [1, 0, 0],
9832 rosybrown: [188 / 255, 143 / 255, 143 / 255],
9833 royalblue: [65 / 255, 105 / 255, 225 / 255],
9834 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
9835 salmon: [250 / 255, 128 / 255, 114 / 255],
9836 sandybrown: [244 / 255, 164 / 255, 96 / 255],
9837 seagreen: [46 / 255, 139 / 255, 87 / 255],
9838 seashell: [1, 245 / 255, 238 / 255],
9839 sienna: [160 / 255, 82 / 255, 45 / 255],
9840 silver: [192 / 255, 192 / 255, 192 / 255],
9841 skyblue: [135 / 255, 206 / 255, 235 / 255],
9842 slateblue: [106 / 255, 90 / 255, 205 / 255],
9843 slategray: [112 / 255, 128 / 255, 144 / 255],
9844 slategrey: [112 / 255, 128 / 255, 144 / 255],
9845 snow: [1, 250 / 255, 250 / 255],
9846 springgreen: [0, 1, 127 / 255],
9847 steelblue: [70 / 255, 130 / 255, 180 / 255],
9848 tan: [210 / 255, 180 / 255, 140 / 255],
9849 teal: [0, 128 / 255, 128 / 255],
9850 thistle: [216 / 255, 191 / 255, 216 / 255],
9851 tomato: [1, 99 / 255, 71 / 255],
9852 turquoise: [64 / 255, 224 / 255, 208 / 255],
9853 violet: [238 / 255, 130 / 255, 238 / 255],
9854 wheat: [245 / 255, 222 / 255, 179 / 255],
9855 white: [1, 1, 1],
9856 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
9857 yellow: [1, 1, 0],
9858 yellowgreen: [154 / 255, 205 / 255, 50 / 255]
9859 };
9860
9861 /** @import { Coords } from "../types.js" */
9862
9863 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
9864 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
9865 var sRGB = new RGBColorSpace({
9866 id: "srgb",
9867 name: "sRGB",
9868 base: sRGBLinear,
9869 linearGamut: sRGBLinear,
9870 fromBase: rgb => {
9871 // convert an array of linear-light sRGB values in the range 0.0-1.0
9872 // to gamma corrected form
9873 // https://en.wikipedia.org/wiki/SRGB
9874 return rgb.map(val => {
9875 let sign = val < 0 ? -1 : 1;
9876 let abs = val * sign;
9877 if (abs > 0.0031308) {
9878 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
9879 }
9880 return 12.92 * val;
9881 });
9882 },
9883 toBase: rgb => {
9884 // convert an array of sRGB values in the range 0.0 - 1.0
9885 // to linear light (un-companded) form.
9886 // https://en.wikipedia.org/wiki/SRGB
9887 return rgb.map(val => {
9888 let sign = val < 0 ? -1 : 1;
9889 let abs = val * sign;
9890 if (abs <= 0.04045) {
9891 return val / 12.92;
9892 }
9893 return sign * ((abs + 0.055) / 1.055) ** 2.4;
9894 });
9895 },
9896 formats: {
9897 rgb: {
9898 coords: coordGrammar
9899 },
9900 rgb_number: {
9901 name: "rgb",
9902 commas: true,
9903 coords: coordGrammarNumber,
9904 alpha: false
9905 },
9906 color: {
9907 /* use defaults */
9908 },
9909 rgba: {
9910 coords: coordGrammar,
9911 commas: true,
9912 alpha: true
9913 },
9914 rgba_number: {
9915 name: "rgba",
9916 commas: true,
9917 coords: coordGrammarNumber
9918 },
9919 hex: {
9920 type: "custom",
9921 toGamut: true,
9922 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
9923 parse(str) {
9924 if (str.length <= 5) {
9925 // #rgb or #rgba, duplicate digits
9926 str = str.replace(/[a-f0-9]/gi, "$&$&");
9927 }
9928
9929 /** @type {number[]} */
9930 let rgba = [];
9931 // @ts-expect-error Type 'void' is not assignable to type 'string'
9932 str.replace(/[a-f0-9]{2}/gi, component => {
9933 rgba.push(parseInt(component, 16) / 255);
9934 });
9935 return {
9936 spaceId: "srgb",
9937 coords: (/** @type {Coords} */rgba.slice(0, 3)),
9938 alpha: (/** @type {number} */rgba.slice(3)[0])
9939 };
9940 },
9941 serialize: (coords, alpha, {
9942 collapse = true,
9943 // collapse to 3-4 digit hex when possible?
9944 alpha: alphaFormat
9945 } = {}) => {
9946 if (alphaFormat !== false && alpha < 1 || alphaFormat === true) {
9947 coords.push(alpha);
9948 }
9949 coords = /** @type {[number, number, number]} */
9950 coords.map(c => Math.round(c * 255));
9951 let collapsible = collapse && coords.every(c => c % 17 === 0);
9952 let hex = coords.map(c => {
9953 if (collapsible) {
9954 return (c / 17).toString(16);
9955 }
9956 return c.toString(16).padStart(2, "0");
9957 }).join("");
9958 return "#" + hex;
9959 }
9960 },
9961 keyword: {
9962 type: "custom",
9963 test: str => /^[a-z]+$/i.test(str),
9964 parse(str) {
9965 str = str.toLowerCase();
9966 let ret = {
9967 spaceId: "srgb",
9968 coords: null,
9969 alpha: 1
9970 };
9971 if (str === "transparent") {
9972 ret.coords = KEYWORDS.black;
9973 ret.alpha = 0;
9974 } else {
9975 ret.coords = KEYWORDS[str];
9976 }
9977 if (ret.coords) {
9978 return ret;
9979 }
9980 }
9981 }
9982 }
9983 });
9984
9985 var P3 = new RGBColorSpace({
9986 id: "p3",
9987 cssId: "display-p3",
9988 name: "P3",
9989 base: P3Linear,
9990 linearGamut: P3Linear,
9991 // Gamma encoding/decoding is the same as sRGB
9992 fromBase: sRGB.fromBase,
9993 toBase: sRGB.toBase
9994 });
9995
9996 /** @import ColorSpace from "./ColorSpace.js" */
9997 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
9998
9999 // Type re-exports
10000 /** @typedef {import("./types.js").Display} Display */
10001
10002 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
10003 defaults.display_space = sRGB;
10004 let supportsNone;
10005 if (typeof CSS !== "undefined" && CSS.supports) {
10006 // Find widest supported color space for CSS
10007 for (let space of [lab, REC2020, P3]) {
10008 let coords = space.getMinCoords();
10009 let color = {
10010 space,
10011 coords,
10012 alpha: 1
10013 };
10014 let str = serialize(color);
10015 if (CSS.supports("color", str)) {
10016 defaults.display_space = space;
10017 break;
10018 }
10019 }
10020 }
10021
10022 /**
10023 * Returns a serialization of the color that can actually be displayed in the browser.
10024 * If the default serialization can be displayed, it is returned.
10025 * Otherwise, if a `space` is given, the color is converted directly to it.
10026 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
10027 * else the closest supported space in its base color space chain (which preserves its gamut),
10028 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
10029 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
10030 * @param {ColorTypes} color
10031 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
10032 * @returns {Display} String object containing the serialized color
10033 * with a color property containing the converted color (or the original, if no conversion was necessary)
10034 */
10035 function display(color, {
10036 space,
10037 supports = (_globalThis$CSS => (_globalThis$CSS = globalThis.CSS) === null || _globalThis$CSS === void 0 ? void 0 : _globalThis$CSS.supports)(),
10038 ...options
10039 } = {}) {
10040 color = getColor(color);
10041 let ret = /** @type {Display} */serialize(color, options);
10042 if (!supports || supports("color", /** @type {string} */ret) || !defaults.display_space) {
10043 ret = /** @type {Display} */new String(ret);
10044 ret.color = /** @type {PlainColorObject} */color;
10045 } else {
10046 // If we're here, what we were about to output is not supported
10047 let fallbackColor = /** @type {PlainColorObject} */color;
10048
10049 // First, check if the culprit is none values
10050 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
10051 if (hasNone) {
10052 var _supportsNone;
10053 // Does the browser support none values?
10054 if (!((_supportsNone = supportsNone) !== null && _supportsNone !== void 0 ? _supportsNone : supportsNone = supports("color", "hsl(none 50% 50%)"))) {
10055 // Nope, try again without none
10056 fallbackColor = clone(/** @type {PlainColorObject} */color);
10057 fallbackColor.coords = /** @type {[number, number, number]} */
10058 fallbackColor.coords.map(skipNone);
10059 fallbackColor.alpha = skipNone(fallbackColor.alpha);
10060
10061 // @ts-expect-error This is set to the correct type later
10062 ret = serialize(fallbackColor, options);
10063 if (supports("color", /** @type {string} */ret)) {
10064 // We're done, now it's supported
10065 ret = /** @type {Display} */new String(ret);
10066 ret.color = fallbackColor;
10067 return ret;
10068 }
10069 }
10070 }
10071
10072 // If we're here, the color function is not supported.
10073 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
10074 // color space chain (closest first, skipping XYZ connection spaces), and use the first
10075 // space the browser supports, before falling back to the default space.
10076 if (space === undefined) {
10077 var _space$displaySpaces;
10078 space = fallbackColor.space;
10079 let candidates = (_space$displaySpaces = space.displaySpaces) !== null && _space$displaySpaces !== void 0 ? _space$displaySpaces : space.bases;
10080
10081 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
10082 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
10083 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
10084 }
10085 for (let candidate of candidates) {
10086 let candidateColor = to(fallbackColor, candidate);
10087 let str = serialize(candidateColor, options);
10088 if (supports("color", /** @type {string} */str)) {
10089 ret = /** @type {Display} */new String(str);
10090 ret.color = candidateColor;
10091 return ret;
10092 }
10093 }
10094 space = defaults.display_space;
10095 }
10096
10097 // Fall back to fallback space
10098 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */space);
10099 ret = /** @type {Display} */new String(serialize(fallbackColor, options));
10100 ret.color = fallbackColor;
10101 }
10102 return ret;
10103 }
10104
10105 /** @import { ColorTypes } from "./types.js" */
10106
10107 // Type re-exports
10108 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
10109
10110 /**
10111 * Get color differences per-component, on any color space
10112 * @param {ColorTypes} c1
10113 * @param {ColorTypes} c2
10114 * @param {object} options
10115 * @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.
10116 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
10117 * @returns {DeltasReturn}
10118 */
10119 function deltas(c1, c2, {
10120 space,
10121 hue = "shorter"
10122 } = {}) {
10123 c1 = getColor(c1);
10124 space || (space = c1.space);
10125 space = ColorSpace.get(space);
10126 let spaceCoords = Object.values(space.coords);
10127 [c1, c2] = [c1, c2].map(c => to(c, space));
10128 let [coords1, coords2] = [c1, c2].map(c => c.coords);
10129 let coords = /** @type {[number, number, number]} */
10130 coords1.map((coord1, i) => {
10131 let coordMeta = spaceCoords[i];
10132 let coord2 = coords2[i];
10133 if (coordMeta.type === "angle") {
10134 [coord1, coord2] = adjust(hue, [coord1, coord2]);
10135 }
10136 return subtractCoords(coord1, coord2);
10137 });
10138 let alpha = subtractCoords(c1.alpha, c2.alpha);
10139 return {
10140 space: (/** @type {ColorSpace} */space),
10141 coords,
10142 alpha
10143 };
10144 }
10145 function subtractCoords(c1, c2) {
10146 if (isNone(c1) || isNone(c2)) {
10147 return c1 === c2 ? null : 0;
10148 }
10149 return c1 - c2;
10150 }
10151
10152 /** @import { ColorTypes } from "./types.js" */
10153
10154 /**
10155 * @param {ColorTypes} color1
10156 * @param {ColorTypes} color2
10157 * @returns {boolean}
10158 */
10159 function equals(color1, color2) {
10160 color1 = getColor(color1);
10161 color2 = getColor(color2);
10162 return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every((c, i) => c === color2.coords[i]);
10163 }
10164
10165 /**
10166 * Relative luminance
10167 */
10168
10169 /** @import { ColorTypes } from "./types.js" */
10170
10171 /**
10172 *
10173 * @param {ColorTypes} color
10174 * @returns {number}
10175 */
10176 function getLuminance(color) {
10177 // Assume getColor() is called on color in get()
10178 return get(color, [XYZ_D65, "y"]);
10179 }
10180
10181 /**
10182 * @param {ColorTypes} color
10183 * @param {number | ((coord: number) => number)} value
10184 */
10185 function setLuminance(color, value) {
10186 // Assume getColor() is called on color in set()
10187 set(color, [XYZ_D65, "y"], value);
10188 }
10189
10190 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
10191 // Simple contrast, with fixed 5% viewing flare contribution
10192 // Symmetric, does not matter which is foreground and which is background
10193
10194
10195 /**
10196 * @param {import("../types.js").ColorTypes} color1
10197 * @param {import("../types.js").ColorTypes} color2
10198 * @returns {number}
10199 */
10200 function contrastWCAG21(color1, color2) {
10201 color1 = getColor(color1);
10202 color2 = getColor(color2);
10203 let Y1 = Math.max(getLuminance(color1), 0);
10204 let Y2 = Math.max(getLuminance(color2), 0);
10205 if (Y2 > Y1) {
10206 [Y1, Y2] = [Y2, Y1];
10207 }
10208 return (Y1 + 0.05) / (Y2 + 0.05);
10209 }
10210
10211 // exponents
10212 const normBG = 0.56;
10213 const normTXT = 0.57;
10214 const revTXT = 0.62;
10215 const revBG = 0.65;
10216
10217 // clamps
10218 const blkThrs = 0.022;
10219 const blkClmp = 1.414;
10220 const loClip = 0.1;
10221 const deltaYmin = 0.0005;
10222
10223 // scalers
10224 // see https://github.com/w3c/silver/issues/645
10225 const scaleBoW = 1.14;
10226 const loBoWoffset = 0.027;
10227 const scaleWoB = 1.14;
10228 function fclamp(Y) {
10229 if (Y >= blkThrs) {
10230 return Y;
10231 }
10232 return Y + (blkThrs - Y) ** blkClmp;
10233 }
10234 function linearize(val) {
10235 let sign = val < 0 ? -1 : 1;
10236 let abs = Math.abs(val);
10237 return sign * Math.pow(abs, 2.4);
10238 }
10239
10240 /**
10241 * Not symmetric, requires a foreground (text) color, and a background color
10242 * @param {import("../types.js").ColorTypes} background
10243 * @param {import("../types.js").ColorTypes} foreground
10244 * @returns {number}
10245 */
10246 function contrastAPCA(background, foreground) {
10247 foreground = getColor(foreground);
10248 background = getColor(background);
10249 let S;
10250 let C;
10251 let Sapc;
10252
10253 // Myndex as-published, assumes sRGB inputs
10254 let R, G, B;
10255 foreground = to(foreground, "srgb");
10256 // Should these be clamped to in-gamut values?
10257
10258 // Calculates "screen luminance" with non-standard simple gamma EOTF
10259 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
10260 [R, G, B] = foreground.coords.map(c => {
10261 return isNone(c) ? 0 : c;
10262 });
10263 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10264 background = to(background, "srgb");
10265 [R, G, B] = background.coords.map(c => {
10266 return isNone(c) ? 0 : c;
10267 });
10268 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10269
10270 // toe clamping of very dark values to account for flare
10271 let Ytxt = fclamp(lumTxt);
10272 let Ybg = fclamp(lumBg);
10273
10274 // are we "Black on White" (dark on light), or light on dark?
10275 let BoW = Ybg > Ytxt;
10276
10277 // why is this a delta, when Y is not perceptually uniform?
10278 // Answer: it is a noise gate, see
10279 // https://github.com/LeaVerou/color.js/issues/208
10280 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
10281 C = 0;
10282 } else {
10283 if (BoW) {
10284 // dark text on light background
10285 S = Ybg ** normBG - Ytxt ** normTXT;
10286 C = S * scaleBoW;
10287 } else {
10288 // light text on dark background
10289 S = Ybg ** revBG - Ytxt ** revTXT;
10290 C = S * scaleWoB;
10291 }
10292 }
10293 if (Math.abs(C) < loClip) {
10294 Sapc = 0;
10295 } else if (C > 0) {
10296 // not clear whether Woffset is loBoWoffset or loWoBoffset
10297 // but they have the same value
10298 Sapc = C - loBoWoffset;
10299 } else {
10300 Sapc = C + loBoWoffset;
10301 }
10302 return Sapc * 100;
10303 }
10304
10305 // Michelson luminance contrast
10306 // the relation between the spread and the sum of the two luminances
10307 // Symmetric, does not matter which is foreground and which is background
10308 // No black level compensation for flare.
10309
10310
10311 /**
10312 * @param {import("../types.js").ColorTypes} color1
10313 * @param {import("../types.js").ColorTypes} color2
10314 * @returns {number}
10315 */
10316 function contrastMichelson(color1, color2) {
10317 color1 = getColor(color1);
10318 color2 = getColor(color2);
10319 let Y1 = Math.max(getLuminance(color1), 0);
10320 let Y2 = Math.max(getLuminance(color2), 0);
10321 if (Y2 > Y1) {
10322 [Y1, Y2] = [Y2, Y1];
10323 }
10324 let denom = Y1 + Y2;
10325 return denom === 0 ? 0 : (Y1 - Y2) / denom;
10326 }
10327
10328 // Weber luminance contrast
10329 // The difference between the two luminances divided by the lower luminance
10330 // Symmetric, does not matter which is foreground and which is background
10331 // No black level compensation for flare.
10332
10333
10334 // the darkest sRGB color above black is #000001 and this produces
10335 // a plain Weber contrast of ~45647.
10336 // So, setting the divide-by-zero result at 50000 is a reasonable
10337 // max clamp for the plain Weber
10338 const max = 50000;
10339
10340 /**
10341 * @param {import("../types.js").ColorTypes} color1
10342 * @param {import("../types.js").ColorTypes} color2
10343 * @returns {number}
10344 */
10345 function contrastWeber(color1, color2) {
10346 color1 = getColor(color1);
10347 color2 = getColor(color2);
10348 let Y1 = Math.max(getLuminance(color1), 0);
10349 let Y2 = Math.max(getLuminance(color2), 0);
10350 if (Y2 > Y1) {
10351 [Y1, Y2] = [Y2, Y1];
10352 }
10353 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
10354 }
10355
10356 // CIE Lightness difference, as used by Google Material Design
10357 // Google HCT Tone is the same as CIE Lightness
10358 // https://material.io/blog/science-of-color-design
10359
10360
10361 /**
10362 * @param {import("../types.js").ColorTypes} color1
10363 * @param {import("../types.js").ColorTypes} color2
10364 * @returns {number}
10365 */
10366 function contrastLstar(color1, color2) {
10367 color1 = getColor(color1);
10368 color2 = getColor(color2);
10369 let L1 = get(color1, [lab, "l"]);
10370 let L2 = get(color2, [lab, "l"]);
10371 return Math.abs(L1 - L2);
10372 }
10373
10374 // κ * ε = 2^3 = 8
10375 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10376 const ε3 = 24 / 116;
10377 const κ$2 = 24389 / 27; // 29^3/3^3
10378
10379 let white$1 = WHITES.D65;
10380 var lab_d65 = new ColorSpace({
10381 id: "lab-d65",
10382 name: "Lab D65",
10383 coords: {
10384 l: {
10385 refRange: [0, 100],
10386 name: "Lightness"
10387 },
10388 a: {
10389 refRange: [-125, 125]
10390 },
10391 b: {
10392 refRange: [-125, 125]
10393 }
10394 },
10395 // Assuming XYZ is relative to D65, convert to CIE Lab
10396 // from CIE standard, which now defines these as a rational fraction
10397 white: white$1,
10398 base: XYZ_D65,
10399 // Convert D65-adapted XYZ to Lab
10400 // CIE 15.3:2004 section 8.2.1.1
10401 fromBase(XYZ) {
10402 // compute xyz, which is XYZ scaled relative to reference white
10403 let xyz = XYZ.map((value, i) => value / white$1[i]);
10404
10405 // now compute f
10406 let f = xyz.map(value => value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116);
10407 return [116 * f[1] - 16,
10408 // L
10409 500 * (f[0] - f[1]),
10410 // a
10411 200 * (f[1] - f[2]) // b
10412 ];
10413 },
10414 // Convert Lab to D65-adapted XYZ
10415 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
10416 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
10417 toBase(Lab) {
10418 // compute f, starting with the luminance-related term
10419 let f = [];
10420 f[1] = (Lab[0] + 16) / 116;
10421 f[0] = Lab[1] / 500 + f[1];
10422 f[2] = f[1] - Lab[2] / 200;
10423
10424 // compute xyz
10425 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];
10426
10427 // Compute XYZ by scaling xyz by reference white
10428 return xyz.map((value, i) => value * white$1[i]);
10429 },
10430 formats: {
10431 "lab-d65": {
10432 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
10433 }
10434 }
10435 });
10436
10437 // Delta Phi Star perceptual lightness contrast
10438 // See https://github.com/Myndex/deltaphistar
10439 // The (difference between two Lstars each raised to phi) raised to (1/phi)
10440 // Symmetric, does not matter which is foreground and which is background
10441
10442 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
10443
10444 /**
10445 * @param {import("../types.js").ColorTypes} color1
10446 * @param {import("../types.js").ColorTypes} color2
10447 * @returns {number}
10448 */
10449 function contrastDeltaPhi(color1, color2) {
10450 color1 = getColor(color1);
10451 color2 = getColor(color2);
10452 let Lstr1 = get(color1, [lab_d65, "l"]);
10453 let Lstr2 = get(color2, [lab_d65, "l"]);
10454 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
10455 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
10456 return contrast < 7.5 ? 0.0 : contrast;
10457 }
10458
10459 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
10460
10461 var contrastAlgorithms = /*#__PURE__*/Object.freeze({
10462 __proto__: null,
10463 contrastAPCA: contrastAPCA,
10464 contrastDeltaPhi: contrastDeltaPhi,
10465 contrastLstar: contrastLstar,
10466 contrastMichelson: contrastMichelson,
10467 contrastWCAG21: contrastWCAG21,
10468 contrastWeber: contrastWeber
10469 });
10470
10471 /** @import { ColorTypes } from "./types.js" */
10472
10473 // Type re-exports
10474 /** @typedef {import("./types.js").Algorithms} Algorithms */
10475
10476 /**
10477 *
10478 * @param {ColorTypes} background
10479 * @param {ColorTypes} foreground
10480 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
10481 * Algorithm to use as well as any other options to pass to the contrast function
10482 * @returns {number}
10483 * @throws {TypeError} Unknown or unspecified algorithm
10484 */
10485 function contrast(background, foreground, o) {
10486 if (isString(o)) {
10487 o = {
10488 algorithm: o
10489 };
10490 }
10491 let {
10492 algorithm,
10493 ...rest
10494 } = o || {};
10495 if (!algorithm) {
10496 let algorithms = Object.keys(contrastAlgorithms).map(a => a.replace(/^contrast/, "")).join(", ");
10497 throw new TypeError(`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`);
10498 }
10499 background = getColor(background);
10500 foreground = getColor(foreground);
10501 for (let a in contrastAlgorithms) {
10502 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
10503 return contrastAlgorithms[a](background, foreground, rest);
10504 }
10505 }
10506 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
10507 }
10508
10509 /** @import Color, { ColorTypes } from "./color.js" */
10510
10511 // Chromaticity coordinates
10512 /**
10513 * @param {ColorTypes} color
10514 * @returns {[number, number]}
10515 */
10516 function uv(color) {
10517 // Assumes getAll() calls getColor() on color
10518 let [X, Y, Z] = getAll(color, XYZ_D65);
10519 let denom = X + 15 * Y + 3 * Z;
10520 return [4 * X / denom, 9 * Y / denom];
10521 }
10522
10523 /**
10524 * @param {ColorTypes} color
10525 * @returns {[number, number]}
10526 */
10527 function xy(color) {
10528 // Assumes getAll() calls getColor() on color
10529 let [X, Y, Z] = getAll(color, XYZ_D65);
10530 let sum = X + Y + Z;
10531 return [X / sum, Y / sum];
10532 }
10533
10534 /** @import { ColorTypes } from "./types.js" */
10535
10536 // Type re-exports
10537 /** @typedef {import("./types.js").Methods} Methods */
10538
10539 /**
10540 *
10541 * @param {ColorTypes} c1
10542 * @param {ColorTypes} c2
10543 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
10544 * deltaE method to use as well as any other options to pass to the deltaE function
10545 * @returns {number}
10546 * @throws {TypeError} Unknown or unspecified method
10547 */
10548 function deltaE(c1, c2, o = {}) {
10549 if (isString(o)) {
10550 o = {
10551 method: o
10552 };
10553 }
10554 let {
10555 method = defaults.deltaE,
10556 ...rest
10557 } = o;
10558 for (let m in deltaEMethods) {
10559 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
10560 return deltaEMethods[m](c1, c2, rest);
10561 }
10562 }
10563 throw new TypeError(`Unknown deltaE method: ${method}`);
10564 }
10565
10566 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10567
10568 /**
10569 * @param {ColorTypes} color
10570 * @param {number} amount
10571 * @returns {PlainColorObject}
10572 */
10573 function lighten(color, amount = 0.25) {
10574 let space = ColorSpace.get("oklch", "lch");
10575 let /** @type {Ref} */lightness = [space, "l"];
10576 return set(color, lightness, l => l * (1 + amount));
10577 }
10578
10579 /**
10580 * @param {ColorTypes} color
10581 * @param {number} amount
10582 * @returns {PlainColorObject}
10583 */
10584 function darken(color, amount = 0.25) {
10585 let space = ColorSpace.get("oklch", "lch");
10586 let /** @type {Ref} */lightness = [space, "l"];
10587 return set(color, lightness, l => l * (1 - amount));
10588 }
10589
10590 /** @type {"color"} */
10591 lighten.returns = "color";
10592
10593 /** @type {"color"} */
10594 darken.returns = "color";
10595
10596 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10597
10598 // Type re-exports
10599 /** @typedef {import("./types.js").MixOptions} MixOptions */
10600 /** @typedef {import("./types.js").Range} Range */
10601 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
10602 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
10603
10604 /**
10605 * Return an intermediate color between two colors
10606 * @overload
10607 * @param {ColorTypes} c1
10608 * @param {ColorTypes} c2
10609 * @param {MixOptions} [options]
10610 * @returns {PlainColorObject}
10611 */
10612 /**
10613 * @overload
10614 * @param {ColorTypes} c1
10615 * @param {ColorTypes} c2
10616 * @param {number} [p=0.5]
10617 * @param {MixOptions} [options]
10618 * @returns {PlainColorObject}
10619 */
10620 function mix(c1, c2, p, o = {}) {
10621 var _p;
10622 [c1, c2] = [getColor(c1), getColor(c2)];
10623 if (type(p) === "object") {
10624 [p, o] = [0.5, p];
10625 }
10626 let r = range(c1, c2, o);
10627 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
10628 }
10629
10630 /**
10631 * Get an array of discrete steps
10632 * @overload
10633 * @param {ColorTypes} c1
10634 * @param {ColorTypes} c2
10635 * @param {StepsOptions} [options]
10636 * @returns {PlainColorObject[]}
10637 */
10638 /**
10639 * @overload
10640 * @param {Range} range
10641 * @param {StepsOptions} [options]
10642 * @returns {PlainColorObject[]}
10643 */
10644 function steps(c1, c2, options = {}) {
10645 let colorRange;
10646 if (isRange(c1)) {
10647 // Tweaking existing range
10648 [colorRange, options] = [c1, c2];
10649 [c1, c2] = colorRange.rangeArgs.colors;
10650 }
10651 let {
10652 maxDeltaE,
10653 deltaEMethod,
10654 steps = 2,
10655 maxSteps = 1000,
10656 ...rangeOptions
10657 } = options;
10658 if (!colorRange) {
10659 [c1, c2] = [getColor(c1), getColor(c2)];
10660 colorRange = range(c1, c2, rangeOptions);
10661 }
10662 let totalDelta = deltaE(c1, c2, deltaEMethod);
10663 let actualSteps = maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
10664 let ret = [];
10665 if (maxSteps !== undefined) {
10666 actualSteps = Math.min(actualSteps, maxSteps);
10667 }
10668 if (actualSteps === 1) {
10669 ret = [{
10670 p: 0.5,
10671 color: colorRange(0.5)
10672 }];
10673 } else {
10674 let step = 1 / (actualSteps - 1);
10675 ret = Array.from({
10676 length: actualSteps
10677 }, (_, i) => {
10678 let p = i * step;
10679 return {
10680 p,
10681 color: colorRange(p)
10682 };
10683 });
10684 }
10685 if (maxDeltaE > 0) {
10686 // Iterate over all stops and find max deltaE
10687 let maxDelta = ret.reduce((acc, cur, i) => {
10688 if (i === 0) {
10689 return 0;
10690 }
10691 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
10692 return Math.max(acc, ΔΕ);
10693 }, 0);
10694 while (maxDelta > maxDeltaE) {
10695 // Insert intermediate stops and measure maxDelta again
10696 // We need to do this for all pairs, otherwise the midpoint shifts
10697 maxDelta = 0;
10698 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
10699 let prev = ret[i - 1];
10700 let cur = ret[i];
10701 let p = (cur.p + prev.p) / 2;
10702 let color = colorRange(p);
10703 maxDelta = Math.max(maxDelta, deltaE(color, prev.color, deltaEMethod), deltaE(color, cur.color, deltaEMethod));
10704 ret.splice(i, 0, {
10705 p,
10706 color: colorRange(p)
10707 });
10708 i++;
10709 }
10710 }
10711 }
10712 ret = ret.map(a => a.color);
10713 return ret;
10714 }
10715
10716 /**
10717 * Creates a function that accepts a number and returns a color.
10718 * For numbers in the range 0 to 1, the function interpolates;
10719 * for numbers outside that range, the function extrapolates
10720 * (and thus may not return the results you expect)
10721 * @overload
10722 * @param {Range} range
10723 * @param {RangeOptions} [options]
10724 * @returns {Range}
10725 */
10726 /**
10727 * @overload
10728 * @param {ColorTypes} color1
10729 * @param {ColorTypes} color2
10730 * @param {RangeOptions & Record<string, any>} [options]
10731 * @returns {Range}
10732 */
10733 function range(color1, color2, options = {}) {
10734 if (isRange(color1)) {
10735 // Tweaking existing range
10736 let [r, options] = [color1, color2];
10737 return range(...r.rangeArgs.colors, {
10738 ...r.rangeArgs.options,
10739 ...options
10740 });
10741 }
10742 let {
10743 space,
10744 outputSpace,
10745 progression,
10746 premultiplied
10747 } = options;
10748 color1 = getColor(color1);
10749 color2 = getColor(color2);
10750
10751 // Make sure we're working on copies of these colors
10752 color1 = clone(color1);
10753 color2 = clone(color2);
10754 let rangeArgs = {
10755 colors: [color1, color2],
10756 options
10757 };
10758 if (space) {
10759 space = ColorSpace.get(space);
10760 } else {
10761 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
10762 }
10763 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
10764 color1 = to(color1, space);
10765 color2 = to(color2, space);
10766
10767 // Gamut map to avoid areas of flat color
10768 color1 = toGamut(color1);
10769 color2 = toGamut(color2);
10770
10771 // The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz)
10772 let hueId = space.hueId;
10773 let hueIndex = space.hueIndex;
10774
10775 // Handle hue interpolation
10776 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
10777 if (hueId) {
10778 let arc = options.hue = options.hue || "shorter";
10779 let /** @type {Ref} */hue = [space, hueId];
10780 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
10781 // Undefined hues must be evaluated before hue fix-up to properly
10782 // calculate hue arcs between undefined and defined hues.
10783 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
10784 if (isNone(θ1) && !isNone(θ2)) {
10785 θ1 = θ2;
10786 } else if (isNone(θ2) && !isNone(θ1)) {
10787 θ2 = θ1;
10788 }
10789 [θ1, θ2] = adjust(arc, [θ1, θ2]);
10790 set(color1, hue, θ1);
10791 set(color2, hue, θ2);
10792 }
10793
10794 // An undefined alpha takes the other color's alpha, and premultiplication must use
10795 // that carried forward value, rather than the zero it would otherwise be treated as.
10796 // If both alphas are undefined, they stay that way, and no premultiplication happens.
10797 // See https://drafts.csswg.org/css-color-4/#interpolation-missing
10798 if (isNone(color1.alpha) && !isNone(color2.alpha)) {
10799 color1.alpha = color2.alpha;
10800 } else if (isNone(color2.alpha) && !isNone(color1.alpha)) {
10801 color2.alpha = color1.alpha;
10802 }
10803 if (premultiplied) {
10804 color1.coords = premultiply(color1.coords, color1.alpha, hueIndex);
10805 color2.coords = premultiply(color2.coords, color2.alpha, hueIndex);
10806 }
10807 return Object.assign(p => {
10808 p = progression ? progression(p) : p;
10809 let coords = color1.coords.map((start, i) => {
10810 let end = color2.coords[i];
10811 return interpolate(start, end, p);
10812 });
10813 let alpha = interpolate(color1.alpha, color2.alpha, p);
10814 let ret = {
10815 space,
10816 coords,
10817 alpha
10818 };
10819 if (premultiplied) {
10820 // Undo premultiplication, again leaving any hue angle untouched
10821 ret.coords = premultiply(ret.coords, alpha, hueIndex, true);
10822 }
10823 if (outputSpace !== space) {
10824 ret = to(ret, outputSpace);
10825 }
10826 return ret;
10827 }, {
10828 rangeArgs
10829 });
10830 }
10831
10832 /**
10833 * Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it.
10834 * Per CSS Color 4, the hue angle of a polar space is never premultiplied,
10835 * `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all,
10836 * and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero.
10837 * See https://drafts.csswg.org/css-color-4/#interpolation-alpha
10838 * @param {(number | null)[]} coords
10839 * @param {number | null} alpha
10840 * @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none
10841 * @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it
10842 * @returns {[number, number, number]}
10843 */
10844 function premultiply(coords, alpha, hueIndex, undo = false) {
10845 if (isNone(alpha) || undo && alpha === 0) {
10846 // The (un-)premultiplied value is the value itself
10847 return /** @type {[number, number, number]} */coords;
10848 }
10849 return /** @type {[number, number, number]} */coords.map((c, i) => {
10850 if (i === hueIndex || isNone(c)) {
10851 return c;
10852 }
10853 return undo ? c / alpha : c * alpha;
10854 });
10855 }
10856
10857 /**
10858 * @param {any} val
10859 * @returns {val is Range}
10860 */
10861 function isRange(val) {
10862 return type(val) === "function" && !!val.rangeArgs;
10863 }
10864 defaults.interpolationSpace = "lab";
10865
10866 var HSL = new ColorSpace({
10867 id: "hsl",
10868 name: "HSL",
10869 coords: {
10870 h: {
10871 refRange: [0, 360],
10872 type: "angle",
10873 name: "Hue"
10874 },
10875 s: {
10876 range: [0, 100],
10877 name: "Saturation"
10878 },
10879 l: {
10880 range: [0, 100],
10881 name: "Lightness"
10882 }
10883 },
10884 base: sRGB,
10885 rgbGamut: sRGB,
10886 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
10887 fromBase: rgb => {
10888 let max = Math.max(...rgb);
10889 let min = Math.min(...rgb);
10890 let [r, g, b] = rgb;
10891 let [h, s, l] = [null, 0, (min + max) / 2];
10892 let d = max - min;
10893 if (d !== 0) {
10894 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
10895 switch (max) {
10896 case r:
10897 h = (g - b) / d + (g < b ? 6 : 0);
10898 break;
10899 case g:
10900 h = (b - r) / d + 2;
10901 break;
10902 case b:
10903 h = (r - g) / d + 4;
10904 }
10905 h = h * 60;
10906 }
10907
10908 // Very out of gamut colors can produce negative saturation
10909 // If so, just rotate the hue by 180 and use a positive saturation
10910 // see https://github.com/w3c/csswg-drafts/issues/9222
10911 if (s < 0) {
10912 h += 180;
10913 s = Math.abs(s);
10914 }
10915 if (h >= 360) {
10916 h -= 360;
10917 }
10918 return [h, s * 100, l * 100];
10919 },
10920 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
10921 toBase: hsl => {
10922 let [h, s, l] = hsl;
10923 h = h % 360;
10924 if (h < 0) {
10925 h += 360;
10926 }
10927 s /= 100;
10928 l /= 100;
10929 function f(n) {
10930 let k = (n + h / 30) % 12;
10931 let a = s * Math.min(l, 1 - l);
10932 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
10933 }
10934 return [f(0), f(8), f(4)];
10935 },
10936 formats: {
10937 hsl: {
10938 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10939 },
10940 hsla: {
10941 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
10942 commas: true,
10943 alpha: true
10944 }
10945 }
10946 });
10947
10948 var hslP3 = new ColorSpace({
10949 id: "hsl-p3",
10950 cssId: "--hsl-p3",
10951 name: "HSL P3",
10952 coords: {
10953 h: {
10954 refRange: [0, 360],
10955 type: "angle",
10956 name: "Hue"
10957 },
10958 s: {
10959 range: [0, 100],
10960 name: "Saturation"
10961 },
10962 l: {
10963 range: [0, 100],
10964 name: "Lightness"
10965 }
10966 },
10967 base: P3,
10968 rgbGamut: P3,
10969 fromBase: HSL.fromBase,
10970 toBase: HSL.toBase
10971 });
10972
10973 var hslRec2020 = new ColorSpace({
10974 id: "hsl-rec2020",
10975 cssId: "--hsl-rec2020",
10976 name: "HSL Rec.2020",
10977 coords: {
10978 h: {
10979 refRange: [0, 360],
10980 type: "angle",
10981 name: "Hue"
10982 },
10983 s: {
10984 range: [0, 100],
10985 name: "Saturation"
10986 },
10987 l: {
10988 range: [0, 100],
10989 name: "Lightness"
10990 }
10991 },
10992 base: REC2020,
10993 rgbGamut: REC2020,
10994 fromBase: HSL.fromBase,
10995 toBase: HSL.toBase
10996 });
10997
10998 // Note that, like HSL, calculations are done directly on
10999 // gamma-corrected sRGB values rather than linearising them first.
11000
11001 var HSV = new ColorSpace({
11002 id: "hsv",
11003 name: "HSV",
11004 coords: {
11005 h: {
11006 refRange: [0, 360],
11007 type: "angle",
11008 name: "Hue"
11009 },
11010 s: {
11011 range: [0, 100],
11012 name: "Saturation"
11013 },
11014 v: {
11015 range: [0, 100],
11016 name: "Value"
11017 }
11018 },
11019 base: sRGB,
11020 rgbGamut: sRGB,
11021 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
11022 fromBase(rgb) {
11023 let max = Math.max(...rgb);
11024 let min = Math.min(...rgb);
11025 let [r, g, b] = rgb;
11026 let [h, s, v] = [null, 0, max];
11027 let d = max - min;
11028 if (d !== 0) {
11029 switch (max) {
11030 case r:
11031 h = (g - b) / d + (g < b ? 6 : 0);
11032 break;
11033 case g:
11034 h = (b - r) / d + 2;
11035 break;
11036 case b:
11037 h = (r - g) / d + 4;
11038 }
11039 h = h * 60;
11040 }
11041 if (v) {
11042 s = d / v;
11043 }
11044 if (h >= 360) {
11045 h -= 360;
11046 }
11047 return [h, s * 100, v * 100];
11048 },
11049 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
11050 toBase(hsv) {
11051 let [h, s, v] = hsv;
11052 h = h % 360;
11053 if (h < 0) {
11054 h += 360;
11055 }
11056 s /= 100;
11057 v /= 100;
11058 function f(n) {
11059 let k = (n + h / 60) % 6;
11060 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
11061 }
11062 return [f(5), f(3), f(1)];
11063 },
11064 formats: {
11065 color: {
11066 id: "--hsv",
11067 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11068 }
11069 }
11070 });
11071
11072 // The Hue, Whiteness Blackness (HWB) colorspace
11073 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
11074 // Note that, like HSL, calculations are done directly on
11075 // gamma-corrected sRGB values rather than linearising them first.
11076
11077 var hwb = new ColorSpace({
11078 id: "hwb",
11079 name: "HWB",
11080 coords: {
11081 h: {
11082 refRange: [0, 360],
11083 type: "angle",
11084 name: "Hue"
11085 },
11086 w: {
11087 range: [0, 100],
11088 name: "Whiteness"
11089 },
11090 b: {
11091 range: [0, 100],
11092 name: "Blackness"
11093 }
11094 },
11095 base: HSV,
11096 rgbGamut: sRGB,
11097 fromBase(hsv) {
11098 let [h, s, v] = hsv;
11099 return [h, v * (100 - s) / 100, 100 - v];
11100 },
11101 toBase(hwb) {
11102 let [h, w, b] = hwb;
11103
11104 // Now convert percentages to [0..1]
11105 w /= 100;
11106 b /= 100;
11107
11108 // Achromatic check (white plus black >= 1)
11109 let sum = w + b;
11110 if (sum >= 1) {
11111 let gray = w / sum;
11112 return [h, 0, gray * 100];
11113 }
11114 let v = 1 - b;
11115 let s = v === 0 ? 0 : 1 - w / v;
11116 return [h, s * 100, v * 100];
11117 },
11118 formats: {
11119 hwb: {
11120 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11121 }
11122 }
11123 });
11124
11125 /** @import { Matrix3x3 } from "../types.js" */
11126
11127 // convert an array of linear-light a98-rgb values to CIE XYZ
11128 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
11129 // has greater numerical precision than section 4.3.5.3 of
11130 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
11131 // but the values below were calculated from first principles
11132 // from the chromaticity coordinates of R G B W
11133
11134 /**
11135 * Matrices used by this color space, also available as `A98RGB_Linear.M`
11136 * @type {Record<string, Matrix3x3>}
11137 */
11138 // prettier-ignore
11139 const M$5 = {
11140 toXYZ: [[0.5766690429101305, 0.1855582379065463, 0.1882286462349947], [0.29734497525053605, 0.6273635662554661, 0.07529145849399788], [0.02703136138641234, 0.07068885253582723, 0.9913375368376388]],
11141 fromXYZ: [[2.0415879038107465, -0.5650069742788596, -0.34473135077832956], [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557], [0.013444280632031142, -0.11836239223101838, 1.0151749943912054]]
11142 };
11143 var A98Linear = new RGBColorSpace({
11144 id: "a98rgb-linear",
11145 cssId: "--a98-rgb-linear",
11146 name: "Linear Adobe® 98 RGB compatible",
11147 white: "D65",
11148 M: M$5
11149 });
11150
11151 var a98rgb = new RGBColorSpace({
11152 id: "a98rgb",
11153 cssId: "a98-rgb",
11154 name: "Adobe® 98 RGB compatible",
11155 base: A98Linear,
11156 linearGamut: A98Linear,
11157 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
11158 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val))
11159 });
11160
11161 /** @import { Matrix3x3 } from "../types.js" */
11162
11163 /**
11164 * Matrices used by this color space, also available as `ProPhoto_Linear.M`.
11165 * Uses D50 (so no chromatic adaptation needed afterwards). The matrix cannot
11166 * be expressed in rational form, but is calculated to 64 bit accuracy.
11167 * see https://github.com/w3c/csswg-drafts/issues/7675
11168 * @type {Record<string, Matrix3x3>}
11169 */
11170 // prettier-ignore
11171 const M$4 = {
11172 toXYZ: [[0.79776664490064230, 0.13518129740053308, 0.03134773412839220], [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], [0.00000000000000000, 0.00000000000000000, 0.82510460251046020]],
11173 fromXYZ: [[1.34578688164715830, -0.25557208737979464, -0.05110186497554526], [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], [0.00000000000000000, 0.00000000000000000, 1.21196754563894520]]
11174 };
11175 var ProPhotoLinear = new RGBColorSpace({
11176 id: "prophoto-linear",
11177 cssId: "--prophoto-rgb-linear",
11178 name: "Linear ProPhoto",
11179 white: "D50",
11180 base: XYZ_D50,
11181 M: M$4
11182 });
11183
11184 const Et = 1 / 512;
11185 const Et2 = 16 / 512;
11186 var prophoto = new RGBColorSpace({
11187 id: "prophoto",
11188 cssId: "prophoto-rgb",
11189 name: "ProPhoto",
11190 base: ProPhotoLinear,
11191 linearGamut: ProPhotoLinear,
11192 toBase(RGB) {
11193 // Transfer curve is gamma 1.8 with a small linear portion
11194 return RGB.map(v => {
11195 let sign = v < 0 ? -1 : 1;
11196 let abs = v * sign;
11197 if (abs < Et2) {
11198 return v / 16;
11199 }
11200 return sign * abs ** 1.8;
11201 });
11202 },
11203 fromBase(RGB) {
11204 return RGB.map(v => {
11205 let sign = v < 0 ? -1 : 1;
11206 let abs = v * sign;
11207 if (abs >= Et) {
11208 return sign * abs ** (1 / 1.8);
11209 }
11210 return 16 * v;
11211 });
11212 }
11213 });
11214
11215 // import sRGB from "./srgb.js";
11216
11217 const α = 1.09929682680944;
11218 const β = 0.018053968510807;
11219 var rec2020Oetf = new RGBColorSpace({
11220 id: "--rec2020-oetf",
11221 name: "REC.2020_Scene_Referred",
11222 base: REC2020Linear,
11223 linearGamut: REC2020Linear,
11224 referred: "scene",
11225 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
11226 toBase(RGB) {
11227 return RGB.map(function (val) {
11228 let sign = val < 0 ? -1 : 1;
11229 let abs = val * sign;
11230 if (abs < β * 4.5) {
11231 return val / 4.5;
11232 }
11233 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
11234 });
11235 },
11236 fromBase(RGB) {
11237 return RGB.map(function (val) {
11238 let sign = val < 0 ? -1 : 1;
11239 let abs = val * sign;
11240 if (abs >= β) {
11241 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
11242 }
11243 return 4.5 * val;
11244 });
11245 }
11246 });
11247
11248 var oklchP3 = new GamutRelativeColorSpace({
11249 id: "oklch-p3",
11250 cssId: "--oklch-p3",
11251 name: "OKLCh P3",
11252 base: OKLCH,
11253 gamutSpace: P3
11254 });
11255
11256 var oklchSrgb = new GamutRelativeColorSpace({
11257 id: "oklch-srgb",
11258 cssId: "--oklch-srgb",
11259 name: "OKLCh sRGB",
11260 base: OKLCH,
11261 gamutSpace: sRGB
11262 });
11263
11264 var oklchRec2020 = new GamutRelativeColorSpace({
11265 id: "oklch-rec2020",
11266 cssId: "--oklch-rec2020",
11267 name: "OKLCh Rec.2020",
11268 base: OKLCH,
11269 gamutSpace: REC2020
11270 });
11271
11272 var lchP3 = new GamutRelativeColorSpace({
11273 id: "lch-p3",
11274 cssId: "--lch-p3",
11275 name: "LCH P3",
11276 base: lch,
11277 gamutSpace: P3
11278 });
11279
11280 var lchSrgb = new GamutRelativeColorSpace({
11281 id: "lch-srgb",
11282 cssId: "--lch-srgb",
11283 name: "LCH sRGB",
11284 base: lch,
11285 gamutSpace: sRGB
11286 });
11287
11288 var lchRec2020 = new GamutRelativeColorSpace({
11289 id: "lch-rec2020",
11290 cssId: "--lch-rec2020",
11291 name: "LCH Rec.2020",
11292 base: lch,
11293 gamutSpace: REC2020
11294 });
11295
11296 /** @import { Matrix3x3, Vector3 } from "../types.js" */
11297
11298 // Type re-exports
11299 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
11300
11301 const tau = 2 * Math.PI;
11302
11303 /**
11304 * Matrices used by this color space (Oklab's, plus its own),
11305 * also available as `Okhsl.M`
11306 * @type {Record<string, Matrix3x3>}
11307 */
11308 // prettier-ignore
11309 const M$3 = {
11310 ...Oklab.M,
11311 toLMS: [[0.4122214694707629, 0.5363325372617349, 0.0514459932675022], [0.2119034958178251, 0.6806995506452344, 0.1073969535369405], [0.0883024591900564, 0.2817188391361215, 0.6299787016738222]],
11312 toSRGBLinear: [[4.0767416360759583, -3.3077115392580629, 0.2309699031821043], [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117]]
11313 };
11314
11315 /** @type {OKCoeff} */
11316 const RGBCoeff = [
11317 // Red
11318 [
11319 // Limit
11320 [-1.8817031, -0.80936501],
11321 // `Kn` coefficients
11322 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245]],
11323 // Green
11324 [
11325 // Limit
11326 [1.8144408, -1.19445267],
11327 // `Kn` coefficients
11328 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204]],
11329 // Blue
11330 [
11331 // Limit
11332 [0.13110758, 1.81333971],
11333 // `Kn` coefficients
11334 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167]]];
11335 const floatMax = Number.MAX_VALUE;
11336 const K1 = 0.206;
11337 const K2 = 0.03;
11338 const K3 = (1.0 + K1) / (1.0 + K2);
11339 function vdot(a, b) {
11340 // Dot two vectors
11341
11342 let l = a.length;
11343 if (l !== b.length) {
11344 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
11345 }
11346 let s = 0.0;
11347 a.forEach((c, i) => {
11348 s += c * b[i];
11349 });
11350 return s;
11351 }
11352
11353 /**
11354 * Toe function for L_r
11355 * @param {number} x
11356 */
11357 function toe(x) {
11358 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
11359 }
11360
11361 /**
11362 * Inverse toe function for L_r
11363 * @param {number} x
11364 */
11365 function toeInv(x) {
11366 return (x ** 2 + K1 * x) / (K3 * (x + K2));
11367 }
11368
11369 /**
11370 * @param {readonly [number, number]} cusp
11371 * @returns {[number, number]}
11372 */
11373 function toSt(cusp) {
11374 // To ST.
11375
11376 let [l, c] = cusp;
11377 return [c / l, c / (1 - l)];
11378 }
11379 function getStMid(a, b) {
11380 // Returns a smooth approximation of the location of the cusp.
11381 //
11382 // This polynomial was created by an optimization process.
11383 // It has been designed so that S_mid < S_max and T_mid < T_max.
11384
11385 // prettier-ignore
11386 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))));
11387
11388 // prettier-ignore
11389 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))));
11390 return [s, t];
11391 }
11392
11393 /**
11394 * @param {Vector3} lab
11395 * @param {Matrix3x3} lmsToRgb
11396 */
11397 function oklabToLinearRGB(lab, lmsToRgb) {
11398 // Convert from Oklab to linear RGB.
11399 //
11400 // Can be any gamut as long as `lmsToRgb` is a matrix
11401 // that transform the LMS values to the linear RGB space.
11402
11403 let lms = multiply_v3_m3x3(lab, M$3.LabtoLMS);
11404 lms[0] = lms[0] ** 3;
11405 lms[1] = lms[1] ** 3;
11406 lms[2] = lms[2] ** 3;
11407 return multiply_v3_m3x3(lms, lmsToRgb, lms);
11408 }
11409
11410 /**
11411 * @param {number} a
11412 * @param {number} b
11413 * @param {Matrix3x3} lmsToRgb
11414 * @param {OKCoeff} okCoeff
11415 * @returns {[number, number]}
11416 * @todo Could probably make these types more specific/better-documented if desired
11417 */
11418 function findCusp(a, b, lmsToRgb, okCoeff) {
11419 // Finds L_cusp and C_cusp for a given hue.
11420 //
11421 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11422
11423 // First, find the maximum saturation (saturation `S = C/L`)
11424 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
11425
11426 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
11427 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
11428 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
11429 let cCusp = lCusp * sCusp;
11430 return [lCusp, cCusp];
11431 }
11432
11433 /**
11434 * @param {number} a
11435 * @param {number} b
11436 * @param {number} l1
11437 * @param {number} c1
11438 * @param {number} l0
11439 * @param {Matrix3x3} lmsToRgb
11440 * @param {OKCoeff} okCoeff
11441 * @param {[number, number]} cusp
11442 * @returns {Number}
11443 * @todo Could probably make these types more specific/better-documented if desired
11444 */
11445 function findGamutIntersection(a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
11446 // Finds intersection of the line.
11447 //
11448 // Defined by the following:
11449 //
11450 // ```
11451 // L = L0 * (1 - t) + t * L1
11452 // C = t * C1
11453 // ```
11454 //
11455 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11456
11457 let t;
11458 if (cusp === undefined) {
11459 cusp = findCusp(a, b, lmsToRgb, okCoeff);
11460 }
11461
11462 // Find the intersection for upper and lower half separately
11463 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
11464 // Lower half
11465 t = cusp[1] * l0 / (c1 * cusp[0] + cusp[1] * (l0 - l1));
11466 } else {
11467 // Upper half
11468
11469 // First intersect with triangle
11470 t = cusp[1] * (l0 - 1.0) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
11471
11472 // Then one step Halley's method
11473 let dl = l1 - l0;
11474 let dc = c1;
11475 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11476 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11477 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11478 let ldt_ = dl + dc * kl;
11479 let mdt_ = dl + dc * km;
11480 let sdt_ = dl + dc * ks;
11481
11482 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
11483 let L = l0 * (1.0 - t) + t * l1;
11484 let C = t * c1;
11485 let l_ = L + C * kl;
11486 let m_ = L + C * km;
11487 let s_ = L + C * ks;
11488 let l = l_ ** 3;
11489 let m = m_ ** 3;
11490 let s = s_ ** 3;
11491 let ldt = 3 * ldt_ * l_ ** 2;
11492 let mdt = 3 * mdt_ * m_ ** 2;
11493 let sdt = 3 * sdt_ * s_ ** 2;
11494 let ldt2 = 6 * ldt_ ** 2 * l_;
11495 let mdt2 = 6 * mdt_ ** 2 * m_;
11496 let sdt2 = 6 * sdt_ ** 2 * s_;
11497 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
11498 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
11499 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
11500 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
11501 let tr = -r_ * ur;
11502 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
11503 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
11504 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
11505 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
11506 let tg = -g_ * ug;
11507 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
11508 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
11509 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
11510 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
11511 let tb = -b_ * ub;
11512 tr = ur >= 0.0 ? tr : floatMax;
11513 tg = ug >= 0.0 ? tg : floatMax;
11514 tb = ub >= 0.0 ? tb : floatMax;
11515 t += Math.min(tr, Math.min(tg, tb));
11516 }
11517 return t;
11518 }
11519 function getCs(lab, lmsToRgb, okCoeff) {
11520 // Get Cs
11521
11522 let [l, a, b] = lab;
11523 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
11524 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
11525 let stMax = toSt(cusp);
11526
11527 // Scale factor to compensate for the curved part of gamut shape:
11528 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
11529 let stMid = getStMid(a, b);
11530
11531 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11532 let ca = l * stMid[0];
11533 let cb = (1.0 - l) * stMid[1];
11534 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
11535
11536 // For `C_0`, the shape is independent of hue, so `ST` are constant.
11537 // Values picked to roughly be the average values of `ST`.
11538 ca = l * 0.4;
11539 cb = (1.0 - l) * 0.8;
11540
11541 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11542 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
11543 return [c0, cMid, cMax];
11544 }
11545 function computeMaxSaturation(a, b, lmsToRgb, okCoeff) {
11546 // Finds the maximum saturation possible for a given hue that fits in RGB.
11547 //
11548 // Saturation here is defined as `S = C/L`.
11549 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11550
11551 // Max saturation will be when one of r, g or b goes below zero.
11552
11553 // Select different coefficients depending on which component goes below zero first.
11554
11555 let k0, k1, k2, k3, k4, wl, wm, ws;
11556 if (vdot(okCoeff[0][0], [a, b]) > 1) {
11557 // Red component
11558 [k0, k1, k2, k3, k4] = okCoeff[0][1];
11559 [wl, wm, ws] = lmsToRgb[0];
11560 } else if (vdot(okCoeff[1][0], [a, b]) > 1) {
11561 // Green component
11562 [k0, k1, k2, k3, k4] = okCoeff[1][1];
11563 [wl, wm, ws] = lmsToRgb[1];
11564 } else {
11565 // Blue component
11566 [k0, k1, k2, k3, k4] = okCoeff[2][1];
11567 [wl, wm, ws] = lmsToRgb[2];
11568 }
11569
11570 // Approximate max saturation using a polynomial:
11571 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
11572
11573 // Do one step Halley's method to get closer.
11574 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
11575 // This should be sufficient for most applications, otherwise do two/three steps.
11576
11577 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11578 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11579 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11580 let l_ = 1.0 + sat * kl;
11581 let m_ = 1.0 + sat * km;
11582 let s_ = 1.0 + sat * ks;
11583 let l = l_ ** 3;
11584 let m = m_ ** 3;
11585 let s = s_ ** 3;
11586 let lds = 3.0 * kl * l_ ** 2;
11587 let mds = 3.0 * km * m_ ** 2;
11588 let sds = 3.0 * ks * s_ ** 2;
11589 let lds2 = 6.0 * kl ** 2 * l_;
11590 let mds2 = 6.0 * km ** 2 * m_;
11591 let sds2 = 6.0 * ks ** 2 * s_;
11592 let f = wl * l + wm * m + ws * s;
11593 let f1 = wl * lds + wm * mds + ws * sds;
11594 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
11595 sat = sat - f * f1 / (f1 ** 2 - 0.5 * f * f2);
11596 return sat;
11597 }
11598 function okhslToOklab(hsl, lmsToRgb, okCoeff) {
11599 // Convert Okhsl to Oklab.
11600
11601 let [h, s, l] = hsl;
11602 let L = toeInv(l);
11603 let a = null;
11604 let b = null;
11605 h = constrain(h) / 360.0;
11606 if (L !== 0.0 && L !== 1.0 && s !== 0) {
11607 let a_ = Math.cos(tau * h);
11608 let b_ = Math.sin(tau * h);
11609 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
11610
11611 // Interpolate the three values for C so that:
11612 // ```
11613 // At s=0: dC/ds = C_0, C=0
11614 // At s=0.8: C=C_mid
11615 // At s=1.0: C=C_max
11616 // ```
11617
11618 let mid = 0.8;
11619 let midInv = 1.25;
11620 let t, k0, k1, k2;
11621 if (s < mid) {
11622 t = midInv * s;
11623 k0 = 0.0;
11624 k1 = mid * c0;
11625 k2 = 1.0 - k1 / cMid;
11626 } else {
11627 t = 5 * (s - 0.8);
11628 k0 = cMid;
11629 k1 = 0.2 * cMid ** 2 * 1.25 ** 2 / c0;
11630 k2 = 1.0 - k1 / (cMax - cMid);
11631 }
11632 let c = k0 + t * k1 / (1.0 - k2 * t);
11633 a = c * a_;
11634 b = c * b_;
11635 }
11636 return [L, a, b];
11637 }
11638 function oklabToOkhsl(lab, lmsToRgb, okCoeff) {
11639 // Oklab to Okhsl.
11640
11641 // Epsilon for lightness should approach close to 32 bit lightness
11642 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
11643 let εL = 1e-7;
11644 let εS = 1e-4;
11645 let L = lab[0];
11646 let s = 0.0;
11647 let l = toe(L);
11648 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
11649 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
11650 if (l !== 0.0 && l !== 1.0 && c !== 0) {
11651 let a_ = lab[1] / c;
11652 let b_ = lab[2] / c;
11653 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
11654 let mid = 0.8;
11655 let midInv = 1.25;
11656 let k0, k1, k2, t;
11657 if (c < cMid) {
11658 k1 = mid * c0;
11659 k2 = 1.0 - k1 / cMid;
11660 t = c / (k1 + k2 * c);
11661 s = t * mid;
11662 } else {
11663 k0 = cMid;
11664 k1 = 0.2 * cMid ** 2 * midInv ** 2 / c0;
11665 k2 = 1.0 - k1 / (cMax - cMid);
11666 t = (c - k0) / (k1 + k2 * (c - k0));
11667 s = mid + 0.2 * t;
11668 }
11669 }
11670 const achromatic = Math.abs(s) < εS;
11671 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
11672 h = null;
11673 // Due to floating point imprecision near lightness of 1, we can end up
11674 // with really high around white, this is to provide consistency as
11675 // saturation can be really high for white due this imprecision.
11676 if (!achromatic) {
11677 s = 0.0;
11678 }
11679 } else {
11680 h = constrain(h * 360);
11681 }
11682 return [h, s, l];
11683 }
11684 const Okhsl = new ColorSpace({
11685 id: "okhsl",
11686 name: "Okhsl",
11687 coords: {
11688 h: {
11689 refRange: [0, 360],
11690 type: "angle",
11691 name: "Hue"
11692 },
11693 s: {
11694 range: [0, 1],
11695 name: "Saturation"
11696 },
11697 l: {
11698 range: [0, 1],
11699 name: "Lightness"
11700 }
11701 },
11702 base: Oklab,
11703 gamutSpace: "self",
11704 M: M$3,
11705 // Convert Oklab to Okhsl
11706 fromBase(lab) {
11707 return oklabToOkhsl(lab, M$3.toSRGBLinear, RGBCoeff);
11708 },
11709 // Convert Okhsl to Oklab
11710 toBase(hsl) {
11711 return okhslToOklab(hsl, M$3.toSRGBLinear, RGBCoeff);
11712 },
11713 formats: {
11714 color: {
11715 id: "--okhsl",
11716 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11717 }
11718 }
11719 });
11720 Okhsl.rgbGamut = new RGBColorSpace({
11721 id: "okhsl-prism",
11722 cssId: "--okhsl-prism",
11723 name: "Okhsl Prism",
11724 base: Okhsl,
11725 fromBase(hsl) {
11726 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
11727 },
11728 toBase(rgb) {
11729 const hsl = HSL.fromBase(rgb);
11730 hsl[1] /= 100;
11731 hsl[2] /= 100;
11732 return hsl;
11733 }
11734 });
11735
11736 var OKLrab = new ColorSpace({
11737 id: "oklrab",
11738 name: "Oklrab",
11739 coords: {
11740 l: {
11741 refRange: [0, 1],
11742 name: "Lightness"
11743 },
11744 a: {
11745 refRange: [-0.4, 0.4]
11746 },
11747 b: {
11748 refRange: [-0.4, 0.4]
11749 }
11750 },
11751 // Note that XYZ is relative to D65
11752 white: "D65",
11753 base: Oklab,
11754 fromBase(oklab) {
11755 return [toe(oklab[0]), oklab[1], oklab[2]];
11756 },
11757 toBase(oklrab) {
11758 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
11759 },
11760 formats: {
11761 color: {
11762 coords: ["<percentage> | <number>", "<number> | <percentage>[-1,1]", "<number> | <percentage>[-1,1]"]
11763 }
11764 }
11765 });
11766
11767 var oklrch = new ColorSpace({
11768 id: "oklrch",
11769 name: "Oklrch",
11770 coords: {
11771 l: {
11772 refRange: [0, 1],
11773 name: "Lightness"
11774 },
11775 c: {
11776 refRange: [0, 0.4],
11777 name: "Chroma"
11778 },
11779 h: {
11780 refRange: [0, 360],
11781 type: "angle",
11782 name: "Hue"
11783 }
11784 },
11785 white: "D65",
11786 base: OKLrab,
11787 fromBase: lch.fromBase,
11788 toBase: lch.toBase,
11789 formats: {
11790 color: {
11791 coords: ["<percentage> | <number>", "<number> | <percentage>[0,1]", "<number> | <angle>"]
11792 }
11793 }
11794 });
11795
11796 // Okhsv class.
11797 //
11798 // ---- License ----
11799 //
11800 // Copyright (c) 2021 Björn Ottosson
11801 //
11802 // Permission is hereby granted, free of charge, to any person obtaining a copy of
11803 // this software and associated documentation files (the "Software"), to deal in
11804 // the Software without restriction, including without limitation the rights to
11805 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11806 // of the Software, and to permit persons to whom the Software is furnished to do
11807 // so, subject to the following conditions:
11808 //
11809 // The above copyright notice and this permission notice shall be included in all
11810 // copies or substantial portions of the Software.
11811 //
11812 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11813 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11814 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
11815 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11816 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
11817 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
11818 // SOFTWARE.
11819
11820 /**
11821 * Matrices used by this color space (reused from Okhsl), also available as `Okhsv.M`
11822 * @type {Record<string, Matrix3x3>}
11823 */
11824 const M$2 = {
11825 toSRGBLinear: Okhsl.M.toSRGBLinear
11826 };
11827
11828 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
11829
11830 /**
11831 *
11832 * @param {Vector3} hsv
11833 * @param {Matrix3x3} lmsToRgb
11834 * @param {OKCoeff} okCoeff
11835 * @returns {Coords}
11836 */
11837 function okhsvToOklab(hsv, lmsToRgb, okCoeff) {
11838 // Convert from Okhsv to Oklab."""
11839
11840 let [h, s, v] = hsv;
11841 h = constrain(h) / 360.0;
11842 let l = toeInv(v);
11843 let a = null;
11844 let b = null;
11845
11846 // Avoid processing gray or colors with undefined hues
11847 if (l !== 0.0 && s !== 0.0) {
11848 let a_ = Math.cos(tau * h);
11849 let b_ = Math.sin(tau * h);
11850 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
11851 let [sMax, tMax] = toSt(cusp);
11852 let s0 = 0.5;
11853 let k = 1 - s0 / sMax;
11854
11855 // first we compute L and V as if the gamut is a perfect triangle:
11856
11857 // L, C when v==1:
11858 let lv = 1 - s * s0 / (s0 + tMax - tMax * k * s);
11859 let cv = s * tMax * s0 / (s0 + tMax - tMax * k * s);
11860 l = v * lv;
11861 let c = v * cv;
11862
11863 // then we compensate for both toe and the curved top part of the triangle:
11864 let lvt = toeInv(lv);
11865 let cvt = cv * lvt / lv;
11866 let lNew = toeInv(l);
11867 c = c * lNew / l;
11868 l = lNew;
11869
11870 // RGB scale
11871 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
11872 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
11873 l = l * scaleL;
11874 c = c * scaleL;
11875 a = c * a_;
11876 b = c * b_;
11877 }
11878 return [l, a, b];
11879 }
11880
11881 /**
11882 *
11883 * @param {Vector3} lab
11884 * @param {Matrix3x3} lmsToRgb
11885 * @param {OKCoeff} okCoeff
11886 * @returns {Coords}
11887 */
11888 function oklabToOkhsv(lab, lmsToRgb, okCoeff) {
11889 // Oklab to Okhsv.
11890
11891 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
11892 let ε = 1e-4;
11893 let l = lab[0];
11894 let s = 0.0;
11895 let v = toe(l);
11896 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
11897 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
11898 if (l !== 0.0 && l !== 1 && c !== 0.0) {
11899 let a_ = lab[1] / c;
11900 let b_ = lab[2] / c;
11901 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
11902 let [sMax, tMax] = toSt(cusp);
11903 let s0 = 0.5;
11904 let k = 1 - s0 / sMax;
11905
11906 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
11907 let t = tMax / (c + l * tMax);
11908 let lv = t * l;
11909 let cv = t * c;
11910 let lvt = toeInv(lv);
11911 let cvt = cv * lvt / lv;
11912
11913 // we can then use these to invert the step that compensates
11914 // for the toe and the curved top part of the triangle:
11915 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
11916 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
11917 l = l / scaleL;
11918 c = c / scaleL;
11919 c = c * toe(l) / l;
11920 l = toe(l);
11921
11922 // we can now compute v and s:
11923 v = l / lv;
11924 s = (s0 + tMax) * cv / (tMax * s0 + tMax * k * cv);
11925 }
11926 if (Math.abs(s) < ε || v === 0.0) {
11927 h = null;
11928 } else {
11929 h = constrain(h * 360);
11930 }
11931 return [h, s, v];
11932 }
11933 const Okhsv = new ColorSpace({
11934 id: "okhsv",
11935 name: "Okhsv",
11936 coords: {
11937 h: {
11938 refRange: [0, 360],
11939 type: "angle",
11940 name: "Hue"
11941 },
11942 s: {
11943 range: [0, 1],
11944 name: "Saturation"
11945 },
11946 v: {
11947 range: [0, 1],
11948 name: "Value"
11949 }
11950 },
11951 base: Oklab,
11952 gamutSpace: "self",
11953 M: M$2,
11954 // Convert Oklab to Okhsl
11955 fromBase(lab) {
11956 return oklabToOkhsv(lab, M$2.toSRGBLinear, RGBCoeff);
11957 },
11958 // Convert Okhsl to Oklab
11959 toBase(hsl) {
11960 return okhsvToOklab(hsl, M$2.toSRGBLinear, RGBCoeff);
11961 },
11962 formats: {
11963 color: {
11964 id: "--okhsv",
11965 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11966 }
11967 }
11968 });
11969 Okhsv.rgbGamut = new RGBColorSpace({
11970 id: "okhsv-prism",
11971 cssId: "--okhsv-prism",
11972 name: "Okhsv Prism",
11973 base: Okhsv,
11974 fromBase(hsl) {
11975 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
11976 },
11977 toBase(rgb) {
11978 const hsl = HSL.fromBase(rgb);
11979 hsl[1] /= 100;
11980 hsl[2] /= 100;
11981 return hsl;
11982 }
11983 });
11984
11985 let white = WHITES.D65;
11986 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
11987 const κ$1 = 24389 / 27; // 29^3/3^3
11988 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({
11989 space: XYZ_D65,
11990 coords: white
11991 });
11992 var Luv = new ColorSpace({
11993 id: "luv",
11994 name: "Luv",
11995 coords: {
11996 l: {
11997 refRange: [0, 100],
11998 name: "Lightness"
11999 },
12000 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
12001 u: {
12002 refRange: [-215, 215]
12003 },
12004 v: {
12005 refRange: [-215, 215]
12006 }
12007 },
12008 white: white,
12009 base: XYZ_D65,
12010 // Convert D65-adapted XYZ to Luv
12011 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
12012 fromBase(XYZ) {
12013 let xyz = /** @type {[number, number, number]} */[skipNone(XYZ[0]), skipNone(XYZ[1]), skipNone(XYZ[2])];
12014 let y = xyz[1];
12015 let [up, vp] = uv({
12016 space: XYZ_D65,
12017 coords: xyz
12018 });
12019
12020 // Protect against XYZ of [0, 0, 0]
12021 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
12022 return [0, 0, 0];
12023 }
12024 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
12025 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
12026 },
12027 // Convert Luv to D65-adapted XYZ
12028 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
12029 toBase(Luv) {
12030 let [L, u, v] = Luv;
12031
12032 // Protect against division by zero and none Lightness
12033 if (L === 0 || isNone(L)) {
12034 return [0, 0, 0];
12035 }
12036 u = skipNone(u);
12037 v = skipNone(v);
12038 let up = u / (13 * L) + U_PRIME_WHITE;
12039 let vp = v / (13 * L) + V_PRIME_WHITE;
12040 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
12041 return [y * (9 * up / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
12042 },
12043 formats: {
12044 color: {
12045 id: "--luv",
12046 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
12047 }
12048 }
12049 });
12050
12051 var LCHuv = new ColorSpace({
12052 id: "lchuv",
12053 name: "LChuv",
12054 coords: {
12055 l: {
12056 refRange: [0, 100],
12057 name: "Lightness"
12058 },
12059 c: {
12060 refRange: [0, 220],
12061 name: "Chroma"
12062 },
12063 h: {
12064 refRange: [0, 360],
12065 type: "angle",
12066 name: "Hue"
12067 }
12068 },
12069 base: Luv,
12070 fromBase: lch.fromBase,
12071 toBase: lch.toBase,
12072 formats: {
12073 color: {
12074 id: "--lchuv",
12075 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"]
12076 }
12077 }
12078 });
12079
12080 /*
12081 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12082
12083 Copyright (c) 2012-2022 Alexei Boronine
12084
12085 Permission is hereby granted, free of charge, to any person obtaining a copy
12086 of this software and associated documentation files (the "Software"), to deal
12087 in the Software without restriction, including without limitation the rights
12088 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12089 copies of the Software, and to permit persons to whom the Software is
12090 furnished to do so, subject to the following conditions:
12091
12092 The above copyright notice and this permission notice shall be included in all
12093 copies or substantial portions of the Software.
12094
12095 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12096 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12097 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12098 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12099 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12100 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12101 SOFTWARE.
12102 */
12103
12104 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
12105 const κ = 24389 / 27; // 29^3/3^3
12106
12107 const fromXYZ_M$1 = M$6.fromXYZ;
12108 const m_r0 = fromXYZ_M$1[0][0];
12109 const m_r1 = fromXYZ_M$1[0][1];
12110 const m_r2 = fromXYZ_M$1[0][2];
12111 const m_g0 = fromXYZ_M$1[1][0];
12112 const m_g1 = fromXYZ_M$1[1][1];
12113 const m_g2 = fromXYZ_M$1[1][2];
12114 const m_b0 = fromXYZ_M$1[2][0];
12115 const m_b1 = fromXYZ_M$1[2][1];
12116 const m_b2 = fromXYZ_M$1[2][2];
12117 function distanceFromOriginAngle(slope, intercept, angle) {
12118 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
12119 return d < 0 ? Infinity : d;
12120 }
12121
12122 /**
12123 * @param {number} l
12124 */
12125 function calculateBoundingLines(l) {
12126 const sub1 = Math.pow(l + 16, 3) / 1560896;
12127 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
12128 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
12129 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
12130 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
12131 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
12132 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
12133 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
12134 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
12135 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
12136 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
12137 return {
12138 r0s: s1r / s3r,
12139 r0i: s2r * l / s3r,
12140 r1s: s1r / (s3r + 126452),
12141 r1i: (s2r - 769860) * l / (s3r + 126452),
12142 g0s: s1g / s3g,
12143 g0i: s2g * l / s3g,
12144 g1s: s1g / (s3g + 126452),
12145 g1i: (s2g - 769860) * l / (s3g + 126452),
12146 b0s: s1b / s3b,
12147 b0i: s2b * l / s3b,
12148 b1s: s1b / (s3b + 126452),
12149 b1i: (s2b - 769860) * l / (s3b + 126452)
12150 };
12151 }
12152 function calcMaxChromaHsluv(lines, h) {
12153 const hueRad = h / 360 * Math.PI * 2;
12154 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
12155 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
12156 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
12157 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
12158 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
12159 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
12160 return Math.min(r0, r1, g0, g1, b0, b1);
12161 }
12162 var hsluv = new ColorSpace({
12163 id: "hsluv",
12164 name: "HSLuv",
12165 coords: {
12166 h: {
12167 refRange: [0, 360],
12168 type: "angle",
12169 name: "Hue"
12170 },
12171 s: {
12172 range: [0, 100],
12173 name: "Saturation"
12174 },
12175 l: {
12176 range: [0, 100],
12177 name: "Lightness"
12178 }
12179 },
12180 base: LCHuv,
12181 gamutSpace: sRGB,
12182 rgbGamut: sRGB,
12183 // Convert LCHuv to HSLuv
12184 fromBase(lch) {
12185 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12186 let s;
12187 if (l > 99.9999999) {
12188 s = 0;
12189 l = 100;
12190 } else if (l < 0.00000001) {
12191 s = 0;
12192 l = 0;
12193 } else {
12194 let lines = calculateBoundingLines(l);
12195 let max = calcMaxChromaHsluv(lines, h);
12196 s = c / max * 100;
12197 }
12198 return [h, s, l];
12199 },
12200 // Convert HSLuv to LCHuv
12201 toBase(hsl) {
12202 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12203 let c;
12204 if (l > 99.9999999) {
12205 l = 100;
12206 c = 0;
12207 } else if (l < 0.00000001) {
12208 l = 0;
12209 c = 0;
12210 } else {
12211 let lines = calculateBoundingLines(l);
12212 let max = calcMaxChromaHsluv(lines, h);
12213 c = max / 100 * s;
12214 }
12215 return [l, c, h];
12216 },
12217 formats: {
12218 color: {
12219 id: "--hsluv",
12220 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12221 }
12222 }
12223 });
12224
12225 /*
12226 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12227
12228 Copyright (c) 2012-2022 Alexei Boronine
12229
12230 Permission is hereby granted, free of charge, to any person obtaining a copy
12231 of this software and associated documentation files (the "Software"), to deal
12232 in the Software without restriction, including without limitation the rights
12233 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12234 copies of the Software, and to permit persons to whom the Software is
12235 furnished to do so, subject to the following conditions:
12236
12237 The above copyright notice and this permission notice shall be included in all
12238 copies or substantial portions of the Software.
12239
12240 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12241 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12242 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12243 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12244 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12245 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12246 SOFTWARE.
12247 */
12248
12249
12250 const fromXYZ_M = M$6.fromXYZ;
12251 fromXYZ_M[0][0];
12252 fromXYZ_M[0][1];
12253 fromXYZ_M[0][2];
12254 fromXYZ_M[1][0];
12255 fromXYZ_M[1][1];
12256 fromXYZ_M[1][2];
12257 fromXYZ_M[2][0];
12258 fromXYZ_M[2][1];
12259 fromXYZ_M[2][2];
12260 function distanceFromOrigin(slope, intercept) {
12261 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
12262 }
12263 function calcMaxChromaHpluv(lines) {
12264 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
12265 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
12266 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
12267 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
12268 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
12269 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
12270 return Math.min(r0, r1, g0, g1, b0, b1);
12271 }
12272 const HPLuv = new ColorSpace({
12273 id: "hpluv",
12274 name: "HPLuv",
12275 coords: {
12276 h: {
12277 refRange: [0, 360],
12278 type: "angle",
12279 name: "Hue"
12280 },
12281 s: {
12282 range: [0, 100],
12283 name: "Saturation"
12284 },
12285 l: {
12286 range: [0, 100],
12287 name: "Lightness"
12288 }
12289 },
12290 base: LCHuv,
12291 gamutSpace: "self",
12292 // Convert LCHuv to HPLuv
12293 fromBase(lch) {
12294 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12295 let s;
12296 if (l > 99.9999999) {
12297 s = 0;
12298 l = 100;
12299 } else if (l < 0.00000001) {
12300 s = 0;
12301 l = 0;
12302 } else {
12303 let lines = calculateBoundingLines(l);
12304 let max = calcMaxChromaHpluv(lines);
12305 s = c / max * 100;
12306 }
12307 return [h, s, l];
12308 },
12309 // Convert HPLuv to LCHuv
12310 toBase(hsl) {
12311 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12312 let c;
12313 if (l > 99.9999999) {
12314 l = 100;
12315 c = 0;
12316 } else if (l < 0.00000001) {
12317 l = 0;
12318 c = 0;
12319 } else {
12320 let lines = calculateBoundingLines(l);
12321 let max = calcMaxChromaHpluv(lines);
12322 c = max / 100 * s;
12323 }
12324 return [l, c, h];
12325 },
12326 formats: {
12327 color: {
12328 id: "--hpluv",
12329 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12330 }
12331 }
12332 });
12333 HPLuv.rgbGamut = new RGBColorSpace({
12334 id: "hpluv-prism",
12335 cssId: "--hpluv-prism",
12336 name: "HPLuv Prism",
12337 base: HPLuv,
12338 fromBase(hsl) {
12339 return HSL.toBase(hsl);
12340 },
12341 toBase(rgb) {
12342 return HSL.fromBase(rgb);
12343 }
12344 });
12345
12346 /**
12347 * Helmlab GenSpace — generation-optimized color space for interpolation.
12348 *
12349 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
12350 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
12351 * PW_L → L-gated hue enrichment → Lab
12352 *
12353 * Optimized for perceptually uniform gradients, palette generation,
12354 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
12355 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
12356 *
12357 * Key properties:
12358 * - Depressed cubic: y³ + αy = x, finite derivative at zero
12359 * - Chroma power (0.978): improves gradient CV uniformity
12360 * - L-gated hue enrichment: fixes blue→white purple shift
12361 * - Structurally achromatic: a=b≈0 for all grays
12362 *
12363 * Note on blue-region gamut fold:
12364 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
12365 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
12366 * mixing LMS channels before applying a power-like transfer: the inverse
12367 * creates a cubic polynomial that can have two positive roots in the blue
12368 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
12369 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
12370 *
12371 * Reference: arXiv:2602.23010
12372 * @see https://github.com/Grkmyldz148/helmlab
12373 */
12374
12375 /** @import { Matrix3x3 } from "../types.js" */
12376
12377 // ── Depressed cubic parameter ──────────────────────────────────────
12378 const ALPHA = 0.021;
12379 const S = Math.sqrt(ALPHA / 3);
12380 const S3 = S * S * S;
12381
12382 // ── Chroma power ───────────────────────────────────────────────────
12383 const CP = 0.978;
12384
12385 // ── L-gated hue enrichment parameters ──────────────────────────────
12386 const ENR_AMP = 0.058;
12387 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
12388 const ENR_SIGMA = 0.7;
12389 const ENR_LLO = 0.37;
12390 const ENR_LHI = 1.0;
12391
12392 // ── Core matrices (v0.11.1) ────────────────────────────────────────
12393
12394 /**
12395 * Matrices used by this color space, also available as `HelmGen.M`
12396 * @type {Record<string, Matrix3x3>}
12397 */
12398 // prettier-ignore
12399 const M$1 = {
12400 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
12401 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]],
12402 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]],
12403 M2: [[0.21193779684470104, 0.7992121834263127, -0.00410075161564345], [2.4672018828033475, -2.9877348024830788, 0.520532919679731], [-0.11390787868068575, 1.3932982808117473, -1.279390402131062]],
12404 M2_INV: [[0.9930001151336143, 0.32599327253052285, 0.12945085631713921], [0.9930001151336139, -0.08708353111074627, -0.03861361743004929], [0.9930001151336136, -0.12386097008215022, -0.8351991365871061]]
12405 };
12406
12407 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
12408 // prettier-ignore
12409 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];
12410 // prettier-ignore
12411 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];
12412 const PW_N = PW_L_IN.length;
12413
12414 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
12415
12416 function depcubicFwd(x) {
12417 let t = x / (2 * S3);
12418 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
12419 // Halley refinement
12420 let f = y * y * y + ALPHA * y - x;
12421 let fp = 3 * y * y + ALPHA;
12422 let fpp = 6 * y;
12423 let denom = 2 * fp * fp - f * fpp;
12424 if (Math.abs(denom) > 1e-30) {
12425 y -= 2 * f * fp / denom;
12426 }
12427 return y;
12428 }
12429 function depcubicInv(y) {
12430 return y * y * y + ALPHA * y;
12431 }
12432
12433 // ── L-gated hue enrichment ─────────────────────────────────────────
12434
12435 function enrichGate(L) {
12436 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
12437 return Math.sin(Math.PI * t) ** 2;
12438 }
12439 function enrichFwd(L, a, b) {
12440 let C = Math.sqrt(a * a + b * b);
12441 if (C < 1e-12) {
12442 return [a, b];
12443 }
12444 let gate = enrichGate(L);
12445 if (gate < 1e-12) {
12446 return [a, b];
12447 }
12448 let h = Math.atan2(b, a);
12449 let dh = h - ENR_CENTER;
12450 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12451 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
12452 let hNew = h + ENR_AMP * gate * gauss;
12453 return [C * Math.cos(hNew), C * Math.sin(hNew)];
12454 }
12455 function enrichInv(L, a, b) {
12456 let C = Math.sqrt(a * a + b * b);
12457 if (C < 1e-12) {
12458 return [a, b];
12459 }
12460 let gate = enrichGate(L);
12461 if (gate < 1e-12) {
12462 return [a, b];
12463 }
12464 let hTarget = Math.atan2(b, a);
12465 let sig2 = ENR_SIGMA * ENR_SIGMA;
12466 let ag = ENR_AMP * gate;
12467 let h = hTarget;
12468 for (let i = 0; i < 8; i++) {
12469 let dh = h - ENR_CENTER;
12470 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12471 let gauss = Math.exp(-0.5 * dh * dh / sig2);
12472 let F = h + ag * gauss - hTarget;
12473 let Fp = 1 + ag * gauss * (-dh / sig2);
12474 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
12475 let den = 2 * Fp * Fp - F * Fpp;
12476 if (Math.abs(den) > 1e-30) {
12477 h -= 2 * F * Fp / den;
12478 }
12479 }
12480 return [C * Math.cos(h), C * Math.sin(h)];
12481 }
12482
12483 // ── PW L correction ───────────────────────────────────────────────
12484
12485 function pwLForward(L) {
12486 if (L <= 0 || L >= 1) {
12487 return L;
12488 }
12489 let lo = 0,
12490 hi = PW_N - 1;
12491 while (hi - lo > 1) {
12492 let mid = lo + hi >> 1;
12493 if (PW_L_IN[mid] <= L) {
12494 lo = mid;
12495 } else {
12496 hi = mid;
12497 }
12498 }
12499 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
12500 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
12501 }
12502 function pwLInverse(L) {
12503 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
12504 return L;
12505 }
12506 let lo = 0,
12507 hi = PW_N - 1;
12508 while (hi - lo > 1) {
12509 let mid = lo + hi >> 1;
12510 if (PW_L_OUT[mid] <= L) {
12511 lo = mid;
12512 } else {
12513 hi = mid;
12514 }
12515 }
12516 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
12517 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
12518 }
12519
12520 // ── Color space definition ─────────────────────────────────────────
12521
12522 var HelmGen = new ColorSpace({
12523 id: "helmgen",
12524 name: "HelmGen",
12525 cssId: "--helmgen",
12526 coords: {
12527 l: {
12528 refRange: [0, 1],
12529 name: "Lightness"
12530 },
12531 a: {
12532 refRange: [-0.6, 0.6]
12533 },
12534 b: {
12535 refRange: [-0.6, 0.6]
12536 }
12537 },
12538 white: "D65",
12539 base: XYZ_D65,
12540 M: M$1,
12541 fromBase(xyz) {
12542 // Stage 1: XYZ → LMS (M1)
12543 let lms = multiply_v3_m3x3(xyz, M$1.M1);
12544
12545 // Stage 2: Depressed cubic transfer (y³ + αy = x)
12546 let c0 = depcubicFwd(Math.max(lms[0], 0));
12547 let c1 = depcubicFwd(Math.max(lms[1], 0));
12548 let c2 = depcubicFwd(Math.max(lms[2], 0));
12549
12550 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
12551 {
12552 let mean = (c0 + c1 + c2) / 3;
12553 let mx = Math.max(c0, c1, c2);
12554 let mn = Math.min(c0, c1, c2);
12555 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12556 let w = Math.exp(-((spread / 1e-5) ** 2));
12557 c0 += w * (mean - c0);
12558 c1 += w * (mean - c1);
12559 c2 += w * (mean - c2);
12560 }
12561
12562 // Stage 3: LMS_c → Lab (M2)
12563 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$1.M2);
12564
12565 // Stage 3.5: Chroma power (cp=0.978)
12566 {
12567 let C = Math.sqrt(a * a + b * b);
12568 if (C > 1e-12) {
12569 let Cnew = Math.pow(C, CP);
12570 let s = Cnew / C;
12571 a *= s;
12572 b *= s;
12573 }
12574 }
12575
12576 // Stage 4: Piecewise-linear L correction
12577 L = pwLForward(L);
12578
12579 // Stage 5: L-gated hue enrichment
12580 [a, b] = enrichFwd(L, a, b);
12581 return [L, a, b];
12582 },
12583 toBase(lab) {
12584 let [L, a, b] = lab;
12585
12586 // Undo Stage 5: L-gated hue enrichment
12587 [a, b] = enrichInv(L, a, b);
12588
12589 // Undo Stage 4: PW L correction
12590 L = pwLInverse(L);
12591
12592 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
12593 {
12594 let C = Math.sqrt(a * a + b * b);
12595 if (C > 1e-12) {
12596 let Corig = Math.pow(C, 1 / CP);
12597 let s = Corig / C;
12598 a *= s;
12599 b *= s;
12600 }
12601 }
12602
12603 // Undo Stage 3: Lab → LMS_c (M2_inv)
12604 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$1.M2_INV);
12605
12606 // Undo Stage 2.5: Smooth neutral blend
12607 {
12608 let mean = (lc0 + lc1 + lc2) / 3;
12609 let mx = Math.max(lc0, lc1, lc2);
12610 let mn = Math.min(lc0, lc1, lc2);
12611 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12612 let w = Math.exp(-((spread / 1e-5) ** 2));
12613 lc0 += w * (mean - lc0);
12614 lc1 += w * (mean - lc1);
12615 lc2 += w * (mean - lc2);
12616 }
12617
12618 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
12619 let l0 = depcubicInv(lc0);
12620 let l1 = depcubicInv(lc1);
12621 let l2 = depcubicInv(lc2);
12622
12623 // Undo Stage 1: LMS → XYZ (M1_inv)
12624 return multiply_v3_m3x3([l0, l1, l2], M$1.M1_INV);
12625 }
12626 });
12627
12628 /**
12629 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
12630 *
12631 * Converts GenSpace's rectangular (L, a, b) coordinates to
12632 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
12633 * like gradients and color-mix where hue angle matters.
12634 *
12635 * @see https://github.com/Grkmyldz148/helmlab
12636 */
12637 var helmgenlch = new ColorSpace({
12638 id: "helmgenlch",
12639 name: "HelmGenLCh",
12640 cssId: "--helmgenlch",
12641 coords: {
12642 l: {
12643 refRange: [0, 1],
12644 name: "Lightness"
12645 },
12646 c: {
12647 refRange: [0, 0.65],
12648 name: "Chroma"
12649 },
12650 h: {
12651 refRange: [0, 360],
12652 type: "angle",
12653 name: "Hue"
12654 }
12655 },
12656 white: "D65",
12657 base: HelmGen,
12658 fromBase: lch.fromBase,
12659 toBase: lch.toBase
12660 });
12661
12662 var REC_2100_Linear = new RGBColorSpace({
12663 id: "rec2100-linear",
12664 name: "Linear REC.2100",
12665 white: "D65",
12666 M: M$8
12667 });
12668
12669 const Yw = 203; // absolute luminance of media white, cd/m²
12670 const n = 2610 / 2 ** 14;
12671 const ninv = 2 ** 14 / 2610;
12672 const m = 2523 / 2 ** 5;
12673 const minv = 2 ** 5 / 2523;
12674 const c1 = 3424 / 2 ** 12;
12675 const c2 = 2413 / 2 ** 7;
12676 const c3 = 2392 / 2 ** 7;
12677 var rec2100Pq = new RGBColorSpace({
12678 id: "rec2100pq",
12679 cssId: "rec2100-pq",
12680 name: "REC.2100-PQ",
12681 base: REC_2100_Linear,
12682 linearGamut: REC_2100_Linear,
12683 toBase(RGB) {
12684 // given PQ encoded component in range [0, 1]
12685 // return media-white relative linear-light
12686 return RGB.map(function (val) {
12687 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
12688 return x * 10000 / Yw; // luminance relative to diffuse white, [0, 70 or so].
12689 });
12690 },
12691 fromBase(RGB) {
12692 // given media-white relative linear-light
12693 // returnPQ encoded component in range [0, 1]
12694 return RGB.map(function (val) {
12695 let x = Math.max(val * Yw / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
12696 let num = c1 + c2 * x ** n;
12697 let denom = 1 + c3 * x ** n;
12698 return (num / denom) ** m;
12699 });
12700 }
12701 });
12702
12703 const a = 0.17883277;
12704 const b = 0.28466892; // 1 - (4 * a)
12705 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
12706
12707 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
12708
12709 var rec2100Hlg = new RGBColorSpace({
12710 id: "rec2100hlg",
12711 cssId: "rec2100-hlg",
12712 name: "REC.2100-HLG",
12713 referred: "scene",
12714 base: REC_2100_Linear,
12715 linearGamut: REC_2100_Linear,
12716 toBase(RGB) {
12717 // given HLG encoded component in range [0, 1]
12718 // return media-white relative linear-light
12719 return RGB.map(function (val) {
12720 // first the HLG EOTF
12721 // ITU-R BT.2390-10 p.30 section
12722 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
12723 // Then scale by 3 so media white is 1.0
12724 if (val <= 0.5) {
12725 return val ** 2 / 3 * scale;
12726 }
12727 return (Math.exp((val - c) / a) + b) / 12 * scale;
12728 });
12729 },
12730 fromBase(RGB) {
12731 // given media-white relative linear-light
12732 // where diffuse white is 1.0,
12733 // return HLG encoded component in range [0, 1]
12734 return RGB.map(function (val) {
12735 // first scale to put linear-light media white at 1/3
12736 val /= scale;
12737 // now the HLG OETF
12738 // ITU-R BT.2390-10 p.23
12739 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
12740 if (val <= 1 / 12) {
12741 return spow(3 * val, 0.5);
12742 }
12743 return a * Math.log(12 * val - b) + c;
12744 });
12745 }
12746 });
12747
12748 /** @import { White } from "./types.js" */
12749
12750 // Type re-exports
12751 /** @typedef {import("./types.js").CAT} CAT */
12752
12753 /** @type {Record<string, CAT>} */
12754 const CATs = {};
12755 hooks.add("chromatic-adaptation-start", env => {
12756 if (env.options.method) {
12757 env.M = adapt(env.W1, env.W2, env.options.method);
12758 }
12759 });
12760 hooks.add("chromatic-adaptation-end", env => {
12761 if (!env.M) {
12762 env.M = adapt(env.W1, env.W2, env.options.method);
12763 }
12764 });
12765 function defineCAT(/** @type {CAT} */{
12766 id,
12767 toCone_M,
12768 fromCone_M
12769 }) {
12770 // Use id, toCone_M, fromCone_M like variables
12771 CATs[id] = arguments[0];
12772 }
12773
12774 /**
12775 *
12776 * @param {White} W1
12777 * @param {White} W2
12778 * @param {string} id
12779 * @returns {number[][]}
12780 */
12781 function adapt(W1, W2, id = "Bradford") {
12782 // adapt from a source whitepoint or illuminant W1
12783 // to a destination whitepoint or illuminant W2,
12784 // using the given chromatic adaptation transform (CAT)
12785 // debugger;
12786 let method = CATs[id];
12787 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
12788 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
12789
12790 // all practical illuminants have non-zero XYZ so no division by zero can occur below
12791 // prettier-ignore
12792 let scale = [[ρd / ρs, 0, 0], [0, γd / γs, 0], [0, 0, βd / βs]];
12793 // console.log({scale});
12794
12795 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
12796 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
12797 // console.log({scaled_cone_M, adapt_M});
12798 return adapt_M;
12799 }
12800
12801 // prettier-ignore
12802 defineCAT({
12803 id: "von Kries",
12804 toCone_M: [[0.4002400, 0.7076000, -0.0808100], [-0.2263000, 1.1653200, 0.0457000], [0.0000000, 0.0000000, 0.9182200]],
12805 fromCone_M: [[1.8599363874558397, -1.1293816185800916, 0.21989740959619328], [0.3611914362417676, 0.6388124632850422, -0.000006370596838649899], [0, 0, 1.0890636230968613]]
12806 });
12807
12808 // prettier-ignore
12809 defineCAT({
12810 id: "Bradford",
12811 // Convert an array of XYZ values in the range 0.0 - 1.0
12812 // to cone fundamentals
12813 toCone_M: [[0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000]],
12814 // and back
12815 fromCone_M: [[0.9869929054667121, -0.14705425642099013, 0.15996265166373122], [0.4323052697233945, 0.5183602715367774, 0.049291228212855594], [-0.00852866457517732, 0.04004282165408486, 0.96848669578755]]
12816 });
12817
12818 // prettier-ignore
12819 defineCAT({
12820 id: "CAT02",
12821 // with complete chromatic adaptation to W2, so D = 1.0
12822 toCone_M: [[0.7328000, 0.4296000, -0.1624000], [-0.7036000, 1.6975000, 0.0061000], [0.0030000, 0.0136000, 0.9834000]],
12823 fromCone_M: [[1.0961238208355142, -0.27886900021828726, 0.18274517938277307], [0.4543690419753592, 0.4735331543074117, 0.07209780371722911], [-0.009627608738429355, -0.00569803121611342, 1.0153256399545427]]
12824 });
12825
12826 // prettier-ignore
12827 defineCAT({
12828 id: "CAT16",
12829 toCone_M: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
12830 // the extra precision is needed to avoid roundtripping errors
12831 fromCone_M: [[1.862067855087233, -1.0112546305316845, 0.14918677544445172], [0.3875265432361372, 0.6214474419314753, -0.008973985167612521], [-0.01584149884933386, -0.03412293802851557, 1.0499644368778496]]
12832 });
12833
12834 // prettier-ignore
12835 Object.assign(WHITES, {
12836 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
12837 // all normalized to Y (luminance) = 1.00000
12838 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
12839 A: [1.09850, 1.00000, 0.35585],
12840 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
12841 C: [0.98074, 1.000000, 1.18232],
12842 // The daylight series of illuminants simulate natural daylight.
12843 // The color temperature (in degrees Kelvin/100) ranges from
12844 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
12845 D55: [0.95682, 1.00000, 0.92149],
12846 D75: [0.94972, 1.00000, 1.22638],
12847 // Equal-energy illuminant, used in two-stage CAT16
12848 E: [1.00000, 1.00000, 1.00000],
12849 // The F series of illuminants represent fluorescent lights
12850 F2: [0.99186, 1.00000, 0.67393],
12851 F7: [0.95041, 1.00000, 1.08747],
12852 F11: [1.00962, 1.00000, 0.64350]
12853 });
12854
12855 /** @import { Matrix3x3 } from "../types.js" */
12856
12857 // The ACES whitepoint
12858 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
12859 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
12860 // Similar to D60
12861 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
12862
12863 /**
12864 * Matrices used by this color space, also available as `ACEScg.M`
12865 * @type {Record<string, Matrix3x3>}
12866 */
12867 // prettier-ignore
12868 const M = {
12869 // convert an array of linear-light ACEScg values to CIE XYZ
12870 toXYZ: [[0.6624541811085053, 0.13400420645643313, 0.1561876870049078], [0.27222871678091454, 0.6740817658111484, 0.05368951740793705], [-0.005574649490394108, 0.004060733528982826, 1.0103391003129971]],
12871 fromXYZ: [[1.6410233796943257, -0.32480329418479, -0.23642469523761225], [-0.6636628587229829, 1.6153315916573379, 0.016756347685530137], [0.011721894328375376, -0.008284441996237409, 0.9883948585390215]]
12872 };
12873 var ACEScg = new RGBColorSpace({
12874 id: "acescg",
12875 cssId: "--acescg",
12876 name: "ACEScg",
12877 // ACEScg – A scene-referred, linear-light encoding of ACES Data
12878 // https://docs.acescentral.com/specifications/acescg/
12879 // uses the AP1 primaries, see section 4.3.1 Color primaries
12880 coords: {
12881 r: {
12882 range: [0, 65504],
12883 name: "Red"
12884 },
12885 g: {
12886 range: [0, 65504],
12887 name: "Green"
12888 },
12889 b: {
12890 range: [0, 65504],
12891 name: "Blue"
12892 }
12893 },
12894 referred: "scene",
12895 white: WHITES.ACES,
12896 M
12897 });
12898
12899 // export default Color;
12900
12901 const ε = 2 ** -16;
12902
12903 // the smallest value which, in the 32bit IEEE 754 float encoding,
12904 // decodes as a non-negative value
12905 const ACES_min_nonzero = -0.35828683;
12906
12907 // brightest encoded value, decodes to 65504
12908 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
12909
12910 var acescc = new RGBColorSpace({
12911 id: "acescc",
12912 cssId: "--acescc",
12913 name: "ACEScc",
12914 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
12915 // https://docs.acescentral.com/specifications/acescc/
12916 // uses the AP1 primaries, see section 4.3.1 Color primaries
12917
12918 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
12919 // below 18% middle gray are encoded as negative ACEScc values.
12920 // These values should be preserved per the encoding in Section 4.4
12921 // so that all positive ACES values are maintained."
12922 coords: {
12923 r: {
12924 range: [ACES_min_nonzero, ACES_cc_max],
12925 name: "Red"
12926 },
12927 g: {
12928 range: [ACES_min_nonzero, ACES_cc_max],
12929 name: "Green"
12930 },
12931 b: {
12932 range: [ACES_min_nonzero, ACES_cc_max],
12933 name: "Blue"
12934 }
12935 },
12936 referred: "scene",
12937 base: ACEScg,
12938 linearGamut: ACEScg,
12939 // from section 4.4.2 Decoding Function
12940 toBase(RGB) {
12941 const low = (9.72 - 15) / 17.52; // -0.3014
12942
12943 return RGB.map(function (val) {
12944 if (val <= low) {
12945 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
12946 } else if (val < ACES_cc_max) {
12947 return 2 ** (val * 17.52 - 9.72);
12948 } else {
12949 // val >= ACES_cc_max
12950 return 65504;
12951 }
12952 });
12953 },
12954 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
12955 fromBase(RGB) {
12956 return RGB.map(function (val) {
12957 if (val <= 0) {
12958 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
12959 } else if (val < ε) {
12960 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
12961 } else {
12962 // val >= ε
12963 return (Math.log2(val) + 9.72) / 17.52;
12964 }
12965 });
12966 }
12967 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
12968 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
12969 });
12970
12971 /**
12972 * @packageDocumentation
12973 * Re-exports all the spaces built into Color.js.
12974 */
12975
12976 var indexFn = /*#__PURE__*/Object.freeze({
12977 __proto__: null,
12978 A98RGB: a98rgb,
12979 A98RGB_Linear: A98Linear,
12980 ACEScc: acescc,
12981 ACEScg: ACEScg,
12982 CAM16_JMh: cam16,
12983 HCT: hct,
12984 HPLuv: HPLuv,
12985 HSL: HSL,
12986 HSL_P3: hslP3,
12987 HSL_REC2020: hslRec2020,
12988 HSLuv: hsluv,
12989 HSV: HSV,
12990 HWB: hwb,
12991 HelmGen: HelmGen,
12992 HelmGenLCh: helmgenlch,
12993 Helmlab: helmlab,
12994 ICTCP: ictcp,
12995 JzCzHz: jzczhz,
12996 Jzazbz: Jzazbz,
12997 LCH: lch,
12998 LCH_P3: lchP3,
12999 LCH_REC_2020: lchRec2020,
13000 LCH_sRGB: lchSrgb,
13001 LCHuv: LCHuv,
13002 Lab: lab,
13003 Lab_D65: lab_d65,
13004 Luv: Luv,
13005 OKLCH: OKLCH,
13006 OKLCH_P3: oklchP3,
13007 OKLCH_REC_2020: oklchRec2020,
13008 OKLCH_sRGB: oklchSrgb,
13009 OKLab: Oklab,
13010 OKLrCH: oklrch,
13011 OKLrab: OKLrab,
13012 Okhsl: Okhsl,
13013 Okhsv: Okhsv,
13014 P3: P3,
13015 P3_Linear: P3Linear,
13016 ProPhoto: prophoto,
13017 ProPhoto_Linear: ProPhotoLinear,
13018 REC_2020: REC2020,
13019 REC_2020_Linear: REC2020Linear,
13020 REC_2020_Scene_Referred: rec2020Oetf,
13021 REC_2100_HLG: rec2100Hlg,
13022 REC_2100_Linear: REC_2100_Linear,
13023 REC_2100_PQ: rec2100Pq,
13024 XYZ_ABS_D65: XYZ_Abs_D65,
13025 XYZ_D50: XYZ_D50,
13026 XYZ_D65: XYZ_D65,
13027 sRGB: sRGB,
13028 sRGB_Linear: sRGBLinear
13029 });
13030
13031 exports.A98RGB = a98rgb;
13032 exports.A98RGB_Linear = A98Linear;
13033 exports.ACEScc = acescc;
13034 exports.ACEScg = ACEScg;
13035 exports.CAM16_JMh = cam16;
13036 exports.ColorSpace = ColorSpace;
13037 exports.GamutRelativeColorSpace = GamutRelativeColorSpace;
13038 exports.HCT = hct;
13039 exports.HPLuv = HPLuv;
13040 exports.HSL = HSL;
13041 exports.HSL_P3 = hslP3;
13042 exports.HSL_REC2020 = hslRec2020;
13043 exports.HSLuv = hsluv;
13044 exports.HSV = HSV;
13045 exports.HWB = hwb;
13046 exports.HelmGen = HelmGen;
13047 exports.HelmGenLCh = helmgenlch;
13048 exports.Helmlab = helmlab;
13049 exports.Hooks = Hooks;
13050 exports.ICTCP = ictcp;
13051 exports.JzCzHz = jzczhz;
13052 exports.Jzazbz = Jzazbz;
13053 exports.LCH = lch;
13054 exports.LCH_P3 = lchP3;
13055 exports.LCH_REC_2020 = lchRec2020;
13056 exports.LCH_sRGB = lchSrgb;
13057 exports.LCHuv = LCHuv;
13058 exports.Lab = lab;
13059 exports.Lab_D65 = lab_d65;
13060 exports.Luv = Luv;
13061 exports.OKLCH = OKLCH;
13062 exports.OKLCH_P3 = oklchP3;
13063 exports.OKLCH_REC_2020 = oklchRec2020;
13064 exports.OKLCH_sRGB = oklchSrgb;
13065 exports.OKLab = Oklab;
13066 exports.OKLrCH = oklrch;
13067 exports.OKLrab = OKLrab;
13068 exports.Okhsl = Okhsl;
13069 exports.Okhsv = Okhsv;
13070 exports.P3 = P3;
13071 exports.P3_Linear = P3Linear;
13072 exports.ProPhoto = prophoto;
13073 exports.ProPhoto_Linear = ProPhotoLinear;
13074 exports.REC_2020 = REC2020;
13075 exports.REC_2020_Linear = REC2020Linear;
13076 exports.REC_2020_Scene_Referred = rec2020Oetf;
13077 exports.REC_2100_HLG = rec2100Hlg;
13078 exports.REC_2100_Linear = REC_2100_Linear;
13079 exports.REC_2100_PQ = rec2100Pq;
13080 exports.RGBColorSpace = RGBColorSpace;
13081 exports.XYZ_ABS_D65 = XYZ_Abs_D65;
13082 exports.XYZ_D50 = XYZ_D50;
13083 exports.XYZ_D65 = XYZ_D65;
13084 exports.clone = clone;
13085 exports.contrast = contrast;
13086 exports.contrastAPCA = contrastAPCA;
13087 exports.contrastDeltaPhi = contrastDeltaPhi;
13088 exports.contrastLstar = contrastLstar;
13089 exports.contrastMichelson = contrastMichelson;
13090 exports.contrastWCAG21 = contrastWCAG21;
13091 exports.contrastWeber = contrastWeber;
13092 exports.darken = darken;
13093 exports.defaults = defaults;
13094 exports.deltaE = deltaE;
13095 exports.deltaE2000 = deltaE2000;
13096 exports.deltaE76 = deltaE76;
13097 exports.deltaECMC = deltaECMC;
13098 exports.deltaEHCT = deltaEHCT;
13099 exports.deltaEHelmlab = deltaEHelmlab;
13100 exports.deltaEITP = deltaEITP;
13101 exports.deltaEJz = deltaEJz;
13102 exports.deltaEMethods = deltaEMethods;
13103 exports.deltaEOK = deltaEOK;
13104 exports.deltaEOK2 = deltaEOK2;
13105 exports.deltas = deltas;
13106 exports.display = display;
13107 exports.distance = distance;
13108 exports.equals = equals;
13109 exports.get = get;
13110 exports.getAll = getAll;
13111 exports.getColor = getColor;
13112 exports.getLuminance = getLuminance;
13113 exports.hooks = hooks;
13114 exports.inGamut = inGamut;
13115 exports.isRange = isRange;
13116 exports.lighten = lighten;
13117 exports.mix = mix;
13118 exports.parse = parse;
13119 exports.range = range;
13120 exports.sRGB = sRGB;
13121 exports.sRGB_Linear = sRGBLinear;
13122 exports.serialize = serialize;
13123 exports.set = set;
13124 exports.setAll = setAll;
13125 exports.setLuminance = setLuminance;
13126 exports.spaces = indexFn;
13127 exports.steps = steps;
13128 exports.to = to;
13129 exports.toGamut = toGamut;
13130 exports.toGamutCSS = toGamutCSS;
13131 exports.tryColor = tryColor;
13132 exports.uv = uv;
13133 exports.xy = xy;
13134 //# sourceMappingURL=color-fn.legacy.cjs.map