UNPKG

289 kBJavaScriptView Raw
1/**
2 * Dark Reader v4.9.58
3 * https://darkreader.org/
4 */
5
6(function (global, factory) {
7 typeof exports === "object" && typeof module !== "undefined"
8 ? factory(exports)
9 : typeof define === "function" && define.amd
10 ? define(["exports"], factory)
11 : ((global =
12 typeof globalThis !== "undefined" ? globalThis : global || self),
13 factory((global.DarkReader = {})));
14})(this, function (exports) {
15 "use strict";
16
17 /******************************************************************************
18 Copyright (c) Microsoft Corporation.
19
20 Permission to use, copy, modify, and/or distribute this software for any
21 purpose with or without fee is hereby granted.
22
23 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
24 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
25 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
26 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
27 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
28 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
29 PERFORMANCE OF THIS SOFTWARE.
30 ***************************************************************************** */
31
32 var __assign = function () {
33 __assign =
34 Object.assign ||
35 function __assign(t) {
36 for (var s, i = 1, n = arguments.length; i < n; i++) {
37 s = arguments[i];
38 for (var p in s)
39 if (Object.prototype.hasOwnProperty.call(s, p))
40 t[p] = s[p];
41 }
42 return t;
43 };
44 return __assign.apply(this, arguments);
45 };
46
47 function __awaiter(thisArg, _arguments, P, generator) {
48 function adopt(value) {
49 return value instanceof P
50 ? value
51 : new P(function (resolve) {
52 resolve(value);
53 });
54 }
55 return new (P || (P = Promise))(function (resolve, reject) {
56 function fulfilled(value) {
57 try {
58 step(generator.next(value));
59 } catch (e) {
60 reject(e);
61 }
62 }
63 function rejected(value) {
64 try {
65 step(generator["throw"](value));
66 } catch (e) {
67 reject(e);
68 }
69 }
70 function step(result) {
71 result.done
72 ? resolve(result.value)
73 : adopt(result.value).then(fulfilled, rejected);
74 }
75 step(
76 (generator = generator.apply(thisArg, _arguments || [])).next()
77 );
78 });
79 }
80
81 function __generator(thisArg, body) {
82 var _ = {
83 label: 0,
84 sent: function () {
85 if (t[0] & 1) throw t[1];
86 return t[1];
87 },
88 trys: [],
89 ops: []
90 },
91 f,
92 y,
93 t,
94 g;
95 return (
96 (g = {next: verb(0), throw: verb(1), return: verb(2)}),
97 typeof Symbol === "function" &&
98 (g[Symbol.iterator] = function () {
99 return this;
100 }),
101 g
102 );
103 function verb(n) {
104 return function (v) {
105 return step([n, v]);
106 };
107 }
108 function step(op) {
109 if (f) throw new TypeError("Generator is already executing.");
110 while (_)
111 try {
112 if (
113 ((f = 1),
114 y &&
115 (t =
116 op[0] & 2
117 ? y["return"]
118 : op[0]
119 ? y["throw"] ||
120 ((t = y["return"]) && t.call(y), 0)
121 : y.next) &&
122 !(t = t.call(y, op[1])).done)
123 )
124 return t;
125 if (((y = 0), t)) op = [op[0] & 2, t.value];
126 switch (op[0]) {
127 case 0:
128 case 1:
129 t = op;
130 break;
131 case 4:
132 _.label++;
133 return {value: op[1], done: false};
134 case 5:
135 _.label++;
136 y = op[1];
137 op = [0];
138 continue;
139 case 7:
140 op = _.ops.pop();
141 _.trys.pop();
142 continue;
143 default:
144 if (
145 !((t = _.trys),
146 (t = t.length > 0 && t[t.length - 1])) &&
147 (op[0] === 6 || op[0] === 2)
148 ) {
149 _ = 0;
150 continue;
151 }
152 if (
153 op[0] === 3 &&
154 (!t || (op[1] > t[0] && op[1] < t[3]))
155 ) {
156 _.label = op[1];
157 break;
158 }
159 if (op[0] === 6 && _.label < t[1]) {
160 _.label = t[1];
161 t = op;
162 break;
163 }
164 if (t && _.label < t[2]) {
165 _.label = t[2];
166 _.ops.push(op);
167 break;
168 }
169 if (t[2]) _.ops.pop();
170 _.trys.pop();
171 continue;
172 }
173 op = body.call(thisArg, _);
174 } catch (e) {
175 op = [6, e];
176 y = 0;
177 } finally {
178 f = t = 0;
179 }
180 if (op[0] & 5) throw op[1];
181 return {value: op[0] ? op[1] : void 0, done: true};
182 }
183 }
184
185 function __values(o) {
186 var s = typeof Symbol === "function" && Symbol.iterator,
187 m = s && o[s],
188 i = 0;
189 if (m) return m.call(o);
190 if (o && typeof o.length === "number")
191 return {
192 next: function () {
193 if (o && i >= o.length) o = void 0;
194 return {value: o && o[i++], done: !o};
195 }
196 };
197 throw new TypeError(
198 s ? "Object is not iterable." : "Symbol.iterator is not defined."
199 );
200 }
201
202 function __read(o, n) {
203 var m = typeof Symbol === "function" && o[Symbol.iterator];
204 if (!m) return o;
205 var i = m.call(o),
206 r,
207 ar = [],
208 e;
209 try {
210 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
211 ar.push(r.value);
212 } catch (error) {
213 e = {error: error};
214 } finally {
215 try {
216 if (r && !r.done && (m = i["return"])) m.call(i);
217 } finally {
218 if (e) throw e.error;
219 }
220 }
221 return ar;
222 }
223
224 function __spreadArray(to, from, pack) {
225 if (pack || arguments.length === 2)
226 for (var i = 0, l = from.length, ar; i < l; i++) {
227 if (ar || !(i in from)) {
228 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
229 ar[i] = from[i];
230 }
231 }
232 return to.concat(ar || Array.prototype.slice.call(from));
233 }
234
235 var MessageType;
236 (function (MessageType) {
237 MessageType["UI_GET_DATA"] = "ui-get-data";
238 MessageType["UI_SUBSCRIBE_TO_CHANGES"] = "ui-subscribe-to-changes";
239 MessageType["UI_UNSUBSCRIBE_FROM_CHANGES"] =
240 "ui-unsubscribe-from-changes";
241 MessageType["UI_CHANGE_SETTINGS"] = "ui-change-settings";
242 MessageType["UI_SET_THEME"] = "ui-set-theme";
243 MessageType["UI_SET_SHORTCUT"] = "ui-set-shortcut";
244 MessageType["UI_TOGGLE_ACTIVE_TAB"] = "ui-toggle-active-tab";
245 MessageType["UI_MARK_NEWS_AS_READ"] = "ui-mark-news-as-read";
246 MessageType["UI_MARK_NEWS_AS_DISPLAYED"] = "ui-mark-news-as-displayed";
247 MessageType["UI_LOAD_CONFIG"] = "ui-load-config";
248 MessageType["UI_APPLY_DEV_DYNAMIC_THEME_FIXES"] =
249 "ui-apply-dev-dynamic-theme-fixes";
250 MessageType["UI_RESET_DEV_DYNAMIC_THEME_FIXES"] =
251 "ui-reset-dev-dynamic-theme-fixes";
252 MessageType["UI_APPLY_DEV_INVERSION_FIXES"] =
253 "ui-apply-dev-inversion-fixes";
254 MessageType["UI_RESET_DEV_INVERSION_FIXES"] =
255 "ui-reset-dev-inversion-fixes";
256 MessageType["UI_APPLY_DEV_STATIC_THEMES"] =
257 "ui-apply-dev-static-themes";
258 MessageType["UI_RESET_DEV_STATIC_THEMES"] =
259 "ui-reset-dev-static-themes";
260 MessageType["UI_SAVE_FILE"] = "ui-save-file";
261 MessageType["UI_REQUEST_EXPORT_CSS"] = "ui-request-export-css";
262 MessageType["UI_COLOR_SCHEME_CHANGE"] = "ui-color-scheme-change";
263 MessageType["BG_CHANGES"] = "bg-changes";
264 MessageType["BG_ADD_CSS_FILTER"] = "bg-add-css-filter";
265 MessageType["BG_ADD_STATIC_THEME"] = "bg-add-static-theme";
266 MessageType["BG_ADD_SVG_FILTER"] = "bg-add-svg-filter";
267 MessageType["BG_ADD_DYNAMIC_THEME"] = "bg-add-dynamic-theme";
268 MessageType["BG_EXPORT_CSS"] = "bg-export-css";
269 MessageType["BG_UNSUPPORTED_SENDER"] = "bg-unsupported-sender";
270 MessageType["BG_CLEAN_UP"] = "bg-clean-up";
271 MessageType["BG_RELOAD"] = "bg-reload";
272 MessageType["BG_FETCH_RESPONSE"] = "bg-fetch-response";
273 MessageType["BG_UI_UPDATE"] = "bg-ui-update";
274 MessageType["BG_CSS_UPDATE"] = "bg-css-update";
275 MessageType["CS_COLOR_SCHEME_CHANGE"] = "cs-color-scheme-change";
276 MessageType["CS_FRAME_CONNECT"] = "cs-frame-connect";
277 MessageType["CS_FRAME_FORGET"] = "cs-frame-forget";
278 MessageType["CS_FRAME_FREEZE"] = "cs-frame-freeze";
279 MessageType["CS_FRAME_RESUME"] = "cs-frame-resume";
280 MessageType["CS_EXPORT_CSS_RESPONSE"] = "cs-export-css-response";
281 MessageType["CS_FETCH"] = "cs-fetch";
282 MessageType["CS_DARK_THEME_DETECTED"] = "cs-dark-theme-detected";
283 MessageType["CS_DARK_THEME_NOT_DETECTED"] =
284 "cs-dark-theme-not-detected";
285 MessageType["CS_LOG"] = "cs-log";
286 })(MessageType || (MessageType = {}));
287
288 var isNavigatorDefined = typeof navigator !== "undefined";
289 var userAgent = isNavigatorDefined
290 ? navigator.userAgentData &&
291 Array.isArray(navigator.userAgentData.brands)
292 ? navigator.userAgentData.brands
293 .map(function (brand) {
294 return ""
295 .concat(brand.brand.toLowerCase(), " ")
296 .concat(brand.version);
297 })
298 .join(" ")
299 : navigator.userAgent.toLowerCase()
300 : "some useragent";
301 var platform = isNavigatorDefined
302 ? navigator.userAgentData &&
303 typeof navigator.userAgentData.platform === "string"
304 ? navigator.userAgentData.platform.toLowerCase()
305 : navigator.platform.toLowerCase()
306 : "some platform";
307 var isChromium =
308 userAgent.includes("chrome") || userAgent.includes("chromium");
309 var isThunderbird = userAgent.includes("thunderbird");
310 var isFirefox =
311 userAgent.includes("firefox") ||
312 userAgent.includes("librewolf") ||
313 isThunderbird;
314 userAgent.includes("vivaldi");
315 userAgent.includes("yabrowser");
316 userAgent.includes("opr") || userAgent.includes("opera");
317 userAgent.includes("edg");
318 var isSafari = userAgent.includes("safari") && !isChromium;
319 var isWindows = platform.startsWith("win");
320 var isMacOS = platform.startsWith("mac");
321 isNavigatorDefined && navigator.userAgentData
322 ? navigator.userAgentData.mobile
323 : userAgent.includes("mobile");
324 var isShadowDomSupported = typeof ShadowRoot === "function";
325 var isMatchMediaChangeEventListenerSupported =
326 typeof MediaQueryList === "function" &&
327 typeof MediaQueryList.prototype.addEventListener === "function";
328 (function () {
329 var m = userAgent.match(/chrom(?:e|ium)(?:\/| )([^ ]+)/);
330 if (m && m[1]) {
331 return m[1];
332 }
333 return "";
334 })();
335 (function () {
336 var m = userAgent.match(/(?:firefox|librewolf)(?:\/| )([^ ]+)/);
337 if (m && m[1]) {
338 return m[1];
339 }
340 return "";
341 })();
342 var isDefinedSelectorSupported = (function () {
343 try {
344 document.querySelector(":defined");
345 return true;
346 } catch (err) {
347 return false;
348 }
349 })();
350 var isCSSColorSchemePropSupported = (function () {
351 if (typeof document === "undefined") {
352 return false;
353 }
354 var el = document.createElement("div");
355 el.setAttribute("style", "color-scheme: dark");
356 return el.style && el.style.colorScheme === "dark";
357 })();
358
359 function getOKResponse(url, mimeType, origin) {
360 return __awaiter(this, void 0, void 0, function () {
361 var response;
362 return __generator(this, function (_a) {
363 switch (_a.label) {
364 case 0:
365 return [
366 4,
367 fetch(url, {
368 cache: "force-cache",
369 credentials: "omit",
370 referrer: origin
371 })
372 ];
373 case 1:
374 response = _a.sent();
375 if (
376 isFirefox &&
377 mimeType === "text/css" &&
378 url.startsWith("moz-extension://") &&
379 url.endsWith(".css")
380 ) {
381 return [2, response];
382 }
383 if (
384 mimeType &&
385 !response.headers
386 .get("Content-Type")
387 .startsWith(mimeType)
388 ) {
389 throw new Error(
390 "Mime type mismatch when loading ".concat(url)
391 );
392 }
393 if (!response.ok) {
394 throw new Error(
395 "Unable to load "
396 .concat(url, " ")
397 .concat(response.status, " ")
398 .concat(response.statusText)
399 );
400 }
401 return [2, response];
402 }
403 });
404 });
405 }
406 function loadAsDataURL(url, mimeType) {
407 return __awaiter(this, void 0, void 0, function () {
408 var response;
409 return __generator(this, function (_a) {
410 switch (_a.label) {
411 case 0:
412 return [4, getOKResponse(url, mimeType)];
413 case 1:
414 response = _a.sent();
415 return [4, readResponseAsDataURL(response)];
416 case 2:
417 return [2, _a.sent()];
418 }
419 });
420 });
421 }
422 function readResponseAsDataURL(response) {
423 return __awaiter(this, void 0, void 0, function () {
424 var blob, dataURL;
425 return __generator(this, function (_a) {
426 switch (_a.label) {
427 case 0:
428 return [4, response.blob()];
429 case 1:
430 blob = _a.sent();
431 return [
432 4,
433 new Promise(function (resolve) {
434 var reader = new FileReader();
435 reader.onloadend = function () {
436 return resolve(reader.result);
437 };
438 reader.readAsDataURL(blob);
439 })
440 ];
441 case 2:
442 dataURL = _a.sent();
443 return [2, dataURL];
444 }
445 });
446 });
447 }
448
449 var throwCORSError = function (url) {
450 return __awaiter(void 0, void 0, void 0, function () {
451 return __generator(this, function (_a) {
452 return [
453 2,
454 Promise.reject(
455 new Error(
456 [
457 "Embedded Dark Reader cannot access a cross-origin resource",
458 url,
459 "Overview your URLs and CORS policies or use",
460 "`DarkReader.setFetchMethod(fetch: (url) => Promise<Response>))`.",
461 "See if using `DarkReader.setFetchMethod(window.fetch)`",
462 "before `DarkReader.enable()` works."
463 ].join(" ")
464 )
465 )
466 ];
467 });
468 });
469 };
470 var fetcher = throwCORSError;
471 function setFetchMethod$1(fetch) {
472 if (fetch) {
473 fetcher = fetch;
474 } else {
475 fetcher = throwCORSError;
476 }
477 }
478 function callFetchMethod(url) {
479 return __awaiter(this, void 0, void 0, function () {
480 return __generator(this, function (_a) {
481 switch (_a.label) {
482 case 0:
483 return [4, fetcher(url)];
484 case 1:
485 return [2, _a.sent()];
486 }
487 });
488 });
489 }
490
491 if (!window.chrome) {
492 window.chrome = {};
493 }
494 if (!chrome.runtime) {
495 chrome.runtime = {};
496 }
497 var messageListeners = new Set();
498 function sendMessage() {
499 var args = [];
500 for (var _i = 0; _i < arguments.length; _i++) {
501 args[_i] = arguments[_i];
502 }
503 return __awaiter(this, void 0, void 0, function () {
504 var id_1, _a, url, responseType, response, text_1, error_1;
505 return __generator(this, function (_b) {
506 switch (_b.label) {
507 case 0:
508 if (!(args[0] && args[0].type === MessageType.CS_FETCH))
509 return [3, 8];
510 id_1 = args[0].id;
511 _b.label = 1;
512 case 1:
513 _b.trys.push([1, 7, , 8]);
514 (_a = args[0].data),
515 (url = _a.url),
516 (responseType = _a.responseType);
517 return [4, callFetchMethod(url)];
518 case 2:
519 response = _b.sent();
520 if (!(responseType === "data-url")) return [3, 4];
521 return [4, readResponseAsDataURL(response)];
522 case 3:
523 text_1 = _b.sent();
524 return [3, 6];
525 case 4:
526 return [4, response.text()];
527 case 5:
528 text_1 = _b.sent();
529 _b.label = 6;
530 case 6:
531 messageListeners.forEach(function (cb) {
532 return cb({
533 type: MessageType.BG_FETCH_RESPONSE,
534 data: text_1,
535 error: null,
536 id: id_1
537 });
538 });
539 return [3, 8];
540 case 7:
541 error_1 = _b.sent();
542 console.error(error_1);
543 messageListeners.forEach(function (cb) {
544 return cb({
545 type: MessageType.BG_FETCH_RESPONSE,
546 data: null,
547 error: error_1,
548 id: id_1
549 });
550 });
551 return [3, 8];
552 case 8:
553 return [2];
554 }
555 });
556 });
557 }
558 function addMessageListener(callback) {
559 messageListeners.add(callback);
560 }
561 if (typeof chrome.runtime.sendMessage === "function") {
562 var nativeSendMessage_1 = chrome.runtime.sendMessage;
563 chrome.runtime.sendMessage = function () {
564 var args = [];
565 for (var _i = 0; _i < arguments.length; _i++) {
566 args[_i] = arguments[_i];
567 }
568 sendMessage.apply(void 0, __spreadArray([], __read(args), false));
569 nativeSendMessage_1.apply(chrome.runtime, args);
570 };
571 } else {
572 chrome.runtime.sendMessage = sendMessage;
573 }
574 if (!chrome.runtime.onMessage) {
575 chrome.runtime.onMessage = {};
576 }
577 if (typeof chrome.runtime.onMessage.addListener === "function") {
578 var nativeAddListener_1 = chrome.runtime.onMessage.addListener;
579 chrome.runtime.onMessage.addListener = function () {
580 var args = [];
581 for (var _i = 0; _i < arguments.length; _i++) {
582 args[_i] = arguments[_i];
583 }
584 addMessageListener(args[0]);
585 nativeAddListener_1.apply(chrome.runtime.onMessage, args);
586 };
587 } else {
588 chrome.runtime.onMessage.addListener = function () {
589 var args = [];
590 for (var _i = 0; _i < arguments.length; _i++) {
591 args[_i] = arguments[_i];
592 }
593 return addMessageListener(args[0]);
594 };
595 }
596
597 var ThemeEngine;
598 (function (ThemeEngine) {
599 ThemeEngine["cssFilter"] = "cssFilter";
600 ThemeEngine["svgFilter"] = "svgFilter";
601 ThemeEngine["staticTheme"] = "staticTheme";
602 ThemeEngine["dynamicTheme"] = "dynamicTheme";
603 })(ThemeEngine || (ThemeEngine = {}));
604
605 var AutomationMode;
606 (function (AutomationMode) {
607 AutomationMode["NONE"] = "";
608 AutomationMode["TIME"] = "time";
609 AutomationMode["SYSTEM"] = "system";
610 AutomationMode["LOCATION"] = "location";
611 })(AutomationMode || (AutomationMode = {}));
612
613 var DEFAULT_COLORS = {
614 darkScheme: {
615 background: "#181a1b",
616 text: "#e8e6e3"
617 },
618 lightScheme: {
619 background: "#dcdad7",
620 text: "#181a1b"
621 }
622 };
623 var DEFAULT_THEME = {
624 mode: 1,
625 brightness: 100,
626 contrast: 100,
627 grayscale: 0,
628 sepia: 0,
629 useFont: false,
630 fontFamily: isMacOS
631 ? "Helvetica Neue"
632 : isWindows
633 ? "Segoe UI"
634 : "Open Sans",
635 textStroke: 0,
636 engine: ThemeEngine.dynamicTheme,
637 stylesheet: "",
638 darkSchemeBackgroundColor: DEFAULT_COLORS.darkScheme.background,
639 darkSchemeTextColor: DEFAULT_COLORS.darkScheme.text,
640 lightSchemeBackgroundColor: DEFAULT_COLORS.lightScheme.background,
641 lightSchemeTextColor: DEFAULT_COLORS.lightScheme.text,
642 scrollbarColor: isMacOS ? "" : "auto",
643 selectionColor: "auto",
644 styleSystemControls: !isCSSColorSchemePropSupported,
645 lightColorScheme: "Default",
646 darkColorScheme: "Default",
647 immediateModify: false
648 };
649 ({
650 enabled: true,
651 fetchNews: true,
652 theme: DEFAULT_THEME,
653 presets: [],
654 customThemes: [],
655 siteList: [],
656 siteListEnabled: [],
657 applyToListedOnly: false,
658 changeBrowserTheme: false,
659 syncSettings: true,
660 syncSitesFixes: false,
661 automation: {
662 enabled: false,
663 mode: AutomationMode.NONE,
664 behavior: "OnOff"
665 },
666 time: {
667 activation: "18:00",
668 deactivation: "9:00"
669 },
670 location: {
671 latitude: null,
672 longitude: null
673 },
674 previewNewDesign: false,
675 enableForPDF: true,
676 enableForProtectedPages: false,
677 enableContextMenus: false,
678 detectDarkTheme: false
679 });
680
681 function isArrayLike(items) {
682 return items.length != null;
683 }
684 function forEach(items, iterator) {
685 var e_1, _a;
686 if (isArrayLike(items)) {
687 for (var i = 0, len = items.length; i < len; i++) {
688 iterator(items[i]);
689 }
690 } else {
691 try {
692 for (
693 var items_1 = __values(items), items_1_1 = items_1.next();
694 !items_1_1.done;
695 items_1_1 = items_1.next()
696 ) {
697 var item = items_1_1.value;
698 iterator(item);
699 }
700 } catch (e_1_1) {
701 e_1 = {error: e_1_1};
702 } finally {
703 try {
704 if (items_1_1 && !items_1_1.done && (_a = items_1.return))
705 _a.call(items_1);
706 } finally {
707 if (e_1) throw e_1.error;
708 }
709 }
710 }
711 }
712 function push(array, addition) {
713 forEach(addition, function (a) {
714 return array.push(a);
715 });
716 }
717 function toArray(items) {
718 var results = [];
719 for (var i = 0, len = items.length; i < len; i++) {
720 results.push(items[i]);
721 }
722 return results;
723 }
724
725 function logInfo() {}
726 function logWarn() {}
727
728 function throttle(callback) {
729 var pending = false;
730 var frameId = null;
731 var lastArgs;
732 var throttled = function () {
733 var args = [];
734 for (var _i = 0; _i < arguments.length; _i++) {
735 args[_i] = arguments[_i];
736 }
737 lastArgs = args;
738 if (frameId) {
739 pending = true;
740 } else {
741 callback.apply(
742 void 0,
743 __spreadArray([], __read(lastArgs), false)
744 );
745 frameId = requestAnimationFrame(function () {
746 frameId = null;
747 if (pending) {
748 callback.apply(
749 void 0,
750 __spreadArray([], __read(lastArgs), false)
751 );
752 pending = false;
753 }
754 });
755 }
756 };
757 var cancel = function () {
758 cancelAnimationFrame(frameId);
759 pending = false;
760 frameId = null;
761 };
762 return Object.assign(throttled, {cancel: cancel});
763 }
764 function createAsyncTasksQueue() {
765 var tasks = [];
766 var frameId = null;
767 function runTasks() {
768 var task;
769 while ((task = tasks.shift())) {
770 task();
771 }
772 frameId = null;
773 }
774 function add(task) {
775 tasks.push(task);
776 if (!frameId) {
777 frameId = requestAnimationFrame(runTasks);
778 }
779 }
780 function cancel() {
781 tasks.splice(0);
782 cancelAnimationFrame(frameId);
783 frameId = null;
784 }
785 return {add: add, cancel: cancel};
786 }
787
788 function getDuration(time) {
789 var duration = 0;
790 if (time.seconds) {
791 duration += time.seconds * 1000;
792 }
793 if (time.minutes) {
794 duration += time.minutes * 60 * 1000;
795 }
796 if (time.hours) {
797 duration += time.hours * 60 * 60 * 1000;
798 }
799 if (time.days) {
800 duration += time.days * 24 * 60 * 60 * 1000;
801 }
802 return duration;
803 }
804
805 function removeNode(node) {
806 node && node.parentNode && node.parentNode.removeChild(node);
807 }
808 function watchForNodePosition(node, mode, onRestore) {
809 if (onRestore === void 0) {
810 onRestore = Function.prototype;
811 }
812 var MAX_ATTEMPTS_COUNT = 10;
813 var RETRY_TIMEOUT = getDuration({seconds: 2});
814 var ATTEMPTS_INTERVAL = getDuration({seconds: 10});
815 var prevSibling = node.previousSibling;
816 var parent = node.parentNode;
817 if (!parent) {
818 throw new Error(
819 "Unable to watch for node position: parent element not found"
820 );
821 }
822 if (mode === "prev-sibling" && !prevSibling) {
823 throw new Error(
824 "Unable to watch for node position: there is no previous sibling"
825 );
826 }
827 var attempts = 0;
828 var start = null;
829 var timeoutId = null;
830 var restore = throttle(function () {
831 if (timeoutId) {
832 return;
833 }
834 attempts++;
835 var now = Date.now();
836 if (start == null) {
837 start = now;
838 } else if (attempts >= MAX_ATTEMPTS_COUNT) {
839 if (now - start < ATTEMPTS_INTERVAL) {
840 timeoutId = setTimeout(function () {
841 start = null;
842 attempts = 0;
843 timeoutId = null;
844 restore();
845 }, RETRY_TIMEOUT);
846 return;
847 }
848 start = now;
849 attempts = 1;
850 }
851 if (mode === "parent") {
852 if (prevSibling && prevSibling.parentNode !== parent) {
853 stop();
854 return;
855 }
856 }
857 if (mode === "prev-sibling") {
858 if (prevSibling.parentNode == null) {
859 stop();
860 return;
861 }
862 if (prevSibling.parentNode !== parent) {
863 updateParent(prevSibling.parentNode);
864 }
865 }
866 parent.insertBefore(
867 node,
868 prevSibling ? prevSibling.nextSibling : parent.firstChild
869 );
870 observer.takeRecords();
871 onRestore && onRestore();
872 });
873 var observer = new MutationObserver(function () {
874 if (
875 (mode === "parent" && node.parentNode !== parent) ||
876 (mode === "prev-sibling" &&
877 node.previousSibling !== prevSibling)
878 ) {
879 restore();
880 }
881 });
882 var run = function () {
883 observer.observe(parent, {childList: true});
884 };
885 var stop = function () {
886 clearTimeout(timeoutId);
887 observer.disconnect();
888 restore.cancel();
889 };
890 var skip = function () {
891 observer.takeRecords();
892 };
893 var updateParent = function (parentNode) {
894 parent = parentNode;
895 stop();
896 run();
897 };
898 run();
899 return {run: run, stop: stop, skip: skip};
900 }
901 function iterateShadowHosts(root, iterator) {
902 if (root == null) {
903 return;
904 }
905 var walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
906 acceptNode: function (node) {
907 return node.shadowRoot == null
908 ? NodeFilter.FILTER_SKIP
909 : NodeFilter.FILTER_ACCEPT;
910 }
911 });
912 for (
913 var node = root.shadowRoot ? walker.currentNode : walker.nextNode();
914 node != null;
915 node = walker.nextNode()
916 ) {
917 if (node.classList.contains("surfingkeys_hints_host")) {
918 continue;
919 }
920 iterator(node);
921 iterateShadowHosts(node.shadowRoot, iterator);
922 }
923 }
924 var isDOMReady = function () {
925 return (
926 document.readyState === "complete" ||
927 document.readyState === "interactive"
928 );
929 };
930 function setIsDOMReady(newFunc) {
931 isDOMReady = newFunc;
932 }
933 var readyStateListeners = new Set();
934 function addDOMReadyListener(listener) {
935 isDOMReady() ? listener() : readyStateListeners.add(listener);
936 }
937 function removeDOMReadyListener(listener) {
938 readyStateListeners.delete(listener);
939 }
940 function isReadyStateComplete() {
941 return document.readyState === "complete";
942 }
943 var readyStateCompleteListeners = new Set();
944 function addReadyStateCompleteListener(listener) {
945 isReadyStateComplete()
946 ? listener()
947 : readyStateCompleteListeners.add(listener);
948 }
949 function cleanReadyStateCompleteListeners() {
950 readyStateCompleteListeners.clear();
951 }
952 if (!isDOMReady()) {
953 var onReadyStateChange_1 = function () {
954 if (isDOMReady()) {
955 readyStateListeners.forEach(function (listener) {
956 return listener();
957 });
958 readyStateListeners.clear();
959 if (isReadyStateComplete()) {
960 document.removeEventListener(
961 "readystatechange",
962 onReadyStateChange_1
963 );
964 readyStateCompleteListeners.forEach(function (listener) {
965 return listener();
966 });
967 readyStateCompleteListeners.clear();
968 }
969 }
970 };
971 document.addEventListener("readystatechange", onReadyStateChange_1);
972 }
973 var HUGE_MUTATIONS_COUNT = 1000;
974 function isHugeMutation(mutations) {
975 if (mutations.length > HUGE_MUTATIONS_COUNT) {
976 return true;
977 }
978 var addedNodesCount = 0;
979 for (var i = 0; i < mutations.length; i++) {
980 addedNodesCount += mutations[i].addedNodes.length;
981 if (addedNodesCount > HUGE_MUTATIONS_COUNT) {
982 return true;
983 }
984 }
985 return false;
986 }
987 function getElementsTreeOperations(mutations) {
988 var additions = new Set();
989 var deletions = new Set();
990 var moves = new Set();
991 mutations.forEach(function (m) {
992 forEach(m.addedNodes, function (n) {
993 if (n instanceof Element && n.isConnected) {
994 additions.add(n);
995 }
996 });
997 forEach(m.removedNodes, function (n) {
998 if (n instanceof Element) {
999 if (n.isConnected) {
1000 moves.add(n);
1001 additions.delete(n);
1002 } else {
1003 deletions.add(n);
1004 }
1005 }
1006 });
1007 });
1008 var duplicateAdditions = [];
1009 var duplicateDeletions = [];
1010 additions.forEach(function (node) {
1011 if (additions.has(node.parentElement)) {
1012 duplicateAdditions.push(node);
1013 }
1014 });
1015 deletions.forEach(function (node) {
1016 if (deletions.has(node.parentElement)) {
1017 duplicateDeletions.push(node);
1018 }
1019 });
1020 duplicateAdditions.forEach(function (node) {
1021 return additions.delete(node);
1022 });
1023 duplicateDeletions.forEach(function (node) {
1024 return deletions.delete(node);
1025 });
1026 return {additions: additions, moves: moves, deletions: deletions};
1027 }
1028 var optimizedTreeObservers = new Map();
1029 var optimizedTreeCallbacks = new WeakMap();
1030 function createOptimizedTreeObserver(root, callbacks) {
1031 var observer;
1032 var observerCallbacks;
1033 var domReadyListener;
1034 if (optimizedTreeObservers.has(root)) {
1035 observer = optimizedTreeObservers.get(root);
1036 observerCallbacks = optimizedTreeCallbacks.get(observer);
1037 } else {
1038 var hadHugeMutationsBefore_1 = false;
1039 var subscribedForReadyState_1 = false;
1040 observer = new MutationObserver(function (mutations) {
1041 if (isHugeMutation(mutations)) {
1042 if (!hadHugeMutationsBefore_1 || isDOMReady()) {
1043 observerCallbacks.forEach(function (_a) {
1044 var onHugeMutations = _a.onHugeMutations;
1045 return onHugeMutations(root);
1046 });
1047 } else if (!subscribedForReadyState_1) {
1048 domReadyListener = function () {
1049 return observerCallbacks.forEach(function (_a) {
1050 var onHugeMutations = _a.onHugeMutations;
1051 return onHugeMutations(root);
1052 });
1053 };
1054 addDOMReadyListener(domReadyListener);
1055 subscribedForReadyState_1 = true;
1056 }
1057 hadHugeMutationsBefore_1 = true;
1058 } else {
1059 var elementsOperations_1 =
1060 getElementsTreeOperations(mutations);
1061 observerCallbacks.forEach(function (_a) {
1062 var onMinorMutations = _a.onMinorMutations;
1063 return onMinorMutations(elementsOperations_1);
1064 });
1065 }
1066 });
1067 observer.observe(root, {childList: true, subtree: true});
1068 optimizedTreeObservers.set(root, observer);
1069 observerCallbacks = new Set();
1070 optimizedTreeCallbacks.set(observer, observerCallbacks);
1071 }
1072 observerCallbacks.add(callbacks);
1073 return {
1074 disconnect: function () {
1075 observerCallbacks.delete(callbacks);
1076 if (domReadyListener) {
1077 removeDOMReadyListener(domReadyListener);
1078 }
1079 if (observerCallbacks.size === 0) {
1080 observer.disconnect();
1081 optimizedTreeCallbacks.delete(observer);
1082 optimizedTreeObservers.delete(root);
1083 }
1084 }
1085 };
1086 }
1087
1088 var anchor;
1089 var parsedURLCache = new Map();
1090 function fixBaseURL($url) {
1091 if (!anchor) {
1092 anchor = document.createElement("a");
1093 }
1094 anchor.href = $url;
1095 return anchor.href;
1096 }
1097 function parseURL($url, $base) {
1098 if ($base === void 0) {
1099 $base = null;
1100 }
1101 var key = "".concat($url).concat($base ? ";".concat($base) : "");
1102 if (parsedURLCache.has(key)) {
1103 return parsedURLCache.get(key);
1104 }
1105 if ($base) {
1106 var parsedURL_1 = new URL($url, fixBaseURL($base));
1107 parsedURLCache.set(key, parsedURL_1);
1108 return parsedURL_1;
1109 }
1110 var parsedURL = new URL(fixBaseURL($url));
1111 parsedURLCache.set($url, parsedURL);
1112 return parsedURL;
1113 }
1114 function getAbsoluteURL($base, $relative) {
1115 if ($relative.match(/^data\\?\:/)) {
1116 return $relative;
1117 }
1118 if (/^\/\//.test($relative)) {
1119 return "".concat(location.protocol).concat($relative);
1120 }
1121 var b = parseURL($base);
1122 var a = parseURL($relative, b.href);
1123 return a.href;
1124 }
1125 function isRelativeHrefOnAbsolutePath(href) {
1126 if (href.startsWith("data:")) {
1127 return true;
1128 }
1129 var url = parseURL(href);
1130 if (url.protocol !== location.protocol) {
1131 return false;
1132 }
1133 if (url.hostname !== location.hostname) {
1134 return false;
1135 }
1136 if (url.port !== location.port) {
1137 return false;
1138 }
1139 return url.pathname === location.pathname;
1140 }
1141
1142 function iterateCSSRules(rules, iterate, onMediaRuleError) {
1143 forEach(rules, function (rule) {
1144 if (rule.selectorText) {
1145 iterate(rule);
1146 } else if (rule.href) {
1147 try {
1148 iterateCSSRules(
1149 rule.styleSheet.cssRules,
1150 iterate,
1151 onMediaRuleError
1152 );
1153 } catch (err) {
1154 logInfo("Found a non-loaded link.");
1155 onMediaRuleError && onMediaRuleError();
1156 }
1157 } else if (rule.media) {
1158 var media = Array.from(rule.media);
1159 var isScreenOrAllOrQuery = media.some(function (m) {
1160 return (
1161 m.startsWith("screen") ||
1162 m.startsWith("all") ||
1163 m.startsWith("(")
1164 );
1165 });
1166 var isPrintOrSpeech = media.some(function (m) {
1167 return m.startsWith("print") || m.startsWith("speech");
1168 });
1169 if (isScreenOrAllOrQuery || !isPrintOrSpeech) {
1170 iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);
1171 }
1172 } else if (rule.conditionText) {
1173 if (CSS.supports(rule.conditionText)) {
1174 iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);
1175 }
1176 } else {
1177 logWarn("CSSRule type not supported", rule);
1178 }
1179 });
1180 }
1181 var shorthandVarDependantProperties = [
1182 "background",
1183 "border",
1184 "border-color",
1185 "border-bottom",
1186 "border-left",
1187 "border-right",
1188 "border-top",
1189 "outline",
1190 "outline-color"
1191 ];
1192 var shorthandVarDepPropRegexps = isSafari
1193 ? shorthandVarDependantProperties.map(function (prop) {
1194 var regexp = new RegExp("".concat(prop, ":\\s*(.*?)\\s*;"));
1195 return [prop, regexp];
1196 })
1197 : null;
1198 function iterateCSSDeclarations(style, iterate) {
1199 forEach(style, function (property) {
1200 var value = style.getPropertyValue(property).trim();
1201 if (!value) {
1202 return;
1203 }
1204 iterate(property, value);
1205 });
1206 var cssText = style.cssText;
1207 if (cssText.includes("var(")) {
1208 if (isSafari) {
1209 shorthandVarDepPropRegexps.forEach(function (_a) {
1210 var _b = __read(_a, 2),
1211 prop = _b[0],
1212 regexp = _b[1];
1213 var match = cssText.match(regexp);
1214 if (match && match[1]) {
1215 var val = match[1].trim();
1216 iterate(prop, val);
1217 }
1218 });
1219 } else {
1220 shorthandVarDependantProperties.forEach(function (prop) {
1221 var val = style.getPropertyValue(prop);
1222 if (val && val.includes("var(")) {
1223 iterate(prop, val);
1224 }
1225 });
1226 }
1227 }
1228 }
1229 var cssURLRegex = /url\((('.*?')|(".*?")|([^\)]*?))\)/g;
1230 var cssImportRegex =
1231 /@import\s*(url\()?(('.+?')|(".+?")|([^\)]*?))\)? ?(screen)?;?/gi;
1232 function getCSSURLValue(cssURL) {
1233 return cssURL
1234 .trim()
1235 .replace(/[\n\r\\]+/g, "")
1236 .replace(/^url\((.*)\)$/, "$1")
1237 .trim()
1238 .replace(/^"(.*)"$/, "$1")
1239 .replace(/^'(.*)'$/, "$1")
1240 .replace(/(?:\\(.))/g, "$1");
1241 }
1242 function getCSSBaseBath(url) {
1243 var cssURL = parseURL(url);
1244 return ""
1245 .concat(cssURL.origin)
1246 .concat(
1247 cssURL.pathname
1248 .replace(/\?.*$/, "")
1249 .replace(/(\/)([^\/]+)$/i, "$1")
1250 );
1251 }
1252 function replaceCSSRelativeURLsWithAbsolute($css, cssBasePath) {
1253 return $css.replace(cssURLRegex, function (match) {
1254 var pathValue = getCSSURLValue(match);
1255 try {
1256 return "url('".concat(
1257 getAbsoluteURL(cssBasePath, pathValue),
1258 "')"
1259 );
1260 } catch (err) {
1261 return match;
1262 }
1263 });
1264 }
1265 var cssCommentsRegex = /\/\*[\s\S]*?\*\//g;
1266 function removeCSSComments($css) {
1267 return $css.replace(cssCommentsRegex, "");
1268 }
1269 var fontFaceRegex = /@font-face\s*{[^}]*}/g;
1270 function replaceCSSFontFace($css) {
1271 return $css.replace(fontFaceRegex, "");
1272 }
1273
1274 function evalMath(expression) {
1275 var rpnStack = [];
1276 var workingStack = [];
1277 var lastToken;
1278 for (var i = 0, len = expression.length; i < len; i++) {
1279 var token = expression[i];
1280 if (!token || token === " ") {
1281 continue;
1282 }
1283 if (operators.has(token)) {
1284 var op = operators.get(token);
1285 while (workingStack.length) {
1286 var currentOp = operators.get(workingStack[0]);
1287 if (!currentOp) {
1288 break;
1289 }
1290 if (op.lessOrEqualThan(currentOp)) {
1291 rpnStack.push(workingStack.shift());
1292 } else {
1293 break;
1294 }
1295 }
1296 workingStack.unshift(token);
1297 } else if (!lastToken || operators.has(lastToken)) {
1298 rpnStack.push(token);
1299 } else {
1300 rpnStack[rpnStack.length - 1] += token;
1301 }
1302 lastToken = token;
1303 }
1304 rpnStack.push.apply(
1305 rpnStack,
1306 __spreadArray([], __read(workingStack), false)
1307 );
1308 var stack = [];
1309 for (var i = 0, len = rpnStack.length; i < len; i++) {
1310 var op = operators.get(rpnStack[i]);
1311 if (op) {
1312 var args = stack.splice(0, 2);
1313 stack.push(op.exec(args[1], args[0]));
1314 } else {
1315 stack.unshift(parseFloat(rpnStack[i]));
1316 }
1317 }
1318 return stack[0];
1319 }
1320 var Operator = (function () {
1321 function Operator(precedence, method) {
1322 this.precendce = precedence;
1323 this.execMethod = method;
1324 }
1325 Operator.prototype.exec = function (left, right) {
1326 return this.execMethod(left, right);
1327 };
1328 Operator.prototype.lessOrEqualThan = function (op) {
1329 return this.precendce <= op.precendce;
1330 };
1331 return Operator;
1332 })();
1333 var operators = new Map([
1334 [
1335 "+",
1336 new Operator(1, function (left, right) {
1337 return left + right;
1338 })
1339 ],
1340 [
1341 "-",
1342 new Operator(1, function (left, right) {
1343 return left - right;
1344 })
1345 ],
1346 [
1347 "*",
1348 new Operator(2, function (left, right) {
1349 return left * right;
1350 })
1351 ],
1352 [
1353 "/",
1354 new Operator(2, function (left, right) {
1355 return left / right;
1356 })
1357 ]
1358 ]);
1359
1360 function getMatches(regex, input, group) {
1361 if (group === void 0) {
1362 group = 0;
1363 }
1364 var matches = [];
1365 var m;
1366 while ((m = regex.exec(input))) {
1367 matches.push(m[group]);
1368 }
1369 return matches;
1370 }
1371 function formatCSS(text) {
1372 function trimLeft(text) {
1373 return text.replace(/^\s+/, "");
1374 }
1375 function getIndent(depth) {
1376 if (depth === 0) {
1377 return "";
1378 }
1379 return " ".repeat(4 * depth);
1380 }
1381 if (text.length < 50000) {
1382 var emptyRuleRegexp = /[^{}]+{\s*}/;
1383 while (emptyRuleRegexp.test(text)) {
1384 text = text.replace(emptyRuleRegexp, "");
1385 }
1386 }
1387 var css = text
1388 .replace(/\s{2,}/g, " ")
1389 .replace(/\{/g, "{\n")
1390 .replace(/\}/g, "\n}\n")
1391 .replace(/\;(?![^\(|\"]*(\)|\"))/g, ";\n")
1392 .replace(/\,(?![^\(|\"]*(\)|\"))/g, ",\n")
1393 .replace(/\n\s*\n/g, "\n")
1394 .split("\n");
1395 var depth = 0;
1396 var formatted = [];
1397 for (var x = 0, len = css.length; x < len; x++) {
1398 var line = "".concat(css[x], "\n");
1399 if (line.includes("{")) {
1400 formatted.push(getIndent(depth++) + trimLeft(line));
1401 } else if (line.includes("}")) {
1402 formatted.push(getIndent(--depth) + trimLeft(line));
1403 } else {
1404 formatted.push(getIndent(depth) + trimLeft(line));
1405 }
1406 }
1407 return formatted.join("").trim();
1408 }
1409 function getParenthesesRange(input, searchStartIndex) {
1410 if (searchStartIndex === void 0) {
1411 searchStartIndex = 0;
1412 }
1413 var length = input.length;
1414 var depth = 0;
1415 var firstOpenIndex = -1;
1416 for (var i = searchStartIndex; i < length; i++) {
1417 if (depth === 0) {
1418 var openIndex = input.indexOf("(", i);
1419 if (openIndex < 0) {
1420 break;
1421 }
1422 firstOpenIndex = openIndex;
1423 depth++;
1424 i = openIndex;
1425 } else {
1426 var closingIndex = input.indexOf(")", i);
1427 if (closingIndex < 0) {
1428 break;
1429 }
1430 var openIndex = input.indexOf("(", i);
1431 if (openIndex < 0 || closingIndex < openIndex) {
1432 depth--;
1433 if (depth === 0) {
1434 return {start: firstOpenIndex, end: closingIndex + 1};
1435 }
1436 i = closingIndex;
1437 } else {
1438 depth++;
1439 i = openIndex;
1440 }
1441 }
1442 }
1443 return null;
1444 }
1445
1446 var hslaParseCache = new Map();
1447 var rgbaParseCache = new Map();
1448 function parseColorWithCache($color) {
1449 $color = $color.trim();
1450 if (rgbaParseCache.has($color)) {
1451 return rgbaParseCache.get($color);
1452 }
1453 if ($color.includes("calc(")) {
1454 $color = lowerCalcExpression($color);
1455 }
1456 var color = parse($color);
1457 color && rgbaParseCache.set($color, color);
1458 return color;
1459 }
1460 function parseToHSLWithCache(color) {
1461 if (hslaParseCache.has(color)) {
1462 return hslaParseCache.get(color);
1463 }
1464 var rgb = parseColorWithCache(color);
1465 if (!rgb) {
1466 return null;
1467 }
1468 var hsl = rgbToHSL(rgb);
1469 hslaParseCache.set(color, hsl);
1470 return hsl;
1471 }
1472 function clearColorCache() {
1473 hslaParseCache.clear();
1474 rgbaParseCache.clear();
1475 }
1476 function hslToRGB(_a) {
1477 var h = _a.h,
1478 s = _a.s,
1479 l = _a.l,
1480 _b = _a.a,
1481 a = _b === void 0 ? 1 : _b;
1482 if (s === 0) {
1483 var _c = __read(
1484 [l, l, l].map(function (x) {
1485 return Math.round(x * 255);
1486 }),
1487 3
1488 ),
1489 r_1 = _c[0],
1490 b_1 = _c[1],
1491 g_1 = _c[2];
1492 return {r: r_1, g: g_1, b: b_1, a: a};
1493 }
1494 var c = (1 - Math.abs(2 * l - 1)) * s;
1495 var x = c * (1 - Math.abs(((h / 60) % 2) - 1));
1496 var m = l - c / 2;
1497 var _d = __read(
1498 (h < 60
1499 ? [c, x, 0]
1500 : h < 120
1501 ? [x, c, 0]
1502 : h < 180
1503 ? [0, c, x]
1504 : h < 240
1505 ? [0, x, c]
1506 : h < 300
1507 ? [x, 0, c]
1508 : [c, 0, x]
1509 ).map(function (n) {
1510 return Math.round((n + m) * 255);
1511 }),
1512 3
1513 ),
1514 r = _d[0],
1515 g = _d[1],
1516 b = _d[2];
1517 return {r: r, g: g, b: b, a: a};
1518 }
1519 function rgbToHSL(_a) {
1520 var r255 = _a.r,
1521 g255 = _a.g,
1522 b255 = _a.b,
1523 _b = _a.a,
1524 a = _b === void 0 ? 1 : _b;
1525 var r = r255 / 255;
1526 var g = g255 / 255;
1527 var b = b255 / 255;
1528 var max = Math.max(r, g, b);
1529 var min = Math.min(r, g, b);
1530 var c = max - min;
1531 var l = (max + min) / 2;
1532 if (c === 0) {
1533 return {h: 0, s: 0, l: l, a: a};
1534 }
1535 var h =
1536 (max === r
1537 ? ((g - b) / c) % 6
1538 : max === g
1539 ? (b - r) / c + 2
1540 : (r - g) / c + 4) * 60;
1541 if (h < 0) {
1542 h += 360;
1543 }
1544 var s = c / (1 - Math.abs(2 * l - 1));
1545 return {h: h, s: s, l: l, a: a};
1546 }
1547 function toFixed(n, digits) {
1548 if (digits === void 0) {
1549 digits = 0;
1550 }
1551 var fixed = n.toFixed(digits);
1552 if (digits === 0) {
1553 return fixed;
1554 }
1555 var dot = fixed.indexOf(".");
1556 if (dot >= 0) {
1557 var zerosMatch = fixed.match(/0+$/);
1558 if (zerosMatch) {
1559 if (zerosMatch.index === dot + 1) {
1560 return fixed.substring(0, dot);
1561 }
1562 return fixed.substring(0, zerosMatch.index);
1563 }
1564 }
1565 return fixed;
1566 }
1567 function rgbToString(rgb) {
1568 var r = rgb.r,
1569 g = rgb.g,
1570 b = rgb.b,
1571 a = rgb.a;
1572 if (a != null && a < 1) {
1573 return "rgba("
1574 .concat(toFixed(r), ", ")
1575 .concat(toFixed(g), ", ")
1576 .concat(toFixed(b), ", ")
1577 .concat(toFixed(a, 2), ")");
1578 }
1579 return "rgb("
1580 .concat(toFixed(r), ", ")
1581 .concat(toFixed(g), ", ")
1582 .concat(toFixed(b), ")");
1583 }
1584 function rgbToHexString(_a) {
1585 var r = _a.r,
1586 g = _a.g,
1587 b = _a.b,
1588 a = _a.a;
1589 return "#".concat(
1590 (a != null && a < 1 ? [r, g, b, Math.round(a * 255)] : [r, g, b])
1591 .map(function (x) {
1592 return "".concat(x < 16 ? "0" : "").concat(x.toString(16));
1593 })
1594 .join("")
1595 );
1596 }
1597 function hslToString(hsl) {
1598 var h = hsl.h,
1599 s = hsl.s,
1600 l = hsl.l,
1601 a = hsl.a;
1602 if (a != null && a < 1) {
1603 return "hsla("
1604 .concat(toFixed(h), ", ")
1605 .concat(toFixed(s * 100), "%, ")
1606 .concat(toFixed(l * 100), "%, ")
1607 .concat(toFixed(a, 2), ")");
1608 }
1609 return "hsl("
1610 .concat(toFixed(h), ", ")
1611 .concat(toFixed(s * 100), "%, ")
1612 .concat(toFixed(l * 100), "%)");
1613 }
1614 var rgbMatch = /^rgba?\([^\(\)]+\)$/;
1615 var hslMatch = /^hsla?\([^\(\)]+\)$/;
1616 var hexMatch = /^#[0-9a-f]+$/i;
1617 function parse($color) {
1618 var c = $color.trim().toLowerCase();
1619 if (c.match(rgbMatch)) {
1620 return parseRGB(c);
1621 }
1622 if (c.match(hslMatch)) {
1623 return parseHSL(c);
1624 }
1625 if (c.match(hexMatch)) {
1626 return parseHex(c);
1627 }
1628 if (knownColors.has(c)) {
1629 return getColorByName(c);
1630 }
1631 if (systemColors.has(c)) {
1632 return getSystemColor(c);
1633 }
1634 if ($color === "transparent") {
1635 return {r: 0, g: 0, b: 0, a: 0};
1636 }
1637 return null;
1638 }
1639 function getNumbers($color) {
1640 var numbers = [];
1641 var prevPos = 0;
1642 var isMining = false;
1643 var startIndex = $color.indexOf("(");
1644 $color = $color.substring(startIndex + 1, $color.length - 1);
1645 for (var i = 0; i < $color.length; i++) {
1646 var c = $color[i];
1647 if ((c >= "0" && c <= "9") || c === "." || c === "+" || c === "-") {
1648 isMining = true;
1649 } else if (isMining && (c === " " || c === ",")) {
1650 numbers.push($color.substring(prevPos, i));
1651 isMining = false;
1652 prevPos = i + 1;
1653 } else if (!isMining) {
1654 prevPos = i + 1;
1655 }
1656 }
1657 if (isMining) {
1658 numbers.push($color.substring(prevPos, $color.length));
1659 }
1660 return numbers;
1661 }
1662 function getNumbersFromString(str, range, units) {
1663 var raw = getNumbers(str);
1664 var unitsList = Object.entries(units);
1665 var numbers = raw
1666 .map(function (r) {
1667 return r.trim();
1668 })
1669 .map(function (r, i) {
1670 var n;
1671 var unit = unitsList.find(function (_a) {
1672 var _b = __read(_a, 1),
1673 u = _b[0];
1674 return r.endsWith(u);
1675 });
1676 if (unit) {
1677 n =
1678 (parseFloat(r.substring(0, r.length - unit[0].length)) /
1679 unit[1]) *
1680 range[i];
1681 } else {
1682 n = parseFloat(r);
1683 }
1684 if (range[i] > 1) {
1685 return Math.round(n);
1686 }
1687 return n;
1688 });
1689 return numbers;
1690 }
1691 var rgbRange = [255, 255, 255, 1];
1692 var rgbUnits = {"%": 100};
1693 function parseRGB($rgb) {
1694 var _a = __read(getNumbersFromString($rgb, rgbRange, rgbUnits), 4),
1695 r = _a[0],
1696 g = _a[1],
1697 b = _a[2],
1698 _b = _a[3],
1699 a = _b === void 0 ? 1 : _b;
1700 return {r: r, g: g, b: b, a: a};
1701 }
1702 var hslRange = [360, 1, 1, 1];
1703 var hslUnits = {"%": 100, "deg": 360, "rad": 2 * Math.PI, "turn": 1};
1704 function parseHSL($hsl) {
1705 var _a = __read(getNumbersFromString($hsl, hslRange, hslUnits), 4),
1706 h = _a[0],
1707 s = _a[1],
1708 l = _a[2],
1709 _b = _a[3],
1710 a = _b === void 0 ? 1 : _b;
1711 return hslToRGB({h: h, s: s, l: l, a: a});
1712 }
1713 function parseHex($hex) {
1714 var h = $hex.substring(1);
1715 switch (h.length) {
1716 case 3:
1717 case 4: {
1718 var _a = __read(
1719 [0, 1, 2].map(function (i) {
1720 return parseInt("".concat(h[i]).concat(h[i]), 16);
1721 }),
1722 3
1723 ),
1724 r = _a[0],
1725 g = _a[1],
1726 b = _a[2];
1727 var a =
1728 h.length === 3
1729 ? 1
1730 : parseInt("".concat(h[3]).concat(h[3]), 16) / 255;
1731 return {r: r, g: g, b: b, a: a};
1732 }
1733 case 6:
1734 case 8: {
1735 var _b = __read(
1736 [0, 2, 4].map(function (i) {
1737 return parseInt(h.substring(i, i + 2), 16);
1738 }),
1739 3
1740 ),
1741 r = _b[0],
1742 g = _b[1],
1743 b = _b[2];
1744 var a =
1745 h.length === 6 ? 1 : parseInt(h.substring(6, 8), 16) / 255;
1746 return {r: r, g: g, b: b, a: a};
1747 }
1748 }
1749 return null;
1750 }
1751 function getColorByName($color) {
1752 var n = knownColors.get($color);
1753 return {
1754 r: (n >> 16) & 255,
1755 g: (n >> 8) & 255,
1756 b: (n >> 0) & 255,
1757 a: 1
1758 };
1759 }
1760 function getSystemColor($color) {
1761 var n = systemColors.get($color);
1762 return {
1763 r: (n >> 16) & 255,
1764 g: (n >> 8) & 255,
1765 b: (n >> 0) & 255,
1766 a: 1
1767 };
1768 }
1769 function lowerCalcExpression(color) {
1770 var searchIndex = 0;
1771 var replaceBetweenIndices = function (start, end, replacement) {
1772 color =
1773 color.substring(0, start) + replacement + color.substring(end);
1774 };
1775 while ((searchIndex = color.indexOf("calc(")) !== -1) {
1776 var range = getParenthesesRange(color, searchIndex);
1777 if (!range) {
1778 break;
1779 }
1780 var slice = color.slice(range.start + 1, range.end - 1);
1781 var includesPercentage = slice.includes("%");
1782 slice = slice.split("%").join("");
1783 var output = Math.round(evalMath(slice));
1784 replaceBetweenIndices(
1785 range.start - 4,
1786 range.end,
1787 output + (includesPercentage ? "%" : "")
1788 );
1789 }
1790 return color;
1791 }
1792 var knownColors = new Map(
1793 Object.entries({
1794 aliceblue: 0xf0f8ff,
1795 antiquewhite: 0xfaebd7,
1796 aqua: 0x00ffff,
1797 aquamarine: 0x7fffd4,
1798 azure: 0xf0ffff,
1799 beige: 0xf5f5dc,
1800 bisque: 0xffe4c4,
1801 black: 0x000000,
1802 blanchedalmond: 0xffebcd,
1803 blue: 0x0000ff,
1804 blueviolet: 0x8a2be2,
1805 brown: 0xa52a2a,
1806 burlywood: 0xdeb887,
1807 cadetblue: 0x5f9ea0,
1808 chartreuse: 0x7fff00,
1809 chocolate: 0xd2691e,
1810 coral: 0xff7f50,
1811 cornflowerblue: 0x6495ed,
1812 cornsilk: 0xfff8dc,
1813 crimson: 0xdc143c,
1814 cyan: 0x00ffff,
1815 darkblue: 0x00008b,
1816 darkcyan: 0x008b8b,
1817 darkgoldenrod: 0xb8860b,
1818 darkgray: 0xa9a9a9,
1819 darkgrey: 0xa9a9a9,
1820 darkgreen: 0x006400,
1821 darkkhaki: 0xbdb76b,
1822 darkmagenta: 0x8b008b,
1823 darkolivegreen: 0x556b2f,
1824 darkorange: 0xff8c00,
1825 darkorchid: 0x9932cc,
1826 darkred: 0x8b0000,
1827 darksalmon: 0xe9967a,
1828 darkseagreen: 0x8fbc8f,
1829 darkslateblue: 0x483d8b,
1830 darkslategray: 0x2f4f4f,
1831 darkslategrey: 0x2f4f4f,
1832 darkturquoise: 0x00ced1,
1833 darkviolet: 0x9400d3,
1834 deeppink: 0xff1493,
1835 deepskyblue: 0x00bfff,
1836 dimgray: 0x696969,
1837 dimgrey: 0x696969,
1838 dodgerblue: 0x1e90ff,
1839 firebrick: 0xb22222,
1840 floralwhite: 0xfffaf0,
1841 forestgreen: 0x228b22,
1842 fuchsia: 0xff00ff,
1843 gainsboro: 0xdcdcdc,
1844 ghostwhite: 0xf8f8ff,
1845 gold: 0xffd700,
1846 goldenrod: 0xdaa520,
1847 gray: 0x808080,
1848 grey: 0x808080,
1849 green: 0x008000,
1850 greenyellow: 0xadff2f,
1851 honeydew: 0xf0fff0,
1852 hotpink: 0xff69b4,
1853 indianred: 0xcd5c5c,
1854 indigo: 0x4b0082,
1855 ivory: 0xfffff0,
1856 khaki: 0xf0e68c,
1857 lavender: 0xe6e6fa,
1858 lavenderblush: 0xfff0f5,
1859 lawngreen: 0x7cfc00,
1860 lemonchiffon: 0xfffacd,
1861 lightblue: 0xadd8e6,
1862 lightcoral: 0xf08080,
1863 lightcyan: 0xe0ffff,
1864 lightgoldenrodyellow: 0xfafad2,
1865 lightgray: 0xd3d3d3,
1866 lightgrey: 0xd3d3d3,
1867 lightgreen: 0x90ee90,
1868 lightpink: 0xffb6c1,
1869 lightsalmon: 0xffa07a,
1870 lightseagreen: 0x20b2aa,
1871 lightskyblue: 0x87cefa,
1872 lightslategray: 0x778899,
1873 lightslategrey: 0x778899,
1874 lightsteelblue: 0xb0c4de,
1875 lightyellow: 0xffffe0,
1876 lime: 0x00ff00,
1877 limegreen: 0x32cd32,
1878 linen: 0xfaf0e6,
1879 magenta: 0xff00ff,
1880 maroon: 0x800000,
1881 mediumaquamarine: 0x66cdaa,
1882 mediumblue: 0x0000cd,
1883 mediumorchid: 0xba55d3,
1884 mediumpurple: 0x9370db,
1885 mediumseagreen: 0x3cb371,
1886 mediumslateblue: 0x7b68ee,
1887 mediumspringgreen: 0x00fa9a,
1888 mediumturquoise: 0x48d1cc,
1889 mediumvioletred: 0xc71585,
1890 midnightblue: 0x191970,
1891 mintcream: 0xf5fffa,
1892 mistyrose: 0xffe4e1,
1893 moccasin: 0xffe4b5,
1894 navajowhite: 0xffdead,
1895 navy: 0x000080,
1896 oldlace: 0xfdf5e6,
1897 olive: 0x808000,
1898 olivedrab: 0x6b8e23,
1899 orange: 0xffa500,
1900 orangered: 0xff4500,
1901 orchid: 0xda70d6,
1902 palegoldenrod: 0xeee8aa,
1903 palegreen: 0x98fb98,
1904 paleturquoise: 0xafeeee,
1905 palevioletred: 0xdb7093,
1906 papayawhip: 0xffefd5,
1907 peachpuff: 0xffdab9,
1908 peru: 0xcd853f,
1909 pink: 0xffc0cb,
1910 plum: 0xdda0dd,
1911 powderblue: 0xb0e0e6,
1912 purple: 0x800080,
1913 rebeccapurple: 0x663399,
1914 red: 0xff0000,
1915 rosybrown: 0xbc8f8f,
1916 royalblue: 0x4169e1,
1917 saddlebrown: 0x8b4513,
1918 salmon: 0xfa8072,
1919 sandybrown: 0xf4a460,
1920 seagreen: 0x2e8b57,
1921 seashell: 0xfff5ee,
1922 sienna: 0xa0522d,
1923 silver: 0xc0c0c0,
1924 skyblue: 0x87ceeb,
1925 slateblue: 0x6a5acd,
1926 slategray: 0x708090,
1927 slategrey: 0x708090,
1928 snow: 0xfffafa,
1929 springgreen: 0x00ff7f,
1930 steelblue: 0x4682b4,
1931 tan: 0xd2b48c,
1932 teal: 0x008080,
1933 thistle: 0xd8bfd8,
1934 tomato: 0xff6347,
1935 turquoise: 0x40e0d0,
1936 violet: 0xee82ee,
1937 wheat: 0xf5deb3,
1938 white: 0xffffff,
1939 whitesmoke: 0xf5f5f5,
1940 yellow: 0xffff00,
1941 yellowgreen: 0x9acd32
1942 })
1943 );
1944 var systemColors = new Map(
1945 Object.entries({
1946 "ActiveBorder": 0x3b99fc,
1947 "ActiveCaption": 0x000000,
1948 "AppWorkspace": 0xaaaaaa,
1949 "Background": 0x6363ce,
1950 "ButtonFace": 0xffffff,
1951 "ButtonHighlight": 0xe9e9e9,
1952 "ButtonShadow": 0x9fa09f,
1953 "ButtonText": 0x000000,
1954 "CaptionText": 0x000000,
1955 "GrayText": 0x7f7f7f,
1956 "Highlight": 0xb2d7ff,
1957 "HighlightText": 0x000000,
1958 "InactiveBorder": 0xffffff,
1959 "InactiveCaption": 0xffffff,
1960 "InactiveCaptionText": 0x000000,
1961 "InfoBackground": 0xfbfcc5,
1962 "InfoText": 0x000000,
1963 "Menu": 0xf6f6f6,
1964 "MenuText": 0xffffff,
1965 "Scrollbar": 0xaaaaaa,
1966 "ThreeDDarkShadow": 0x000000,
1967 "ThreeDFace": 0xc0c0c0,
1968 "ThreeDHighlight": 0xffffff,
1969 "ThreeDLightShadow": 0xffffff,
1970 "ThreeDShadow": 0x000000,
1971 "Window": 0xececec,
1972 "WindowFrame": 0xaaaaaa,
1973 "WindowText": 0x000000,
1974 "-webkit-focus-ring-color": 0xe59700
1975 }).map(function (_a) {
1976 var _b = __read(_a, 2),
1977 key = _b[0],
1978 value = _b[1];
1979 return [key.toLowerCase(), value];
1980 })
1981 );
1982 function getSRGBLightness(r, g, b) {
1983 return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
1984 }
1985
1986 function scale(x, inLow, inHigh, outLow, outHigh) {
1987 return ((x - inLow) * (outHigh - outLow)) / (inHigh - inLow) + outLow;
1988 }
1989 function clamp(x, min, max) {
1990 return Math.min(max, Math.max(min, x));
1991 }
1992 function multiplyMatrices(m1, m2) {
1993 var result = [];
1994 for (var i = 0, len = m1.length; i < len; i++) {
1995 result[i] = [];
1996 for (var j = 0, len2 = m2[0].length; j < len2; j++) {
1997 var sum = 0;
1998 for (var k = 0, len3 = m1[0].length; k < len3; k++) {
1999 sum += m1[i][k] * m2[k][j];
2000 }
2001 result[i][j] = sum;
2002 }
2003 }
2004 return result;
2005 }
2006
2007 function createFilterMatrix(config) {
2008 var m = Matrix.identity();
2009 if (config.sepia !== 0) {
2010 m = multiplyMatrices(m, Matrix.sepia(config.sepia / 100));
2011 }
2012 if (config.grayscale !== 0) {
2013 m = multiplyMatrices(m, Matrix.grayscale(config.grayscale / 100));
2014 }
2015 if (config.contrast !== 100) {
2016 m = multiplyMatrices(m, Matrix.contrast(config.contrast / 100));
2017 }
2018 if (config.brightness !== 100) {
2019 m = multiplyMatrices(m, Matrix.brightness(config.brightness / 100));
2020 }
2021 if (config.mode === 1) {
2022 m = multiplyMatrices(m, Matrix.invertNHue());
2023 }
2024 return m;
2025 }
2026 function applyColorMatrix(_a, matrix) {
2027 var _b = __read(_a, 3),
2028 r = _b[0],
2029 g = _b[1],
2030 b = _b[2];
2031 var rgb = [[r / 255], [g / 255], [b / 255], [1], [1]];
2032 var result = multiplyMatrices(matrix, rgb);
2033 return [0, 1, 2].map(function (i) {
2034 return clamp(Math.round(result[i][0] * 255), 0, 255);
2035 });
2036 }
2037 var Matrix = {
2038 identity: function () {
2039 return [
2040 [1, 0, 0, 0, 0],
2041 [0, 1, 0, 0, 0],
2042 [0, 0, 1, 0, 0],
2043 [0, 0, 0, 1, 0],
2044 [0, 0, 0, 0, 1]
2045 ];
2046 },
2047 invertNHue: function () {
2048 return [
2049 [0.333, -0.667, -0.667, 0, 1],
2050 [-0.667, 0.333, -0.667, 0, 1],
2051 [-0.667, -0.667, 0.333, 0, 1],
2052 [0, 0, 0, 1, 0],
2053 [0, 0, 0, 0, 1]
2054 ];
2055 },
2056 brightness: function (v) {
2057 return [
2058 [v, 0, 0, 0, 0],
2059 [0, v, 0, 0, 0],
2060 [0, 0, v, 0, 0],
2061 [0, 0, 0, 1, 0],
2062 [0, 0, 0, 0, 1]
2063 ];
2064 },
2065 contrast: function (v) {
2066 var t = (1 - v) / 2;
2067 return [
2068 [v, 0, 0, 0, t],
2069 [0, v, 0, 0, t],
2070 [0, 0, v, 0, t],
2071 [0, 0, 0, 1, 0],
2072 [0, 0, 0, 0, 1]
2073 ];
2074 },
2075 sepia: function (v) {
2076 return [
2077 [
2078 0.393 + 0.607 * (1 - v),
2079 0.769 - 0.769 * (1 - v),
2080 0.189 - 0.189 * (1 - v),
2081 0,
2082 0
2083 ],
2084 [
2085 0.349 - 0.349 * (1 - v),
2086 0.686 + 0.314 * (1 - v),
2087 0.168 - 0.168 * (1 - v),
2088 0,
2089 0
2090 ],
2091 [
2092 0.272 - 0.272 * (1 - v),
2093 0.534 - 0.534 * (1 - v),
2094 0.131 + 0.869 * (1 - v),
2095 0,
2096 0
2097 ],
2098 [0, 0, 0, 1, 0],
2099 [0, 0, 0, 0, 1]
2100 ];
2101 },
2102 grayscale: function (v) {
2103 return [
2104 [
2105 0.2126 + 0.7874 * (1 - v),
2106 0.7152 - 0.7152 * (1 - v),
2107 0.0722 - 0.0722 * (1 - v),
2108 0,
2109 0
2110 ],
2111 [
2112 0.2126 - 0.2126 * (1 - v),
2113 0.7152 + 0.2848 * (1 - v),
2114 0.0722 - 0.0722 * (1 - v),
2115 0,
2116 0
2117 ],
2118 [
2119 0.2126 - 0.2126 * (1 - v),
2120 0.7152 - 0.7152 * (1 - v),
2121 0.0722 + 0.9278 * (1 - v),
2122 0,
2123 0
2124 ],
2125 [0, 0, 0, 1, 0],
2126 [0, 0, 0, 0, 1]
2127 ];
2128 }
2129 };
2130
2131 function getBgPole(theme) {
2132 var isDarkScheme = theme.mode === 1;
2133 var prop = isDarkScheme
2134 ? "darkSchemeBackgroundColor"
2135 : "lightSchemeBackgroundColor";
2136 return theme[prop];
2137 }
2138 function getFgPole(theme) {
2139 var isDarkScheme = theme.mode === 1;
2140 var prop = isDarkScheme
2141 ? "darkSchemeTextColor"
2142 : "lightSchemeTextColor";
2143 return theme[prop];
2144 }
2145 var colorModificationCache = new Map();
2146 function clearColorModificationCache() {
2147 colorModificationCache.clear();
2148 }
2149 var rgbCacheKeys = ["r", "g", "b", "a"];
2150 var themeCacheKeys$1 = [
2151 "mode",
2152 "brightness",
2153 "contrast",
2154 "grayscale",
2155 "sepia",
2156 "darkSchemeBackgroundColor",
2157 "darkSchemeTextColor",
2158 "lightSchemeBackgroundColor",
2159 "lightSchemeTextColor"
2160 ];
2161 function getCacheId(rgb, theme) {
2162 var resultId = "";
2163 rgbCacheKeys.forEach(function (key) {
2164 resultId += "".concat(rgb[key], ";");
2165 });
2166 themeCacheKeys$1.forEach(function (key) {
2167 resultId += "".concat(theme[key], ";");
2168 });
2169 return resultId;
2170 }
2171 function modifyColorWithCache(
2172 rgb,
2173 theme,
2174 modifyHSL,
2175 poleColor,
2176 anotherPoleColor
2177 ) {
2178 var fnCache;
2179 if (colorModificationCache.has(modifyHSL)) {
2180 fnCache = colorModificationCache.get(modifyHSL);
2181 } else {
2182 fnCache = new Map();
2183 colorModificationCache.set(modifyHSL, fnCache);
2184 }
2185 var id = getCacheId(rgb, theme);
2186 if (fnCache.has(id)) {
2187 return fnCache.get(id);
2188 }
2189 var hsl = rgbToHSL(rgb);
2190 var pole = poleColor == null ? null : parseToHSLWithCache(poleColor);
2191 var anotherPole =
2192 anotherPoleColor == null
2193 ? null
2194 : parseToHSLWithCache(anotherPoleColor);
2195 var modified = modifyHSL(hsl, pole, anotherPole);
2196 var _a = hslToRGB(modified),
2197 r = _a.r,
2198 g = _a.g,
2199 b = _a.b,
2200 a = _a.a;
2201 var matrix = createFilterMatrix(theme);
2202 var _b = __read(applyColorMatrix([r, g, b], matrix), 3),
2203 rf = _b[0],
2204 gf = _b[1],
2205 bf = _b[2];
2206 var color =
2207 a === 1
2208 ? rgbToHexString({r: rf, g: gf, b: bf})
2209 : rgbToString({r: rf, g: gf, b: bf, a: a});
2210 fnCache.set(id, color);
2211 return color;
2212 }
2213 function noopHSL(hsl) {
2214 return hsl;
2215 }
2216 function modifyColor(rgb, theme) {
2217 return modifyColorWithCache(rgb, theme, noopHSL);
2218 }
2219 function modifyLightSchemeColor(rgb, theme) {
2220 var poleBg = getBgPole(theme);
2221 var poleFg = getFgPole(theme);
2222 return modifyColorWithCache(
2223 rgb,
2224 theme,
2225 modifyLightModeHSL,
2226 poleFg,
2227 poleBg
2228 );
2229 }
2230 function modifyLightModeHSL(_a, poleFg, poleBg) {
2231 var h = _a.h,
2232 s = _a.s,
2233 l = _a.l,
2234 a = _a.a;
2235 var isDark = l < 0.5;
2236 var isNeutral;
2237 if (isDark) {
2238 isNeutral = l < 0.2 || s < 0.12;
2239 } else {
2240 var isBlue = h > 200 && h < 280;
2241 isNeutral = s < 0.24 || (l > 0.8 && isBlue);
2242 }
2243 var hx = h;
2244 var sx = l;
2245 if (isNeutral) {
2246 if (isDark) {
2247 hx = poleFg.h;
2248 sx = poleFg.s;
2249 } else {
2250 hx = poleBg.h;
2251 sx = poleBg.s;
2252 }
2253 }
2254 var lx = scale(l, 0, 1, poleFg.l, poleBg.l);
2255 return {h: hx, s: sx, l: lx, a: a};
2256 }
2257 var MAX_BG_LIGHTNESS = 0.4;
2258 function modifyBgHSL(_a, pole) {
2259 var h = _a.h,
2260 s = _a.s,
2261 l = _a.l,
2262 a = _a.a;
2263 var isDark = l < 0.5;
2264 var isBlue = h > 200 && h < 280;
2265 var isNeutral = s < 0.12 || (l > 0.8 && isBlue);
2266 if (isDark) {
2267 var lx_1 = scale(l, 0, 0.5, 0, MAX_BG_LIGHTNESS);
2268 if (isNeutral) {
2269 var hx_1 = pole.h;
2270 var sx = pole.s;
2271 return {h: hx_1, s: sx, l: lx_1, a: a};
2272 }
2273 return {h: h, s: s, l: lx_1, a: a};
2274 }
2275 var lx = scale(l, 0.5, 1, MAX_BG_LIGHTNESS, pole.l);
2276 if (isNeutral) {
2277 var hx_2 = pole.h;
2278 var sx = pole.s;
2279 return {h: hx_2, s: sx, l: lx, a: a};
2280 }
2281 var hx = h;
2282 var isYellow = h > 60 && h < 180;
2283 if (isYellow) {
2284 var isCloserToGreen = h > 120;
2285 if (isCloserToGreen) {
2286 hx = scale(h, 120, 180, 135, 180);
2287 } else {
2288 hx = scale(h, 60, 120, 60, 105);
2289 }
2290 }
2291 if (hx > 40 && hx < 80) {
2292 lx *= 0.75;
2293 }
2294 return {h: hx, s: s, l: lx, a: a};
2295 }
2296 function modifyBackgroundColor(rgb, theme) {
2297 if (theme.mode === 0) {
2298 return modifyLightSchemeColor(rgb, theme);
2299 }
2300 var pole = getBgPole(theme);
2301 return modifyColorWithCache(
2302 rgb,
2303 __assign(__assign({}, theme), {mode: 0}),
2304 modifyBgHSL,
2305 pole
2306 );
2307 }
2308 var MIN_FG_LIGHTNESS = 0.55;
2309 function modifyBlueFgHue(hue) {
2310 return scale(hue, 205, 245, 205, 220);
2311 }
2312 function modifyFgHSL(_a, pole) {
2313 var h = _a.h,
2314 s = _a.s,
2315 l = _a.l,
2316 a = _a.a;
2317 var isLight = l > 0.5;
2318 var isNeutral = l < 0.2 || s < 0.24;
2319 var isBlue = !isNeutral && h > 205 && h < 245;
2320 if (isLight) {
2321 var lx_2 = scale(l, 0.5, 1, MIN_FG_LIGHTNESS, pole.l);
2322 if (isNeutral) {
2323 var hx_3 = pole.h;
2324 var sx = pole.s;
2325 return {h: hx_3, s: sx, l: lx_2, a: a};
2326 }
2327 var hx_4 = h;
2328 if (isBlue) {
2329 hx_4 = modifyBlueFgHue(h);
2330 }
2331 return {h: hx_4, s: s, l: lx_2, a: a};
2332 }
2333 if (isNeutral) {
2334 var hx_5 = pole.h;
2335 var sx = pole.s;
2336 var lx_3 = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
2337 return {h: hx_5, s: sx, l: lx_3, a: a};
2338 }
2339 var hx = h;
2340 var lx;
2341 if (isBlue) {
2342 hx = modifyBlueFgHue(h);
2343 lx = scale(l, 0, 0.5, pole.l, Math.min(1, MIN_FG_LIGHTNESS + 0.05));
2344 } else {
2345 lx = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
2346 }
2347 return {h: hx, s: s, l: lx, a: a};
2348 }
2349 function modifyForegroundColor(rgb, theme) {
2350 if (theme.mode === 0) {
2351 return modifyLightSchemeColor(rgb, theme);
2352 }
2353 var pole = getFgPole(theme);
2354 return modifyColorWithCache(
2355 rgb,
2356 __assign(__assign({}, theme), {mode: 0}),
2357 modifyFgHSL,
2358 pole
2359 );
2360 }
2361 function modifyBorderHSL(_a, poleFg, poleBg) {
2362 var h = _a.h,
2363 s = _a.s,
2364 l = _a.l,
2365 a = _a.a;
2366 var isDark = l < 0.5;
2367 var isNeutral = l < 0.2 || s < 0.24;
2368 var hx = h;
2369 var sx = s;
2370 if (isNeutral) {
2371 if (isDark) {
2372 hx = poleFg.h;
2373 sx = poleFg.s;
2374 } else {
2375 hx = poleBg.h;
2376 sx = poleBg.s;
2377 }
2378 }
2379 var lx = scale(l, 0, 1, 0.5, 0.2);
2380 return {h: hx, s: sx, l: lx, a: a};
2381 }
2382 function modifyBorderColor(rgb, theme) {
2383 if (theme.mode === 0) {
2384 return modifyLightSchemeColor(rgb, theme);
2385 }
2386 var poleFg = getFgPole(theme);
2387 var poleBg = getBgPole(theme);
2388 return modifyColorWithCache(
2389 rgb,
2390 __assign(__assign({}, theme), {mode: 0}),
2391 modifyBorderHSL,
2392 poleFg,
2393 poleBg
2394 );
2395 }
2396 function modifyShadowColor(rgb, filter) {
2397 return modifyBackgroundColor(rgb, filter);
2398 }
2399 function modifyGradientColor(rgb, filter) {
2400 return modifyBackgroundColor(rgb, filter);
2401 }
2402
2403 function createTextStyle(config) {
2404 var lines = [];
2405 lines.push(
2406 '*:not(pre, pre *, code, .far, .fa, .glyphicon, [class*="vjs-"], .fab, .fa-github, .fas, .material-icons, .icofont, .typcn, mu, [class*="mu-"], .glyphicon, .icon) {'
2407 );
2408 if (config.useFont && config.fontFamily) {
2409 lines.push(
2410 " font-family: ".concat(config.fontFamily, " !important;")
2411 );
2412 }
2413 if (config.textStroke > 0) {
2414 lines.push(
2415 " -webkit-text-stroke: ".concat(
2416 config.textStroke,
2417 "px !important;"
2418 )
2419 );
2420 lines.push(
2421 " text-stroke: ".concat(config.textStroke, "px !important;")
2422 );
2423 }
2424 lines.push("}");
2425 return lines.join("\n");
2426 }
2427
2428 var FilterMode;
2429 (function (FilterMode) {
2430 FilterMode[(FilterMode["light"] = 0)] = "light";
2431 FilterMode[(FilterMode["dark"] = 1)] = "dark";
2432 })(FilterMode || (FilterMode = {}));
2433 function getCSSFilterValue(config) {
2434 var filters = [];
2435 if (config.mode === FilterMode.dark) {
2436 filters.push("invert(100%) hue-rotate(180deg)");
2437 }
2438 if (config.brightness !== 100) {
2439 filters.push("brightness(".concat(config.brightness, "%)"));
2440 }
2441 if (config.contrast !== 100) {
2442 filters.push("contrast(".concat(config.contrast, "%)"));
2443 }
2444 if (config.grayscale !== 0) {
2445 filters.push("grayscale(".concat(config.grayscale, "%)"));
2446 }
2447 if (config.sepia !== 0) {
2448 filters.push("sepia(".concat(config.sepia, "%)"));
2449 }
2450 if (filters.length === 0) {
2451 return null;
2452 }
2453 return filters.join(" ");
2454 }
2455
2456 function toSVGMatrix(matrix) {
2457 return matrix
2458 .slice(0, 4)
2459 .map(function (m) {
2460 return m
2461 .map(function (m) {
2462 return m.toFixed(3);
2463 })
2464 .join(" ");
2465 })
2466 .join(" ");
2467 }
2468 function getSVGFilterMatrixValue(config) {
2469 return toSVGMatrix(createFilterMatrix(config));
2470 }
2471
2472 var counter = 0;
2473 var resolvers$1 = new Map();
2474 var rejectors = new Map();
2475 function bgFetch(request) {
2476 return __awaiter(this, void 0, void 0, function () {
2477 return __generator(this, function (_a) {
2478 return [
2479 2,
2480 new Promise(function (resolve, reject) {
2481 var id = ++counter;
2482 resolvers$1.set(id, resolve);
2483 rejectors.set(id, reject);
2484 chrome.runtime.sendMessage({
2485 type: MessageType.CS_FETCH,
2486 data: request,
2487 id: id
2488 });
2489 })
2490 ];
2491 });
2492 });
2493 }
2494 chrome.runtime.onMessage.addListener(function (_a) {
2495 var type = _a.type,
2496 data = _a.data,
2497 error = _a.error,
2498 id = _a.id;
2499 if (type === MessageType.BG_FETCH_RESPONSE) {
2500 var resolve = resolvers$1.get(id);
2501 var reject = rejectors.get(id);
2502 resolvers$1.delete(id);
2503 rejectors.delete(id);
2504 if (error) {
2505 reject && reject(error);
2506 } else {
2507 resolve && resolve(data);
2508 }
2509 }
2510 });
2511
2512 var AsyncQueue = (function () {
2513 function AsyncQueue() {
2514 this.queue = [];
2515 this.timerId = null;
2516 this.frameDuration = 1000 / 60;
2517 }
2518 AsyncQueue.prototype.addToQueue = function (entry) {
2519 this.queue.push(entry);
2520 this.startQueue();
2521 };
2522 AsyncQueue.prototype.stopQueue = function () {
2523 if (this.timerId !== null) {
2524 cancelAnimationFrame(this.timerId);
2525 this.timerId = null;
2526 }
2527 this.queue = [];
2528 };
2529 AsyncQueue.prototype.startQueue = function () {
2530 var _this = this;
2531 if (this.timerId) {
2532 return;
2533 }
2534 this.timerId = requestAnimationFrame(function () {
2535 _this.timerId = null;
2536 var start = Date.now();
2537 var cb;
2538 while ((cb = _this.queue.shift())) {
2539 cb();
2540 if (Date.now() - start >= _this.frameDuration) {
2541 _this.startQueue();
2542 break;
2543 }
2544 }
2545 });
2546 };
2547 return AsyncQueue;
2548 })();
2549
2550 var imageManager = new AsyncQueue();
2551 function getImageDetails(url) {
2552 return __awaiter(this, void 0, void 0, function () {
2553 var _this = this;
2554 return __generator(this, function (_a) {
2555 return [
2556 2,
2557 new Promise(function (resolve, reject) {
2558 return __awaiter(_this, void 0, void 0, function () {
2559 var dataURL, error_1, image_1, error_2;
2560 return __generator(this, function (_a) {
2561 switch (_a.label) {
2562 case 0:
2563 if (!url.startsWith("data:"))
2564 return [3, 1];
2565 dataURL = url;
2566 return [3, 4];
2567 case 1:
2568 _a.trys.push([1, 3, , 4]);
2569 return [4, getImageDataURL(url)];
2570 case 2:
2571 dataURL = _a.sent();
2572 return [3, 4];
2573 case 3:
2574 error_1 = _a.sent();
2575 reject(error_1);
2576 return [2];
2577 case 4:
2578 _a.trys.push([4, 6, , 7]);
2579 return [4, urlToImage(dataURL)];
2580 case 5:
2581 image_1 = _a.sent();
2582 imageManager.addToQueue(function () {
2583 resolve(
2584 __assign(
2585 {
2586 src: url,
2587 dataURL: dataURL,
2588 width: image_1.naturalWidth,
2589 height: image_1.naturalHeight
2590 },
2591 analyzeImage(image_1)
2592 )
2593 );
2594 });
2595 return [3, 7];
2596 case 6:
2597 error_2 = _a.sent();
2598 reject(error_2);
2599 return [3, 7];
2600 case 7:
2601 return [2];
2602 }
2603 });
2604 });
2605 })
2606 ];
2607 });
2608 });
2609 }
2610 function getImageDataURL(url) {
2611 return __awaiter(this, void 0, void 0, function () {
2612 var parsedURL;
2613 return __generator(this, function (_a) {
2614 switch (_a.label) {
2615 case 0:
2616 parsedURL = new URL(url);
2617 if (!(parsedURL.origin === location.origin))
2618 return [3, 2];
2619 return [4, loadAsDataURL(url)];
2620 case 1:
2621 return [2, _a.sent()];
2622 case 2:
2623 return [
2624 4,
2625 bgFetch({url: url, responseType: "data-url"})
2626 ];
2627 case 3:
2628 return [2, _a.sent()];
2629 }
2630 });
2631 });
2632 }
2633 function urlToImage(url) {
2634 return __awaiter(this, void 0, void 0, function () {
2635 return __generator(this, function (_a) {
2636 return [
2637 2,
2638 new Promise(function (resolve, reject) {
2639 var image = new Image();
2640 image.onload = function () {
2641 return resolve(image);
2642 };
2643 image.onerror = function () {
2644 return reject("Unable to load image ".concat(url));
2645 };
2646 image.src = url;
2647 })
2648 ];
2649 });
2650 });
2651 }
2652 var MAX_ANALIZE_PIXELS_COUNT = 32 * 32;
2653 var canvas;
2654 var context;
2655 function createCanvas() {
2656 var maxWidth = MAX_ANALIZE_PIXELS_COUNT;
2657 var maxHeight = MAX_ANALIZE_PIXELS_COUNT;
2658 canvas = document.createElement("canvas");
2659 canvas.width = maxWidth;
2660 canvas.height = maxHeight;
2661 context = canvas.getContext("2d");
2662 context.imageSmoothingEnabled = false;
2663 }
2664 function removeCanvas() {
2665 canvas = null;
2666 context = null;
2667 }
2668 var MAX_IMAGE_SIZE = 5 * 1024 * 1024;
2669 function analyzeImage(image) {
2670 if (!canvas) {
2671 createCanvas();
2672 }
2673 var naturalWidth = image.naturalWidth,
2674 naturalHeight = image.naturalHeight;
2675 if (naturalHeight === 0 || naturalWidth === 0) {
2676 logWarn("logWarn(Image is empty ".concat(image.currentSrc, ")"));
2677 return null;
2678 }
2679 var size = naturalWidth * naturalHeight * 4;
2680 if (size > MAX_IMAGE_SIZE) {
2681 return {
2682 isDark: false,
2683 isLight: false,
2684 isTransparent: false,
2685 isLarge: false,
2686 isTooLarge: true
2687 };
2688 }
2689 var naturalPixelsCount = naturalWidth * naturalHeight;
2690 var k = Math.min(
2691 1,
2692 Math.sqrt(MAX_ANALIZE_PIXELS_COUNT / naturalPixelsCount)
2693 );
2694 var width = Math.ceil(naturalWidth * k);
2695 var height = Math.ceil(naturalHeight * k);
2696 context.clearRect(0, 0, width, height);
2697 context.drawImage(
2698 image,
2699 0,
2700 0,
2701 naturalWidth,
2702 naturalHeight,
2703 0,
2704 0,
2705 width,
2706 height
2707 );
2708 var imageData = context.getImageData(0, 0, width, height);
2709 var d = imageData.data;
2710 var TRANSPARENT_ALPHA_THRESHOLD = 0.05;
2711 var DARK_LIGHTNESS_THRESHOLD = 0.4;
2712 var LIGHT_LIGHTNESS_THRESHOLD = 0.7;
2713 var transparentPixelsCount = 0;
2714 var darkPixelsCount = 0;
2715 var lightPixelsCount = 0;
2716 var i, x, y;
2717 var r, g, b, a;
2718 var l;
2719 for (y = 0; y < height; y++) {
2720 for (x = 0; x < width; x++) {
2721 i = 4 * (y * width + x);
2722 r = d[i + 0];
2723 g = d[i + 1];
2724 b = d[i + 2];
2725 a = d[i + 3];
2726 if (a / 255 < TRANSPARENT_ALPHA_THRESHOLD) {
2727 transparentPixelsCount++;
2728 } else {
2729 l = getSRGBLightness(r, g, b);
2730 if (l < DARK_LIGHTNESS_THRESHOLD) {
2731 darkPixelsCount++;
2732 }
2733 if (l > LIGHT_LIGHTNESS_THRESHOLD) {
2734 lightPixelsCount++;
2735 }
2736 }
2737 }
2738 }
2739 var totalPixelsCount = width * height;
2740 var opaquePixelsCount = totalPixelsCount - transparentPixelsCount;
2741 var DARK_IMAGE_THRESHOLD = 0.7;
2742 var LIGHT_IMAGE_THRESHOLD = 0.7;
2743 var TRANSPARENT_IMAGE_THRESHOLD = 0.1;
2744 var LARGE_IMAGE_PIXELS_COUNT = 800 * 600;
2745 return {
2746 isDark: darkPixelsCount / opaquePixelsCount >= DARK_IMAGE_THRESHOLD,
2747 isLight:
2748 lightPixelsCount / opaquePixelsCount >= LIGHT_IMAGE_THRESHOLD,
2749 isTransparent:
2750 transparentPixelsCount / totalPixelsCount >=
2751 TRANSPARENT_IMAGE_THRESHOLD,
2752 isLarge: naturalPixelsCount >= LARGE_IMAGE_PIXELS_COUNT,
2753 isTooLarge: false
2754 };
2755 }
2756 function getFilteredImageDataURL(_a, theme) {
2757 var dataURL = _a.dataURL,
2758 width = _a.width,
2759 height = _a.height;
2760 var matrix = getSVGFilterMatrixValue(theme);
2761 var svg = [
2762 '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="'
2763 .concat(width, '" height="')
2764 .concat(height, '">'),
2765 "<defs>",
2766 '<filter id="darkreader-image-filter">',
2767 '<feColorMatrix type="matrix" values="'.concat(matrix, '" />'),
2768 "</filter>",
2769 "</defs>",
2770 '<image width="'
2771 .concat(width, '" height="')
2772 .concat(
2773 height,
2774 '" filter="url(#darkreader-image-filter)" xlink:href="'
2775 )
2776 .concat(dataURL, '" />'),
2777 "</svg>"
2778 ].join("");
2779 return "data:image/svg+xml;base64,".concat(btoa(svg));
2780 }
2781 function cleanImageProcessingCache() {
2782 imageManager && imageManager.stopQueue();
2783 removeCanvas();
2784 }
2785
2786 var gradientLength = "gradient".length;
2787 var conicGradient = "conic-";
2788 var conicGradientLength = conicGradient.length;
2789 var radialGradient = "radial-";
2790 var linearGradient = "linear-";
2791 function parseGradient(value) {
2792 var result = [];
2793 var index = 0;
2794 var startIndex = conicGradient.length;
2795 var _loop_1 = function () {
2796 var typeGradient;
2797 [linearGradient, radialGradient, conicGradient].find(function (
2798 possibleType
2799 ) {
2800 if (index - possibleType.length >= 0) {
2801 var possibleGradient = value.substring(
2802 index - possibleType.length,
2803 index
2804 );
2805 if (possibleGradient === possibleType) {
2806 if (
2807 value.slice(
2808 index - possibleType.length - 10,
2809 index - possibleType.length - 1
2810 ) === "repeating"
2811 ) {
2812 typeGradient = "repeating-".concat(
2813 possibleType,
2814 "gradient"
2815 );
2816 return true;
2817 }
2818 if (
2819 value.slice(
2820 index - possibleType.length - 8,
2821 index - possibleType.length - 1
2822 ) === "-webkit"
2823 ) {
2824 typeGradient = "-webkit-".concat(
2825 possibleType,
2826 "gradient"
2827 );
2828 return true;
2829 }
2830 typeGradient = "".concat(possibleType, "gradient");
2831 return true;
2832 }
2833 }
2834 });
2835 if (!typeGradient) {
2836 return "break";
2837 }
2838 var _a = getParenthesesRange(value, index + gradientLength),
2839 start = _a.start,
2840 end = _a.end;
2841 var match = value.substring(start + 1, end - 1);
2842 startIndex = end + 1 + conicGradientLength;
2843 result.push({
2844 typeGradient: typeGradient,
2845 match: match,
2846 offset: typeGradient.length + 2,
2847 index: index - typeGradient.length + gradientLength,
2848 hasComma: true
2849 });
2850 };
2851 while ((index = value.indexOf("gradient", startIndex)) !== -1) {
2852 var state_1 = _loop_1();
2853 if (state_1 === "break") break;
2854 }
2855 if (result.length) {
2856 result[result.length - 1].hasComma = false;
2857 }
2858 return result;
2859 }
2860
2861 function getPriority(ruleStyle, property) {
2862 return Boolean(ruleStyle && ruleStyle.getPropertyPriority(property));
2863 }
2864 function getModifiableCSSDeclaration(
2865 property,
2866 value,
2867 rule,
2868 variablesStore,
2869 ignoreImageSelectors,
2870 isCancelled
2871 ) {
2872 if (property.startsWith("--")) {
2873 var modifier = getVariableModifier(
2874 variablesStore,
2875 property,
2876 value,
2877 rule,
2878 ignoreImageSelectors,
2879 isCancelled
2880 );
2881 if (modifier) {
2882 return {
2883 property: property,
2884 value: modifier,
2885 important: getPriority(rule.style, property),
2886 sourceValue: value
2887 };
2888 }
2889 } else if (value.includes("var(")) {
2890 var modifier = getVariableDependantModifier(
2891 variablesStore,
2892 property,
2893 value
2894 );
2895 if (modifier) {
2896 return {
2897 property: property,
2898 value: modifier,
2899 important: getPriority(rule.style, property),
2900 sourceValue: value
2901 };
2902 }
2903 } else if (property === "color-scheme") {
2904 return null;
2905 } else if (
2906 (property.includes("color") &&
2907 property !== "-webkit-print-color-adjust") ||
2908 property === "fill" ||
2909 property === "stroke" ||
2910 property === "stop-color"
2911 ) {
2912 var modifier = getColorModifier(property, value, rule);
2913 if (modifier) {
2914 return {
2915 property: property,
2916 value: modifier,
2917 important: getPriority(rule.style, property),
2918 sourceValue: value
2919 };
2920 }
2921 } else if (
2922 property === "background-image" ||
2923 property === "list-style-image"
2924 ) {
2925 var modifier = getBgImageModifier(
2926 value,
2927 rule,
2928 ignoreImageSelectors,
2929 isCancelled
2930 );
2931 if (modifier) {
2932 return {
2933 property: property,
2934 value: modifier,
2935 important: getPriority(rule.style, property),
2936 sourceValue: value
2937 };
2938 }
2939 } else if (property.includes("shadow")) {
2940 var modifier = getShadowModifier(value);
2941 if (modifier) {
2942 return {
2943 property: property,
2944 value: modifier,
2945 important: getPriority(rule.style, property),
2946 sourceValue: value
2947 };
2948 }
2949 }
2950 return null;
2951 }
2952 function joinSelectors() {
2953 var selectors = [];
2954 for (var _i = 0; _i < arguments.length; _i++) {
2955 selectors[_i] = arguments[_i];
2956 }
2957 return selectors.filter(Boolean).join(", ");
2958 }
2959 function getModifiedUserAgentStyle(theme, isIFrame, styleSystemControls) {
2960 var lines = [];
2961 if (!isIFrame) {
2962 lines.push("html {");
2963 lines.push(
2964 " background-color: ".concat(
2965 modifyBackgroundColor({r: 255, g: 255, b: 255}, theme),
2966 " !important;"
2967 )
2968 );
2969 lines.push("}");
2970 }
2971 if (isCSSColorSchemePropSupported) {
2972 lines.push("html {");
2973 lines.push(
2974 " color-scheme: ".concat(
2975 theme.mode === 1 ? "dark" : "dark light",
2976 " !important;"
2977 )
2978 );
2979 lines.push("}");
2980 }
2981 var bgSelectors = joinSelectors(
2982 isIFrame ? "" : "html, body",
2983 styleSystemControls ? "input, textarea, select, button, dialog" : ""
2984 );
2985 if (bgSelectors) {
2986 lines.push("".concat(bgSelectors, " {"));
2987 lines.push(
2988 " background-color: ".concat(
2989 modifyBackgroundColor({r: 255, g: 255, b: 255}, theme),
2990 ";"
2991 )
2992 );
2993 lines.push("}");
2994 }
2995 lines.push(
2996 "".concat(
2997 joinSelectors(
2998 "html, body",
2999 styleSystemControls ? "input, textarea, select, button" : ""
3000 ),
3001 " {"
3002 )
3003 );
3004 lines.push(
3005 " border-color: ".concat(
3006 modifyBorderColor({r: 76, g: 76, b: 76}, theme),
3007 ";"
3008 )
3009 );
3010 lines.push(
3011 " color: ".concat(
3012 modifyForegroundColor({r: 0, g: 0, b: 0}, theme),
3013 ";"
3014 )
3015 );
3016 lines.push("}");
3017 lines.push("a {");
3018 lines.push(
3019 " color: ".concat(
3020 modifyForegroundColor({r: 0, g: 64, b: 255}, theme),
3021 ";"
3022 )
3023 );
3024 lines.push("}");
3025 lines.push("table {");
3026 lines.push(
3027 " border-color: ".concat(
3028 modifyBorderColor({r: 128, g: 128, b: 128}, theme),
3029 ";"
3030 )
3031 );
3032 lines.push("}");
3033 lines.push("::placeholder {");
3034 lines.push(
3035 " color: ".concat(
3036 modifyForegroundColor({r: 169, g: 169, b: 169}, theme),
3037 ";"
3038 )
3039 );
3040 lines.push("}");
3041 lines.push("input:-webkit-autofill,");
3042 lines.push("textarea:-webkit-autofill,");
3043 lines.push("select:-webkit-autofill {");
3044 lines.push(
3045 " background-color: ".concat(
3046 modifyBackgroundColor({r: 250, g: 255, b: 189}, theme),
3047 " !important;"
3048 )
3049 );
3050 lines.push(
3051 " color: ".concat(
3052 modifyForegroundColor({r: 0, g: 0, b: 0}, theme),
3053 " !important;"
3054 )
3055 );
3056 lines.push("}");
3057 if (theme.scrollbarColor) {
3058 lines.push(getModifiedScrollbarStyle(theme));
3059 }
3060 if (theme.selectionColor) {
3061 lines.push(getModifiedSelectionStyle(theme));
3062 }
3063 return lines.join("\n");
3064 }
3065 function getSelectionColor(theme) {
3066 var backgroundColorSelection;
3067 var foregroundColorSelection;
3068 if (theme.selectionColor === "auto") {
3069 backgroundColorSelection = modifyBackgroundColor(
3070 {r: 0, g: 96, b: 212},
3071 __assign(__assign({}, theme), {grayscale: 0})
3072 );
3073 foregroundColorSelection = modifyForegroundColor(
3074 {r: 255, g: 255, b: 255},
3075 __assign(__assign({}, theme), {grayscale: 0})
3076 );
3077 } else {
3078 var rgb = parseColorWithCache(theme.selectionColor);
3079 var hsl = rgbToHSL(rgb);
3080 backgroundColorSelection = theme.selectionColor;
3081 if (hsl.l < 0.5) {
3082 foregroundColorSelection = "#FFF";
3083 } else {
3084 foregroundColorSelection = "#000";
3085 }
3086 }
3087 return {
3088 backgroundColorSelection: backgroundColorSelection,
3089 foregroundColorSelection: foregroundColorSelection
3090 };
3091 }
3092 function getModifiedSelectionStyle(theme) {
3093 var lines = [];
3094 var modifiedSelectionColor = getSelectionColor(theme);
3095 var backgroundColorSelection =
3096 modifiedSelectionColor.backgroundColorSelection;
3097 var foregroundColorSelection =
3098 modifiedSelectionColor.foregroundColorSelection;
3099 ["::selection", "::-moz-selection"].forEach(function (selection) {
3100 lines.push("".concat(selection, " {"));
3101 lines.push(
3102 " background-color: ".concat(
3103 backgroundColorSelection,
3104 " !important;"
3105 )
3106 );
3107 lines.push(
3108 " color: ".concat(foregroundColorSelection, " !important;")
3109 );
3110 lines.push("}");
3111 });
3112 return lines.join("\n");
3113 }
3114 function getModifiedScrollbarStyle(theme) {
3115 var lines = [];
3116 var colorTrack;
3117 var colorIcons;
3118 var colorThumb;
3119 var colorThumbHover;
3120 var colorThumbActive;
3121 var colorCorner;
3122 if (theme.scrollbarColor === "auto") {
3123 colorTrack = modifyBackgroundColor({r: 241, g: 241, b: 241}, theme);
3124 colorIcons = modifyForegroundColor({r: 96, g: 96, b: 96}, theme);
3125 colorThumb = modifyBackgroundColor({r: 176, g: 176, b: 176}, theme);
3126 colorThumbHover = modifyBackgroundColor(
3127 {r: 144, g: 144, b: 144},
3128 theme
3129 );
3130 colorThumbActive = modifyBackgroundColor(
3131 {r: 96, g: 96, b: 96},
3132 theme
3133 );
3134 colorCorner = modifyBackgroundColor(
3135 {r: 255, g: 255, b: 255},
3136 theme
3137 );
3138 } else {
3139 var rgb = parseColorWithCache(theme.scrollbarColor);
3140 var hsl_1 = rgbToHSL(rgb);
3141 var isLight = hsl_1.l > 0.5;
3142 var lighten = function (lighter) {
3143 return __assign(__assign({}, hsl_1), {
3144 l: clamp(hsl_1.l + lighter, 0, 1)
3145 });
3146 };
3147 var darken = function (darker) {
3148 return __assign(__assign({}, hsl_1), {
3149 l: clamp(hsl_1.l - darker, 0, 1)
3150 });
3151 };
3152 colorTrack = hslToString(darken(0.4));
3153 colorIcons = hslToString(isLight ? darken(0.4) : lighten(0.4));
3154 colorThumb = hslToString(hsl_1);
3155 colorThumbHover = hslToString(lighten(0.1));
3156 colorThumbActive = hslToString(lighten(0.2));
3157 }
3158 lines.push("::-webkit-scrollbar {");
3159 lines.push(" background-color: ".concat(colorTrack, ";"));
3160 lines.push(" color: ".concat(colorIcons, ";"));
3161 lines.push("}");
3162 lines.push("::-webkit-scrollbar-thumb {");
3163 lines.push(" background-color: ".concat(colorThumb, ";"));
3164 lines.push("}");
3165 lines.push("::-webkit-scrollbar-thumb:hover {");
3166 lines.push(" background-color: ".concat(colorThumbHover, ";"));
3167 lines.push("}");
3168 lines.push("::-webkit-scrollbar-thumb:active {");
3169 lines.push(" background-color: ".concat(colorThumbActive, ";"));
3170 lines.push("}");
3171 lines.push("::-webkit-scrollbar-corner {");
3172 lines.push(" background-color: ".concat(colorCorner, ";"));
3173 lines.push("}");
3174 if (isFirefox) {
3175 lines.push("* {");
3176 lines.push(
3177 " scrollbar-color: "
3178 .concat(colorThumb, " ")
3179 .concat(colorTrack, ";")
3180 );
3181 lines.push("}");
3182 }
3183 return lines.join("\n");
3184 }
3185 function getModifiedFallbackStyle(filter, _a) {
3186 var strict = _a.strict;
3187 var lines = [];
3188 var isMicrosoft = ["microsoft.com", "docs.microsoft.com"].includes(
3189 location.hostname
3190 );
3191 lines.push(
3192 "html, body, ".concat(
3193 strict
3194 ? "body :not(iframe)".concat(
3195 isMicrosoft
3196 ? ':not(div[style^="position:absolute;top:0;left:-"]'
3197 : ""
3198 )
3199 : "body > :not(iframe)",
3200 " {"
3201 )
3202 );
3203 lines.push(
3204 " background-color: ".concat(
3205 modifyBackgroundColor({r: 255, g: 255, b: 255}, filter),
3206 " !important;"
3207 )
3208 );
3209 lines.push(
3210 " border-color: ".concat(
3211 modifyBorderColor({r: 64, g: 64, b: 64}, filter),
3212 " !important;"
3213 )
3214 );
3215 lines.push(
3216 " color: ".concat(
3217 modifyForegroundColor({r: 0, g: 0, b: 0}, filter),
3218 " !important;"
3219 )
3220 );
3221 lines.push("}");
3222 return lines.join("\n");
3223 }
3224 var unparsableColors = new Set([
3225 "inherit",
3226 "transparent",
3227 "initial",
3228 "currentcolor",
3229 "none",
3230 "unset"
3231 ]);
3232 function getColorModifier(prop, value, rule) {
3233 if (unparsableColors.has(value.toLowerCase())) {
3234 return value;
3235 }
3236 var rgb = parseColorWithCache(value);
3237 if (!rgb) {
3238 return null;
3239 }
3240 if (prop.includes("background")) {
3241 if (
3242 (rule.style.webkitMaskImage &&
3243 rule.style.webkitMaskImage !== "none") ||
3244 (rule.style.webkitMask &&
3245 !rule.style.webkitMask.startsWith("none")) ||
3246 (rule.style.mask && rule.style.mask !== "none") ||
3247 (rule.style.getPropertyValue("mask-image") &&
3248 rule.style.getPropertyValue("mask-image") !== "none")
3249 ) {
3250 return function (filter) {
3251 return modifyForegroundColor(rgb, filter);
3252 };
3253 }
3254 return function (filter) {
3255 return modifyBackgroundColor(rgb, filter);
3256 };
3257 }
3258 if (prop.includes("border") || prop.includes("outline")) {
3259 return function (filter) {
3260 return modifyBorderColor(rgb, filter);
3261 };
3262 }
3263 return function (filter) {
3264 return modifyForegroundColor(rgb, filter);
3265 };
3266 }
3267 var imageDetailsCache = new Map();
3268 var awaitingForImageLoading = new Map();
3269 function shouldIgnoreImage(selectorText, selectors) {
3270 if (!selectorText || selectors.length === 0) {
3271 return false;
3272 }
3273 if (
3274 selectors.some(function (s) {
3275 return s === "*";
3276 })
3277 ) {
3278 return true;
3279 }
3280 var ruleSelectors = selectorText.split(/,\s*/g);
3281 var _loop_1 = function (i) {
3282 var ignoredSelector = selectors[i];
3283 if (
3284 ruleSelectors.some(function (s) {
3285 return s === ignoredSelector;
3286 })
3287 ) {
3288 return {value: true};
3289 }
3290 };
3291 for (var i = 0; i < selectors.length; i++) {
3292 var state_1 = _loop_1(i);
3293 if (typeof state_1 === "object") return state_1.value;
3294 }
3295 return false;
3296 }
3297 function getBgImageModifier(
3298 value,
3299 rule,
3300 ignoreImageSelectors,
3301 isCancelled
3302 ) {
3303 var _this = this;
3304 try {
3305 var gradients = parseGradient(value);
3306 var urls = getMatches(cssURLRegex, value);
3307 if (urls.length === 0 && gradients.length === 0) {
3308 return value;
3309 }
3310 var getIndices = function (matches) {
3311 var index = 0;
3312 return matches.map(function (match) {
3313 var valueIndex = value.indexOf(match, index);
3314 index = valueIndex + match.length;
3315 return {match: match, index: valueIndex};
3316 });
3317 };
3318 var matches_1 = gradients
3319 .map(function (i) {
3320 return __assign({type: "gradient"}, i);
3321 })
3322 .concat(
3323 getIndices(urls).map(function (i) {
3324 return __assign({type: "url", offset: 0}, i);
3325 })
3326 )
3327 .sort(function (a, b) {
3328 return a.index > b.index ? 1 : -1;
3329 });
3330 var getGradientModifier_1 = function (gradient) {
3331 var typeGradient = gradient.typeGradient,
3332 match = gradient.match,
3333 hasComma = gradient.hasComma;
3334 var partsRegex =
3335 /([^\(\),]+(\([^\(\)]*(\([^\(\)]*\)*[^\(\)]*)?\))?([^\(\), ]|( (?!calc)))*),?/g;
3336 var colorStopRegex =
3337 /^(from|color-stop|to)\(([^\(\)]*?,\s*)?(.*?)\)$/;
3338 var parts = getMatches(partsRegex, match, 1).map(function (
3339 part
3340 ) {
3341 part = part.trim();
3342 var rgb = parseColorWithCache(part);
3343 if (rgb) {
3344 return function (filter) {
3345 return modifyGradientColor(rgb, filter);
3346 };
3347 }
3348 var space = part.lastIndexOf(" ");
3349 rgb = parseColorWithCache(part.substring(0, space));
3350 if (rgb) {
3351 return function (filter) {
3352 return ""
3353 .concat(modifyGradientColor(rgb, filter), " ")
3354 .concat(part.substring(space + 1));
3355 };
3356 }
3357 var colorStopMatch = part.match(colorStopRegex);
3358 if (colorStopMatch) {
3359 rgb = parseColorWithCache(colorStopMatch[3]);
3360 if (rgb) {
3361 return function (filter) {
3362 return ""
3363 .concat(colorStopMatch[1], "(")
3364 .concat(
3365 colorStopMatch[2]
3366 ? "".concat(colorStopMatch[2], ", ")
3367 : ""
3368 )
3369 .concat(
3370 modifyGradientColor(rgb, filter),
3371 ")"
3372 );
3373 };
3374 }
3375 }
3376 return function () {
3377 return part;
3378 };
3379 });
3380 return function (filter) {
3381 return ""
3382 .concat(typeGradient, "(")
3383 .concat(
3384 parts
3385 .map(function (modify) {
3386 return modify(filter);
3387 })
3388 .join(", "),
3389 ")"
3390 )
3391 .concat(hasComma ? ", " : "");
3392 };
3393 };
3394 var getURLModifier_1 = function (urlValue) {
3395 var _a;
3396 if (
3397 shouldIgnoreImage(rule.selectorText, ignoreImageSelectors)
3398 ) {
3399 return null;
3400 }
3401 var url = getCSSURLValue(urlValue);
3402 var isURLEmpty = url.length === 0;
3403 var parentStyleSheet = rule.parentStyleSheet;
3404 var baseURL =
3405 parentStyleSheet && parentStyleSheet.href
3406 ? getCSSBaseBath(parentStyleSheet.href)
3407 : ((_a = parentStyleSheet.ownerNode) === null ||
3408 _a === void 0
3409 ? void 0
3410 : _a.baseURI) || location.origin;
3411 url = getAbsoluteURL(baseURL, url);
3412 var absoluteValue = 'url("'.concat(url, '")');
3413 return function (filter) {
3414 return __awaiter(_this, void 0, void 0, function () {
3415 var imageDetails, awaiters_1, err_1, bgImageValue;
3416 return __generator(this, function (_a) {
3417 switch (_a.label) {
3418 case 0:
3419 if (isURLEmpty) {
3420 return [2, "url('')"];
3421 }
3422 if (!imageDetailsCache.has(url))
3423 return [3, 1];
3424 imageDetails = imageDetailsCache.get(url);
3425 return [3, 7];
3426 case 1:
3427 _a.trys.push([1, 6, , 7]);
3428 if (!awaitingForImageLoading.has(url))
3429 return [3, 3];
3430 awaiters_1 =
3431 awaitingForImageLoading.get(url);
3432 return [
3433 4,
3434 new Promise(function (resolve) {
3435 return awaiters_1.push(resolve);
3436 })
3437 ];
3438 case 2:
3439 imageDetails = _a.sent();
3440 if (!imageDetails) {
3441 return [2, null];
3442 }
3443 return [3, 5];
3444 case 3:
3445 awaitingForImageLoading.set(url, []);
3446 return [4, getImageDetails(url)];
3447 case 4:
3448 imageDetails = _a.sent();
3449 imageDetailsCache.set(url, imageDetails);
3450 awaitingForImageLoading
3451 .get(url)
3452 .forEach(function (resolve) {
3453 return resolve(imageDetails);
3454 });
3455 awaitingForImageLoading.delete(url);
3456 _a.label = 5;
3457 case 5:
3458 if (isCancelled()) {
3459 return [2, null];
3460 }
3461 return [3, 7];
3462 case 6:
3463 err_1 = _a.sent();
3464 logWarn(err_1);
3465 if (awaitingForImageLoading.has(url)) {
3466 awaitingForImageLoading
3467 .get(url)
3468 .forEach(function (resolve) {
3469 return resolve(null);
3470 });
3471 awaitingForImageLoading.delete(url);
3472 }
3473 return [2, absoluteValue];
3474 case 7:
3475 bgImageValue =
3476 getBgImageValue_1(
3477 imageDetails,
3478 filter
3479 ) || absoluteValue;
3480 return [2, bgImageValue];
3481 }
3482 });
3483 });
3484 };
3485 };
3486 var getBgImageValue_1 = function (imageDetails, filter) {
3487 var isDark = imageDetails.isDark,
3488 isLight = imageDetails.isLight,
3489 isTransparent = imageDetails.isTransparent,
3490 isLarge = imageDetails.isLarge,
3491 isTooLarge = imageDetails.isTooLarge,
3492 width = imageDetails.width;
3493 var result;
3494 if (isTooLarge) {
3495 result = 'url("'.concat(imageDetails.src, '")');
3496 } else if (
3497 isDark &&
3498 isTransparent &&
3499 filter.mode === 1 &&
3500 !isLarge &&
3501 width > 2
3502 ) {
3503 logInfo("Inverting dark image ".concat(imageDetails.src));
3504 var inverted = getFilteredImageDataURL(
3505 imageDetails,
3506 __assign(__assign({}, filter), {
3507 sepia: clamp(filter.sepia + 10, 0, 100)
3508 })
3509 );
3510 result = 'url("'.concat(inverted, '")');
3511 } else if (isLight && !isTransparent && filter.mode === 1) {
3512 if (isLarge) {
3513 result = "none";
3514 } else {
3515 logInfo(
3516 "Dimming light image ".concat(imageDetails.src)
3517 );
3518 var dimmed = getFilteredImageDataURL(
3519 imageDetails,
3520 filter
3521 );
3522 result = 'url("'.concat(dimmed, '")');
3523 }
3524 } else if (filter.mode === 0 && isLight && !isLarge) {
3525 logInfo(
3526 "Applying filter to image ".concat(imageDetails.src)
3527 );
3528 var filtered = getFilteredImageDataURL(
3529 imageDetails,
3530 __assign(__assign({}, filter), {
3531 brightness: clamp(filter.brightness - 10, 5, 200),
3532 sepia: clamp(filter.sepia + 10, 0, 100)
3533 })
3534 );
3535 result = 'url("'.concat(filtered, '")');
3536 } else {
3537 result = null;
3538 }
3539 return result;
3540 };
3541 var modifiers_1 = [];
3542 var matchIndex_1 = 0;
3543 var prevHasComma_1 = false;
3544 matches_1.forEach(function (_a, i) {
3545 var type = _a.type,
3546 match = _a.match,
3547 index = _a.index,
3548 typeGradient = _a.typeGradient,
3549 hasComma = _a.hasComma,
3550 offset = _a.offset;
3551 var matchStart = index;
3552 var prefixStart = matchIndex_1;
3553 var matchEnd = matchStart + match.length + offset;
3554 matchIndex_1 = matchEnd;
3555 if (prefixStart !== matchStart) {
3556 if (prevHasComma_1) {
3557 modifiers_1.push(function () {
3558 var betweenValue = value.substring(
3559 prefixStart,
3560 matchStart
3561 );
3562 if (betweenValue[0] === ",") {
3563 betweenValue = betweenValue.substring(1);
3564 }
3565 return betweenValue;
3566 });
3567 } else {
3568 modifiers_1.push(function () {
3569 return value.substring(prefixStart, matchStart);
3570 });
3571 }
3572 }
3573 prevHasComma_1 = hasComma || false;
3574 if (type === "url") {
3575 modifiers_1.push(getURLModifier_1(match));
3576 } else if (type === "gradient") {
3577 modifiers_1.push(
3578 getGradientModifier_1({
3579 match: match,
3580 index: index,
3581 typeGradient: typeGradient,
3582 hasComma: hasComma,
3583 offset: offset
3584 })
3585 );
3586 }
3587 if (i === matches_1.length - 1) {
3588 modifiers_1.push(function () {
3589 return value.substring(matchEnd);
3590 });
3591 }
3592 });
3593 return function (filter) {
3594 var results = modifiers_1
3595 .filter(Boolean)
3596 .map(function (modify) {
3597 return modify(filter);
3598 });
3599 if (
3600 results.some(function (r) {
3601 return r instanceof Promise;
3602 })
3603 ) {
3604 return Promise.all(results).then(function (asyncResults) {
3605 return asyncResults.filter(Boolean).join("");
3606 });
3607 }
3608 var combinedResult = results.join("");
3609 if (combinedResult.endsWith(", initial")) {
3610 return combinedResult.slice(0, -9);
3611 }
3612 return combinedResult;
3613 };
3614 } catch (err) {
3615 return null;
3616 }
3617 }
3618 function getShadowModifierWithInfo(value) {
3619 try {
3620 var index_1 = 0;
3621 var colorMatches_1 = getMatches(
3622 /(^|\s)(?!calc)([a-z]+\(.+?\)|#[0-9a-f]+|[a-z]+)(.*?(inset|outset)?($|,))/gi,
3623 value,
3624 2
3625 );
3626 var notParsed_1 = 0;
3627 var modifiers_2 = colorMatches_1.map(function (match, i) {
3628 var prefixIndex = index_1;
3629 var matchIndex = value.indexOf(match, index_1);
3630 var matchEnd = matchIndex + match.length;
3631 index_1 = matchEnd;
3632 var rgb = parseColorWithCache(match);
3633 if (!rgb) {
3634 notParsed_1++;
3635 return function () {
3636 return value.substring(prefixIndex, matchEnd);
3637 };
3638 }
3639 return function (filter) {
3640 return ""
3641 .concat(value.substring(prefixIndex, matchIndex))
3642 .concat(modifyShadowColor(rgb, filter))
3643 .concat(
3644 i === colorMatches_1.length - 1
3645 ? value.substring(matchEnd)
3646 : ""
3647 );
3648 };
3649 });
3650 return function (filter) {
3651 var modified = modifiers_2
3652 .map(function (modify) {
3653 return modify(filter);
3654 })
3655 .join("");
3656 return {
3657 matchesLength: colorMatches_1.length,
3658 unparseableMatchesLength: notParsed_1,
3659 result: modified
3660 };
3661 };
3662 } catch (err) {
3663 return null;
3664 }
3665 }
3666 function getShadowModifier(value) {
3667 var shadowModifier = getShadowModifierWithInfo(value);
3668 if (!shadowModifier) {
3669 return null;
3670 }
3671 return function (theme) {
3672 return shadowModifier(theme).result;
3673 };
3674 }
3675 function getVariableModifier(
3676 variablesStore,
3677 prop,
3678 value,
3679 rule,
3680 ignoredImgSelectors,
3681 isCancelled
3682 ) {
3683 return variablesStore.getModifierForVariable({
3684 varName: prop,
3685 sourceValue: value,
3686 rule: rule,
3687 ignoredImgSelectors: ignoredImgSelectors,
3688 isCancelled: isCancelled
3689 });
3690 }
3691 function getVariableDependantModifier(variablesStore, prop, value) {
3692 return variablesStore.getModifierForVarDependant(prop, value);
3693 }
3694 function cleanModificationCache() {
3695 clearColorModificationCache();
3696 imageDetailsCache.clear();
3697 cleanImageProcessingCache();
3698 awaitingForImageLoading.clear();
3699 }
3700
3701 var VAR_TYPE_BGCOLOR = 1 << 0;
3702 var VAR_TYPE_TEXTCOLOR = 1 << 1;
3703 var VAR_TYPE_BORDERCOLOR = 1 << 2;
3704 var VAR_TYPE_BGIMG = 1 << 3;
3705 var VariablesStore = (function () {
3706 function VariablesStore() {
3707 this.varTypes = new Map();
3708 this.rulesQueue = [];
3709 this.definedVars = new Set();
3710 this.varRefs = new Map();
3711 this.unknownColorVars = new Set();
3712 this.unknownBgVars = new Set();
3713 this.undefinedVars = new Set();
3714 this.initialVarTypes = new Map();
3715 this.changedTypeVars = new Set();
3716 this.typeChangeSubscriptions = new Map();
3717 this.unstableVarValues = new Map();
3718 }
3719 VariablesStore.prototype.clear = function () {
3720 this.varTypes.clear();
3721 this.rulesQueue.splice(0);
3722 this.definedVars.clear();
3723 this.varRefs.clear();
3724 this.unknownColorVars.clear();
3725 this.unknownBgVars.clear();
3726 this.undefinedVars.clear();
3727 this.initialVarTypes.clear();
3728 this.changedTypeVars.clear();
3729 this.typeChangeSubscriptions.clear();
3730 this.unstableVarValues.clear();
3731 };
3732 VariablesStore.prototype.isVarType = function (varName, typeNum) {
3733 return (
3734 this.varTypes.has(varName) &&
3735 (this.varTypes.get(varName) & typeNum) > 0
3736 );
3737 };
3738 VariablesStore.prototype.addRulesForMatching = function (rules) {
3739 this.rulesQueue.push(rules);
3740 };
3741 VariablesStore.prototype.matchVariablesAndDependants = function () {
3742 var _this = this;
3743 this.changedTypeVars.clear();
3744 this.initialVarTypes = new Map(this.varTypes);
3745 this.collectRootVariables();
3746 this.collectVariablesAndVarDep(this.rulesQueue);
3747 this.rulesQueue.splice(0);
3748 this.collectRootVarDependants();
3749 this.varRefs.forEach(function (refs, v) {
3750 refs.forEach(function (r) {
3751 if (_this.varTypes.has(v)) {
3752 _this.resolveVariableType(r, _this.varTypes.get(v));
3753 }
3754 });
3755 });
3756 this.unknownColorVars.forEach(function (v) {
3757 if (_this.unknownBgVars.has(v)) {
3758 _this.unknownColorVars.delete(v);
3759 _this.unknownBgVars.delete(v);
3760 _this.resolveVariableType(v, VAR_TYPE_BGCOLOR);
3761 } else if (
3762 _this.isVarType(
3763 v,
3764 VAR_TYPE_BGCOLOR |
3765 VAR_TYPE_TEXTCOLOR |
3766 VAR_TYPE_BORDERCOLOR
3767 )
3768 ) {
3769 _this.unknownColorVars.delete(v);
3770 } else {
3771 _this.undefinedVars.add(v);
3772 }
3773 });
3774 this.unknownBgVars.forEach(function (v) {
3775 var hasColor =
3776 _this.findVarRef(v, function (ref) {
3777 return (
3778 _this.unknownColorVars.has(ref) ||
3779 _this.isVarType(
3780 ref,
3781 VAR_TYPE_TEXTCOLOR | VAR_TYPE_BORDERCOLOR
3782 )
3783 );
3784 }) != null;
3785 if (hasColor) {
3786 _this.itarateVarRefs(v, function (ref) {
3787 _this.resolveVariableType(ref, VAR_TYPE_BGCOLOR);
3788 });
3789 } else if (
3790 _this.isVarType(v, VAR_TYPE_BGCOLOR | VAR_TYPE_BGIMG)
3791 ) {
3792 _this.unknownBgVars.delete(v);
3793 } else {
3794 _this.undefinedVars.add(v);
3795 }
3796 });
3797 this.changedTypeVars.forEach(function (varName) {
3798 if (_this.typeChangeSubscriptions.has(varName)) {
3799 _this.typeChangeSubscriptions
3800 .get(varName)
3801 .forEach(function (callback) {
3802 callback();
3803 });
3804 }
3805 });
3806 this.changedTypeVars.clear();
3807 };
3808 VariablesStore.prototype.getModifierForVariable = function (options) {
3809 var _this = this;
3810 return function (theme) {
3811 var varName = options.varName,
3812 sourceValue = options.sourceValue,
3813 rule = options.rule,
3814 ignoredImgSelectors = options.ignoredImgSelectors,
3815 isCancelled = options.isCancelled;
3816 var getDeclarations = function () {
3817 var declarations = [];
3818 var addModifiedValue = function (
3819 typeNum,
3820 varNameWrapper,
3821 colorModifier
3822 ) {
3823 if (!_this.isVarType(varName, typeNum)) {
3824 return;
3825 }
3826 var property = varNameWrapper(varName);
3827 var modifiedValue;
3828 if (isVarDependant(sourceValue)) {
3829 if (isConstructedColorVar(sourceValue)) {
3830 var value = insertVarValues(
3831 sourceValue,
3832 _this.unstableVarValues
3833 );
3834 if (!value) {
3835 value =
3836 typeNum === VAR_TYPE_BGCOLOR
3837 ? "#ffffff"
3838 : "#000000";
3839 }
3840 modifiedValue = colorModifier(value, theme);
3841 } else {
3842 modifiedValue = replaceCSSVariablesNames(
3843 sourceValue,
3844 function (v) {
3845 return varNameWrapper(v);
3846 },
3847 function (fallback) {
3848 return colorModifier(fallback, theme);
3849 }
3850 );
3851 }
3852 } else {
3853 modifiedValue = colorModifier(sourceValue, theme);
3854 }
3855 declarations.push({
3856 property: property,
3857 value: modifiedValue
3858 });
3859 };
3860 addModifiedValue(
3861 VAR_TYPE_BGCOLOR,
3862 wrapBgColorVariableName,
3863 tryModifyBgColor
3864 );
3865 addModifiedValue(
3866 VAR_TYPE_TEXTCOLOR,
3867 wrapTextColorVariableName,
3868 tryModifyTextColor
3869 );
3870 addModifiedValue(
3871 VAR_TYPE_BORDERCOLOR,
3872 wrapBorderColorVariableName,
3873 tryModifyBorderColor
3874 );
3875 if (_this.isVarType(varName, VAR_TYPE_BGIMG)) {
3876 var property = wrapBgImgVariableName(varName);
3877 var modifiedValue = sourceValue;
3878 if (isVarDependant(sourceValue)) {
3879 modifiedValue = replaceCSSVariablesNames(
3880 sourceValue,
3881 function (v) {
3882 return wrapBgColorVariableName(v);
3883 },
3884 function (fallback) {
3885 return tryModifyBgColor(fallback, theme);
3886 }
3887 );
3888 }
3889 var bgModifier = getBgImageModifier(
3890 modifiedValue,
3891 rule,
3892 ignoredImgSelectors,
3893 isCancelled
3894 );
3895 modifiedValue =
3896 typeof bgModifier === "function"
3897 ? bgModifier(theme)
3898 : bgModifier;
3899 declarations.push({
3900 property: property,
3901 value: modifiedValue
3902 });
3903 }
3904 return declarations;
3905 };
3906 var callbacks = new Set();
3907 var addListener = function (onTypeChange) {
3908 var callback = function () {
3909 var decs = getDeclarations();
3910 onTypeChange(decs);
3911 };
3912 callbacks.add(callback);
3913 _this.subscribeForVarTypeChange(varName, callback);
3914 };
3915 var removeListeners = function () {
3916 callbacks.forEach(function (callback) {
3917 _this.unsubscribeFromVariableTypeChanges(
3918 varName,
3919 callback
3920 );
3921 });
3922 };
3923 return {
3924 declarations: getDeclarations(),
3925 onTypeChange: {
3926 addListener: addListener,
3927 removeListeners: removeListeners
3928 }
3929 };
3930 };
3931 };
3932 VariablesStore.prototype.getModifierForVarDependant = function (
3933 property,
3934 sourceValue
3935 ) {
3936 var _this = this;
3937 if (sourceValue.match(/^\s*(rgb|hsl)a?\(/)) {
3938 var isBg_1 = property.startsWith("background");
3939 var isText_1 = isTextColorProperty(property);
3940 return function (theme) {
3941 var value = insertVarValues(
3942 sourceValue,
3943 _this.unstableVarValues
3944 );
3945 if (!value) {
3946 value = isBg_1 ? "#ffffff" : "#000000";
3947 }
3948 var modifier = isBg_1
3949 ? tryModifyBgColor
3950 : isText_1
3951 ? tryModifyTextColor
3952 : tryModifyBorderColor;
3953 return modifier(value, theme);
3954 };
3955 }
3956 if (property === "background-color") {
3957 return function (theme) {
3958 return replaceCSSVariablesNames(
3959 sourceValue,
3960 function (v) {
3961 return wrapBgColorVariableName(v);
3962 },
3963 function (fallback) {
3964 return tryModifyBgColor(fallback, theme);
3965 }
3966 );
3967 };
3968 }
3969 if (isTextColorProperty(property)) {
3970 return function (theme) {
3971 return replaceCSSVariablesNames(
3972 sourceValue,
3973 function (v) {
3974 return wrapTextColorVariableName(v);
3975 },
3976 function (fallback) {
3977 return tryModifyTextColor(fallback, theme);
3978 }
3979 );
3980 };
3981 }
3982 if (
3983 property === "background" ||
3984 property === "background-image" ||
3985 property === "box-shadow"
3986 ) {
3987 return function (theme) {
3988 var unknownVars = new Set();
3989 var modify = function () {
3990 var variableReplaced = replaceCSSVariablesNames(
3991 sourceValue,
3992 function (v) {
3993 if (_this.isVarType(v, VAR_TYPE_BGCOLOR)) {
3994 return wrapBgColorVariableName(v);
3995 }
3996 if (_this.isVarType(v, VAR_TYPE_BGIMG)) {
3997 return wrapBgImgVariableName(v);
3998 }
3999 unknownVars.add(v);
4000 return v;
4001 },
4002 function (fallback) {
4003 return tryModifyBgColor(fallback, theme);
4004 }
4005 );
4006 if (property === "box-shadow") {
4007 var shadowModifier =
4008 getShadowModifierWithInfo(variableReplaced);
4009 var modifiedShadow = shadowModifier(theme);
4010 if (
4011 modifiedShadow.unparseableMatchesLength !==
4012 modifiedShadow.matchesLength
4013 ) {
4014 return modifiedShadow.result;
4015 }
4016 }
4017 return variableReplaced;
4018 };
4019 var modified = modify();
4020 if (unknownVars.size > 0) {
4021 return new Promise(function (resolve) {
4022 var firstUnknownVar = unknownVars
4023 .values()
4024 .next().value;
4025 var callback = function () {
4026 _this.unsubscribeFromVariableTypeChanges(
4027 firstUnknownVar,
4028 callback
4029 );
4030 var newValue = modify();
4031 resolve(newValue);
4032 };
4033 _this.subscribeForVarTypeChange(
4034 firstUnknownVar,
4035 callback
4036 );
4037 });
4038 }
4039 return modified;
4040 };
4041 }
4042 if (
4043 property.startsWith("border") ||
4044 property.startsWith("outline")
4045 ) {
4046 return function (theme) {
4047 return replaceCSSVariablesNames(
4048 sourceValue,
4049 function (v) {
4050 return wrapBorderColorVariableName(v);
4051 },
4052 function (fallback) {
4053 return tryModifyBorderColor(fallback, theme);
4054 }
4055 );
4056 };
4057 }
4058 return null;
4059 };
4060 VariablesStore.prototype.subscribeForVarTypeChange = function (
4061 varName,
4062 callback
4063 ) {
4064 if (!this.typeChangeSubscriptions.has(varName)) {
4065 this.typeChangeSubscriptions.set(varName, new Set());
4066 }
4067 var rootStore = this.typeChangeSubscriptions.get(varName);
4068 if (!rootStore.has(callback)) {
4069 rootStore.add(callback);
4070 }
4071 };
4072 VariablesStore.prototype.unsubscribeFromVariableTypeChanges = function (
4073 varName,
4074 callback
4075 ) {
4076 if (this.typeChangeSubscriptions.has(varName)) {
4077 this.typeChangeSubscriptions.get(varName).delete(callback);
4078 }
4079 };
4080 VariablesStore.prototype.collectVariablesAndVarDep = function (
4081 ruleList
4082 ) {
4083 var _this = this;
4084 ruleList.forEach(function (rules) {
4085 iterateCSSRules(rules, function (rule) {
4086 rule.style &&
4087 iterateCSSDeclarations(
4088 rule.style,
4089 function (property, value) {
4090 if (isVariable(property)) {
4091 _this.inspectVariable(property, value);
4092 }
4093 if (isVarDependant(value)) {
4094 _this.inspectVarDependant(property, value);
4095 }
4096 }
4097 );
4098 });
4099 });
4100 };
4101 VariablesStore.prototype.collectRootVariables = function () {
4102 var _this = this;
4103 iterateCSSDeclarations(
4104 document.documentElement.style,
4105 function (property, value) {
4106 if (isVariable(property)) {
4107 _this.inspectVariable(property, value);
4108 }
4109 }
4110 );
4111 };
4112 VariablesStore.prototype.inspectVariable = function (varName, value) {
4113 this.unstableVarValues.set(varName, value);
4114 if (isVarDependant(value) && isConstructedColorVar(value)) {
4115 this.unknownColorVars.add(varName);
4116 this.definedVars.add(varName);
4117 }
4118 if (this.definedVars.has(varName)) {
4119 return;
4120 }
4121 this.definedVars.add(varName);
4122 var color = parseColorWithCache(value);
4123 if (color) {
4124 this.unknownColorVars.add(varName);
4125 } else if (
4126 value.includes("url(") ||
4127 value.includes("linear-gradient(") ||
4128 value.includes("radial-gradient(")
4129 ) {
4130 this.resolveVariableType(varName, VAR_TYPE_BGIMG);
4131 }
4132 };
4133 VariablesStore.prototype.resolveVariableType = function (
4134 varName,
4135 typeNum
4136 ) {
4137 var initialType = this.initialVarTypes.get(varName) || 0;
4138 var currentType = this.varTypes.get(varName) || 0;
4139 var newType = currentType | typeNum;
4140 this.varTypes.set(varName, newType);
4141 if (newType !== initialType || this.undefinedVars.has(varName)) {
4142 this.changedTypeVars.add(varName);
4143 this.undefinedVars.delete(varName);
4144 }
4145 this.unknownColorVars.delete(varName);
4146 this.unknownBgVars.delete(varName);
4147 };
4148 VariablesStore.prototype.collectRootVarDependants = function () {
4149 var _this = this;
4150 iterateCSSDeclarations(
4151 document.documentElement.style,
4152 function (property, value) {
4153 if (isVarDependant(value)) {
4154 _this.inspectVarDependant(property, value);
4155 }
4156 }
4157 );
4158 };
4159 VariablesStore.prototype.inspectVarDependant = function (
4160 property,
4161 value
4162 ) {
4163 var _this = this;
4164 if (isVariable(property)) {
4165 this.iterateVarDeps(value, function (ref) {
4166 if (!_this.varRefs.has(property)) {
4167 _this.varRefs.set(property, new Set());
4168 }
4169 _this.varRefs.get(property).add(ref);
4170 });
4171 } else if (
4172 property === "background-color" ||
4173 property === "box-shadow"
4174 ) {
4175 this.iterateVarDeps(value, function (v) {
4176 return _this.resolveVariableType(v, VAR_TYPE_BGCOLOR);
4177 });
4178 } else if (isTextColorProperty(property)) {
4179 this.iterateVarDeps(value, function (v) {
4180 return _this.resolveVariableType(v, VAR_TYPE_TEXTCOLOR);
4181 });
4182 } else if (
4183 property.startsWith("border") ||
4184 property.startsWith("outline")
4185 ) {
4186 this.iterateVarDeps(value, function (v) {
4187 return _this.resolveVariableType(v, VAR_TYPE_BORDERCOLOR);
4188 });
4189 } else if (
4190 property === "background" ||
4191 property === "background-image"
4192 ) {
4193 this.iterateVarDeps(value, function (v) {
4194 if (_this.isVarType(v, VAR_TYPE_BGCOLOR | VAR_TYPE_BGIMG)) {
4195 return;
4196 }
4197 var isBgColor =
4198 _this.findVarRef(v, function (ref) {
4199 return (
4200 _this.unknownColorVars.has(ref) ||
4201 _this.isVarType(
4202 ref,
4203 VAR_TYPE_TEXTCOLOR | VAR_TYPE_BORDERCOLOR
4204 )
4205 );
4206 }) != null;
4207 _this.itarateVarRefs(v, function (ref) {
4208 if (isBgColor) {
4209 _this.resolveVariableType(ref, VAR_TYPE_BGCOLOR);
4210 } else {
4211 _this.unknownBgVars.add(ref);
4212 }
4213 });
4214 });
4215 }
4216 };
4217 VariablesStore.prototype.iterateVarDeps = function (value, iterator) {
4218 var varDeps = new Set();
4219 iterateVarDependencies(value, function (v) {
4220 return varDeps.add(v);
4221 });
4222 varDeps.forEach(function (v) {
4223 return iterator(v);
4224 });
4225 };
4226 VariablesStore.prototype.findVarRef = function (
4227 varName,
4228 iterator,
4229 stack
4230 ) {
4231 var e_1, _a;
4232 if (stack === void 0) {
4233 stack = new Set();
4234 }
4235 if (stack.has(varName)) {
4236 return null;
4237 }
4238 stack.add(varName);
4239 var result = iterator(varName);
4240 if (result) {
4241 return varName;
4242 }
4243 var refs = this.varRefs.get(varName);
4244 if (!refs || refs.size === 0) {
4245 return null;
4246 }
4247 try {
4248 for (
4249 var refs_1 = __values(refs), refs_1_1 = refs_1.next();
4250 !refs_1_1.done;
4251 refs_1_1 = refs_1.next()
4252 ) {
4253 var ref = refs_1_1.value;
4254 var found = this.findVarRef(ref, iterator, stack);
4255 if (found) {
4256 return found;
4257 }
4258 }
4259 } catch (e_1_1) {
4260 e_1 = {error: e_1_1};
4261 } finally {
4262 try {
4263 if (refs_1_1 && !refs_1_1.done && (_a = refs_1.return))
4264 _a.call(refs_1);
4265 } finally {
4266 if (e_1) throw e_1.error;
4267 }
4268 }
4269 return null;
4270 };
4271 VariablesStore.prototype.itarateVarRefs = function (varName, iterator) {
4272 this.findVarRef(varName, function (ref) {
4273 iterator(ref);
4274 return false;
4275 });
4276 };
4277 VariablesStore.prototype.setOnRootVariableChange = function (callback) {
4278 this.onRootVariableDefined = callback;
4279 };
4280 VariablesStore.prototype.putRootVars = function (styleElement, theme) {
4281 var e_2, _a;
4282 var _this = this;
4283 var sheet = styleElement.sheet;
4284 if (sheet.cssRules.length > 0) {
4285 sheet.deleteRule(0);
4286 }
4287 var declarations = new Map();
4288 iterateCSSDeclarations(
4289 document.documentElement.style,
4290 function (property, value) {
4291 if (isVariable(property)) {
4292 if (_this.isVarType(property, VAR_TYPE_BGCOLOR)) {
4293 declarations.set(
4294 wrapBgColorVariableName(property),
4295 tryModifyBgColor(value, theme)
4296 );
4297 }
4298 if (_this.isVarType(property, VAR_TYPE_TEXTCOLOR)) {
4299 declarations.set(
4300 wrapTextColorVariableName(property),
4301 tryModifyTextColor(value, theme)
4302 );
4303 }
4304 if (_this.isVarType(property, VAR_TYPE_BORDERCOLOR)) {
4305 declarations.set(
4306 wrapBorderColorVariableName(property),
4307 tryModifyBorderColor(value, theme)
4308 );
4309 }
4310 _this.subscribeForVarTypeChange(
4311 property,
4312 _this.onRootVariableDefined
4313 );
4314 }
4315 }
4316 );
4317 var cssLines = [];
4318 cssLines.push(":root {");
4319 try {
4320 for (
4321 var declarations_1 = __values(declarations),
4322 declarations_1_1 = declarations_1.next();
4323 !declarations_1_1.done;
4324 declarations_1_1 = declarations_1.next()
4325 ) {
4326 var _b = __read(declarations_1_1.value, 2),
4327 property = _b[0],
4328 value = _b[1];
4329 cssLines.push(
4330 " ".concat(property, ": ").concat(value, ";")
4331 );
4332 }
4333 } catch (e_2_1) {
4334 e_2 = {error: e_2_1};
4335 } finally {
4336 try {
4337 if (
4338 declarations_1_1 &&
4339 !declarations_1_1.done &&
4340 (_a = declarations_1.return)
4341 )
4342 _a.call(declarations_1);
4343 } finally {
4344 if (e_2) throw e_2.error;
4345 }
4346 }
4347 cssLines.push("}");
4348 var cssText = cssLines.join("\n");
4349 sheet.insertRule(cssText);
4350 };
4351 return VariablesStore;
4352 })();
4353 var variablesStore = new VariablesStore();
4354 function getVariableRange(input, searchStart) {
4355 if (searchStart === void 0) {
4356 searchStart = 0;
4357 }
4358 var start = input.indexOf("var(", searchStart);
4359 if (start >= 0) {
4360 var range = getParenthesesRange(input, start + 3);
4361 if (range) {
4362 return {start: start, end: range.end};
4363 }
4364 return null;
4365 }
4366 }
4367 function getVariablesMatches(input) {
4368 var ranges = [];
4369 var i = 0;
4370 var range;
4371 while ((range = getVariableRange(input, i))) {
4372 var start = range.start,
4373 end = range.end;
4374 ranges.push({
4375 start: start,
4376 end: end,
4377 value: input.substring(start, end)
4378 });
4379 i = range.end + 1;
4380 }
4381 return ranges;
4382 }
4383 function replaceVariablesMatches(input, replacer) {
4384 var matches = getVariablesMatches(input);
4385 var matchesCount = matches.length;
4386 if (matchesCount === 0) {
4387 return input;
4388 }
4389 var inputLength = input.length;
4390 var replacements = matches.map(function (m) {
4391 return replacer(m.value);
4392 });
4393 var parts = [];
4394 parts.push(input.substring(0, matches[0].start));
4395 for (var i = 0; i < matchesCount; i++) {
4396 parts.push(replacements[i]);
4397 var start = matches[i].end;
4398 var end = i < matchesCount - 1 ? matches[i + 1].start : inputLength;
4399 parts.push(input.substring(start, end));
4400 }
4401 return parts.join("");
4402 }
4403 function getVariableNameAndFallback(match) {
4404 var commaIndex = match.indexOf(",");
4405 var name;
4406 var fallback;
4407 if (commaIndex >= 0) {
4408 name = match.substring(4, commaIndex).trim();
4409 fallback = match.substring(commaIndex + 1, match.length - 1).trim();
4410 } else {
4411 name = match.substring(4, match.length - 1).trim();
4412 fallback = "";
4413 }
4414 return {name: name, fallback: fallback};
4415 }
4416 function replaceCSSVariablesNames(value, nameReplacer, fallbackReplacer) {
4417 var matchReplacer = function (match) {
4418 var _a = getVariableNameAndFallback(match),
4419 name = _a.name,
4420 fallback = _a.fallback;
4421 var newName = nameReplacer(name);
4422 if (!fallback) {
4423 return "var(".concat(newName, ")");
4424 }
4425 var newFallback;
4426 if (isVarDependant(fallback)) {
4427 newFallback = replaceCSSVariablesNames(
4428 fallback,
4429 nameReplacer,
4430 fallbackReplacer
4431 );
4432 } else if (fallbackReplacer) {
4433 newFallback = fallbackReplacer(fallback);
4434 } else {
4435 newFallback = fallback;
4436 }
4437 return "var(".concat(newName, ", ").concat(newFallback, ")");
4438 };
4439 return replaceVariablesMatches(value, matchReplacer);
4440 }
4441 function iterateVarDependencies(value, iterator) {
4442 replaceCSSVariablesNames(value, function (varName) {
4443 iterator(varName);
4444 return varName;
4445 });
4446 }
4447 function wrapBgColorVariableName(name) {
4448 return "--darkreader-bg".concat(name);
4449 }
4450 function wrapTextColorVariableName(name) {
4451 return "--darkreader-text".concat(name);
4452 }
4453 function wrapBorderColorVariableName(name) {
4454 return "--darkreader-border".concat(name);
4455 }
4456 function wrapBgImgVariableName(name) {
4457 return "--darkreader-bgimg".concat(name);
4458 }
4459 function isVariable(property) {
4460 return property.startsWith("--");
4461 }
4462 function isVarDependant(value) {
4463 return value.includes("var(");
4464 }
4465 function isConstructedColorVar(value) {
4466 return value.match(/^\s*(rgb|hsl)a?\(/);
4467 }
4468 function isTextColorProperty(property) {
4469 return (
4470 property === "color" ||
4471 property === "caret-color" ||
4472 property === "-webkit-text-fill-color"
4473 );
4474 }
4475 var rawValueRegex = /^\d{1,3}, ?\d{1,3}, ?\d{1,3}$/;
4476 function parseRawValue(color) {
4477 if (rawValueRegex.test(color)) {
4478 var splitted = color.split(",");
4479 var resultInRGB_1 = "rgb(";
4480 splitted.forEach(function (number) {
4481 resultInRGB_1 += "".concat(number.trim(), ", ");
4482 });
4483 resultInRGB_1 = resultInRGB_1.substring(
4484 0,
4485 resultInRGB_1.length - 2
4486 );
4487 resultInRGB_1 += ")";
4488 return {isRaw: true, color: resultInRGB_1};
4489 }
4490 return {isRaw: false, color: color};
4491 }
4492 function handleRawValue(color, theme, modifyFunction) {
4493 var _a = parseRawValue(color),
4494 isRaw = _a.isRaw,
4495 newColor = _a.color;
4496 var rgb = parseColorWithCache(newColor);
4497 if (rgb) {
4498 var outputColor = modifyFunction(rgb, theme);
4499 if (isRaw) {
4500 var outputInRGB = parseColorWithCache(outputColor);
4501 return outputInRGB
4502 ? ""
4503 .concat(outputInRGB.r, ", ")
4504 .concat(outputInRGB.g, ", ")
4505 .concat(outputInRGB.b)
4506 : outputColor;
4507 }
4508 return outputColor;
4509 }
4510 return newColor;
4511 }
4512 function tryModifyBgColor(color, theme) {
4513 return handleRawValue(color, theme, modifyBackgroundColor);
4514 }
4515 function tryModifyTextColor(color, theme) {
4516 return handleRawValue(color, theme, modifyForegroundColor);
4517 }
4518 function tryModifyBorderColor(color, theme) {
4519 return handleRawValue(color, theme, modifyBorderColor);
4520 }
4521 function insertVarValues(source, varValues, stack) {
4522 if (stack === void 0) {
4523 stack = new Set();
4524 }
4525 var containsUnresolvedVar = false;
4526 var matchReplacer = function (match) {
4527 var _a = getVariableNameAndFallback(match),
4528 name = _a.name,
4529 fallback = _a.fallback;
4530 if (stack.has(name)) {
4531 containsUnresolvedVar = true;
4532 return null;
4533 }
4534 stack.add(name);
4535 var varValue = varValues.get(name) || fallback;
4536 var inserted = null;
4537 if (varValue) {
4538 if (isVarDependant(varValue)) {
4539 inserted = insertVarValues(varValue, varValues, stack);
4540 } else {
4541 inserted = varValue;
4542 }
4543 }
4544 if (!inserted) {
4545 containsUnresolvedVar = true;
4546 return null;
4547 }
4548 return inserted;
4549 };
4550 var replaced = replaceVariablesMatches(source, matchReplacer);
4551 if (containsUnresolvedVar) {
4552 return null;
4553 }
4554 return replaced;
4555 }
4556
4557 var overrides = {
4558 "background-color": {
4559 customProp: "--darkreader-inline-bgcolor",
4560 cssProp: "background-color",
4561 dataAttr: "data-darkreader-inline-bgcolor"
4562 },
4563 "background-image": {
4564 customProp: "--darkreader-inline-bgimage",
4565 cssProp: "background-image",
4566 dataAttr: "data-darkreader-inline-bgimage"
4567 },
4568 "border-color": {
4569 customProp: "--darkreader-inline-border",
4570 cssProp: "border-color",
4571 dataAttr: "data-darkreader-inline-border"
4572 },
4573 "border-bottom-color": {
4574 customProp: "--darkreader-inline-border-bottom",
4575 cssProp: "border-bottom-color",
4576 dataAttr: "data-darkreader-inline-border-bottom"
4577 },
4578 "border-left-color": {
4579 customProp: "--darkreader-inline-border-left",
4580 cssProp: "border-left-color",
4581 dataAttr: "data-darkreader-inline-border-left"
4582 },
4583 "border-right-color": {
4584 customProp: "--darkreader-inline-border-right",
4585 cssProp: "border-right-color",
4586 dataAttr: "data-darkreader-inline-border-right"
4587 },
4588 "border-top-color": {
4589 customProp: "--darkreader-inline-border-top",
4590 cssProp: "border-top-color",
4591 dataAttr: "data-darkreader-inline-border-top"
4592 },
4593 "box-shadow": {
4594 customProp: "--darkreader-inline-boxshadow",
4595 cssProp: "box-shadow",
4596 dataAttr: "data-darkreader-inline-boxshadow"
4597 },
4598 "color": {
4599 customProp: "--darkreader-inline-color",
4600 cssProp: "color",
4601 dataAttr: "data-darkreader-inline-color"
4602 },
4603 "fill": {
4604 customProp: "--darkreader-inline-fill",
4605 cssProp: "fill",
4606 dataAttr: "data-darkreader-inline-fill"
4607 },
4608 "stroke": {
4609 customProp: "--darkreader-inline-stroke",
4610 cssProp: "stroke",
4611 dataAttr: "data-darkreader-inline-stroke"
4612 },
4613 "outline-color": {
4614 customProp: "--darkreader-inline-outline",
4615 cssProp: "outline-color",
4616 dataAttr: "data-darkreader-inline-outline"
4617 },
4618 "stop-color": {
4619 customProp: "--darkreader-inline-stopcolor",
4620 cssProp: "stop-color",
4621 dataAttr: "data-darkreader-inline-stopcolor"
4622 }
4623 };
4624 var overridesList = Object.values(overrides);
4625 var normalizedPropList = {};
4626 overridesList.forEach(function (_a) {
4627 var cssProp = _a.cssProp,
4628 customProp = _a.customProp;
4629 return (normalizedPropList[customProp] = cssProp);
4630 });
4631 var INLINE_STYLE_ATTRS = [
4632 "style",
4633 "fill",
4634 "stop-color",
4635 "stroke",
4636 "bgcolor",
4637 "color"
4638 ];
4639 var INLINE_STYLE_SELECTOR = INLINE_STYLE_ATTRS.map(function (attr) {
4640 return "[".concat(attr, "]");
4641 }).join(", ");
4642 function getInlineOverrideStyle() {
4643 return overridesList
4644 .map(function (_a) {
4645 var dataAttr = _a.dataAttr,
4646 customProp = _a.customProp,
4647 cssProp = _a.cssProp;
4648 return [
4649 "[".concat(dataAttr, "] {"),
4650 " "
4651 .concat(cssProp, ": var(")
4652 .concat(customProp, ") !important;"),
4653 "}"
4654 ].join("\n");
4655 })
4656 .join("\n");
4657 }
4658 function getInlineStyleElements(root) {
4659 var results = [];
4660 if (root instanceof Element && root.matches(INLINE_STYLE_SELECTOR)) {
4661 results.push(root);
4662 }
4663 if (
4664 root instanceof Element ||
4665 (isShadowDomSupported && root instanceof ShadowRoot) ||
4666 root instanceof Document
4667 ) {
4668 push(results, root.querySelectorAll(INLINE_STYLE_SELECTOR));
4669 }
4670 return results;
4671 }
4672 var treeObservers = new Map();
4673 var attrObservers = new Map();
4674 function watchForInlineStyles(elementStyleDidChange, shadowRootDiscovered) {
4675 deepWatchForInlineStyles(
4676 document,
4677 elementStyleDidChange,
4678 shadowRootDiscovered
4679 );
4680 iterateShadowHosts(document.documentElement, function (host) {
4681 deepWatchForInlineStyles(
4682 host.shadowRoot,
4683 elementStyleDidChange,
4684 shadowRootDiscovered
4685 );
4686 });
4687 }
4688 function deepWatchForInlineStyles(
4689 root,
4690 elementStyleDidChange,
4691 shadowRootDiscovered
4692 ) {
4693 if (treeObservers.has(root)) {
4694 treeObservers.get(root).disconnect();
4695 attrObservers.get(root).disconnect();
4696 }
4697 var discoveredNodes = new WeakSet();
4698 function discoverNodes(node) {
4699 getInlineStyleElements(node).forEach(function (el) {
4700 if (discoveredNodes.has(el)) {
4701 return;
4702 }
4703 discoveredNodes.add(el);
4704 elementStyleDidChange(el);
4705 });
4706 iterateShadowHosts(node, function (n) {
4707 if (discoveredNodes.has(node)) {
4708 return;
4709 }
4710 discoveredNodes.add(node);
4711 shadowRootDiscovered(n.shadowRoot);
4712 deepWatchForInlineStyles(
4713 n.shadowRoot,
4714 elementStyleDidChange,
4715 shadowRootDiscovered
4716 );
4717 });
4718 }
4719 var treeObserver = createOptimizedTreeObserver(root, {
4720 onMinorMutations: function (_a) {
4721 var additions = _a.additions;
4722 additions.forEach(function (added) {
4723 return discoverNodes(added);
4724 });
4725 },
4726 onHugeMutations: function () {
4727 discoverNodes(root);
4728 }
4729 });
4730 treeObservers.set(root, treeObserver);
4731 var attemptCount = 0;
4732 var start = null;
4733 var ATTEMPTS_INTERVAL = getDuration({seconds: 10});
4734 var RETRY_TIMEOUT = getDuration({seconds: 2});
4735 var MAX_ATTEMPTS_COUNT = 50;
4736 var cache = [];
4737 var timeoutId = null;
4738 var handleAttributeMutations = throttle(function (mutations) {
4739 mutations.forEach(function (m) {
4740 if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
4741 elementStyleDidChange(m.target);
4742 }
4743 });
4744 });
4745 var attrObserver = new MutationObserver(function (mutations) {
4746 if (timeoutId) {
4747 cache.push.apply(
4748 cache,
4749 __spreadArray([], __read(mutations), false)
4750 );
4751 return;
4752 }
4753 attemptCount++;
4754 var now = Date.now();
4755 if (start == null) {
4756 start = now;
4757 } else if (attemptCount >= MAX_ATTEMPTS_COUNT) {
4758 if (now - start < ATTEMPTS_INTERVAL) {
4759 timeoutId = setTimeout(function () {
4760 start = null;
4761 attemptCount = 0;
4762 timeoutId = null;
4763 var attributeCache = cache;
4764 cache = [];
4765 handleAttributeMutations(attributeCache);
4766 }, RETRY_TIMEOUT);
4767 cache.push.apply(
4768 cache,
4769 __spreadArray([], __read(mutations), false)
4770 );
4771 return;
4772 }
4773 start = now;
4774 attemptCount = 1;
4775 }
4776 handleAttributeMutations(mutations);
4777 });
4778 attrObserver.observe(root, {
4779 attributes: true,
4780 attributeFilter: INLINE_STYLE_ATTRS.concat(
4781 overridesList.map(function (_a) {
4782 var dataAttr = _a.dataAttr;
4783 return dataAttr;
4784 })
4785 ),
4786 subtree: true
4787 });
4788 attrObservers.set(root, attrObserver);
4789 }
4790 function stopWatchingForInlineStyles() {
4791 treeObservers.forEach(function (o) {
4792 return o.disconnect();
4793 });
4794 attrObservers.forEach(function (o) {
4795 return o.disconnect();
4796 });
4797 treeObservers.clear();
4798 attrObservers.clear();
4799 }
4800 var inlineStyleCache = new WeakMap();
4801 var filterProps = ["brightness", "contrast", "grayscale", "sepia", "mode"];
4802 function getInlineStyleCacheKey(el, theme) {
4803 return INLINE_STYLE_ATTRS.map(function (attr) {
4804 return "".concat(attr, '="').concat(el.getAttribute(attr), '"');
4805 })
4806 .concat(
4807 filterProps.map(function (prop) {
4808 return "".concat(prop, '="').concat(theme[prop], '"');
4809 })
4810 )
4811 .join(" ");
4812 }
4813 function shouldIgnoreInlineStyle(element, selectors) {
4814 for (var i = 0, len = selectors.length; i < len; i++) {
4815 var ingnoredSelector = selectors[i];
4816 if (element.matches(ingnoredSelector)) {
4817 return true;
4818 }
4819 }
4820 return false;
4821 }
4822 function overrideInlineStyle(
4823 element,
4824 theme,
4825 ignoreInlineSelectors,
4826 ignoreImageSelectors
4827 ) {
4828 var cacheKey = getInlineStyleCacheKey(element, theme);
4829 if (cacheKey === inlineStyleCache.get(element)) {
4830 return;
4831 }
4832 var unsetProps = new Set(Object.keys(overrides));
4833 function setCustomProp(targetCSSProp, modifierCSSProp, cssVal) {
4834 var isPropertyVariable = targetCSSProp.startsWith("--");
4835 var _a = isPropertyVariable ? {} : overrides[targetCSSProp],
4836 customProp = _a.customProp,
4837 dataAttr = _a.dataAttr;
4838 var mod = getModifiableCSSDeclaration(
4839 modifierCSSProp,
4840 cssVal,
4841 {style: element.style},
4842 variablesStore,
4843 ignoreImageSelectors,
4844 null
4845 );
4846 if (!mod) {
4847 return;
4848 }
4849 var value = mod.value;
4850 if (typeof value === "function") {
4851 value = value(theme);
4852 }
4853 if (isPropertyVariable && typeof value === "object") {
4854 var typedValue = value;
4855 typedValue.declarations.forEach(function (_a) {
4856 var property = _a.property,
4857 value = _a.value;
4858 !(value instanceof Promise) &&
4859 element.style.setProperty(property, value);
4860 });
4861 } else {
4862 element.style.setProperty(customProp, value);
4863 if (!element.hasAttribute(dataAttr)) {
4864 element.setAttribute(dataAttr, "");
4865 }
4866 unsetProps.delete(targetCSSProp);
4867 }
4868 }
4869 if (ignoreInlineSelectors.length > 0) {
4870 if (shouldIgnoreInlineStyle(element, ignoreInlineSelectors)) {
4871 unsetProps.forEach(function (cssProp) {
4872 element.removeAttribute(overrides[cssProp].dataAttr);
4873 });
4874 return;
4875 }
4876 }
4877 if (element.hasAttribute("bgcolor")) {
4878 var value = element.getAttribute("bgcolor");
4879 if (
4880 value.match(/^[0-9a-f]{3}$/i) ||
4881 value.match(/^[0-9a-f]{6}$/i)
4882 ) {
4883 value = "#".concat(value);
4884 }
4885 setCustomProp("background-color", "background-color", value);
4886 }
4887 if (element.hasAttribute("color") && element.rel !== "mask-icon") {
4888 var value = element.getAttribute("color");
4889 if (
4890 value.match(/^[0-9a-f]{3}$/i) ||
4891 value.match(/^[0-9a-f]{6}$/i)
4892 ) {
4893 value = "#".concat(value);
4894 }
4895 setCustomProp("color", "color", value);
4896 }
4897 if (element instanceof SVGElement) {
4898 if (element.hasAttribute("fill")) {
4899 var SMALL_SVG_LIMIT_1 = 32;
4900 var value_1 = element.getAttribute("fill");
4901 if (value_1 !== "none") {
4902 if (!(element instanceof SVGTextElement)) {
4903 var handleSVGElement = function () {
4904 var _a = element.getBoundingClientRect(),
4905 width = _a.width,
4906 height = _a.height;
4907 var isBg =
4908 width > SMALL_SVG_LIMIT_1 ||
4909 height > SMALL_SVG_LIMIT_1;
4910 setCustomProp(
4911 "fill",
4912 isBg ? "background-color" : "color",
4913 value_1
4914 );
4915 };
4916 if (isReadyStateComplete()) {
4917 handleSVGElement();
4918 } else {
4919 addReadyStateCompleteListener(handleSVGElement);
4920 }
4921 } else {
4922 setCustomProp("fill", "color", value_1);
4923 }
4924 }
4925 }
4926 if (element.hasAttribute("stop-color")) {
4927 setCustomProp(
4928 "stop-color",
4929 "background-color",
4930 element.getAttribute("stop-color")
4931 );
4932 }
4933 }
4934 if (element.hasAttribute("stroke")) {
4935 var value = element.getAttribute("stroke");
4936 setCustomProp(
4937 "stroke",
4938 element instanceof SVGLineElement ||
4939 element instanceof SVGTextElement
4940 ? "border-color"
4941 : "color",
4942 value
4943 );
4944 }
4945 element.style &&
4946 iterateCSSDeclarations(element.style, function (property, value) {
4947 if (property === "background-image" && value.includes("url")) {
4948 return;
4949 }
4950 if (
4951 overrides.hasOwnProperty(property) ||
4952 (property.startsWith("--") && !normalizedPropList[property])
4953 ) {
4954 setCustomProp(property, property, value);
4955 } else {
4956 var overridenProp = normalizedPropList[property];
4957 if (
4958 overridenProp &&
4959 !element.style.getPropertyValue(overridenProp) &&
4960 !element.hasAttribute(overridenProp)
4961 ) {
4962 if (
4963 overridenProp === "background-color" &&
4964 element.hasAttribute("bgcolor")
4965 ) {
4966 return;
4967 }
4968 element.style.setProperty(property, "");
4969 }
4970 }
4971 });
4972 if (
4973 element.style &&
4974 element instanceof SVGTextElement &&
4975 element.style.fill
4976 ) {
4977 setCustomProp(
4978 "fill",
4979 "color",
4980 element.style.getPropertyValue("fill")
4981 );
4982 }
4983 forEach(unsetProps, function (cssProp) {
4984 element.removeAttribute(overrides[cssProp].dataAttr);
4985 });
4986 inlineStyleCache.set(element, getInlineStyleCacheKey(element, theme));
4987 }
4988
4989 var metaThemeColorName = "theme-color";
4990 var metaThemeColorSelector = 'meta[name="'.concat(metaThemeColorName, '"]');
4991 var srcMetaThemeColor = null;
4992 var observer = null;
4993 function changeMetaThemeColor(meta, theme) {
4994 srcMetaThemeColor = srcMetaThemeColor || meta.content;
4995 var color = parseColorWithCache(srcMetaThemeColor);
4996 if (!color) {
4997 return;
4998 }
4999 meta.content = modifyBackgroundColor(color, theme);
5000 }
5001 function changeMetaThemeColorWhenAvailable(theme) {
5002 var meta = document.querySelector(metaThemeColorSelector);
5003 if (meta) {
5004 changeMetaThemeColor(meta, theme);
5005 } else {
5006 if (observer) {
5007 observer.disconnect();
5008 }
5009 observer = new MutationObserver(function (mutations) {
5010 loop: for (var i = 0; i < mutations.length; i++) {
5011 var addedNodes = mutations[i].addedNodes;
5012 for (var j = 0; j < addedNodes.length; j++) {
5013 var node = addedNodes[j];
5014 if (
5015 node instanceof HTMLMetaElement &&
5016 node.name === metaThemeColorName
5017 ) {
5018 observer.disconnect();
5019 observer = null;
5020 changeMetaThemeColor(node, theme);
5021 break loop;
5022 }
5023 }
5024 }
5025 });
5026 observer.observe(document.head, {childList: true});
5027 }
5028 }
5029 function restoreMetaThemeColor() {
5030 if (observer) {
5031 observer.disconnect();
5032 observer = null;
5033 }
5034 var meta = document.querySelector(metaThemeColorSelector);
5035 if (meta && srcMetaThemeColor) {
5036 meta.content = srcMetaThemeColor;
5037 }
5038 }
5039
5040 var themeCacheKeys = [
5041 "mode",
5042 "brightness",
5043 "contrast",
5044 "grayscale",
5045 "sepia",
5046 "darkSchemeBackgroundColor",
5047 "darkSchemeTextColor",
5048 "lightSchemeBackgroundColor",
5049 "lightSchemeTextColor"
5050 ];
5051 function getThemeKey(theme) {
5052 var resultKey = "";
5053 themeCacheKeys.forEach(function (key) {
5054 resultKey += "".concat(key, ":").concat(theme[key], ";");
5055 });
5056 return resultKey;
5057 }
5058 var asyncQueue = createAsyncTasksQueue();
5059 function createStyleSheetModifier() {
5060 var renderId = 0;
5061 var rulesTextCache = new Set();
5062 var rulesModCache = new Map();
5063 var varTypeChangeCleaners = new Set();
5064 var prevFilterKey = null;
5065 var hasNonLoadedLink = false;
5066 var wasRebuilt = false;
5067 function shouldRebuildStyle() {
5068 return hasNonLoadedLink && !wasRebuilt;
5069 }
5070 function modifySheet(options) {
5071 var rules = options.sourceCSSRules;
5072 var theme = options.theme,
5073 ignoreImageAnalysis = options.ignoreImageAnalysis,
5074 force = options.force,
5075 prepareSheet = options.prepareSheet,
5076 isAsyncCancelled = options.isAsyncCancelled;
5077 var rulesChanged = rulesModCache.size === 0;
5078 var notFoundCacheKeys = new Set(rulesModCache.keys());
5079 var themeKey = getThemeKey(theme);
5080 var themeChanged = themeKey !== prevFilterKey;
5081 if (hasNonLoadedLink) {
5082 wasRebuilt = true;
5083 }
5084 var modRules = [];
5085 iterateCSSRules(
5086 rules,
5087 function (rule) {
5088 var cssText = rule.cssText;
5089 var textDiffersFromPrev = false;
5090 notFoundCacheKeys.delete(cssText);
5091 if (rule.parentRule instanceof CSSMediaRule) {
5092 cssText += ";".concat(rule.parentRule.media.mediaText);
5093 }
5094 if (!rulesTextCache.has(cssText)) {
5095 rulesTextCache.add(cssText);
5096 textDiffersFromPrev = true;
5097 }
5098 if (textDiffersFromPrev) {
5099 rulesChanged = true;
5100 } else {
5101 modRules.push(rulesModCache.get(cssText));
5102 return;
5103 }
5104 var modDecs = [];
5105 rule.style &&
5106 iterateCSSDeclarations(
5107 rule.style,
5108 function (property, value) {
5109 var mod = getModifiableCSSDeclaration(
5110 property,
5111 value,
5112 rule,
5113 variablesStore,
5114 ignoreImageAnalysis,
5115 isAsyncCancelled
5116 );
5117 if (mod) {
5118 modDecs.push(mod);
5119 }
5120 }
5121 );
5122 var modRule = null;
5123 if (modDecs.length > 0) {
5124 var parentRule = rule.parentRule;
5125 modRule = {
5126 selector: rule.selectorText,
5127 declarations: modDecs,
5128 parentRule: parentRule
5129 };
5130 modRules.push(modRule);
5131 }
5132 rulesModCache.set(cssText, modRule);
5133 },
5134 function () {
5135 hasNonLoadedLink = true;
5136 }
5137 );
5138 notFoundCacheKeys.forEach(function (key) {
5139 rulesTextCache.delete(key);
5140 rulesModCache.delete(key);
5141 });
5142 prevFilterKey = themeKey;
5143 if (!force && !rulesChanged && !themeChanged) {
5144 return;
5145 }
5146 renderId++;
5147 function setRule(target, index, rule) {
5148 var selector = rule.selector,
5149 declarations = rule.declarations;
5150 var getDeclarationText = function (dec) {
5151 var property = dec.property,
5152 value = dec.value,
5153 important = dec.important,
5154 sourceValue = dec.sourceValue;
5155 return ""
5156 .concat(property, ": ")
5157 .concat(value == null ? sourceValue : value)
5158 .concat(important ? " !important" : "", ";");
5159 };
5160 var cssRulesText = "";
5161 declarations.forEach(function (declarations) {
5162 cssRulesText += "".concat(
5163 getDeclarationText(declarations),
5164 " "
5165 );
5166 });
5167 var ruleText = ""
5168 .concat(selector, " { ")
5169 .concat(cssRulesText, " }");
5170 target.insertRule(ruleText, index);
5171 }
5172 var asyncDeclarations = new Map();
5173 var varDeclarations = new Map();
5174 var asyncDeclarationCounter = 0;
5175 var varDeclarationCounter = 0;
5176 var rootReadyGroup = {rule: null, rules: [], isGroup: true};
5177 var groupRefs = new WeakMap();
5178 function getGroup(rule) {
5179 if (rule == null) {
5180 return rootReadyGroup;
5181 }
5182 if (groupRefs.has(rule)) {
5183 return groupRefs.get(rule);
5184 }
5185 var group = {rule: rule, rules: [], isGroup: true};
5186 groupRefs.set(rule, group);
5187 var parentGroup = getGroup(rule.parentRule);
5188 parentGroup.rules.push(group);
5189 return group;
5190 }
5191 varTypeChangeCleaners.forEach(function (clear) {
5192 return clear();
5193 });
5194 varTypeChangeCleaners.clear();
5195 modRules
5196 .filter(function (r) {
5197 return r;
5198 })
5199 .forEach(function (_a) {
5200 var selector = _a.selector,
5201 declarations = _a.declarations,
5202 parentRule = _a.parentRule;
5203 var group = getGroup(parentRule);
5204 var readyStyleRule = {
5205 selector: selector,
5206 declarations: [],
5207 isGroup: false
5208 };
5209 var readyDeclarations = readyStyleRule.declarations;
5210 group.rules.push(readyStyleRule);
5211 function handleAsyncDeclaration(
5212 property,
5213 modified,
5214 important,
5215 sourceValue
5216 ) {
5217 var asyncKey = ++asyncDeclarationCounter;
5218 var asyncDeclaration = {
5219 property: property,
5220 value: null,
5221 important: important,
5222 asyncKey: asyncKey,
5223 sourceValue: sourceValue
5224 };
5225 readyDeclarations.push(asyncDeclaration);
5226 var currentRenderId = renderId;
5227 modified.then(function (asyncValue) {
5228 if (
5229 !asyncValue ||
5230 isAsyncCancelled() ||
5231 currentRenderId !== renderId
5232 ) {
5233 return;
5234 }
5235 asyncDeclaration.value = asyncValue;
5236 asyncQueue.add(function () {
5237 if (
5238 isAsyncCancelled() ||
5239 currentRenderId !== renderId
5240 ) {
5241 return;
5242 }
5243 rebuildAsyncRule(asyncKey);
5244 });
5245 });
5246 }
5247 function handleVarDeclarations(
5248 property,
5249 modified,
5250 important,
5251 sourceValue
5252 ) {
5253 var _a = modified,
5254 varDecs = _a.declarations,
5255 onTypeChange = _a.onTypeChange;
5256 var varKey = ++varDeclarationCounter;
5257 var currentRenderId = renderId;
5258 var initialIndex = readyDeclarations.length;
5259 var oldDecs = [];
5260 if (varDecs.length === 0) {
5261 var tempDec = {
5262 property: property,
5263 value: sourceValue,
5264 important: important,
5265 sourceValue: sourceValue,
5266 varKey: varKey
5267 };
5268 readyDeclarations.push(tempDec);
5269 oldDecs = [tempDec];
5270 }
5271 varDecs.forEach(function (mod) {
5272 if (mod.value instanceof Promise) {
5273 handleAsyncDeclaration(
5274 mod.property,
5275 mod.value,
5276 important,
5277 sourceValue
5278 );
5279 } else {
5280 var readyDec = {
5281 property: mod.property,
5282 value: mod.value,
5283 important: important,
5284 sourceValue: sourceValue,
5285 varKey: varKey
5286 };
5287 readyDeclarations.push(readyDec);
5288 oldDecs.push(readyDec);
5289 }
5290 });
5291 onTypeChange.addListener(function (newDecs) {
5292 if (
5293 isAsyncCancelled() ||
5294 currentRenderId !== renderId
5295 ) {
5296 return;
5297 }
5298 var readyVarDecs = newDecs.map(function (mod) {
5299 return {
5300 property: mod.property,
5301 value: mod.value,
5302 important: important,
5303 sourceValue: sourceValue,
5304 varKey: varKey
5305 };
5306 });
5307 var index = readyDeclarations.indexOf(
5308 oldDecs[0],
5309 initialIndex
5310 );
5311 readyDeclarations.splice.apply(
5312 readyDeclarations,
5313 __spreadArray(
5314 [index, oldDecs.length],
5315 __read(readyVarDecs),
5316 false
5317 )
5318 );
5319 oldDecs = readyVarDecs;
5320 rebuildVarRule(varKey);
5321 });
5322 varTypeChangeCleaners.add(function () {
5323 return onTypeChange.removeListeners();
5324 });
5325 }
5326 declarations.forEach(function (_a) {
5327 var property = _a.property,
5328 value = _a.value,
5329 important = _a.important,
5330 sourceValue = _a.sourceValue;
5331 if (typeof value === "function") {
5332 var modified = value(theme);
5333 if (modified instanceof Promise) {
5334 handleAsyncDeclaration(
5335 property,
5336 modified,
5337 important,
5338 sourceValue
5339 );
5340 } else if (property.startsWith("--")) {
5341 handleVarDeclarations(
5342 property,
5343 modified,
5344 important,
5345 sourceValue
5346 );
5347 } else {
5348 readyDeclarations.push({
5349 property: property,
5350 value: modified,
5351 important: important,
5352 sourceValue: sourceValue
5353 });
5354 }
5355 } else {
5356 readyDeclarations.push({
5357 property: property,
5358 value: value,
5359 important: important,
5360 sourceValue: sourceValue
5361 });
5362 }
5363 });
5364 });
5365 var sheet = prepareSheet();
5366 function buildStyleSheet() {
5367 function createTarget(group, parent) {
5368 var rule = group.rule;
5369 if (rule instanceof CSSMediaRule) {
5370 var media = rule.media;
5371 var index = parent.cssRules.length;
5372 parent.insertRule(
5373 "@media ".concat(media.mediaText, " {}"),
5374 index
5375 );
5376 return parent.cssRules[index];
5377 }
5378 return parent;
5379 }
5380 function iterateReadyRules(group, target, styleIterator) {
5381 group.rules.forEach(function (r) {
5382 if (r.isGroup) {
5383 var t = createTarget(r, target);
5384 iterateReadyRules(r, t, styleIterator);
5385 } else {
5386 styleIterator(r, target);
5387 }
5388 });
5389 }
5390 iterateReadyRules(
5391 rootReadyGroup,
5392 sheet,
5393 function (rule, target) {
5394 var index = target.cssRules.length;
5395 rule.declarations.forEach(function (_a) {
5396 var asyncKey = _a.asyncKey,
5397 varKey = _a.varKey;
5398 if (asyncKey != null) {
5399 asyncDeclarations.set(asyncKey, {
5400 rule: rule,
5401 target: target,
5402 index: index
5403 });
5404 }
5405 if (varKey != null) {
5406 varDeclarations.set(varKey, {
5407 rule: rule,
5408 target: target,
5409 index: index
5410 });
5411 }
5412 });
5413 setRule(target, index, rule);
5414 }
5415 );
5416 }
5417 function rebuildAsyncRule(key) {
5418 var _a = asyncDeclarations.get(key),
5419 rule = _a.rule,
5420 target = _a.target,
5421 index = _a.index;
5422 target.deleteRule(index);
5423 setRule(target, index, rule);
5424 asyncDeclarations.delete(key);
5425 }
5426 function rebuildVarRule(key) {
5427 var _a = varDeclarations.get(key),
5428 rule = _a.rule,
5429 target = _a.target,
5430 index = _a.index;
5431 target.deleteRule(index);
5432 setRule(target, index, rule);
5433 }
5434 buildStyleSheet();
5435 }
5436 return {
5437 modifySheet: modifySheet,
5438 shouldRebuildStyle: shouldRebuildStyle
5439 };
5440 }
5441
5442 var STYLE_SELECTOR = 'style, link[rel*="stylesheet" i]:not([disabled])';
5443 function isFontsGoogleApiStyle(element) {
5444 if (!element.href) {
5445 return false;
5446 }
5447 try {
5448 var elementURL = new URL(element.href);
5449 return elementURL.hostname === "fonts.googleapis.com";
5450 } catch (err) {
5451 logInfo("Couldn't construct ".concat(element.href, " as URL"));
5452 return false;
5453 }
5454 }
5455 function shouldManageStyle(element) {
5456 return (
5457 (element instanceof HTMLStyleElement ||
5458 element instanceof SVGStyleElement ||
5459 (element instanceof HTMLLinkElement &&
5460 element.rel &&
5461 element.rel.toLowerCase().includes("stylesheet") &&
5462 element.href &&
5463 !element.disabled &&
5464 (isFirefox
5465 ? !element.href.startsWith("moz-extension://")
5466 : true) &&
5467 !isFontsGoogleApiStyle(element))) &&
5468 !element.classList.contains("darkreader") &&
5469 element.media.toLowerCase() !== "print" &&
5470 !element.classList.contains("stylus")
5471 );
5472 }
5473 function getManageableStyles(node, results, deep) {
5474 if (results === void 0) {
5475 results = [];
5476 }
5477 if (deep === void 0) {
5478 deep = true;
5479 }
5480 if (shouldManageStyle(node)) {
5481 results.push(node);
5482 } else if (
5483 node instanceof Element ||
5484 (isShadowDomSupported && node instanceof ShadowRoot) ||
5485 node === document
5486 ) {
5487 forEach(node.querySelectorAll(STYLE_SELECTOR), function (style) {
5488 return getManageableStyles(style, results, false);
5489 });
5490 if (deep) {
5491 iterateShadowHosts(node, function (host) {
5492 return getManageableStyles(host.shadowRoot, results, false);
5493 });
5494 }
5495 }
5496 return results;
5497 }
5498 var syncStyleSet = new WeakSet();
5499 var corsStyleSet = new WeakSet();
5500 var canOptimizeUsingProxy$1 = false;
5501 document.addEventListener(
5502 "__darkreader__inlineScriptsAllowed",
5503 function () {
5504 canOptimizeUsingProxy$1 = true;
5505 }
5506 );
5507 var loadingLinkCounter = 0;
5508 var rejectorsForLoadingLinks = new Map();
5509 function cleanLoadingLinks() {
5510 rejectorsForLoadingLinks.clear();
5511 }
5512 function manageStyle(element, _a) {
5513 var update = _a.update,
5514 loadingStart = _a.loadingStart,
5515 loadingEnd = _a.loadingEnd;
5516 var prevStyles = [];
5517 var next = element;
5518 while (
5519 (next = next.nextElementSibling) &&
5520 next.matches(".darkreader")
5521 ) {
5522 prevStyles.push(next);
5523 }
5524 var corsCopy =
5525 prevStyles.find(function (el) {
5526 return el.matches(".darkreader--cors") && !corsStyleSet.has(el);
5527 }) || null;
5528 var syncStyle =
5529 prevStyles.find(function (el) {
5530 return el.matches(".darkreader--sync") && !syncStyleSet.has(el);
5531 }) || null;
5532 var corsCopyPositionWatcher = null;
5533 var syncStylePositionWatcher = null;
5534 var cancelAsyncOperations = false;
5535 var isOverrideEmpty = true;
5536 var sheetModifier = createStyleSheetModifier();
5537 var observer = new MutationObserver(function () {
5538 update();
5539 });
5540 var observerOptions = {
5541 attributes: true,
5542 childList: true,
5543 subtree: true,
5544 characterData: true
5545 };
5546 function containsCSSImport() {
5547 return (
5548 element instanceof HTMLStyleElement &&
5549 element.textContent.trim().match(cssImportRegex)
5550 );
5551 }
5552 function hasImports(cssRules, checkCrossOrigin) {
5553 var result = false;
5554 if (cssRules) {
5555 var rule = void 0;
5556 cssRulesLoop: for (
5557 var i = 0, len = cssRules.length;
5558 i < len;
5559 i++
5560 ) {
5561 rule = cssRules[i];
5562 if (rule.href) {
5563 if (checkCrossOrigin) {
5564 if (
5565 rule.href.startsWith("http") &&
5566 !rule.href.startsWith(location.origin)
5567 ) {
5568 result = true;
5569 break cssRulesLoop;
5570 }
5571 } else {
5572 result = true;
5573 break cssRulesLoop;
5574 }
5575 }
5576 }
5577 }
5578 return result;
5579 }
5580 function getRulesSync() {
5581 if (corsCopy) {
5582 return corsCopy.sheet.cssRules;
5583 }
5584 if (containsCSSImport()) {
5585 return null;
5586 }
5587 var cssRules = safeGetSheetRules();
5588 if (
5589 element instanceof HTMLLinkElement &&
5590 !isRelativeHrefOnAbsolutePath(element.href) &&
5591 hasImports(cssRules, false)
5592 ) {
5593 return null;
5594 }
5595 if (hasImports(cssRules, true)) {
5596 return null;
5597 }
5598 return cssRules;
5599 }
5600 function insertStyle() {
5601 if (corsCopy) {
5602 if (element.nextSibling !== corsCopy) {
5603 element.parentNode.insertBefore(
5604 corsCopy,
5605 element.nextSibling
5606 );
5607 }
5608 if (corsCopy.nextSibling !== syncStyle) {
5609 element.parentNode.insertBefore(
5610 syncStyle,
5611 corsCopy.nextSibling
5612 );
5613 }
5614 } else if (element.nextSibling !== syncStyle) {
5615 element.parentNode.insertBefore(syncStyle, element.nextSibling);
5616 }
5617 }
5618 function createSyncStyle() {
5619 syncStyle =
5620 element instanceof SVGStyleElement
5621 ? document.createElementNS(
5622 "http://www.w3.org/2000/svg",
5623 "style"
5624 )
5625 : document.createElement("style");
5626 syncStyle.classList.add("darkreader");
5627 syncStyle.classList.add("darkreader--sync");
5628 syncStyle.media = "screen";
5629 if (element.title) {
5630 syncStyle.title = element.title;
5631 }
5632 syncStyleSet.add(syncStyle);
5633 }
5634 var isLoadingRules = false;
5635 var wasLoadingError = false;
5636 var loadingLinkId = ++loadingLinkCounter;
5637 function getRulesAsync() {
5638 return __awaiter(this, void 0, void 0, function () {
5639 var cssText,
5640 cssBasePath,
5641 _a,
5642 cssRules,
5643 accessError,
5644 fullCSSText;
5645 var _b;
5646 return __generator(this, function (_c) {
5647 switch (_c.label) {
5648 case 0:
5649 if (!(element instanceof HTMLLinkElement))
5650 return [3, 7];
5651 (_a = __read(getRulesOrError(), 2)),
5652 (cssRules = _a[0]),
5653 (accessError = _a[1]);
5654 if (
5655 !(
5656 (!cssRules && !accessError && !isSafari) ||
5657 (isSafari && !element.sheet) ||
5658 isStillLoadingError(accessError)
5659 )
5660 )
5661 return [3, 5];
5662 _c.label = 1;
5663 case 1:
5664 _c.trys.push([1, 3, , 4]);
5665 return [4, linkLoading(element, loadingLinkId)];
5666 case 2:
5667 _c.sent();
5668 return [3, 4];
5669 case 3:
5670 _c.sent();
5671 wasLoadingError = true;
5672 return [3, 4];
5673 case 4:
5674 if (cancelAsyncOperations) {
5675 return [2, null];
5676 }
5677 (_b = __read(getRulesOrError(), 2)),
5678 (cssRules = _b[0]),
5679 (accessError = _b[1]);
5680 _c.label = 5;
5681 case 5:
5682 if (cssRules) {
5683 if (!hasImports(cssRules, false)) {
5684 return [2, cssRules];
5685 }
5686 }
5687 return [4, loadText(element.href)];
5688 case 6:
5689 cssText = _c.sent();
5690 cssBasePath = getCSSBaseBath(element.href);
5691 if (cancelAsyncOperations) {
5692 return [2, null];
5693 }
5694 return [3, 8];
5695 case 7:
5696 if (containsCSSImport()) {
5697 cssText = element.textContent.trim();
5698 cssBasePath = getCSSBaseBath(location.href);
5699 } else {
5700 return [2, null];
5701 }
5702 _c.label = 8;
5703 case 8:
5704 if (!cssText) return [3, 13];
5705 _c.label = 9;
5706 case 9:
5707 _c.trys.push([9, 11, , 12]);
5708 return [4, replaceCSSImports(cssText, cssBasePath)];
5709 case 10:
5710 fullCSSText = _c.sent();
5711 corsCopy = createCORSCopy(element, fullCSSText);
5712 return [3, 12];
5713 case 11:
5714 _c.sent();
5715 return [3, 12];
5716 case 12:
5717 if (corsCopy) {
5718 corsCopyPositionWatcher = watchForNodePosition(
5719 corsCopy,
5720 "prev-sibling"
5721 );
5722 return [2, corsCopy.sheet.cssRules];
5723 }
5724 _c.label = 13;
5725 case 13:
5726 return [2, null];
5727 }
5728 });
5729 });
5730 }
5731 function details(options) {
5732 var rules = getRulesSync();
5733 if (!rules) {
5734 if (options.secondRound) {
5735 return null;
5736 }
5737 if (isLoadingRules || wasLoadingError) {
5738 return null;
5739 }
5740 isLoadingRules = true;
5741 loadingStart();
5742 getRulesAsync()
5743 .then(function (results) {
5744 isLoadingRules = false;
5745 loadingEnd();
5746 if (results) {
5747 update();
5748 }
5749 })
5750 .catch(function (err) {
5751 isLoadingRules = false;
5752 loadingEnd();
5753 });
5754 return null;
5755 }
5756 return {rules: rules};
5757 }
5758 var forceRenderStyle = false;
5759 function render(theme, ignoreImageAnalysis) {
5760 var rules = getRulesSync();
5761 if (!rules) {
5762 return;
5763 }
5764 cancelAsyncOperations = false;
5765 function removeCSSRulesFromSheet(sheet) {
5766 for (var i = sheet.cssRules.length - 1; i >= 0; i--) {
5767 sheet.deleteRule(i);
5768 }
5769 }
5770 function prepareOverridesSheet() {
5771 if (!syncStyle) {
5772 createSyncStyle();
5773 }
5774 syncStylePositionWatcher && syncStylePositionWatcher.stop();
5775 insertStyle();
5776 if (syncStyle.sheet == null) {
5777 syncStyle.textContent = "";
5778 }
5779 var sheet = syncStyle.sheet;
5780 removeCSSRulesFromSheet(sheet);
5781 if (syncStylePositionWatcher) {
5782 syncStylePositionWatcher.run();
5783 } else {
5784 syncStylePositionWatcher = watchForNodePosition(
5785 syncStyle,
5786 "prev-sibling",
5787 function () {
5788 forceRenderStyle = true;
5789 buildOverrides();
5790 }
5791 );
5792 }
5793 return syncStyle.sheet;
5794 }
5795 function buildOverrides() {
5796 var force = forceRenderStyle;
5797 forceRenderStyle = false;
5798 sheetModifier.modifySheet({
5799 prepareSheet: prepareOverridesSheet,
5800 sourceCSSRules: rules,
5801 theme: theme,
5802 ignoreImageAnalysis: ignoreImageAnalysis,
5803 force: force,
5804 isAsyncCancelled: function () {
5805 return cancelAsyncOperations;
5806 }
5807 });
5808 isOverrideEmpty = syncStyle.sheet.cssRules.length === 0;
5809 if (sheetModifier.shouldRebuildStyle()) {
5810 addReadyStateCompleteListener(function () {
5811 return update();
5812 });
5813 }
5814 }
5815 buildOverrides();
5816 }
5817 function getRulesOrError() {
5818 try {
5819 if (element.sheet == null) {
5820 return [null, null];
5821 }
5822 return [element.sheet.cssRules, null];
5823 } catch (err) {
5824 return [null, err];
5825 }
5826 }
5827 function isStillLoadingError(error) {
5828 return error && error.message && error.message.includes("loading");
5829 }
5830 function safeGetSheetRules() {
5831 var _a = __read(getRulesOrError(), 2),
5832 cssRules = _a[0],
5833 err = _a[1];
5834 if (err) {
5835 return null;
5836 }
5837 return cssRules;
5838 }
5839 function watchForSheetChanges() {
5840 watchForSheetChangesUsingProxy();
5841 if (!(canOptimizeUsingProxy$1 && element.sheet)) {
5842 watchForSheetChangesUsingRAF();
5843 }
5844 }
5845 var rulesChangeKey = null;
5846 var rulesCheckFrameId = null;
5847 function getRulesChangeKey() {
5848 var rules = safeGetSheetRules();
5849 return rules ? rules.length : null;
5850 }
5851 function didRulesKeyChange() {
5852 return getRulesChangeKey() !== rulesChangeKey;
5853 }
5854 function watchForSheetChangesUsingRAF() {
5855 rulesChangeKey = getRulesChangeKey();
5856 stopWatchingForSheetChangesUsingRAF();
5857 var checkForUpdate = function () {
5858 if (didRulesKeyChange()) {
5859 rulesChangeKey = getRulesChangeKey();
5860 update();
5861 }
5862 if (canOptimizeUsingProxy$1 && element.sheet) {
5863 stopWatchingForSheetChangesUsingRAF();
5864 return;
5865 }
5866 rulesCheckFrameId = requestAnimationFrame(checkForUpdate);
5867 };
5868 checkForUpdate();
5869 }
5870 function stopWatchingForSheetChangesUsingRAF() {
5871 cancelAnimationFrame(rulesCheckFrameId);
5872 }
5873 var areSheetChangesPending = false;
5874 function onSheetChange() {
5875 canOptimizeUsingProxy$1 = true;
5876 stopWatchingForSheetChangesUsingRAF();
5877 if (areSheetChangesPending) {
5878 return;
5879 }
5880 function handleSheetChanges() {
5881 areSheetChangesPending = false;
5882 if (cancelAsyncOperations) {
5883 return;
5884 }
5885 update();
5886 }
5887 areSheetChangesPending = true;
5888 if (typeof queueMicrotask === "function") {
5889 queueMicrotask(handleSheetChanges);
5890 } else {
5891 requestAnimationFrame(handleSheetChanges);
5892 }
5893 }
5894 function watchForSheetChangesUsingProxy() {
5895 element.addEventListener(
5896 "__darkreader__updateSheet",
5897 onSheetChange
5898 );
5899 }
5900 function stopWatchingForSheetChangesUsingProxy() {
5901 element.removeEventListener(
5902 "__darkreader__updateSheet",
5903 onSheetChange
5904 );
5905 }
5906 function stopWatchingForSheetChanges() {
5907 stopWatchingForSheetChangesUsingProxy();
5908 stopWatchingForSheetChangesUsingRAF();
5909 }
5910 function pause() {
5911 observer.disconnect();
5912 cancelAsyncOperations = true;
5913 corsCopyPositionWatcher && corsCopyPositionWatcher.stop();
5914 syncStylePositionWatcher && syncStylePositionWatcher.stop();
5915 stopWatchingForSheetChanges();
5916 }
5917 function destroy() {
5918 pause();
5919 removeNode(corsCopy);
5920 removeNode(syncStyle);
5921 loadingEnd();
5922 if (rejectorsForLoadingLinks.has(loadingLinkId)) {
5923 var reject = rejectorsForLoadingLinks.get(loadingLinkId);
5924 rejectorsForLoadingLinks.delete(loadingLinkId);
5925 reject && reject();
5926 }
5927 }
5928 function watch() {
5929 observer.observe(element, observerOptions);
5930 if (element instanceof HTMLStyleElement) {
5931 watchForSheetChanges();
5932 }
5933 }
5934 var maxMoveCount = 10;
5935 var moveCount = 0;
5936 function restore() {
5937 if (!syncStyle) {
5938 return;
5939 }
5940 moveCount++;
5941 if (moveCount > maxMoveCount) {
5942 return;
5943 }
5944 insertStyle();
5945 corsCopyPositionWatcher && corsCopyPositionWatcher.skip();
5946 syncStylePositionWatcher && syncStylePositionWatcher.skip();
5947 if (!isOverrideEmpty) {
5948 forceRenderStyle = true;
5949 update();
5950 }
5951 }
5952 return {
5953 details: details,
5954 render: render,
5955 pause: pause,
5956 destroy: destroy,
5957 watch: watch,
5958 restore: restore
5959 };
5960 }
5961 function linkLoading(link, loadingId) {
5962 return __awaiter(this, void 0, void 0, function () {
5963 return __generator(this, function (_a) {
5964 return [
5965 2,
5966 new Promise(function (resolve, reject) {
5967 var cleanUp = function () {
5968 link.removeEventListener("load", onLoad);
5969 link.removeEventListener("error", onError);
5970 rejectorsForLoadingLinks.delete(loadingId);
5971 };
5972 var onLoad = function () {
5973 cleanUp();
5974 resolve();
5975 };
5976 var onError = function () {
5977 cleanUp();
5978 reject(
5979 "Linkelement "
5980 .concat(loadingId, " couldn't be loaded. ")
5981 .concat(link.href)
5982 );
5983 };
5984 rejectorsForLoadingLinks.set(loadingId, function () {
5985 cleanUp();
5986 reject();
5987 });
5988 link.addEventListener("load", onLoad);
5989 link.addEventListener("error", onError);
5990 if (!link.href) {
5991 onError();
5992 }
5993 })
5994 ];
5995 });
5996 });
5997 }
5998 function getCSSImportURL(importDeclaration) {
5999 return getCSSURLValue(
6000 importDeclaration
6001 .substring(7)
6002 .trim()
6003 .replace(/;$/, "")
6004 .replace(/screen$/, "")
6005 );
6006 }
6007 function loadText(url) {
6008 return __awaiter(this, void 0, void 0, function () {
6009 return __generator(this, function (_a) {
6010 switch (_a.label) {
6011 case 0:
6012 if (!url.startsWith("data:")) return [3, 3];
6013 return [4, fetch(url)];
6014 case 1:
6015 return [4, _a.sent().text()];
6016 case 2:
6017 return [2, _a.sent()];
6018 case 3:
6019 return [
6020 4,
6021 bgFetch({
6022 url: url,
6023 responseType: "text",
6024 mimeType: "text/css",
6025 origin: window.location.origin
6026 })
6027 ];
6028 case 4:
6029 return [2, _a.sent()];
6030 }
6031 });
6032 });
6033 }
6034 function replaceCSSImports(cssText, basePath, cache) {
6035 if (cache === void 0) {
6036 cache = new Map();
6037 }
6038 return __awaiter(this, void 0, void 0, function () {
6039 var importMatches,
6040 importMatches_1,
6041 importMatches_1_1,
6042 match,
6043 importURL,
6044 absoluteURL,
6045 importedCSS,
6046 e_1_1;
6047 var e_1, _a;
6048 return __generator(this, function (_b) {
6049 switch (_b.label) {
6050 case 0:
6051 cssText = removeCSSComments(cssText);
6052 cssText = replaceCSSFontFace(cssText);
6053 cssText = replaceCSSRelativeURLsWithAbsolute(
6054 cssText,
6055 basePath
6056 );
6057 importMatches = getMatches(cssImportRegex, cssText);
6058 _b.label = 1;
6059 case 1:
6060 _b.trys.push([1, 10, 11, 12]);
6061 (importMatches_1 = __values(importMatches)),
6062 (importMatches_1_1 = importMatches_1.next());
6063 _b.label = 2;
6064 case 2:
6065 if (!!importMatches_1_1.done) return [3, 9];
6066 match = importMatches_1_1.value;
6067 importURL = getCSSImportURL(match);
6068 absoluteURL = getAbsoluteURL(basePath, importURL);
6069 importedCSS = void 0;
6070 if (!cache.has(absoluteURL)) return [3, 3];
6071 importedCSS = cache.get(absoluteURL);
6072 return [3, 7];
6073 case 3:
6074 _b.trys.push([3, 6, , 7]);
6075 return [4, loadText(absoluteURL)];
6076 case 4:
6077 importedCSS = _b.sent();
6078 cache.set(absoluteURL, importedCSS);
6079 return [
6080 4,
6081 replaceCSSImports(
6082 importedCSS,
6083 getCSSBaseBath(absoluteURL),
6084 cache
6085 )
6086 ];
6087 case 5:
6088 importedCSS = _b.sent();
6089 return [3, 7];
6090 case 6:
6091 _b.sent();
6092 importedCSS = "";
6093 return [3, 7];
6094 case 7:
6095 cssText = cssText.split(match).join(importedCSS);
6096 _b.label = 8;
6097 case 8:
6098 importMatches_1_1 = importMatches_1.next();
6099 return [3, 2];
6100 case 9:
6101 return [3, 12];
6102 case 10:
6103 e_1_1 = _b.sent();
6104 e_1 = {error: e_1_1};
6105 return [3, 12];
6106 case 11:
6107 try {
6108 if (
6109 importMatches_1_1 &&
6110 !importMatches_1_1.done &&
6111 (_a = importMatches_1.return)
6112 )
6113 _a.call(importMatches_1);
6114 } finally {
6115 if (e_1) throw e_1.error;
6116 }
6117 return [7];
6118 case 12:
6119 cssText = cssText.trim();
6120 return [2, cssText];
6121 }
6122 });
6123 });
6124 }
6125 function createCORSCopy(srcElement, cssText) {
6126 if (!cssText) {
6127 return null;
6128 }
6129 var cors = document.createElement("style");
6130 cors.classList.add("darkreader");
6131 cors.classList.add("darkreader--cors");
6132 cors.media = "screen";
6133 cors.textContent = cssText;
6134 srcElement.parentNode.insertBefore(cors, srcElement.nextSibling);
6135 cors.sheet.disabled = true;
6136 corsStyleSet.add(cors);
6137 return cors;
6138 }
6139
6140 var observers = [];
6141 var observedRoots;
6142 var undefinedGroups = new Map();
6143 var elementsDefinitionCallback;
6144 function collectUndefinedElements(root) {
6145 if (!isDefinedSelectorSupported) {
6146 return;
6147 }
6148 forEach(root.querySelectorAll(":not(:defined)"), function (el) {
6149 var tag = el.tagName.toLowerCase();
6150 if (!tag.includes("-")) {
6151 var extendedTag = el.getAttribute("is");
6152 if (extendedTag) {
6153 tag = extendedTag;
6154 } else {
6155 return;
6156 }
6157 }
6158 if (!undefinedGroups.has(tag)) {
6159 undefinedGroups.set(tag, new Set());
6160 customElementsWhenDefined(tag).then(function () {
6161 if (elementsDefinitionCallback) {
6162 var elements = undefinedGroups.get(tag);
6163 undefinedGroups.delete(tag);
6164 elementsDefinitionCallback(Array.from(elements));
6165 }
6166 });
6167 }
6168 undefinedGroups.get(tag).add(el);
6169 });
6170 }
6171 var canOptimizeUsingProxy = false;
6172 document.addEventListener(
6173 "__darkreader__inlineScriptsAllowed",
6174 function () {
6175 canOptimizeUsingProxy = true;
6176 }
6177 );
6178 var resolvers = new Map();
6179 function handleIsDefined(e) {
6180 canOptimizeUsingProxy = true;
6181 if (resolvers.has(e.detail.tag)) {
6182 var resolve = resolvers.get(e.detail.tag);
6183 resolve();
6184 }
6185 }
6186 function customElementsWhenDefined(tag) {
6187 return __awaiter(this, void 0, void 0, function () {
6188 return __generator(this, function (_a) {
6189 return [
6190 2,
6191 new Promise(function (resolve) {
6192 if (
6193 window.customElements &&
6194 typeof customElements.whenDefined === "function"
6195 ) {
6196 customElements.whenDefined(tag).then(function () {
6197 return resolve();
6198 });
6199 } else if (canOptimizeUsingProxy) {
6200 resolvers.set(tag, resolve);
6201 document.dispatchEvent(
6202 new CustomEvent(
6203 "__darkreader__addUndefinedResolver",
6204 {detail: {tag: tag}}
6205 )
6206 );
6207 } else {
6208 var checkIfDefined_1 = function () {
6209 var elements = undefinedGroups.get(tag);
6210 if (elements && elements.size > 0) {
6211 if (
6212 elements
6213 .values()
6214 .next()
6215 .value.matches(":defined")
6216 ) {
6217 resolve();
6218 } else {
6219 requestAnimationFrame(checkIfDefined_1);
6220 }
6221 }
6222 };
6223 requestAnimationFrame(checkIfDefined_1);
6224 }
6225 })
6226 ];
6227 });
6228 });
6229 }
6230 function watchWhenCustomElementsDefined(callback) {
6231 elementsDefinitionCallback = callback;
6232 }
6233 function unsubscribeFromDefineCustomElements() {
6234 elementsDefinitionCallback = null;
6235 undefinedGroups.clear();
6236 document.removeEventListener(
6237 "__darkreader__isDefined",
6238 handleIsDefined
6239 );
6240 }
6241 function watchForStyleChanges(currentStyles, update, shadowRootDiscovered) {
6242 stopWatchingForStyleChanges();
6243 var prevStyles = new Set(currentStyles);
6244 var prevStyleSiblings = new WeakMap();
6245 var nextStyleSiblings = new WeakMap();
6246 function saveStylePosition(style) {
6247 prevStyleSiblings.set(style, style.previousElementSibling);
6248 nextStyleSiblings.set(style, style.nextElementSibling);
6249 }
6250 function forgetStylePosition(style) {
6251 prevStyleSiblings.delete(style);
6252 nextStyleSiblings.delete(style);
6253 }
6254 function didStylePositionChange(style) {
6255 return (
6256 style.previousElementSibling !== prevStyleSiblings.get(style) ||
6257 style.nextElementSibling !== nextStyleSiblings.get(style)
6258 );
6259 }
6260 currentStyles.forEach(saveStylePosition);
6261 function handleStyleOperations(operations) {
6262 var createdStyles = operations.createdStyles,
6263 removedStyles = operations.removedStyles,
6264 movedStyles = operations.movedStyles;
6265 createdStyles.forEach(function (s) {
6266 return saveStylePosition(s);
6267 });
6268 movedStyles.forEach(function (s) {
6269 return saveStylePosition(s);
6270 });
6271 removedStyles.forEach(function (s) {
6272 return forgetStylePosition(s);
6273 });
6274 createdStyles.forEach(function (s) {
6275 return prevStyles.add(s);
6276 });
6277 removedStyles.forEach(function (s) {
6278 return prevStyles.delete(s);
6279 });
6280 if (
6281 createdStyles.size + removedStyles.size + movedStyles.size >
6282 0
6283 ) {
6284 update({
6285 created: Array.from(createdStyles),
6286 removed: Array.from(removedStyles),
6287 moved: Array.from(movedStyles),
6288 updated: []
6289 });
6290 }
6291 }
6292 function handleMinorTreeMutations(_a) {
6293 var additions = _a.additions,
6294 moves = _a.moves,
6295 deletions = _a.deletions;
6296 var createdStyles = new Set();
6297 var removedStyles = new Set();
6298 var movedStyles = new Set();
6299 additions.forEach(function (node) {
6300 return getManageableStyles(node).forEach(function (style) {
6301 return createdStyles.add(style);
6302 });
6303 });
6304 deletions.forEach(function (node) {
6305 return getManageableStyles(node).forEach(function (style) {
6306 return removedStyles.add(style);
6307 });
6308 });
6309 moves.forEach(function (node) {
6310 return getManageableStyles(node).forEach(function (style) {
6311 return movedStyles.add(style);
6312 });
6313 });
6314 handleStyleOperations({
6315 createdStyles: createdStyles,
6316 removedStyles: removedStyles,
6317 movedStyles: movedStyles
6318 });
6319 additions.forEach(function (n) {
6320 iterateShadowHosts(n, subscribeForShadowRootChanges);
6321 collectUndefinedElements(n);
6322 });
6323 }
6324 function handleHugeTreeMutations(root) {
6325 var styles = new Set(getManageableStyles(root));
6326 var createdStyles = new Set();
6327 var removedStyles = new Set();
6328 var movedStyles = new Set();
6329 styles.forEach(function (s) {
6330 if (!prevStyles.has(s)) {
6331 createdStyles.add(s);
6332 }
6333 });
6334 prevStyles.forEach(function (s) {
6335 if (!styles.has(s)) {
6336 removedStyles.add(s);
6337 }
6338 });
6339 styles.forEach(function (s) {
6340 if (
6341 !createdStyles.has(s) &&
6342 !removedStyles.has(s) &&
6343 didStylePositionChange(s)
6344 ) {
6345 movedStyles.add(s);
6346 }
6347 });
6348 handleStyleOperations({
6349 createdStyles: createdStyles,
6350 removedStyles: removedStyles,
6351 movedStyles: movedStyles
6352 });
6353 iterateShadowHosts(root, subscribeForShadowRootChanges);
6354 collectUndefinedElements(root);
6355 }
6356 function handleAttributeMutations(mutations) {
6357 var updatedStyles = new Set();
6358 var removedStyles = new Set();
6359 mutations.forEach(function (m) {
6360 var target = m.target;
6361 if (target.isConnected) {
6362 if (shouldManageStyle(target)) {
6363 updatedStyles.add(target);
6364 } else if (
6365 target instanceof HTMLLinkElement &&
6366 target.disabled
6367 ) {
6368 removedStyles.add(target);
6369 }
6370 }
6371 });
6372 if (updatedStyles.size + removedStyles.size > 0) {
6373 update({
6374 updated: Array.from(updatedStyles),
6375 created: [],
6376 removed: Array.from(removedStyles),
6377 moved: []
6378 });
6379 }
6380 }
6381 function observe(root) {
6382 var treeObserver = createOptimizedTreeObserver(root, {
6383 onMinorMutations: handleMinorTreeMutations,
6384 onHugeMutations: handleHugeTreeMutations
6385 });
6386 var attrObserver = new MutationObserver(handleAttributeMutations);
6387 attrObserver.observe(root, {
6388 attributes: true,
6389 attributeFilter: ["rel", "disabled", "media", "href"],
6390 subtree: true
6391 });
6392 observers.push(treeObserver, attrObserver);
6393 observedRoots.add(root);
6394 }
6395 function subscribeForShadowRootChanges(node) {
6396 var shadowRoot = node.shadowRoot;
6397 if (shadowRoot == null || observedRoots.has(shadowRoot)) {
6398 return;
6399 }
6400 observe(shadowRoot);
6401 shadowRootDiscovered(shadowRoot);
6402 }
6403 observe(document);
6404 iterateShadowHosts(
6405 document.documentElement,
6406 subscribeForShadowRootChanges
6407 );
6408 watchWhenCustomElementsDefined(function (hosts) {
6409 var newStyles = [];
6410 hosts.forEach(function (host) {
6411 return push(newStyles, getManageableStyles(host.shadowRoot));
6412 });
6413 update({created: newStyles, updated: [], removed: [], moved: []});
6414 hosts.forEach(function (host) {
6415 var shadowRoot = host.shadowRoot;
6416 if (shadowRoot == null) {
6417 return;
6418 }
6419 subscribeForShadowRootChanges(host);
6420 iterateShadowHosts(shadowRoot, subscribeForShadowRootChanges);
6421 collectUndefinedElements(shadowRoot);
6422 });
6423 });
6424 document.addEventListener("__darkreader__isDefined", handleIsDefined);
6425 collectUndefinedElements(document);
6426 }
6427 function resetObservers() {
6428 observers.forEach(function (o) {
6429 return o.disconnect();
6430 });
6431 observers.splice(0, observers.length);
6432 observedRoots = new WeakSet();
6433 }
6434 function stopWatchingForStyleChanges() {
6435 resetObservers();
6436 unsubscribeFromDefineCustomElements();
6437 }
6438
6439 function hexify(number) {
6440 return (number < 16 ? "0" : "") + number.toString(16);
6441 }
6442 function generateUID() {
6443 if ("randomUUID" in crypto) {
6444 var uuid = crypto.randomUUID();
6445 return (
6446 uuid.substring(0, 8) +
6447 uuid.substring(9, 13) +
6448 uuid.substring(14, 18) +
6449 uuid.substring(19, 23) +
6450 uuid.substring(24)
6451 );
6452 }
6453 return Array.from(crypto.getRandomValues(new Uint8Array(16)))
6454 .map(function (x) {
6455 return hexify(x);
6456 })
6457 .join("");
6458 }
6459
6460 var adoptedStyleOverrides = new WeakMap();
6461 var overrideList = new WeakSet();
6462 function createAdoptedStyleSheetOverride(node) {
6463 var cancelAsyncOperations = false;
6464 function injectSheet(sheet, override) {
6465 var newSheets = __spreadArray(
6466 [],
6467 __read(node.adoptedStyleSheets),
6468 false
6469 );
6470 var sheetIndex = newSheets.indexOf(sheet);
6471 var existingIndex = newSheets.indexOf(override);
6472 if (sheetIndex === existingIndex - 1) {
6473 return;
6474 }
6475 if (existingIndex >= 0) {
6476 newSheets.splice(existingIndex, 1);
6477 }
6478 newSheets.splice(sheetIndex + 1, 0, override);
6479 node.adoptedStyleSheets = newSheets;
6480 }
6481 function destroy() {
6482 cancelAsyncOperations = true;
6483 var newSheets = __spreadArray(
6484 [],
6485 __read(node.adoptedStyleSheets),
6486 false
6487 );
6488 node.adoptedStyleSheets.forEach(function (adoptedStyleSheet) {
6489 if (overrideList.has(adoptedStyleSheet)) {
6490 var existingIndex = newSheets.indexOf(adoptedStyleSheet);
6491 if (existingIndex >= 0) {
6492 newSheets.splice(existingIndex, 1);
6493 }
6494 adoptedStyleOverrides.delete(adoptedStyleSheet);
6495 overrideList.delete(adoptedStyleSheet);
6496 }
6497 });
6498 node.adoptedStyleSheets = newSheets;
6499 }
6500 function render(theme, ignoreImageAnalysis) {
6501 node.adoptedStyleSheets.forEach(function (sheet) {
6502 if (overrideList.has(sheet)) {
6503 return;
6504 }
6505 var rules = sheet.rules;
6506 var override = new CSSStyleSheet();
6507 function prepareOverridesSheet() {
6508 for (var i = override.cssRules.length - 1; i >= 0; i--) {
6509 override.deleteRule(i);
6510 }
6511 injectSheet(sheet, override);
6512 adoptedStyleOverrides.set(sheet, override);
6513 overrideList.add(override);
6514 return override;
6515 }
6516 var sheetModifier = createStyleSheetModifier();
6517 sheetModifier.modifySheet({
6518 prepareSheet: prepareOverridesSheet,
6519 sourceCSSRules: rules,
6520 theme: theme,
6521 ignoreImageAnalysis: ignoreImageAnalysis,
6522 force: false,
6523 isAsyncCancelled: function () {
6524 return cancelAsyncOperations;
6525 }
6526 });
6527 });
6528 }
6529 return {
6530 render: render,
6531 destroy: destroy
6532 };
6533 }
6534
6535 function injectProxy(enableStyleSheetsProxy) {
6536 document.dispatchEvent(
6537 new CustomEvent("__darkreader__inlineScriptsAllowed")
6538 );
6539 var addRuleDescriptor = Object.getOwnPropertyDescriptor(
6540 CSSStyleSheet.prototype,
6541 "addRule"
6542 );
6543 var insertRuleDescriptor = Object.getOwnPropertyDescriptor(
6544 CSSStyleSheet.prototype,
6545 "insertRule"
6546 );
6547 var deleteRuleDescriptor = Object.getOwnPropertyDescriptor(
6548 CSSStyleSheet.prototype,
6549 "deleteRule"
6550 );
6551 var removeRuleDescriptor = Object.getOwnPropertyDescriptor(
6552 CSSStyleSheet.prototype,
6553 "removeRule"
6554 );
6555 var documentStyleSheetsDescriptor = enableStyleSheetsProxy
6556 ? Object.getOwnPropertyDescriptor(Document.prototype, "styleSheets")
6557 : null;
6558 var shouldWrapHTMLElement = [
6559 "baidu.com",
6560 "baike.baidu.com",
6561 "ditu.baidu.com",
6562 "map.baidu.com",
6563 "maps.baidu.com",
6564 "haokan.baidu.com",
6565 "pan.baidu.com",
6566 "passport.baidu.com",
6567 "tieba.baidu.com",
6568 "www.baidu.com"
6569 ].includes(location.hostname);
6570 var getElementsByTagNameDescriptor = shouldWrapHTMLElement
6571 ? Object.getOwnPropertyDescriptor(
6572 Element.prototype,
6573 "getElementsByTagName"
6574 )
6575 : null;
6576 var cleanUp = function () {
6577 Object.defineProperty(
6578 CSSStyleSheet.prototype,
6579 "addRule",
6580 addRuleDescriptor
6581 );
6582 Object.defineProperty(
6583 CSSStyleSheet.prototype,
6584 "insertRule",
6585 insertRuleDescriptor
6586 );
6587 Object.defineProperty(
6588 CSSStyleSheet.prototype,
6589 "deleteRule",
6590 deleteRuleDescriptor
6591 );
6592 Object.defineProperty(
6593 CSSStyleSheet.prototype,
6594 "removeRule",
6595 removeRuleDescriptor
6596 );
6597 document.removeEventListener("__darkreader__cleanUp", cleanUp);
6598 document.removeEventListener(
6599 "__darkreader__addUndefinedResolver",
6600 addUndefinedResolver
6601 );
6602 if (enableStyleSheetsProxy) {
6603 Object.defineProperty(
6604 Document.prototype,
6605 "styleSheets",
6606 documentStyleSheetsDescriptor
6607 );
6608 }
6609 if (shouldWrapHTMLElement) {
6610 Object.defineProperty(
6611 Element.prototype,
6612 "getElementsByTagName",
6613 getElementsByTagNameDescriptor
6614 );
6615 }
6616 };
6617 var addUndefinedResolver = function (e) {
6618 customElements.whenDefined(e.detail.tag).then(function () {
6619 document.dispatchEvent(
6620 new CustomEvent("__darkreader__isDefined", {
6621 detail: {tag: e.detail.tag}
6622 })
6623 );
6624 });
6625 };
6626 document.addEventListener("__darkreader__cleanUp", cleanUp);
6627 document.addEventListener(
6628 "__darkreader__addUndefinedResolver",
6629 addUndefinedResolver
6630 );
6631 var updateSheetEvent = new Event("__darkreader__updateSheet");
6632 function proxyAddRule(selector, style, index) {
6633 addRuleDescriptor.value.call(this, selector, style, index);
6634 if (
6635 this.ownerNode &&
6636 !this.ownerNode.classList.contains("darkreader")
6637 ) {
6638 this.ownerNode.dispatchEvent(updateSheetEvent);
6639 }
6640 return -1;
6641 }
6642 function proxyInsertRule(rule, index) {
6643 var returnValue = insertRuleDescriptor.value.call(
6644 this,
6645 rule,
6646 index
6647 );
6648 if (
6649 this.ownerNode &&
6650 !this.ownerNode.classList.contains("darkreader")
6651 ) {
6652 this.ownerNode.dispatchEvent(updateSheetEvent);
6653 }
6654 return returnValue;
6655 }
6656 function proxyDeleteRule(index) {
6657 deleteRuleDescriptor.value.call(this, index);
6658 if (
6659 this.ownerNode &&
6660 !this.ownerNode.classList.contains("darkreader")
6661 ) {
6662 this.ownerNode.dispatchEvent(updateSheetEvent);
6663 }
6664 }
6665 function proxyRemoveRule(index) {
6666 removeRuleDescriptor.value.call(this, index);
6667 if (
6668 this.ownerNode &&
6669 !this.ownerNode.classList.contains("darkreader")
6670 ) {
6671 this.ownerNode.dispatchEvent(updateSheetEvent);
6672 }
6673 }
6674 function proxyDocumentStyleSheets() {
6675 var _this = this;
6676 var getCurrentValue = function () {
6677 var docSheets = documentStyleSheetsDescriptor.get.call(_this);
6678 var filteredSheets = __spreadArray(
6679 [],
6680 __read(docSheets),
6681 false
6682 ).filter(function (styleSheet) {
6683 return !styleSheet.ownerNode.classList.contains(
6684 "darkreader"
6685 );
6686 });
6687 filteredSheets.item = function (item) {
6688 return filteredSheets[item];
6689 };
6690 return Object.setPrototypeOf(
6691 filteredSheets,
6692 StyleSheetList.prototype
6693 );
6694 };
6695 var elements = getCurrentValue();
6696 var styleSheetListBehavior = {
6697 get: function (_, property) {
6698 return getCurrentValue()[property];
6699 }
6700 };
6701 elements = new Proxy(elements, styleSheetListBehavior);
6702 return elements;
6703 }
6704 function proxyGetElementsByTagName(tagName) {
6705 var _this = this;
6706 if (tagName !== "style") {
6707 return getElementsByTagNameDescriptor.value.call(this, tagName);
6708 }
6709 var getCurrentElementValue = function () {
6710 var elements = getElementsByTagNameDescriptor.value.call(
6711 _this,
6712 tagName
6713 );
6714 return Object.setPrototypeOf(
6715 __spreadArray([], __read(elements), false).filter(function (
6716 element
6717 ) {
6718 return !element.classList.contains("darkreader");
6719 }),
6720 NodeList.prototype
6721 );
6722 };
6723 var elements = getCurrentElementValue();
6724 var nodeListBehavior = {
6725 get: function (_, property) {
6726 return getCurrentElementValue()[
6727 Number(property) || property
6728 ];
6729 }
6730 };
6731 elements = new Proxy(elements, nodeListBehavior);
6732 return elements;
6733 }
6734 Object.defineProperty(
6735 CSSStyleSheet.prototype,
6736 "addRule",
6737 Object.assign({}, addRuleDescriptor, {value: proxyAddRule})
6738 );
6739 Object.defineProperty(
6740 CSSStyleSheet.prototype,
6741 "insertRule",
6742 Object.assign({}, insertRuleDescriptor, {value: proxyInsertRule})
6743 );
6744 Object.defineProperty(
6745 CSSStyleSheet.prototype,
6746 "deleteRule",
6747 Object.assign({}, deleteRuleDescriptor, {value: proxyDeleteRule})
6748 );
6749 Object.defineProperty(
6750 CSSStyleSheet.prototype,
6751 "removeRule",
6752 Object.assign({}, removeRuleDescriptor, {value: proxyRemoveRule})
6753 );
6754 if (enableStyleSheetsProxy) {
6755 Object.defineProperty(
6756 Document.prototype,
6757 "styleSheets",
6758 Object.assign({}, documentStyleSheetsDescriptor, {
6759 get: proxyDocumentStyleSheets
6760 })
6761 );
6762 }
6763 if (shouldWrapHTMLElement) {
6764 Object.defineProperty(
6765 Element.prototype,
6766 "getElementsByTagName",
6767 Object.assign({}, getElementsByTagNameDescriptor, {
6768 value: proxyGetElementsByTagName
6769 })
6770 );
6771 }
6772 }
6773
6774 var INSTANCE_ID = generateUID();
6775 var styleManagers = new Map();
6776 var adoptedStyleManagers = [];
6777 var filter = null;
6778 var fixes = null;
6779 var isIFrame$1 = null;
6780 var ignoredImageAnalysisSelectors = null;
6781 var ignoredInlineSelectors = null;
6782 function createOrUpdateStyle(className, root) {
6783 if (root === void 0) {
6784 root = document.head || document;
6785 }
6786 var element = root.querySelector(".".concat(className));
6787 if (!element) {
6788 element = document.createElement("style");
6789 element.classList.add("darkreader");
6790 element.classList.add(className);
6791 element.media = "screen";
6792 element.textContent = "";
6793 }
6794 return element;
6795 }
6796 function createOrUpdateScript(className, root) {
6797 if (root === void 0) {
6798 root = document.head || document;
6799 }
6800 var element = root.querySelector(".".concat(className));
6801 if (!element) {
6802 element = document.createElement("script");
6803 element.classList.add("darkreader");
6804 element.classList.add(className);
6805 }
6806 return element;
6807 }
6808 var nodePositionWatchers = new Map();
6809 function setupNodePositionWatcher(node, alias) {
6810 nodePositionWatchers.has(alias) &&
6811 nodePositionWatchers.get(alias).stop();
6812 nodePositionWatchers.set(alias, watchForNodePosition(node, "parent"));
6813 }
6814 function stopStylePositionWatchers() {
6815 forEach(nodePositionWatchers.values(), function (watcher) {
6816 return watcher.stop();
6817 });
6818 nodePositionWatchers.clear();
6819 }
6820 function createStaticStyleOverrides() {
6821 var fallbackStyle = createOrUpdateStyle(
6822 "darkreader--fallback",
6823 document
6824 );
6825 fallbackStyle.textContent = getModifiedFallbackStyle(filter, {
6826 strict: true
6827 });
6828 document.head.insertBefore(fallbackStyle, document.head.firstChild);
6829 setupNodePositionWatcher(fallbackStyle, "fallback");
6830 var userAgentStyle = createOrUpdateStyle("darkreader--user-agent");
6831 userAgentStyle.textContent = getModifiedUserAgentStyle(
6832 filter,
6833 isIFrame$1,
6834 filter.styleSystemControls
6835 );
6836 document.head.insertBefore(userAgentStyle, fallbackStyle.nextSibling);
6837 setupNodePositionWatcher(userAgentStyle, "user-agent");
6838 var textStyle = createOrUpdateStyle("darkreader--text");
6839 if (filter.useFont || filter.textStroke > 0) {
6840 textStyle.textContent = createTextStyle(filter);
6841 } else {
6842 textStyle.textContent = "";
6843 }
6844 document.head.insertBefore(textStyle, fallbackStyle.nextSibling);
6845 setupNodePositionWatcher(textStyle, "text");
6846 var invertStyle = createOrUpdateStyle("darkreader--invert");
6847 if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {
6848 invertStyle.textContent = [
6849 "".concat(fixes.invert.join(", "), " {"),
6850 " filter: ".concat(
6851 getCSSFilterValue(
6852 __assign(__assign({}, filter), {
6853 contrast:
6854 filter.mode === 0
6855 ? filter.contrast
6856 : clamp(filter.contrast - 10, 0, 100)
6857 })
6858 ),
6859 " !important;"
6860 ),
6861 "}"
6862 ].join("\n");
6863 } else {
6864 invertStyle.textContent = "";
6865 }
6866 document.head.insertBefore(invertStyle, textStyle.nextSibling);
6867 setupNodePositionWatcher(invertStyle, "invert");
6868 var inlineStyle = createOrUpdateStyle("darkreader--inline");
6869 inlineStyle.textContent = getInlineOverrideStyle();
6870 document.head.insertBefore(inlineStyle, invertStyle.nextSibling);
6871 setupNodePositionWatcher(inlineStyle, "inline");
6872 var overrideStyle = createOrUpdateStyle("darkreader--override");
6873 overrideStyle.textContent =
6874 fixes && fixes.css ? replaceCSSTemplates(fixes.css) : "";
6875 document.head.appendChild(overrideStyle);
6876 setupNodePositionWatcher(overrideStyle, "override");
6877 var variableStyle = createOrUpdateStyle("darkreader--variables");
6878 var selectionColors = getSelectionColor(filter);
6879 var darkSchemeBackgroundColor = filter.darkSchemeBackgroundColor,
6880 darkSchemeTextColor = filter.darkSchemeTextColor,
6881 lightSchemeBackgroundColor = filter.lightSchemeBackgroundColor,
6882 lightSchemeTextColor = filter.lightSchemeTextColor,
6883 mode = filter.mode;
6884 var schemeBackgroundColor =
6885 mode === 0 ? lightSchemeBackgroundColor : darkSchemeBackgroundColor;
6886 var schemeTextColor =
6887 mode === 0 ? lightSchemeTextColor : darkSchemeTextColor;
6888 schemeBackgroundColor = modifyBackgroundColor(
6889 parseColorWithCache(schemeBackgroundColor),
6890 filter
6891 );
6892 schemeTextColor = modifyForegroundColor(
6893 parseColorWithCache(schemeTextColor),
6894 filter
6895 );
6896 variableStyle.textContent = [
6897 ":root {",
6898 " --darkreader-neutral-background: ".concat(
6899 schemeBackgroundColor,
6900 ";"
6901 ),
6902 " --darkreader-neutral-text: ".concat(schemeTextColor, ";"),
6903 " --darkreader-selection-background: ".concat(
6904 selectionColors.backgroundColorSelection,
6905 ";"
6906 ),
6907 " --darkreader-selection-text: ".concat(
6908 selectionColors.foregroundColorSelection,
6909 ";"
6910 ),
6911 "}"
6912 ].join("\n");
6913 document.head.insertBefore(variableStyle, inlineStyle.nextSibling);
6914 setupNodePositionWatcher(variableStyle, "variables");
6915 var rootVarsStyle = createOrUpdateStyle("darkreader--root-vars");
6916 document.head.insertBefore(rootVarsStyle, variableStyle.nextSibling);
6917 var injectProxyArg = !(fixes && fixes.disableStyleSheetsProxy);
6918 {
6919 var proxyScript = createOrUpdateScript("darkreader--proxy");
6920 proxyScript.append(
6921 "(".concat(injectProxy, ")(").concat(injectProxyArg, ")")
6922 );
6923 document.head.insertBefore(proxyScript, rootVarsStyle.nextSibling);
6924 proxyScript.remove();
6925 }
6926 }
6927 var shadowRootsWithOverrides = new Set();
6928 function createShadowStaticStyleOverrides(root) {
6929 var inlineStyle = createOrUpdateStyle("darkreader--inline", root);
6930 inlineStyle.textContent = getInlineOverrideStyle();
6931 root.insertBefore(inlineStyle, root.firstChild);
6932 var overrideStyle = createOrUpdateStyle("darkreader--override", root);
6933 overrideStyle.textContent =
6934 fixes && fixes.css ? replaceCSSTemplates(fixes.css) : "";
6935 root.insertBefore(overrideStyle, inlineStyle.nextSibling);
6936 var invertStyle = createOrUpdateStyle("darkreader--invert", root);
6937 if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {
6938 invertStyle.textContent = [
6939 "".concat(fixes.invert.join(", "), " {"),
6940 " filter: ".concat(
6941 getCSSFilterValue(
6942 __assign(__assign({}, filter), {
6943 contrast:
6944 filter.mode === 0
6945 ? filter.contrast
6946 : clamp(filter.contrast - 10, 0, 100)
6947 })
6948 ),
6949 " !important;"
6950 ),
6951 "}"
6952 ].join("\n");
6953 } else {
6954 invertStyle.textContent = "";
6955 }
6956 root.insertBefore(invertStyle, overrideStyle.nextSibling);
6957 shadowRootsWithOverrides.add(root);
6958 }
6959 function replaceCSSTemplates($cssText) {
6960 return $cssText.replace(/\${(.+?)}/g, function (_, $color) {
6961 var color = parseColorWithCache($color);
6962 if (color) {
6963 return modifyColor(color, filter);
6964 }
6965 return $color;
6966 });
6967 }
6968 function cleanFallbackStyle() {
6969 var fallback = document.querySelector(".darkreader--fallback");
6970 if (fallback) {
6971 fallback.textContent = "";
6972 }
6973 }
6974 function createDynamicStyleOverrides() {
6975 cancelRendering();
6976 var allStyles = getManageableStyles(document);
6977 var newManagers = allStyles
6978 .filter(function (style) {
6979 return !styleManagers.has(style);
6980 })
6981 .map(function (style) {
6982 return createManager(style);
6983 });
6984 newManagers
6985 .map(function (manager) {
6986 return manager.details({secondRound: false});
6987 })
6988 .filter(function (detail) {
6989 return detail && detail.rules.length > 0;
6990 })
6991 .forEach(function (detail) {
6992 variablesStore.addRulesForMatching(detail.rules);
6993 });
6994 variablesStore.matchVariablesAndDependants();
6995 variablesStore.setOnRootVariableChange(function () {
6996 variablesStore.putRootVars(
6997 document.head.querySelector(".darkreader--root-vars"),
6998 filter
6999 );
7000 });
7001 variablesStore.putRootVars(
7002 document.head.querySelector(".darkreader--root-vars"),
7003 filter
7004 );
7005 styleManagers.forEach(function (manager) {
7006 return manager.render(filter, ignoredImageAnalysisSelectors);
7007 });
7008 if (loadingStyles.size === 0) {
7009 cleanFallbackStyle();
7010 }
7011 newManagers.forEach(function (manager) {
7012 return manager.watch();
7013 });
7014 var inlineStyleElements = toArray(
7015 document.querySelectorAll(INLINE_STYLE_SELECTOR)
7016 );
7017 iterateShadowHosts(document.documentElement, function (host) {
7018 createShadowStaticStyleOverrides(host.shadowRoot);
7019 var elements = host.shadowRoot.querySelectorAll(
7020 INLINE_STYLE_SELECTOR
7021 );
7022 if (elements.length > 0) {
7023 push(inlineStyleElements, elements);
7024 }
7025 });
7026 inlineStyleElements.forEach(function (el) {
7027 return overrideInlineStyle(
7028 el,
7029 filter,
7030 ignoredInlineSelectors,
7031 ignoredImageAnalysisSelectors
7032 );
7033 });
7034 handleAdoptedStyleSheets(document);
7035 }
7036 var loadingStylesCounter = 0;
7037 var loadingStyles = new Set();
7038 function createManager(element) {
7039 var loadingStyleId = ++loadingStylesCounter;
7040 function loadingStart() {
7041 if (!isDOMReady() || !didDocumentShowUp) {
7042 loadingStyles.add(loadingStyleId);
7043 logInfo(
7044 "Current amount of styles loading: ".concat(
7045 loadingStyles.size
7046 )
7047 );
7048 var fallbackStyle = document.querySelector(
7049 ".darkreader--fallback"
7050 );
7051 if (!fallbackStyle.textContent) {
7052 fallbackStyle.textContent = getModifiedFallbackStyle(
7053 filter,
7054 {strict: false}
7055 );
7056 }
7057 }
7058 }
7059 function loadingEnd() {
7060 loadingStyles.delete(loadingStyleId);
7061 logInfo(
7062 "Removed loadingStyle "
7063 .concat(loadingStyleId, ", now awaiting: ")
7064 .concat(loadingStyles.size)
7065 );
7066 if (loadingStyles.size === 0 && isDOMReady()) {
7067 cleanFallbackStyle();
7068 }
7069 }
7070 function update() {
7071 var details = manager.details({secondRound: true});
7072 if (!details) {
7073 return;
7074 }
7075 variablesStore.addRulesForMatching(details.rules);
7076 variablesStore.matchVariablesAndDependants();
7077 manager.render(filter, ignoredImageAnalysisSelectors);
7078 }
7079 var manager = manageStyle(element, {
7080 update: update,
7081 loadingStart: loadingStart,
7082 loadingEnd: loadingEnd
7083 });
7084 styleManagers.set(element, manager);
7085 return manager;
7086 }
7087 function removeManager(element) {
7088 var manager = styleManagers.get(element);
7089 if (manager) {
7090 manager.destroy();
7091 styleManagers.delete(element);
7092 }
7093 }
7094 var throttledRenderAllStyles = throttle(function (callback) {
7095 styleManagers.forEach(function (manager) {
7096 return manager.render(filter, ignoredImageAnalysisSelectors);
7097 });
7098 adoptedStyleManagers.forEach(function (manager) {
7099 return manager.render(filter, ignoredImageAnalysisSelectors);
7100 });
7101 callback && callback();
7102 });
7103 var cancelRendering = function () {
7104 throttledRenderAllStyles.cancel();
7105 };
7106 function onDOMReady() {
7107 if (loadingStyles.size === 0) {
7108 cleanFallbackStyle();
7109 return;
7110 }
7111 }
7112 var documentVisibilityListener = null;
7113 var didDocumentShowUp = !document.hidden;
7114 function watchForDocumentVisibility(callback) {
7115 var alreadyWatching = Boolean(documentVisibilityListener);
7116 documentVisibilityListener = function () {
7117 if (!document.hidden) {
7118 stopWatchingForDocumentVisibility();
7119 callback();
7120 didDocumentShowUp = true;
7121 }
7122 };
7123 if (!alreadyWatching) {
7124 document.addEventListener(
7125 "visibilitychange",
7126 documentVisibilityListener
7127 );
7128 }
7129 }
7130 function stopWatchingForDocumentVisibility() {
7131 document.removeEventListener(
7132 "visibilitychange",
7133 documentVisibilityListener
7134 );
7135 documentVisibilityListener = null;
7136 }
7137 function createThemeAndWatchForUpdates() {
7138 createStaticStyleOverrides();
7139 function runDynamicStyle() {
7140 createDynamicStyleOverrides();
7141 watchForUpdates();
7142 }
7143 if (document.hidden && !filter.immediateModify) {
7144 watchForDocumentVisibility(runDynamicStyle);
7145 } else {
7146 runDynamicStyle();
7147 }
7148 changeMetaThemeColorWhenAvailable(filter);
7149 }
7150 function handleAdoptedStyleSheets(node) {
7151 try {
7152 if (Array.isArray(node.adoptedStyleSheets)) {
7153 if (node.adoptedStyleSheets.length > 0) {
7154 var newManger = createAdoptedStyleSheetOverride(node);
7155 adoptedStyleManagers.push(newManger);
7156 newManger.render(filter, ignoredImageAnalysisSelectors);
7157 }
7158 }
7159 } catch (err) {}
7160 }
7161 function watchForUpdates() {
7162 var managedStyles = Array.from(styleManagers.keys());
7163 watchForStyleChanges(
7164 managedStyles,
7165 function (_a) {
7166 var created = _a.created,
7167 updated = _a.updated,
7168 removed = _a.removed,
7169 moved = _a.moved;
7170 var stylesToRemove = removed;
7171 var stylesToManage = created
7172 .concat(updated)
7173 .concat(moved)
7174 .filter(function (style) {
7175 return !styleManagers.has(style);
7176 });
7177 var stylesToRestore = moved.filter(function (style) {
7178 return styleManagers.has(style);
7179 });
7180 stylesToRemove.forEach(function (style) {
7181 return removeManager(style);
7182 });
7183 var newManagers = stylesToManage.map(function (style) {
7184 return createManager(style);
7185 });
7186 newManagers
7187 .map(function (manager) {
7188 return manager.details({secondRound: false});
7189 })
7190 .filter(function (detail) {
7191 return detail && detail.rules.length > 0;
7192 })
7193 .forEach(function (detail) {
7194 variablesStore.addRulesForMatching(detail.rules);
7195 });
7196 variablesStore.matchVariablesAndDependants();
7197 newManagers.forEach(function (manager) {
7198 return manager.render(
7199 filter,
7200 ignoredImageAnalysisSelectors
7201 );
7202 });
7203 newManagers.forEach(function (manager) {
7204 return manager.watch();
7205 });
7206 stylesToRestore.forEach(function (style) {
7207 return styleManagers.get(style).restore();
7208 });
7209 },
7210 function (shadowRoot) {
7211 createShadowStaticStyleOverrides(shadowRoot);
7212 handleAdoptedStyleSheets(shadowRoot);
7213 }
7214 );
7215 watchForInlineStyles(
7216 function (element) {
7217 overrideInlineStyle(
7218 element,
7219 filter,
7220 ignoredInlineSelectors,
7221 ignoredImageAnalysisSelectors
7222 );
7223 if (element === document.documentElement) {
7224 var styleAttr = element.getAttribute("style") || "";
7225 if (styleAttr.includes("--")) {
7226 variablesStore.matchVariablesAndDependants();
7227 variablesStore.putRootVars(
7228 document.head.querySelector(
7229 ".darkreader--root-vars"
7230 ),
7231 filter
7232 );
7233 }
7234 }
7235 },
7236 function (root) {
7237 createShadowStaticStyleOverrides(root);
7238 var inlineStyleElements = root.querySelectorAll(
7239 INLINE_STYLE_SELECTOR
7240 );
7241 if (inlineStyleElements.length > 0) {
7242 forEach(inlineStyleElements, function (el) {
7243 return overrideInlineStyle(
7244 el,
7245 filter,
7246 ignoredInlineSelectors,
7247 ignoredImageAnalysisSelectors
7248 );
7249 });
7250 }
7251 }
7252 );
7253 addDOMReadyListener(onDOMReady);
7254 }
7255 function stopWatchingForUpdates() {
7256 styleManagers.forEach(function (manager) {
7257 return manager.pause();
7258 });
7259 stopStylePositionWatchers();
7260 stopWatchingForStyleChanges();
7261 stopWatchingForInlineStyles();
7262 removeDOMReadyListener(onDOMReady);
7263 cleanReadyStateCompleteListeners();
7264 }
7265 var metaObserver;
7266 function addMetaListener() {
7267 metaObserver = new MutationObserver(function () {
7268 if (document.querySelector('meta[name="darkreader-lock"]')) {
7269 metaObserver.disconnect();
7270 removeDynamicTheme();
7271 }
7272 });
7273 metaObserver.observe(document.head, {childList: true, subtree: true});
7274 }
7275 function createDarkReaderInstanceMarker() {
7276 var metaElement = document.createElement("meta");
7277 metaElement.name = "darkreader";
7278 metaElement.content = INSTANCE_ID;
7279 document.head.appendChild(metaElement);
7280 }
7281 function isAnotherDarkReaderInstanceActive() {
7282 if (document.querySelector('meta[name="darkreader-lock"]')) {
7283 return true;
7284 }
7285 var meta = document.querySelector('meta[name="darkreader"]');
7286 if (meta) {
7287 if (meta.content !== INSTANCE_ID) {
7288 return true;
7289 }
7290 return false;
7291 }
7292 createDarkReaderInstanceMarker();
7293 addMetaListener();
7294 return false;
7295 }
7296 function createOrUpdateDynamicTheme(
7297 filterConfig,
7298 dynamicThemeFixes,
7299 iframe
7300 ) {
7301 filter = filterConfig;
7302 fixes = dynamicThemeFixes;
7303 if (fixes) {
7304 ignoredImageAnalysisSelectors = Array.isArray(
7305 fixes.ignoreImageAnalysis
7306 )
7307 ? fixes.ignoreImageAnalysis
7308 : [];
7309 ignoredInlineSelectors = Array.isArray(fixes.ignoreInlineStyle)
7310 ? fixes.ignoreInlineStyle
7311 : [];
7312 } else {
7313 ignoredImageAnalysisSelectors = [];
7314 ignoredInlineSelectors = [];
7315 }
7316 if (filter.immediateModify) {
7317 setIsDOMReady(function () {
7318 return true;
7319 });
7320 }
7321 isIFrame$1 = iframe;
7322 if (document.head) {
7323 if (isAnotherDarkReaderInstanceActive()) {
7324 return;
7325 }
7326 document.documentElement.setAttribute(
7327 "data-darkreader-mode",
7328 "dynamic"
7329 );
7330 document.documentElement.setAttribute(
7331 "data-darkreader-scheme",
7332 filter.mode ? "dark" : "dimmed"
7333 );
7334 createThemeAndWatchForUpdates();
7335 } else {
7336 if (!isFirefox) {
7337 var fallbackStyle = createOrUpdateStyle("darkreader--fallback");
7338 document.documentElement.appendChild(fallbackStyle);
7339 fallbackStyle.textContent = getModifiedFallbackStyle(filter, {
7340 strict: true
7341 });
7342 }
7343 var headObserver_1 = new MutationObserver(function () {
7344 if (document.head) {
7345 headObserver_1.disconnect();
7346 if (isAnotherDarkReaderInstanceActive()) {
7347 removeDynamicTheme();
7348 return;
7349 }
7350 createThemeAndWatchForUpdates();
7351 }
7352 });
7353 headObserver_1.observe(document, {childList: true, subtree: true});
7354 }
7355 }
7356 function removeProxy() {
7357 document.dispatchEvent(new CustomEvent("__darkreader__cleanUp"));
7358 removeNode(document.head.querySelector(".darkreader--proxy"));
7359 }
7360 function removeDynamicTheme() {
7361 document.documentElement.removeAttribute("data-darkreader-mode");
7362 document.documentElement.removeAttribute("data-darkreader-scheme");
7363 cleanDynamicThemeCache();
7364 removeNode(document.querySelector(".darkreader--fallback"));
7365 if (document.head) {
7366 restoreMetaThemeColor();
7367 removeNode(document.head.querySelector(".darkreader--user-agent"));
7368 removeNode(document.head.querySelector(".darkreader--text"));
7369 removeNode(document.head.querySelector(".darkreader--invert"));
7370 removeNode(document.head.querySelector(".darkreader--inline"));
7371 removeNode(document.head.querySelector(".darkreader--override"));
7372 removeNode(document.head.querySelector(".darkreader--variables"));
7373 removeNode(document.head.querySelector(".darkreader--root-vars"));
7374 removeNode(document.head.querySelector('meta[name="darkreader"]'));
7375 removeProxy();
7376 }
7377 shadowRootsWithOverrides.forEach(function (root) {
7378 removeNode(root.querySelector(".darkreader--inline"));
7379 removeNode(root.querySelector(".darkreader--override"));
7380 });
7381 shadowRootsWithOverrides.clear();
7382 forEach(styleManagers.keys(), function (el) {
7383 return removeManager(el);
7384 });
7385 loadingStyles.clear();
7386 cleanLoadingLinks();
7387 forEach(document.querySelectorAll(".darkreader"), removeNode);
7388 adoptedStyleManagers.forEach(function (manager) {
7389 manager.destroy();
7390 });
7391 adoptedStyleManagers.splice(0);
7392 metaObserver && metaObserver.disconnect();
7393 }
7394 function cleanDynamicThemeCache() {
7395 variablesStore.clear();
7396 parsedURLCache.clear();
7397 stopWatchingForDocumentVisibility();
7398 cancelRendering();
7399 stopWatchingForUpdates();
7400 cleanModificationCache();
7401 clearColorCache();
7402 }
7403
7404 var blobRegex = /url\(\"(blob\:.*?)\"\)/g;
7405 function replaceBlobs(text) {
7406 return __awaiter(this, void 0, void 0, function () {
7407 var promises, data;
7408 return __generator(this, function (_a) {
7409 switch (_a.label) {
7410 case 0:
7411 promises = [];
7412 getMatches(blobRegex, text, 1).forEach(function (url) {
7413 var promise = loadAsDataURL(url);
7414 promises.push(promise);
7415 });
7416 return [4, Promise.all(promises)];
7417 case 1:
7418 data = _a.sent();
7419 return [
7420 2,
7421 text.replace(blobRegex, function () {
7422 return 'url("'.concat(data.shift(), '")');
7423 })
7424 ];
7425 }
7426 });
7427 });
7428 }
7429 var banner =
7430 '/*\n _______\n / \\\n .==. .==.\n (( ))==(( ))\n / "==" "=="\\\n /____|| || ||___\\\n ________ ____ ________ ___ ___\n | ___ \\ / \\ | ___ \\ | | / /\n | | \\ \\ / /\\ \\ | | \\ \\| |_/ /\n | | ) / /__\\ \\ | |__/ /| ___ \\\n | |__/ / ______ \\| ____ \\| | \\ \\\n_______|_______/__/ ____ \\__\\__|___\\__\\__|___\\__\\____\n| ___ \\ | ____/ / \\ | ___ \\ | ____| ___ \\\n| | \\ \\| |___ / /\\ \\ | | \\ \\| |___| | \\ \\\n| |__/ /| ____/ /__\\ \\ | | ) | ____| |__/ /\n| ____ \\| |__/ ______ \\| |__/ /| |___| ____ \\\n|__| \\__\\____/__/ \\__\\_______/ |______|__| \\__\\\n https://darkreader.org\n*/\n\n/*! Dark reader generated CSS | Licensed under MIT https://github.com/darkreader/darkreader/blob/main/LICENSE */\n';
7431 function collectCSS() {
7432 return __awaiter(this, void 0, void 0, function () {
7433 function addStaticCSS(selector, comment) {
7434 var staticStyle = document.querySelector(selector);
7435 if (staticStyle && staticStyle.textContent) {
7436 css.push("/* ".concat(comment, " */"));
7437 css.push(staticStyle.textContent);
7438 css.push("");
7439 }
7440 }
7441 var css, modifiedCSS, formattedCSS, _a, _b;
7442 return __generator(this, function (_c) {
7443 switch (_c.label) {
7444 case 0:
7445 css = [banner];
7446 addStaticCSS(".darkreader--fallback", "Fallback Style");
7447 addStaticCSS(
7448 ".darkreader--user-agent",
7449 "User-Agent Style"
7450 );
7451 addStaticCSS(".darkreader--text", "Text Style");
7452 addStaticCSS(".darkreader--invert", "Invert Style");
7453 addStaticCSS(
7454 ".darkreader--variables",
7455 "Variables Style"
7456 );
7457 modifiedCSS = [];
7458 document
7459 .querySelectorAll(".darkreader--sync")
7460 .forEach(function (element) {
7461 forEach(
7462 element.sheet.cssRules,
7463 function (rule) {
7464 rule &&
7465 rule.cssText &&
7466 modifiedCSS.push(rule.cssText);
7467 }
7468 );
7469 });
7470 if (!modifiedCSS.length) return [3, 2];
7471 formattedCSS = formatCSS(modifiedCSS.join("\n"));
7472 css.push("/* Modified CSS */");
7473 _b = (_a = css).push;
7474 return [4, replaceBlobs(formattedCSS)];
7475 case 1:
7476 _b.apply(_a, [_c.sent()]);
7477 css.push("");
7478 _c.label = 2;
7479 case 2:
7480 addStaticCSS(".darkreader--override", "Override Style");
7481 return [2, css.join("\n")];
7482 }
7483 });
7484 });
7485 }
7486
7487 var isDarkReaderEnabled = false;
7488 var isIFrame = (function () {
7489 try {
7490 return window.self !== window.top;
7491 } catch (err) {
7492 console.warn(err);
7493 return true;
7494 }
7495 })();
7496 function enable(themeOptions, fixes) {
7497 if (themeOptions === void 0) {
7498 themeOptions = {};
7499 }
7500 if (fixes === void 0) {
7501 fixes = null;
7502 }
7503 var theme = __assign(__assign({}, DEFAULT_THEME), themeOptions);
7504 if (theme.engine !== ThemeEngine.dynamicTheme) {
7505 throw new Error("Theme engine is not supported.");
7506 }
7507 createOrUpdateDynamicTheme(theme, fixes, isIFrame);
7508 isDarkReaderEnabled = true;
7509 }
7510 function isEnabled() {
7511 return isDarkReaderEnabled;
7512 }
7513 function disable() {
7514 removeDynamicTheme();
7515 isDarkReaderEnabled = false;
7516 }
7517 var darkScheme = matchMedia("(prefers-color-scheme: dark)");
7518 var store = {
7519 themeOptions: null,
7520 fixes: null
7521 };
7522 function handleColorScheme() {
7523 if (darkScheme.matches) {
7524 enable(store.themeOptions, store.fixes);
7525 } else {
7526 disable();
7527 }
7528 }
7529 function auto(themeOptions, fixes) {
7530 if (themeOptions === void 0) {
7531 themeOptions = {};
7532 }
7533 if (fixes === void 0) {
7534 fixes = null;
7535 }
7536 if (themeOptions) {
7537 store = {themeOptions: themeOptions, fixes: fixes};
7538 handleColorScheme();
7539 if (isMatchMediaChangeEventListenerSupported) {
7540 darkScheme.addEventListener("change", handleColorScheme);
7541 } else {
7542 darkScheme.addListener(handleColorScheme);
7543 }
7544 } else {
7545 if (isMatchMediaChangeEventListenerSupported) {
7546 darkScheme.removeEventListener("change", handleColorScheme);
7547 } else {
7548 darkScheme.removeListener(handleColorScheme);
7549 }
7550 disable();
7551 }
7552 }
7553 function exportGeneratedCSS() {
7554 return __awaiter(this, void 0, void 0, function () {
7555 return __generator(this, function (_a) {
7556 switch (_a.label) {
7557 case 0:
7558 return [4, collectCSS()];
7559 case 1:
7560 return [2, _a.sent()];
7561 }
7562 });
7563 });
7564 }
7565 var setFetchMethod = setFetchMethod$1;
7566
7567 exports.auto = auto;
7568 exports.disable = disable;
7569 exports.enable = enable;
7570 exports.exportGeneratedCSS = exportGeneratedCSS;
7571 exports.isEnabled = isEnabled;
7572 exports.setFetchMethod = setFetchMethod;
7573
7574 Object.defineProperty(exports, "__esModule", {value: true});
7575});