UNPKG

236 kBJavaScriptView Raw
1/**
2 * Dark Reader v4.9.51
3 * https://darkreader.org/
4 */
5
6(function (global, factory) {
7 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
8 typeof define === 'function' && define.amd ? define(['exports'], factory) :
9 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.DarkReader = {}));
10})(this, (function (exports) { 'use strict';
11
12 /*! *****************************************************************************
13 Copyright (c) Microsoft Corporation.
14
15 Permission to use, copy, modify, and/or distribute this software for any
16 purpose with or without fee is hereby granted.
17
18 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
19 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24 PERFORMANCE OF THIS SOFTWARE.
25 ***************************************************************************** */
26
27 var __assign = function() {
28 __assign = Object.assign || function __assign(t) {
29 for (var s, i = 1, n = arguments.length; i < n; i++) {
30 s = arguments[i];
31 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
32 }
33 return t;
34 };
35 return __assign.apply(this, arguments);
36 };
37
38 function __awaiter(thisArg, _arguments, P, generator) {
39 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
40 return new (P || (P = Promise))(function (resolve, reject) {
41 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
42 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
43 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
44 step((generator = generator.apply(thisArg, _arguments || [])).next());
45 });
46 }
47
48 function __generator(thisArg, body) {
49 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
50 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
51 function verb(n) { return function (v) { return step([n, v]); }; }
52 function step(op) {
53 if (f) throw new TypeError("Generator is already executing.");
54 while (_) try {
55 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
56 if (y = 0, t) op = [op[0] & 2, t.value];
57 switch (op[0]) {
58 case 0: case 1: t = op; break;
59 case 4: _.label++; return { value: op[1], done: false };
60 case 5: _.label++; y = op[1]; op = [0]; continue;
61 case 7: op = _.ops.pop(); _.trys.pop(); continue;
62 default:
63 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
64 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
65 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
66 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
67 if (t[2]) _.ops.pop();
68 _.trys.pop(); continue;
69 }
70 op = body.call(thisArg, _);
71 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
72 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
73 }
74 }
75
76 function __values(o) {
77 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
78 if (m) return m.call(o);
79 if (o && typeof o.length === "number") return {
80 next: function () {
81 if (o && i >= o.length) o = void 0;
82 return { value: o && o[i++], done: !o };
83 }
84 };
85 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
86 }
87
88 function __read(o, n) {
89 var m = typeof Symbol === "function" && o[Symbol.iterator];
90 if (!m) return o;
91 var i = m.call(o), r, ar = [], e;
92 try {
93 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
94 }
95 catch (error) { e = { error: error }; }
96 finally {
97 try {
98 if (r && !r.done && (m = i["return"])) m.call(i);
99 }
100 finally { if (e) throw e.error; }
101 }
102 return ar;
103 }
104
105 function __spreadArray(to, from, pack) {
106 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
107 if (ar || !(i in from)) {
108 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
109 ar[i] = from[i];
110 }
111 }
112 return to.concat(ar || Array.prototype.slice.call(from));
113 }
114
115 var MessageType = {
116 UI_GET_DATA: 'ui-get-data',
117 UI_SUBSCRIBE_TO_CHANGES: 'ui-subscribe-to-changes',
118 UI_UNSUBSCRIBE_FROM_CHANGES: 'ui-unsubscribe-from-changes',
119 UI_CHANGE_SETTINGS: 'ui-change-settings',
120 UI_SET_THEME: 'ui-set-theme',
121 UI_SET_SHORTCUT: 'ui-set-shortcut',
122 UI_TOGGLE_ACTIVE_TAB: 'ui-toggle-active-tab',
123 UI_MARK_NEWS_AS_READ: 'ui-mark-news-as-read',
124 UI_MARK_NEWS_AS_DISPLAYED: 'ui-mark-news-as-displayed',
125 UI_LOAD_CONFIG: 'ui-load-config',
126 UI_APPLY_DEV_DYNAMIC_THEME_FIXES: 'ui-apply-dev-dynamic-theme-fixes',
127 UI_RESET_DEV_DYNAMIC_THEME_FIXES: 'ui-reset-dev-dynamic-theme-fixes',
128 UI_APPLY_DEV_INVERSION_FIXES: 'ui-apply-dev-inversion-fixes',
129 UI_RESET_DEV_INVERSION_FIXES: 'ui-reset-dev-inversion-fixes',
130 UI_APPLY_DEV_STATIC_THEMES: 'ui-apply-dev-static-themes',
131 UI_RESET_DEV_STATIC_THEMES: 'ui-reset-dev-static-themes',
132 UI_SAVE_FILE: 'ui-save-file',
133 UI_REQUEST_EXPORT_CSS: 'ui-request-export-css',
134 BG_CHANGES: 'bg-changes',
135 BG_ADD_CSS_FILTER: 'bg-add-css-filter',
136 BG_ADD_STATIC_THEME: 'bg-add-static-theme',
137 BG_ADD_SVG_FILTER: 'bg-add-svg-filter',
138 BG_ADD_DYNAMIC_THEME: 'bg-add-dynamic-theme',
139 BG_EXPORT_CSS: 'bg-export-css',
140 BG_UNSUPPORTED_SENDER: 'bg-unsupported-sender',
141 BG_CLEAN_UP: 'bg-clean-up',
142 BG_RELOAD: 'bg-reload',
143 BG_FETCH_RESPONSE: 'bg-fetch-response',
144 BG_UI_UPDATE: 'bg-ui-update',
145 BG_CSS_UPDATE: 'bg-css-update',
146 CS_COLOR_SCHEME_CHANGE: 'cs-color-scheme-change',
147 CS_FRAME_CONNECT: 'cs-frame-connect',
148 CS_FRAME_FORGET: 'cs-frame-forget',
149 CS_FRAME_FREEZE: 'cs-frame-freeze',
150 CS_FRAME_RESUME: 'cs-frame-resume',
151 CS_EXPORT_CSS_RESPONSE: 'cs-export-css-response',
152 CS_FETCH: 'cs-fetch',
153 CS_DARK_THEME_DETECTED: 'cs-dark-theme-detected',
154 CS_DARK_THEME_NOT_DETECTED: 'cs-dark-theme-not-detected',
155 };
156
157 var userAgent = typeof navigator === 'undefined' ? 'some useragent' : navigator.userAgent.toLowerCase();
158 var platform = typeof navigator === 'undefined' ? 'some platform' : navigator.platform.toLowerCase();
159 var isChromium = userAgent.includes('chrome') || userAgent.includes('chromium');
160 var isThunderbird = userAgent.includes('thunderbird');
161 var isFirefox = userAgent.includes('firefox') || userAgent.includes('librewolf') || isThunderbird;
162 userAgent.includes('vivaldi');
163 userAgent.includes('yabrowser');
164 userAgent.includes('opr') || userAgent.includes('opera');
165 userAgent.includes('edg');
166 var isSafari = userAgent.includes('safari') && !isChromium;
167 var isWindows = platform.startsWith('win');
168 var isMacOS = platform.startsWith('mac');
169 userAgent.includes('mobile');
170 var isShadowDomSupported = typeof ShadowRoot === 'function';
171 var isMatchMediaChangeEventListenerSupported = (typeof MediaQueryList === 'function' &&
172 typeof MediaQueryList.prototype.addEventListener === 'function');
173 ((function () {
174 var m = userAgent.match(/chrom[e|ium]\/([^ ]+)/);
175 if (m && m[1]) {
176 return m[1];
177 }
178 return '';
179 }))();
180 var isDefinedSelectorSupported = (function () {
181 try {
182 document.querySelector(':defined');
183 return true;
184 }
185 catch (err) {
186 return false;
187 }
188 })();
189 globalThis.chrome && globalThis.chrome.runtime && globalThis.chrome.runtime.getManifest && globalThis.chrome.runtime.getManifest().manifest_version === 3;
190 var isCSSColorSchemePropSupported = (function () {
191 if (typeof document === 'undefined') {
192 return false;
193 }
194 var el = document.createElement('div');
195 el.setAttribute('style', 'color-scheme: dark');
196 return el.style && el.style.colorScheme === 'dark';
197 })();
198
199 function getOKResponse(url, mimeType, origin) {
200 return __awaiter(this, void 0, void 0, function () {
201 var response;
202 return __generator(this, function (_a) {
203 switch (_a.label) {
204 case 0: return [4, fetch(url, {
205 cache: 'force-cache',
206 credentials: 'omit',
207 referrer: origin
208 })];
209 case 1:
210 response = _a.sent();
211 if (isFirefox && mimeType === 'text/css' && url.startsWith('moz-extension://') && url.endsWith('.css')) {
212 return [2, response];
213 }
214 if (mimeType && !response.headers.get('Content-Type').startsWith(mimeType)) {
215 throw new Error("Mime type mismatch when loading ".concat(url));
216 }
217 if (!response.ok) {
218 throw new Error("Unable to load ".concat(url, " ").concat(response.status, " ").concat(response.statusText));
219 }
220 return [2, response];
221 }
222 });
223 });
224 }
225 function loadAsDataURL(url, mimeType) {
226 return __awaiter(this, void 0, void 0, function () {
227 var response;
228 return __generator(this, function (_a) {
229 switch (_a.label) {
230 case 0: return [4, getOKResponse(url, mimeType)];
231 case 1:
232 response = _a.sent();
233 return [4, readResponseAsDataURL(response)];
234 case 2: return [2, _a.sent()];
235 }
236 });
237 });
238 }
239 function readResponseAsDataURL(response) {
240 return __awaiter(this, void 0, void 0, function () {
241 var blob, dataURL;
242 return __generator(this, function (_a) {
243 switch (_a.label) {
244 case 0: return [4, response.blob()];
245 case 1:
246 blob = _a.sent();
247 return [4, (new Promise(function (resolve) {
248 var reader = new FileReader();
249 reader.onloadend = function () { return resolve(reader.result); };
250 reader.readAsDataURL(blob);
251 }))];
252 case 2:
253 dataURL = _a.sent();
254 return [2, dataURL];
255 }
256 });
257 });
258 }
259
260 var throwCORSError = function (url) { return __awaiter(void 0, void 0, void 0, function () {
261 return __generator(this, function (_a) {
262 return [2, Promise.reject(new Error([
263 'Embedded Dark Reader cannot access a cross-origin resource',
264 url,
265 'Overview your URLs and CORS policies or use',
266 '`DarkReader.setFetchMethod(fetch: (url) => Promise<Response>))`.',
267 'See if using `DarkReader.setFetchMethod(window.fetch)`',
268 'before `DarkReader.enable()` works.'
269 ].join(' ')))];
270 });
271 }); };
272 var fetcher = throwCORSError;
273 function setFetchMethod$1(fetch) {
274 if (fetch) {
275 fetcher = fetch;
276 }
277 else {
278 fetcher = throwCORSError;
279 }
280 }
281 function callFetchMethod(url) {
282 return __awaiter(this, void 0, void 0, function () {
283 return __generator(this, function (_a) {
284 switch (_a.label) {
285 case 0: return [4, fetcher(url)];
286 case 1: return [2, _a.sent()];
287 }
288 });
289 });
290 }
291
292 if (!window.chrome) {
293 window.chrome = {};
294 }
295 if (!chrome.runtime) {
296 chrome.runtime = {};
297 }
298 var messageListeners = new Set();
299 function sendMessage() {
300 var args = [];
301 for (var _i = 0; _i < arguments.length; _i++) {
302 args[_i] = arguments[_i];
303 }
304 return __awaiter(this, void 0, void 0, function () {
305 var id_1, _a, url, responseType, response, text_1, error_1;
306 return __generator(this, function (_b) {
307 switch (_b.label) {
308 case 0:
309 if (!(args[0] && args[0].type === MessageType.CS_FETCH)) return [3, 8];
310 id_1 = args[0].id;
311 _b.label = 1;
312 case 1:
313 _b.trys.push([1, 7, , 8]);
314 _a = args[0].data, url = _a.url, responseType = _a.responseType;
315 return [4, callFetchMethod(url)];
316 case 2:
317 response = _b.sent();
318 if (!(responseType === 'data-url')) return [3, 4];
319 return [4, readResponseAsDataURL(response)];
320 case 3:
321 text_1 = _b.sent();
322 return [3, 6];
323 case 4: return [4, response.text()];
324 case 5:
325 text_1 = _b.sent();
326 _b.label = 6;
327 case 6:
328 messageListeners.forEach(function (cb) { return cb({ type: MessageType.BG_FETCH_RESPONSE, data: text_1, error: null, id: id_1 }); });
329 return [3, 8];
330 case 7:
331 error_1 = _b.sent();
332 console.error(error_1);
333 messageListeners.forEach(function (cb) { return cb({ type: MessageType.BG_FETCH_RESPONSE, data: null, error: error_1, id: id_1 }); });
334 return [3, 8];
335 case 8: return [2];
336 }
337 });
338 });
339 }
340 function addMessageListener(callback) {
341 messageListeners.add(callback);
342 }
343 if (typeof chrome.runtime.sendMessage === 'function') {
344 var nativeSendMessage_1 = chrome.runtime.sendMessage;
345 chrome.runtime.sendMessage = function () {
346 var args = [];
347 for (var _i = 0; _i < arguments.length; _i++) {
348 args[_i] = arguments[_i];
349 }
350 sendMessage.apply(void 0, __spreadArray([], __read(args), false));
351 nativeSendMessage_1.apply(chrome.runtime, args);
352 };
353 }
354 else {
355 chrome.runtime.sendMessage = sendMessage;
356 }
357 if (!chrome.runtime.onMessage) {
358 chrome.runtime.onMessage = {};
359 }
360 if (typeof chrome.runtime.onMessage.addListener === 'function') {
361 var nativeAddListener_1 = chrome.runtime.onMessage.addListener;
362 chrome.runtime.onMessage.addListener = function () {
363 var args = [];
364 for (var _i = 0; _i < arguments.length; _i++) {
365 args[_i] = arguments[_i];
366 }
367 addMessageListener(args[0]);
368 nativeAddListener_1.apply(chrome.runtime.onMessage, args);
369 };
370 }
371 else {
372 chrome.runtime.onMessage.addListener = function () {
373 var args = [];
374 for (var _i = 0; _i < arguments.length; _i++) {
375 args[_i] = arguments[_i];
376 }
377 return addMessageListener(args[0]);
378 };
379 }
380
381 var ThemeEngines = {
382 cssFilter: 'cssFilter',
383 svgFilter: 'svgFilter',
384 staticTheme: 'staticTheme',
385 dynamicTheme: 'dynamicTheme',
386 };
387
388 var DEFAULT_COLORS = {
389 darkScheme: {
390 background: '#181a1b',
391 text: '#e8e6e3',
392 },
393 lightScheme: {
394 background: '#dcdad7',
395 text: '#181a1b',
396 },
397 };
398 var DEFAULT_THEME = {
399 mode: 1,
400 brightness: 100,
401 contrast: 100,
402 grayscale: 0,
403 sepia: 0,
404 useFont: false,
405 fontFamily: isMacOS ? 'Helvetica Neue' : isWindows ? 'Segoe UI' : 'Open Sans',
406 textStroke: 0,
407 engine: ThemeEngines.dynamicTheme,
408 stylesheet: '',
409 darkSchemeBackgroundColor: DEFAULT_COLORS.darkScheme.background,
410 darkSchemeTextColor: DEFAULT_COLORS.darkScheme.text,
411 lightSchemeBackgroundColor: DEFAULT_COLORS.lightScheme.background,
412 lightSchemeTextColor: DEFAULT_COLORS.lightScheme.text,
413 scrollbarColor: isMacOS ? '' : 'auto',
414 selectionColor: 'auto',
415 styleSystemControls: !isCSSColorSchemePropSupported,
416 lightColorScheme: 'Default',
417 darkColorScheme: 'Default',
418 immediateModify: false,
419 };
420
421 function isArrayLike(items) {
422 return items.length != null;
423 }
424 function forEach(items, iterator) {
425 var e_1, _a;
426 if (isArrayLike(items)) {
427 for (var i = 0, len = items.length; i < len; i++) {
428 iterator(items[i]);
429 }
430 }
431 else {
432 try {
433 for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
434 var item = items_1_1.value;
435 iterator(item);
436 }
437 }
438 catch (e_1_1) { e_1 = { error: e_1_1 }; }
439 finally {
440 try {
441 if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
442 }
443 finally { if (e_1) throw e_1.error; }
444 }
445 }
446 }
447 function push(array, addition) {
448 forEach(addition, function (a) { return array.push(a); });
449 }
450 function toArray(items) {
451 var results = [];
452 for (var i = 0, len = items.length; i < len; i++) {
453 results.push(items[i]);
454 }
455 return results;
456 }
457
458 function logInfo() {
459 var args = [];
460 for (var _i = 0; _i < arguments.length; _i++) {
461 args[_i] = arguments[_i];
462 }
463 }
464 function logWarn() {
465 var args = [];
466 for (var _i = 0; _i < arguments.length; _i++) {
467 args[_i] = arguments[_i];
468 }
469 }
470
471 function throttle(callback) {
472 var pending = false;
473 var frameId = null;
474 var lastArgs;
475 var throttled = (function () {
476 var args = [];
477 for (var _i = 0; _i < arguments.length; _i++) {
478 args[_i] = arguments[_i];
479 }
480 lastArgs = args;
481 if (frameId) {
482 pending = true;
483 }
484 else {
485 callback.apply(void 0, __spreadArray([], __read(lastArgs), false));
486 frameId = requestAnimationFrame(function () {
487 frameId = null;
488 if (pending) {
489 callback.apply(void 0, __spreadArray([], __read(lastArgs), false));
490 pending = false;
491 }
492 });
493 }
494 });
495 var cancel = function () {
496 cancelAnimationFrame(frameId);
497 pending = false;
498 frameId = null;
499 };
500 return Object.assign(throttled, { cancel: cancel });
501 }
502 function createAsyncTasksQueue() {
503 var tasks = [];
504 var frameId = null;
505 function runTasks() {
506 var task;
507 while ((task = tasks.shift())) {
508 task();
509 }
510 frameId = null;
511 }
512 function add(task) {
513 tasks.push(task);
514 if (!frameId) {
515 frameId = requestAnimationFrame(runTasks);
516 }
517 }
518 function cancel() {
519 tasks.splice(0);
520 cancelAnimationFrame(frameId);
521 frameId = null;
522 }
523 return { add: add, cancel: cancel };
524 }
525
526 function getDuration(time) {
527 var duration = 0;
528 if (time.seconds) {
529 duration += time.seconds * 1000;
530 }
531 if (time.minutes) {
532 duration += time.minutes * 60 * 1000;
533 }
534 if (time.hours) {
535 duration += time.hours * 60 * 60 * 1000;
536 }
537 if (time.days) {
538 duration += time.days * 24 * 60 * 60 * 1000;
539 }
540 return duration;
541 }
542
543 function removeNode(node) {
544 node && node.parentNode && node.parentNode.removeChild(node);
545 }
546 function watchForNodePosition(node, mode, onRestore) {
547 if (onRestore === void 0) { onRestore = Function.prototype; }
548 var MAX_ATTEMPTS_COUNT = 10;
549 var RETRY_TIMEOUT = getDuration({ seconds: 2 });
550 var ATTEMPTS_INTERVAL = getDuration({ seconds: 10 });
551 var prevSibling = node.previousSibling;
552 var parent = node.parentNode;
553 if (!parent) {
554 throw new Error('Unable to watch for node position: parent element not found');
555 }
556 if (mode === 'prev-sibling' && !prevSibling) {
557 throw new Error('Unable to watch for node position: there is no previous sibling');
558 }
559 var attempts = 0;
560 var start = null;
561 var timeoutId = null;
562 var restore = throttle(function () {
563 if (timeoutId) {
564 return;
565 }
566 attempts++;
567 var now = Date.now();
568 if (start == null) {
569 start = now;
570 }
571 else if (attempts >= MAX_ATTEMPTS_COUNT) {
572 if (now - start < ATTEMPTS_INTERVAL) {
573 logWarn("Node position watcher paused: retry in ".concat(RETRY_TIMEOUT, "ms"), node, prevSibling);
574 timeoutId = setTimeout(function () {
575 start = null;
576 attempts = 0;
577 timeoutId = null;
578 restore();
579 }, RETRY_TIMEOUT);
580 return;
581 }
582 start = now;
583 attempts = 1;
584 }
585 if (mode === 'parent') {
586 if (prevSibling && prevSibling.parentNode !== parent) {
587 logWarn('Unable to restore node position: sibling parent changed', node, prevSibling, parent);
588 stop();
589 return;
590 }
591 }
592 if (mode === 'prev-sibling') {
593 if (prevSibling.parentNode == null) {
594 logWarn('Unable to restore node position: sibling was removed', node, prevSibling, parent);
595 stop();
596 return;
597 }
598 if (prevSibling.parentNode !== parent) {
599 logWarn('Style was moved to another parent', node, prevSibling, parent);
600 updateParent(prevSibling.parentNode);
601 }
602 }
603 logWarn('Restoring node position', node, prevSibling, parent);
604 parent.insertBefore(node, prevSibling ? prevSibling.nextSibling : parent.firstChild);
605 observer.takeRecords();
606 onRestore && onRestore();
607 });
608 var observer = new MutationObserver(function () {
609 if ((mode === 'parent' && node.parentNode !== parent) ||
610 (mode === 'prev-sibling' && node.previousSibling !== prevSibling)) {
611 restore();
612 }
613 });
614 var run = function () {
615 observer.observe(parent, { childList: true });
616 };
617 var stop = function () {
618 clearTimeout(timeoutId);
619 observer.disconnect();
620 restore.cancel();
621 };
622 var skip = function () {
623 observer.takeRecords();
624 };
625 var updateParent = function (parentNode) {
626 parent = parentNode;
627 stop();
628 run();
629 };
630 run();
631 return { run: run, stop: stop, skip: skip };
632 }
633 function iterateShadowHosts(root, iterator) {
634 if (root == null) {
635 return;
636 }
637 var walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
638 acceptNode: function (node) {
639 return node.shadowRoot == null ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
640 }
641 });
642 for (var node = (root.shadowRoot ? walker.currentNode : walker.nextNode()); node != null; node = walker.nextNode()) {
643 if (node.classList.contains('surfingkeys_hints_host')) {
644 continue;
645 }
646 iterator(node);
647 iterateShadowHosts(node.shadowRoot, iterator);
648 }
649 }
650 var isDOMReady = function () {
651 return document.readyState === 'complete' || document.readyState === 'interactive';
652 };
653 function setIsDOMReady(newFunc) {
654 isDOMReady = newFunc;
655 }
656 var readyStateListeners = new Set();
657 function addDOMReadyListener(listener) {
658 isDOMReady() ? listener() : readyStateListeners.add(listener);
659 }
660 function removeDOMReadyListener(listener) {
661 readyStateListeners.delete(listener);
662 }
663 function isReadyStateComplete() {
664 return document.readyState === 'complete';
665 }
666 var readyStateCompleteListeners = new Set();
667 function addReadyStateCompleteListener(listener) {
668 isReadyStateComplete() ? listener() : readyStateCompleteListeners.add(listener);
669 }
670 function cleanReadyStateCompleteListeners() {
671 readyStateCompleteListeners.clear();
672 }
673 if (!isDOMReady()) {
674 var onReadyStateChange_1 = function () {
675 if (isDOMReady()) {
676 readyStateListeners.forEach(function (listener) { return listener(); });
677 readyStateListeners.clear();
678 if (isReadyStateComplete()) {
679 document.removeEventListener('readystatechange', onReadyStateChange_1);
680 readyStateCompleteListeners.forEach(function (listener) { return listener(); });
681 readyStateCompleteListeners.clear();
682 }
683 }
684 };
685 document.addEventListener('readystatechange', onReadyStateChange_1);
686 }
687 var HUGE_MUTATIONS_COUNT = 1000;
688 function isHugeMutation(mutations) {
689 if (mutations.length > HUGE_MUTATIONS_COUNT) {
690 return true;
691 }
692 var addedNodesCount = 0;
693 for (var i = 0; i < mutations.length; i++) {
694 addedNodesCount += mutations[i].addedNodes.length;
695 if (addedNodesCount > HUGE_MUTATIONS_COUNT) {
696 return true;
697 }
698 }
699 return false;
700 }
701 function getElementsTreeOperations(mutations) {
702 var additions = new Set();
703 var deletions = new Set();
704 var moves = new Set();
705 mutations.forEach(function (m) {
706 forEach(m.addedNodes, function (n) {
707 if (n instanceof Element && n.isConnected) {
708 additions.add(n);
709 }
710 });
711 forEach(m.removedNodes, function (n) {
712 if (n instanceof Element) {
713 if (n.isConnected) {
714 moves.add(n);
715 additions.delete(n);
716 }
717 else {
718 deletions.add(n);
719 }
720 }
721 });
722 });
723 var duplicateAdditions = [];
724 var duplicateDeletions = [];
725 additions.forEach(function (node) {
726 if (additions.has(node.parentElement)) {
727 duplicateAdditions.push(node);
728 }
729 });
730 deletions.forEach(function (node) {
731 if (deletions.has(node.parentElement)) {
732 duplicateDeletions.push(node);
733 }
734 });
735 duplicateAdditions.forEach(function (node) { return additions.delete(node); });
736 duplicateDeletions.forEach(function (node) { return deletions.delete(node); });
737 return { additions: additions, moves: moves, deletions: deletions };
738 }
739 var optimizedTreeObservers = new Map();
740 var optimizedTreeCallbacks = new WeakMap();
741 function createOptimizedTreeObserver(root, callbacks) {
742 var observer;
743 var observerCallbacks;
744 var domReadyListener;
745 if (optimizedTreeObservers.has(root)) {
746 observer = optimizedTreeObservers.get(root);
747 observerCallbacks = optimizedTreeCallbacks.get(observer);
748 }
749 else {
750 var hadHugeMutationsBefore_1 = false;
751 var subscribedForReadyState_1 = false;
752 observer = new MutationObserver(function (mutations) {
753 if (isHugeMutation(mutations)) {
754 if (!hadHugeMutationsBefore_1 || isDOMReady()) {
755 observerCallbacks.forEach(function (_a) {
756 var onHugeMutations = _a.onHugeMutations;
757 return onHugeMutations(root);
758 });
759 }
760 else if (!subscribedForReadyState_1) {
761 domReadyListener = function () { return observerCallbacks.forEach(function (_a) {
762 var onHugeMutations = _a.onHugeMutations;
763 return onHugeMutations(root);
764 }); };
765 addDOMReadyListener(domReadyListener);
766 subscribedForReadyState_1 = true;
767 }
768 hadHugeMutationsBefore_1 = true;
769 }
770 else {
771 var elementsOperations_1 = getElementsTreeOperations(mutations);
772 observerCallbacks.forEach(function (_a) {
773 var onMinorMutations = _a.onMinorMutations;
774 return onMinorMutations(elementsOperations_1);
775 });
776 }
777 });
778 observer.observe(root, { childList: true, subtree: true });
779 optimizedTreeObservers.set(root, observer);
780 observerCallbacks = new Set();
781 optimizedTreeCallbacks.set(observer, observerCallbacks);
782 }
783 observerCallbacks.add(callbacks);
784 return {
785 disconnect: function () {
786 observerCallbacks.delete(callbacks);
787 if (domReadyListener) {
788 removeDOMReadyListener(domReadyListener);
789 }
790 if (observerCallbacks.size === 0) {
791 observer.disconnect();
792 optimizedTreeCallbacks.delete(observer);
793 optimizedTreeObservers.delete(root);
794 }
795 },
796 };
797 }
798
799 var anchor;
800 var parsedURLCache = new Map();
801 function fixBaseURL($url) {
802 if (!anchor) {
803 anchor = document.createElement('a');
804 }
805 anchor.href = $url;
806 return anchor.href;
807 }
808 function parseURL($url, $base) {
809 if ($base === void 0) { $base = null; }
810 var key = "".concat($url).concat($base ? ";".concat($base) : '');
811 if (parsedURLCache.has(key)) {
812 return parsedURLCache.get(key);
813 }
814 if ($base) {
815 var parsedURL_1 = new URL($url, fixBaseURL($base));
816 parsedURLCache.set(key, parsedURL_1);
817 return parsedURL_1;
818 }
819 var parsedURL = new URL(fixBaseURL($url));
820 parsedURLCache.set($url, parsedURL);
821 return parsedURL;
822 }
823 function getAbsoluteURL($base, $relative) {
824 if ($relative.match(/^data\\?\:/)) {
825 return $relative;
826 }
827 if (/^\/\//.test($relative)) {
828 return "".concat(location.protocol).concat($relative);
829 }
830 var b = parseURL($base);
831 var a = parseURL($relative, b.href);
832 return a.href;
833 }
834 function isRelativeHrefOnAbsolutePath(href) {
835 if (href.startsWith('data:')) {
836 return true;
837 }
838 var url = parseURL(href);
839 if (url.protocol !== location.protocol) {
840 return false;
841 }
842 if (url.hostname !== location.hostname) {
843 return false;
844 }
845 if (url.port !== location.port) {
846 return false;
847 }
848 return url.pathname === location.pathname;
849 }
850
851 function iterateCSSRules(rules, iterate, onMediaRuleError) {
852 forEach(rules, function (rule) {
853 if (rule.selectorText) {
854 iterate(rule);
855 }
856 else if (rule.href) {
857 try {
858 iterateCSSRules(rule.styleSheet.cssRules, iterate, onMediaRuleError);
859 }
860 catch (err) {
861 logInfo("Found a non-loaded link.");
862 onMediaRuleError && onMediaRuleError();
863 }
864 }
865 else if (rule.media) {
866 var media = Array.from(rule.media);
867 var isScreenOrAllOrQuery = media.some(function (m) { return m.startsWith('screen') || m.startsWith('all') || m.startsWith('('); });
868 var isPrintOrSpeech = media.some(function (m) { return m.startsWith('print') || m.startsWith('speech'); });
869 if (isScreenOrAllOrQuery || !isPrintOrSpeech) {
870 iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);
871 }
872 }
873 else if (rule.conditionText) {
874 if (CSS.supports(rule.conditionText)) {
875 iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);
876 }
877 }
878 else {
879 logWarn("CSSRule type not supported", rule);
880 }
881 });
882 }
883 var shorthandVarDependantProperties = [
884 'background',
885 'border',
886 'border-color',
887 'border-bottom',
888 'border-left',
889 'border-right',
890 'border-top',
891 'outline',
892 'outline-color',
893 ];
894 var shorthandVarDepPropRegexps = isSafari ? shorthandVarDependantProperties.map(function (prop) {
895 var regexp = new RegExp("".concat(prop, ":\\s*(.*?)\\s*;"));
896 return [prop, regexp];
897 }) : null;
898 function iterateCSSDeclarations(style, iterate) {
899 forEach(style, function (property) {
900 var value = style.getPropertyValue(property).trim();
901 if (!value) {
902 return;
903 }
904 iterate(property, value);
905 });
906 var cssText = style.cssText;
907 if (cssText.includes('var(')) {
908 if (isSafari) {
909 shorthandVarDepPropRegexps.forEach(function (_a) {
910 var _b = __read(_a, 2), prop = _b[0], regexp = _b[1];
911 var match = cssText.match(regexp);
912 if (match && match[1]) {
913 var val = match[1].trim();
914 iterate(prop, val);
915 }
916 });
917 }
918 else {
919 shorthandVarDependantProperties.forEach(function (prop) {
920 var val = style.getPropertyValue(prop);
921 if (val && val.includes('var(')) {
922 iterate(prop, val);
923 }
924 });
925 }
926 }
927 }
928 var cssURLRegex = /url\((('.+?')|(".+?")|([^\)]*?))\)/g;
929 var cssImportRegex = /@import\s*(url\()?(('.+?')|(".+?")|([^\)]*?))\)? ?(screen)?;?/gi;
930 function getCSSURLValue(cssURL) {
931 return cssURL.trim().replace(/^url\((.*)\)$/, '$1').trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
932 }
933 function getCSSBaseBath(url) {
934 var cssURL = parseURL(url);
935 return "".concat(cssURL.origin).concat(cssURL.pathname.replace(/\?.*$/, '').replace(/(\/)([^\/]+)$/i, '$1'));
936 }
937 function replaceCSSRelativeURLsWithAbsolute($css, cssBasePath) {
938 return $css.replace(cssURLRegex, function (match) {
939 var pathValue = getCSSURLValue(match);
940 try {
941 return "url(\"".concat(getAbsoluteURL(cssBasePath, pathValue), "\")");
942 }
943 catch (err) {
944 logWarn('Not able to replace relative URL with Absolute URL, skipping');
945 return match;
946 }
947 });
948 }
949 var cssCommentsRegex = /\/\*[\s\S]*?\*\//g;
950 function removeCSSComments($css) {
951 return $css.replace(cssCommentsRegex, '');
952 }
953 var fontFaceRegex = /@font-face\s*{[^}]*}/g;
954 function replaceCSSFontFace($css) {
955 return $css.replace(fontFaceRegex, '');
956 }
957
958 function evalMath(expression) {
959 var rpnStack = [];
960 var workingStack = [];
961 var lastToken;
962 for (var i = 0, len = expression.length; i < len; i++) {
963 var token = expression[i];
964 if (!token || token === ' ') {
965 continue;
966 }
967 if (operators.has(token)) {
968 var op = operators.get(token);
969 while (workingStack.length) {
970 var currentOp = operators.get(workingStack[0]);
971 if (!currentOp) {
972 break;
973 }
974 if (op.lessOrEqualThan(currentOp)) {
975 rpnStack.push(workingStack.shift());
976 }
977 else {
978 break;
979 }
980 }
981 workingStack.unshift(token);
982 }
983 else if (!lastToken || operators.has(lastToken)) {
984 rpnStack.push(token);
985 }
986 else {
987 rpnStack[rpnStack.length - 1] += token;
988 }
989 lastToken = token;
990 }
991 rpnStack.push.apply(rpnStack, __spreadArray([], __read(workingStack), false));
992 var stack = [];
993 for (var i = 0, len = rpnStack.length; i < len; i++) {
994 var op = operators.get(rpnStack[i]);
995 if (op) {
996 var args = stack.splice(0, 2);
997 stack.push(op.exec(args[1], args[0]));
998 }
999 else {
1000 stack.unshift(parseFloat(rpnStack[i]));
1001 }
1002 }
1003 return stack[0];
1004 }
1005 var Operator = (function () {
1006 function Operator(precedence, method) {
1007 this.precendce = precedence;
1008 this.execMethod = method;
1009 }
1010 Operator.prototype.exec = function (left, right) {
1011 return this.execMethod(left, right);
1012 };
1013 Operator.prototype.lessOrEqualThan = function (op) {
1014 return this.precendce <= op.precendce;
1015 };
1016 return Operator;
1017 }());
1018 var operators = new Map([
1019 ['+', new Operator(1, function (left, right) { return left + right; })],
1020 ['-', new Operator(1, function (left, right) { return left - right; })],
1021 ['*', new Operator(2, function (left, right) { return left * right; })],
1022 ['/', new Operator(2, function (left, right) { return left / right; })],
1023 ]);
1024
1025 function getMatches(regex, input, group) {
1026 if (group === void 0) { group = 0; }
1027 var matches = [];
1028 var m;
1029 while ((m = regex.exec(input))) {
1030 matches.push(m[group]);
1031 }
1032 return matches;
1033 }
1034 function formatCSS(text) {
1035 function trimLeft(text) {
1036 return text.replace(/^\s+/, '');
1037 }
1038 function getIndent(depth) {
1039 if (depth === 0) {
1040 return '';
1041 }
1042 return ' '.repeat(4 * depth);
1043 }
1044 if (text.length < 50000) {
1045 var emptyRuleRegexp = /[^{}]+{\s*}/;
1046 while (emptyRuleRegexp.test(text)) {
1047 text = text.replace(emptyRuleRegexp, '');
1048 }
1049 }
1050 var css = (text
1051 .replace(/\s{2,}/g, ' ')
1052 .replace(/\{/g, '{\n')
1053 .replace(/\}/g, '\n}\n')
1054 .replace(/\;(?![^\(|\"]*(\)|\"))/g, ';\n')
1055 .replace(/\,(?![^\(|\"]*(\)|\"))/g, ',\n')
1056 .replace(/\n\s*\n/g, '\n')
1057 .split('\n'));
1058 var depth = 0;
1059 var formatted = [];
1060 for (var x = 0, len = css.length; x < len; x++) {
1061 var line = "".concat(css[x], "\n");
1062 if (line.includes('{')) {
1063 formatted.push(getIndent(depth++) + trimLeft(line));
1064 }
1065 else if (line.includes('\}')) {
1066 formatted.push(getIndent(--depth) + trimLeft(line));
1067 }
1068 else {
1069 formatted.push(getIndent(depth) + trimLeft(line));
1070 }
1071 }
1072 return formatted.join('').trim();
1073 }
1074 function getParenthesesRange(input, searchStartIndex) {
1075 if (searchStartIndex === void 0) { searchStartIndex = 0; }
1076 var length = input.length;
1077 var depth = 0;
1078 var firstOpenIndex = -1;
1079 for (var i = searchStartIndex; i < length; i++) {
1080 if (depth === 0) {
1081 var openIndex = input.indexOf('(', i);
1082 if (openIndex < 0) {
1083 break;
1084 }
1085 firstOpenIndex = openIndex;
1086 depth++;
1087 i = openIndex;
1088 }
1089 else {
1090 var closingIndex = input.indexOf(')', i);
1091 if (closingIndex < 0) {
1092 break;
1093 }
1094 var openIndex = input.indexOf('(', i);
1095 if (openIndex < 0 || closingIndex < openIndex) {
1096 depth--;
1097 if (depth === 0) {
1098 return { start: firstOpenIndex, end: closingIndex + 1 };
1099 }
1100 i = closingIndex;
1101 }
1102 else {
1103 depth++;
1104 i = openIndex;
1105 }
1106 }
1107 }
1108 return null;
1109 }
1110
1111 function hslToRGB(_a) {
1112 var h = _a.h, s = _a.s, l = _a.l, _b = _a.a, a = _b === void 0 ? 1 : _b;
1113 if (s === 0) {
1114 var _c = __read([l, l, l].map(function (x) { return Math.round(x * 255); }), 3), r_1 = _c[0], b_1 = _c[1], g_1 = _c[2];
1115 return { r: r_1, g: g_1, b: b_1, a: a };
1116 }
1117 var c = (1 - Math.abs(2 * l - 1)) * s;
1118 var x = c * (1 - Math.abs((h / 60) % 2 - 1));
1119 var m = l - c / 2;
1120 var _d = __read((h < 60 ? [c, x, 0] :
1121 h < 120 ? [x, c, 0] :
1122 h < 180 ? [0, c, x] :
1123 h < 240 ? [0, x, c] :
1124 h < 300 ? [x, 0, c] :
1125 [c, 0, x]).map(function (n) { return Math.round((n + m) * 255); }), 3), r = _d[0], g = _d[1], b = _d[2];
1126 return { r: r, g: g, b: b, a: a };
1127 }
1128 function rgbToHSL(_a) {
1129 var r255 = _a.r, g255 = _a.g, b255 = _a.b, _b = _a.a, a = _b === void 0 ? 1 : _b;
1130 var r = r255 / 255;
1131 var g = g255 / 255;
1132 var b = b255 / 255;
1133 var max = Math.max(r, g, b);
1134 var min = Math.min(r, g, b);
1135 var c = max - min;
1136 var l = (max + min) / 2;
1137 if (c === 0) {
1138 return { h: 0, s: 0, l: l, a: a };
1139 }
1140 var h = (max === r ? (((g - b) / c) % 6) :
1141 max === g ? ((b - r) / c + 2) :
1142 ((r - g) / c + 4)) * 60;
1143 if (h < 0) {
1144 h += 360;
1145 }
1146 var s = c / (1 - Math.abs(2 * l - 1));
1147 return { h: h, s: s, l: l, a: a };
1148 }
1149 function toFixed(n, digits) {
1150 if (digits === void 0) { digits = 0; }
1151 var fixed = n.toFixed(digits);
1152 if (digits === 0) {
1153 return fixed;
1154 }
1155 var dot = fixed.indexOf('.');
1156 if (dot >= 0) {
1157 var zerosMatch = fixed.match(/0+$/);
1158 if (zerosMatch) {
1159 if (zerosMatch.index === dot + 1) {
1160 return fixed.substring(0, dot);
1161 }
1162 return fixed.substring(0, zerosMatch.index);
1163 }
1164 }
1165 return fixed;
1166 }
1167 function rgbToString(rgb) {
1168 var r = rgb.r, g = rgb.g, b = rgb.b, a = rgb.a;
1169 if (a != null && a < 1) {
1170 return "rgba(".concat(toFixed(r), ", ").concat(toFixed(g), ", ").concat(toFixed(b), ", ").concat(toFixed(a, 2), ")");
1171 }
1172 return "rgb(".concat(toFixed(r), ", ").concat(toFixed(g), ", ").concat(toFixed(b), ")");
1173 }
1174 function rgbToHexString(_a) {
1175 var r = _a.r, g = _a.g, b = _a.b, a = _a.a;
1176 return "#".concat((a != null && a < 1 ? [r, g, b, Math.round(a * 255)] : [r, g, b]).map(function (x) {
1177 return "".concat(x < 16 ? '0' : '').concat(x.toString(16));
1178 }).join(''));
1179 }
1180 function hslToString(hsl) {
1181 var h = hsl.h, s = hsl.s, l = hsl.l, a = hsl.a;
1182 if (a != null && a < 1) {
1183 return "hsla(".concat(toFixed(h), ", ").concat(toFixed(s * 100), "%, ").concat(toFixed(l * 100), "%, ").concat(toFixed(a, 2), ")");
1184 }
1185 return "hsl(".concat(toFixed(h), ", ").concat(toFixed(s * 100), "%, ").concat(toFixed(l * 100), "%)");
1186 }
1187 var rgbMatch = /^rgba?\([^\(\)]+\)$/;
1188 var hslMatch = /^hsla?\([^\(\)]+\)$/;
1189 var hexMatch = /^#[0-9a-f]+$/i;
1190 function parse($color) {
1191 var c = $color.trim().toLowerCase();
1192 if (c.match(rgbMatch)) {
1193 return parseRGB(c);
1194 }
1195 if (c.match(hslMatch)) {
1196 return parseHSL(c);
1197 }
1198 if (c.match(hexMatch)) {
1199 return parseHex(c);
1200 }
1201 if (knownColors.has(c)) {
1202 return getColorByName(c);
1203 }
1204 if (systemColors.has(c)) {
1205 return getSystemColor(c);
1206 }
1207 if ($color === 'transparent') {
1208 return { r: 0, g: 0, b: 0, a: 0 };
1209 }
1210 throw new Error("Unable to parse ".concat($color));
1211 }
1212 function getNumbers($color) {
1213 var numbers = [];
1214 var prevPos = 0;
1215 var isMining = false;
1216 var startIndex = $color.indexOf('(');
1217 $color = $color.substring(startIndex + 1, $color.length - 1);
1218 for (var i = 0; i < $color.length; i++) {
1219 var c = $color[i];
1220 if (c >= '0' && c <= '9' || c === '.' || c === '+' || c === '-') {
1221 isMining = true;
1222 }
1223 else if (isMining && (c === ' ' || c === ',')) {
1224 numbers.push($color.substring(prevPos, i));
1225 isMining = false;
1226 prevPos = i + 1;
1227 }
1228 else if (!isMining) {
1229 prevPos = i + 1;
1230 }
1231 }
1232 if (isMining) {
1233 numbers.push($color.substring(prevPos, $color.length));
1234 }
1235 return numbers;
1236 }
1237 function getNumbersFromString(str, range, units) {
1238 var raw = getNumbers(str);
1239 var unitsList = Object.entries(units);
1240 var numbers = raw.map(function (r) { return r.trim(); }).map(function (r, i) {
1241 var n;
1242 var unit = unitsList.find(function (_a) {
1243 var _b = __read(_a, 1), u = _b[0];
1244 return r.endsWith(u);
1245 });
1246 if (unit) {
1247 n = parseFloat(r.substring(0, r.length - unit[0].length)) / unit[1] * range[i];
1248 }
1249 else {
1250 n = parseFloat(r);
1251 }
1252 if (range[i] > 1) {
1253 return Math.round(n);
1254 }
1255 return n;
1256 });
1257 return numbers;
1258 }
1259 var rgbRange = [255, 255, 255, 1];
1260 var rgbUnits = { '%': 100 };
1261 function parseRGB($rgb) {
1262 var _a = __read(getNumbersFromString($rgb, rgbRange, rgbUnits), 4), r = _a[0], g = _a[1], b = _a[2], _b = _a[3], a = _b === void 0 ? 1 : _b;
1263 return { r: r, g: g, b: b, a: a };
1264 }
1265 var hslRange = [360, 1, 1, 1];
1266 var hslUnits = { '%': 100, 'deg': 360, 'rad': 2 * Math.PI, 'turn': 1 };
1267 function parseHSL($hsl) {
1268 var _a = __read(getNumbersFromString($hsl, hslRange, hslUnits), 4), h = _a[0], s = _a[1], l = _a[2], _b = _a[3], a = _b === void 0 ? 1 : _b;
1269 return hslToRGB({ h: h, s: s, l: l, a: a });
1270 }
1271 function parseHex($hex) {
1272 var h = $hex.substring(1);
1273 switch (h.length) {
1274 case 3:
1275 case 4: {
1276 var _a = __read([0, 1, 2].map(function (i) { return parseInt("".concat(h[i]).concat(h[i]), 16); }), 3), r = _a[0], g = _a[1], b = _a[2];
1277 var a = h.length === 3 ? 1 : (parseInt("".concat(h[3]).concat(h[3]), 16) / 255);
1278 return { r: r, g: g, b: b, a: a };
1279 }
1280 case 6:
1281 case 8: {
1282 var _b = __read([0, 2, 4].map(function (i) { return parseInt(h.substring(i, i + 2), 16); }), 3), r = _b[0], g = _b[1], b = _b[2];
1283 var a = h.length === 6 ? 1 : (parseInt(h.substring(6, 8), 16) / 255);
1284 return { r: r, g: g, b: b, a: a };
1285 }
1286 }
1287 throw new Error("Unable to parse ".concat($hex));
1288 }
1289 function getColorByName($color) {
1290 var n = knownColors.get($color);
1291 return {
1292 r: (n >> 16) & 255,
1293 g: (n >> 8) & 255,
1294 b: (n >> 0) & 255,
1295 a: 1
1296 };
1297 }
1298 function getSystemColor($color) {
1299 var n = systemColors.get($color);
1300 return {
1301 r: (n >> 16) & 255,
1302 g: (n >> 8) & 255,
1303 b: (n >> 0) & 255,
1304 a: 1
1305 };
1306 }
1307 function lowerCalcExpression(color) {
1308 var searchIndex = 0;
1309 var replaceBetweenIndices = function (start, end, replacement) {
1310 color = color.substring(0, start) + replacement + color.substring(end);
1311 };
1312 while ((searchIndex = color.indexOf('calc(')) !== -1) {
1313 var range = getParenthesesRange(color, searchIndex);
1314 if (!range) {
1315 break;
1316 }
1317 var slice = color.slice(range.start + 1, range.end - 1);
1318 var includesPercentage = slice.includes('%');
1319 slice = slice.split('%').join('');
1320 var output = Math.round(evalMath(slice));
1321 replaceBetweenIndices(range.start - 4, range.end, output + (includesPercentage ? '%' : ''));
1322 }
1323 return color;
1324 }
1325 var knownColors = new Map(Object.entries({
1326 aliceblue: 0xf0f8ff,
1327 antiquewhite: 0xfaebd7,
1328 aqua: 0x00ffff,
1329 aquamarine: 0x7fffd4,
1330 azure: 0xf0ffff,
1331 beige: 0xf5f5dc,
1332 bisque: 0xffe4c4,
1333 black: 0x000000,
1334 blanchedalmond: 0xffebcd,
1335 blue: 0x0000ff,
1336 blueviolet: 0x8a2be2,
1337 brown: 0xa52a2a,
1338 burlywood: 0xdeb887,
1339 cadetblue: 0x5f9ea0,
1340 chartreuse: 0x7fff00,
1341 chocolate: 0xd2691e,
1342 coral: 0xff7f50,
1343 cornflowerblue: 0x6495ed,
1344 cornsilk: 0xfff8dc,
1345 crimson: 0xdc143c,
1346 cyan: 0x00ffff,
1347 darkblue: 0x00008b,
1348 darkcyan: 0x008b8b,
1349 darkgoldenrod: 0xb8860b,
1350 darkgray: 0xa9a9a9,
1351 darkgrey: 0xa9a9a9,
1352 darkgreen: 0x006400,
1353 darkkhaki: 0xbdb76b,
1354 darkmagenta: 0x8b008b,
1355 darkolivegreen: 0x556b2f,
1356 darkorange: 0xff8c00,
1357 darkorchid: 0x9932cc,
1358 darkred: 0x8b0000,
1359 darksalmon: 0xe9967a,
1360 darkseagreen: 0x8fbc8f,
1361 darkslateblue: 0x483d8b,
1362 darkslategray: 0x2f4f4f,
1363 darkslategrey: 0x2f4f4f,
1364 darkturquoise: 0x00ced1,
1365 darkviolet: 0x9400d3,
1366 deeppink: 0xff1493,
1367 deepskyblue: 0x00bfff,
1368 dimgray: 0x696969,
1369 dimgrey: 0x696969,
1370 dodgerblue: 0x1e90ff,
1371 firebrick: 0xb22222,
1372 floralwhite: 0xfffaf0,
1373 forestgreen: 0x228b22,
1374 fuchsia: 0xff00ff,
1375 gainsboro: 0xdcdcdc,
1376 ghostwhite: 0xf8f8ff,
1377 gold: 0xffd700,
1378 goldenrod: 0xdaa520,
1379 gray: 0x808080,
1380 grey: 0x808080,
1381 green: 0x008000,
1382 greenyellow: 0xadff2f,
1383 honeydew: 0xf0fff0,
1384 hotpink: 0xff69b4,
1385 indianred: 0xcd5c5c,
1386 indigo: 0x4b0082,
1387 ivory: 0xfffff0,
1388 khaki: 0xf0e68c,
1389 lavender: 0xe6e6fa,
1390 lavenderblush: 0xfff0f5,
1391 lawngreen: 0x7cfc00,
1392 lemonchiffon: 0xfffacd,
1393 lightblue: 0xadd8e6,
1394 lightcoral: 0xf08080,
1395 lightcyan: 0xe0ffff,
1396 lightgoldenrodyellow: 0xfafad2,
1397 lightgray: 0xd3d3d3,
1398 lightgrey: 0xd3d3d3,
1399 lightgreen: 0x90ee90,
1400 lightpink: 0xffb6c1,
1401 lightsalmon: 0xffa07a,
1402 lightseagreen: 0x20b2aa,
1403 lightskyblue: 0x87cefa,
1404 lightslategray: 0x778899,
1405 lightslategrey: 0x778899,
1406 lightsteelblue: 0xb0c4de,
1407 lightyellow: 0xffffe0,
1408 lime: 0x00ff00,
1409 limegreen: 0x32cd32,
1410 linen: 0xfaf0e6,
1411 magenta: 0xff00ff,
1412 maroon: 0x800000,
1413 mediumaquamarine: 0x66cdaa,
1414 mediumblue: 0x0000cd,
1415 mediumorchid: 0xba55d3,
1416 mediumpurple: 0x9370db,
1417 mediumseagreen: 0x3cb371,
1418 mediumslateblue: 0x7b68ee,
1419 mediumspringgreen: 0x00fa9a,
1420 mediumturquoise: 0x48d1cc,
1421 mediumvioletred: 0xc71585,
1422 midnightblue: 0x191970,
1423 mintcream: 0xf5fffa,
1424 mistyrose: 0xffe4e1,
1425 moccasin: 0xffe4b5,
1426 navajowhite: 0xffdead,
1427 navy: 0x000080,
1428 oldlace: 0xfdf5e6,
1429 olive: 0x808000,
1430 olivedrab: 0x6b8e23,
1431 orange: 0xffa500,
1432 orangered: 0xff4500,
1433 orchid: 0xda70d6,
1434 palegoldenrod: 0xeee8aa,
1435 palegreen: 0x98fb98,
1436 paleturquoise: 0xafeeee,
1437 palevioletred: 0xdb7093,
1438 papayawhip: 0xffefd5,
1439 peachpuff: 0xffdab9,
1440 peru: 0xcd853f,
1441 pink: 0xffc0cb,
1442 plum: 0xdda0dd,
1443 powderblue: 0xb0e0e6,
1444 purple: 0x800080,
1445 rebeccapurple: 0x663399,
1446 red: 0xff0000,
1447 rosybrown: 0xbc8f8f,
1448 royalblue: 0x4169e1,
1449 saddlebrown: 0x8b4513,
1450 salmon: 0xfa8072,
1451 sandybrown: 0xf4a460,
1452 seagreen: 0x2e8b57,
1453 seashell: 0xfff5ee,
1454 sienna: 0xa0522d,
1455 silver: 0xc0c0c0,
1456 skyblue: 0x87ceeb,
1457 slateblue: 0x6a5acd,
1458 slategray: 0x708090,
1459 slategrey: 0x708090,
1460 snow: 0xfffafa,
1461 springgreen: 0x00ff7f,
1462 steelblue: 0x4682b4,
1463 tan: 0xd2b48c,
1464 teal: 0x008080,
1465 thistle: 0xd8bfd8,
1466 tomato: 0xff6347,
1467 turquoise: 0x40e0d0,
1468 violet: 0xee82ee,
1469 wheat: 0xf5deb3,
1470 white: 0xffffff,
1471 whitesmoke: 0xf5f5f5,
1472 yellow: 0xffff00,
1473 yellowgreen: 0x9acd32,
1474 }));
1475 var systemColors = new Map(Object.entries({
1476 ActiveBorder: 0x3b99fc,
1477 ActiveCaption: 0x000000,
1478 AppWorkspace: 0xaaaaaa,
1479 Background: 0x6363ce,
1480 ButtonFace: 0xffffff,
1481 ButtonHighlight: 0xe9e9e9,
1482 ButtonShadow: 0x9fa09f,
1483 ButtonText: 0x000000,
1484 CaptionText: 0x000000,
1485 GrayText: 0x7f7f7f,
1486 Highlight: 0xb2d7ff,
1487 HighlightText: 0x000000,
1488 InactiveBorder: 0xffffff,
1489 InactiveCaption: 0xffffff,
1490 InactiveCaptionText: 0x000000,
1491 InfoBackground: 0xfbfcc5,
1492 InfoText: 0x000000,
1493 Menu: 0xf6f6f6,
1494 MenuText: 0xffffff,
1495 Scrollbar: 0xaaaaaa,
1496 ThreeDDarkShadow: 0x000000,
1497 ThreeDFace: 0xc0c0c0,
1498 ThreeDHighlight: 0xffffff,
1499 ThreeDLightShadow: 0xffffff,
1500 ThreeDShadow: 0x000000,
1501 Window: 0xececec,
1502 WindowFrame: 0xaaaaaa,
1503 WindowText: 0x000000,
1504 '-webkit-focus-ring-color': 0xe59700
1505 }).map(function (_a) {
1506 var _b = __read(_a, 2), key = _b[0], value = _b[1];
1507 return [key.toLowerCase(), value];
1508 }));
1509 function getSRGBLightness(r, g, b) {
1510 return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
1511 }
1512
1513 function scale(x, inLow, inHigh, outLow, outHigh) {
1514 return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
1515 }
1516 function clamp(x, min, max) {
1517 return Math.min(max, Math.max(min, x));
1518 }
1519 function multiplyMatrices(m1, m2) {
1520 var result = [];
1521 for (var i = 0, len = m1.length; i < len; i++) {
1522 result[i] = [];
1523 for (var j = 0, len2 = m2[0].length; j < len2; j++) {
1524 var sum = 0;
1525 for (var k = 0, len3 = m1[0].length; k < len3; k++) {
1526 sum += m1[i][k] * m2[k][j];
1527 }
1528 result[i][j] = sum;
1529 }
1530 }
1531 return result;
1532 }
1533
1534 function createFilterMatrix(config) {
1535 var m = Matrix.identity();
1536 if (config.sepia !== 0) {
1537 m = multiplyMatrices(m, Matrix.sepia(config.sepia / 100));
1538 }
1539 if (config.grayscale !== 0) {
1540 m = multiplyMatrices(m, Matrix.grayscale(config.grayscale / 100));
1541 }
1542 if (config.contrast !== 100) {
1543 m = multiplyMatrices(m, Matrix.contrast(config.contrast / 100));
1544 }
1545 if (config.brightness !== 100) {
1546 m = multiplyMatrices(m, Matrix.brightness(config.brightness / 100));
1547 }
1548 if (config.mode === 1) {
1549 m = multiplyMatrices(m, Matrix.invertNHue());
1550 }
1551 return m;
1552 }
1553 function applyColorMatrix(_a, matrix) {
1554 var _b = __read(_a, 3), r = _b[0], g = _b[1], b = _b[2];
1555 var rgb = [[r / 255], [g / 255], [b / 255], [1], [1]];
1556 var result = multiplyMatrices(matrix, rgb);
1557 return [0, 1, 2].map(function (i) { return clamp(Math.round(result[i][0] * 255), 0, 255); });
1558 }
1559 var Matrix = {
1560 identity: function () {
1561 return [
1562 [1, 0, 0, 0, 0],
1563 [0, 1, 0, 0, 0],
1564 [0, 0, 1, 0, 0],
1565 [0, 0, 0, 1, 0],
1566 [0, 0, 0, 0, 1]
1567 ];
1568 },
1569 invertNHue: function () {
1570 return [
1571 [0.333, -0.667, -0.667, 0, 1],
1572 [-0.667, 0.333, -0.667, 0, 1],
1573 [-0.667, -0.667, 0.333, 0, 1],
1574 [0, 0, 0, 1, 0],
1575 [0, 0, 0, 0, 1]
1576 ];
1577 },
1578 brightness: function (v) {
1579 return [
1580 [v, 0, 0, 0, 0],
1581 [0, v, 0, 0, 0],
1582 [0, 0, v, 0, 0],
1583 [0, 0, 0, 1, 0],
1584 [0, 0, 0, 0, 1]
1585 ];
1586 },
1587 contrast: function (v) {
1588 var t = (1 - v) / 2;
1589 return [
1590 [v, 0, 0, 0, t],
1591 [0, v, 0, 0, t],
1592 [0, 0, v, 0, t],
1593 [0, 0, 0, 1, 0],
1594 [0, 0, 0, 0, 1]
1595 ];
1596 },
1597 sepia: function (v) {
1598 return [
1599 [(0.393 + 0.607 * (1 - v)), (0.769 - 0.769 * (1 - v)), (0.189 - 0.189 * (1 - v)), 0, 0],
1600 [(0.349 - 0.349 * (1 - v)), (0.686 + 0.314 * (1 - v)), (0.168 - 0.168 * (1 - v)), 0, 0],
1601 [(0.272 - 0.272 * (1 - v)), (0.534 - 0.534 * (1 - v)), (0.131 + 0.869 * (1 - v)), 0, 0],
1602 [0, 0, 0, 1, 0],
1603 [0, 0, 0, 0, 1]
1604 ];
1605 },
1606 grayscale: function (v) {
1607 return [
1608 [(0.2126 + 0.7874 * (1 - v)), (0.7152 - 0.7152 * (1 - v)), (0.0722 - 0.0722 * (1 - v)), 0, 0],
1609 [(0.2126 - 0.2126 * (1 - v)), (0.7152 + 0.2848 * (1 - v)), (0.0722 - 0.0722 * (1 - v)), 0, 0],
1610 [(0.2126 - 0.2126 * (1 - v)), (0.7152 - 0.7152 * (1 - v)), (0.0722 + 0.9278 * (1 - v)), 0, 0],
1611 [0, 0, 0, 1, 0],
1612 [0, 0, 0, 0, 1]
1613 ];
1614 },
1615 };
1616
1617 function getBgPole(theme) {
1618 var isDarkScheme = theme.mode === 1;
1619 var prop = isDarkScheme ? 'darkSchemeBackgroundColor' : 'lightSchemeBackgroundColor';
1620 return theme[prop];
1621 }
1622 function getFgPole(theme) {
1623 var isDarkScheme = theme.mode === 1;
1624 var prop = isDarkScheme ? 'darkSchemeTextColor' : 'lightSchemeTextColor';
1625 return theme[prop];
1626 }
1627 var colorModificationCache = new Map();
1628 var colorParseCache$1 = new Map();
1629 function parseToHSLWithCache(color) {
1630 if (colorParseCache$1.has(color)) {
1631 return colorParseCache$1.get(color);
1632 }
1633 var rgb = parse(color);
1634 var hsl = rgbToHSL(rgb);
1635 colorParseCache$1.set(color, hsl);
1636 return hsl;
1637 }
1638 function clearColorModificationCache() {
1639 colorModificationCache.clear();
1640 colorParseCache$1.clear();
1641 }
1642 var rgbCacheKeys = ['r', 'g', 'b', 'a'];
1643 var themeCacheKeys$1 = ['mode', 'brightness', 'contrast', 'grayscale', 'sepia', 'darkSchemeBackgroundColor', 'darkSchemeTextColor', 'lightSchemeBackgroundColor', 'lightSchemeTextColor'];
1644 function getCacheId(rgb, theme) {
1645 var resultId = '';
1646 rgbCacheKeys.forEach(function (key) {
1647 resultId += "".concat(rgb[key], ";");
1648 });
1649 themeCacheKeys$1.forEach(function (key) {
1650 resultId += "".concat(theme[key], ";");
1651 });
1652 return resultId;
1653 }
1654 function modifyColorWithCache(rgb, theme, modifyHSL, poleColor, anotherPoleColor) {
1655 var fnCache;
1656 if (colorModificationCache.has(modifyHSL)) {
1657 fnCache = colorModificationCache.get(modifyHSL);
1658 }
1659 else {
1660 fnCache = new Map();
1661 colorModificationCache.set(modifyHSL, fnCache);
1662 }
1663 var id = getCacheId(rgb, theme);
1664 if (fnCache.has(id)) {
1665 return fnCache.get(id);
1666 }
1667 var hsl = rgbToHSL(rgb);
1668 var pole = poleColor == null ? null : parseToHSLWithCache(poleColor);
1669 var anotherPole = anotherPoleColor == null ? null : parseToHSLWithCache(anotherPoleColor);
1670 var modified = modifyHSL(hsl, pole, anotherPole);
1671 var _a = hslToRGB(modified), r = _a.r, g = _a.g, b = _a.b, a = _a.a;
1672 var matrix = createFilterMatrix(theme);
1673 var _b = __read(applyColorMatrix([r, g, b], matrix), 3), rf = _b[0], gf = _b[1], bf = _b[2];
1674 var color = (a === 1 ?
1675 rgbToHexString({ r: rf, g: gf, b: bf }) :
1676 rgbToString({ r: rf, g: gf, b: bf, a: a }));
1677 fnCache.set(id, color);
1678 return color;
1679 }
1680 function noopHSL(hsl) {
1681 return hsl;
1682 }
1683 function modifyColor(rgb, theme) {
1684 return modifyColorWithCache(rgb, theme, noopHSL);
1685 }
1686 function modifyLightSchemeColor(rgb, theme) {
1687 var poleBg = getBgPole(theme);
1688 var poleFg = getFgPole(theme);
1689 return modifyColorWithCache(rgb, theme, modifyLightModeHSL, poleFg, poleBg);
1690 }
1691 function modifyLightModeHSL(_a, poleFg, poleBg) {
1692 var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
1693 var isDark = l < 0.5;
1694 var isNeutral;
1695 if (isDark) {
1696 isNeutral = l < 0.2 || s < 0.12;
1697 }
1698 else {
1699 var isBlue = h > 200 && h < 280;
1700 isNeutral = s < 0.24 || (l > 0.8 && isBlue);
1701 }
1702 var hx = h;
1703 var sx = l;
1704 if (isNeutral) {
1705 if (isDark) {
1706 hx = poleFg.h;
1707 sx = poleFg.s;
1708 }
1709 else {
1710 hx = poleBg.h;
1711 sx = poleBg.s;
1712 }
1713 }
1714 var lx = scale(l, 0, 1, poleFg.l, poleBg.l);
1715 return { h: hx, s: sx, l: lx, a: a };
1716 }
1717 var MAX_BG_LIGHTNESS = 0.4;
1718 function modifyBgHSL(_a, pole) {
1719 var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
1720 var isDark = l < 0.5;
1721 var isBlue = h > 200 && h < 280;
1722 var isNeutral = s < 0.12 || (l > 0.8 && isBlue);
1723 if (isDark) {
1724 var lx_1 = scale(l, 0, 0.5, 0, MAX_BG_LIGHTNESS);
1725 if (isNeutral) {
1726 var hx_1 = pole.h;
1727 var sx = pole.s;
1728 return { h: hx_1, s: sx, l: lx_1, a: a };
1729 }
1730 return { h: h, s: s, l: lx_1, a: a };
1731 }
1732 var lx = scale(l, 0.5, 1, MAX_BG_LIGHTNESS, pole.l);
1733 if (isNeutral) {
1734 var hx_2 = pole.h;
1735 var sx = pole.s;
1736 return { h: hx_2, s: sx, l: lx, a: a };
1737 }
1738 var hx = h;
1739 var isYellow = h > 60 && h < 180;
1740 if (isYellow) {
1741 var isCloserToGreen = h > 120;
1742 if (isCloserToGreen) {
1743 hx = scale(h, 120, 180, 135, 180);
1744 }
1745 else {
1746 hx = scale(h, 60, 120, 60, 105);
1747 }
1748 }
1749 if (hx > 40 && hx < 80) {
1750 lx *= 0.75;
1751 }
1752 return { h: hx, s: s, l: lx, a: a };
1753 }
1754 function modifyBackgroundColor(rgb, theme) {
1755 if (theme.mode === 0) {
1756 return modifyLightSchemeColor(rgb, theme);
1757 }
1758 var pole = getBgPole(theme);
1759 return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyBgHSL, pole);
1760 }
1761 var MIN_FG_LIGHTNESS = 0.55;
1762 function modifyBlueFgHue(hue) {
1763 return scale(hue, 205, 245, 205, 220);
1764 }
1765 function modifyFgHSL(_a, pole) {
1766 var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
1767 var isLight = l > 0.5;
1768 var isNeutral = l < 0.2 || s < 0.24;
1769 var isBlue = !isNeutral && h > 205 && h < 245;
1770 if (isLight) {
1771 var lx_2 = scale(l, 0.5, 1, MIN_FG_LIGHTNESS, pole.l);
1772 if (isNeutral) {
1773 var hx_3 = pole.h;
1774 var sx = pole.s;
1775 return { h: hx_3, s: sx, l: lx_2, a: a };
1776 }
1777 var hx_4 = h;
1778 if (isBlue) {
1779 hx_4 = modifyBlueFgHue(h);
1780 }
1781 return { h: hx_4, s: s, l: lx_2, a: a };
1782 }
1783 if (isNeutral) {
1784 var hx_5 = pole.h;
1785 var sx = pole.s;
1786 var lx_3 = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
1787 return { h: hx_5, s: sx, l: lx_3, a: a };
1788 }
1789 var hx = h;
1790 var lx;
1791 if (isBlue) {
1792 hx = modifyBlueFgHue(h);
1793 lx = scale(l, 0, 0.5, pole.l, Math.min(1, MIN_FG_LIGHTNESS + 0.05));
1794 }
1795 else {
1796 lx = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
1797 }
1798 return { h: hx, s: s, l: lx, a: a };
1799 }
1800 function modifyForegroundColor(rgb, theme) {
1801 if (theme.mode === 0) {
1802 return modifyLightSchemeColor(rgb, theme);
1803 }
1804 var pole = getFgPole(theme);
1805 return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyFgHSL, pole);
1806 }
1807 function modifyBorderHSL(_a, poleFg, poleBg) {
1808 var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
1809 var isDark = l < 0.5;
1810 var isNeutral = l < 0.2 || s < 0.24;
1811 var hx = h;
1812 var sx = s;
1813 if (isNeutral) {
1814 if (isDark) {
1815 hx = poleFg.h;
1816 sx = poleFg.s;
1817 }
1818 else {
1819 hx = poleBg.h;
1820 sx = poleBg.s;
1821 }
1822 }
1823 var lx = scale(l, 0, 1, 0.5, 0.2);
1824 return { h: hx, s: sx, l: lx, a: a };
1825 }
1826 function modifyBorderColor(rgb, theme) {
1827 if (theme.mode === 0) {
1828 return modifyLightSchemeColor(rgb, theme);
1829 }
1830 var poleFg = getFgPole(theme);
1831 var poleBg = getBgPole(theme);
1832 return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyBorderHSL, poleFg, poleBg);
1833 }
1834 function modifyShadowColor(rgb, filter) {
1835 return modifyBackgroundColor(rgb, filter);
1836 }
1837 function modifyGradientColor(rgb, filter) {
1838 return modifyBackgroundColor(rgb, filter);
1839 }
1840
1841 function createTextStyle(config) {
1842 var lines = [];
1843 lines.push('*:not(pre, pre *, code, .far, .fa, .glyphicon, [class*="vjs-"], .fab, .fa-github, .fas, .material-icons, .icofont, .typcn, mu, [class*="mu-"], .glyphicon, .icon) {');
1844 if (config.useFont && config.fontFamily) {
1845 lines.push(" font-family: ".concat(config.fontFamily, " !important;"));
1846 }
1847 if (config.textStroke > 0) {
1848 lines.push(" -webkit-text-stroke: ".concat(config.textStroke, "px !important;"));
1849 lines.push(" text-stroke: ".concat(config.textStroke, "px !important;"));
1850 }
1851 lines.push('}');
1852 return lines.join('\n');
1853 }
1854
1855 var FilterMode;
1856 (function (FilterMode) {
1857 FilterMode[FilterMode["light"] = 0] = "light";
1858 FilterMode[FilterMode["dark"] = 1] = "dark";
1859 })(FilterMode || (FilterMode = {}));
1860 function getCSSFilterValue(config) {
1861 var filters = [];
1862 if (config.mode === FilterMode.dark) {
1863 filters.push('invert(100%) hue-rotate(180deg)');
1864 }
1865 if (config.brightness !== 100) {
1866 filters.push("brightness(".concat(config.brightness, "%)"));
1867 }
1868 if (config.contrast !== 100) {
1869 filters.push("contrast(".concat(config.contrast, "%)"));
1870 }
1871 if (config.grayscale !== 0) {
1872 filters.push("grayscale(".concat(config.grayscale, "%)"));
1873 }
1874 if (config.sepia !== 0) {
1875 filters.push("sepia(".concat(config.sepia, "%)"));
1876 }
1877 if (filters.length === 0) {
1878 return null;
1879 }
1880 return filters.join(' ');
1881 }
1882
1883 function toSVGMatrix(matrix) {
1884 return matrix.slice(0, 4).map(function (m) { return m.map(function (m) { return m.toFixed(3); }).join(' '); }).join(' ');
1885 }
1886 function getSVGFilterMatrixValue(config) {
1887 return toSVGMatrix(createFilterMatrix(config));
1888 }
1889
1890 var counter = 0;
1891 var resolvers$1 = new Map();
1892 var rejectors = new Map();
1893 function bgFetch(request) {
1894 return __awaiter(this, void 0, void 0, function () {
1895 return __generator(this, function (_a) {
1896 return [2, new Promise(function (resolve, reject) {
1897 var id = ++counter;
1898 resolvers$1.set(id, resolve);
1899 rejectors.set(id, reject);
1900 chrome.runtime.sendMessage({ type: MessageType.CS_FETCH, data: request, id: id });
1901 })];
1902 });
1903 });
1904 }
1905 chrome.runtime.onMessage.addListener(function (_a) {
1906 var type = _a.type, data = _a.data, error = _a.error, id = _a.id;
1907 if (type === MessageType.BG_FETCH_RESPONSE) {
1908 var resolve = resolvers$1.get(id);
1909 var reject = rejectors.get(id);
1910 resolvers$1.delete(id);
1911 rejectors.delete(id);
1912 if (error) {
1913 reject && reject(error);
1914 }
1915 else {
1916 resolve && resolve(data);
1917 }
1918 }
1919 });
1920
1921 var AsyncQueue = (function () {
1922 function AsyncQueue() {
1923 this.queue = [];
1924 this.timerId = null;
1925 this.frameDuration = 1000 / 60;
1926 }
1927 AsyncQueue.prototype.addToQueue = function (entry) {
1928 this.queue.push(entry);
1929 this.startQueue();
1930 };
1931 AsyncQueue.prototype.stopQueue = function () {
1932 if (this.timerId !== null) {
1933 cancelAnimationFrame(this.timerId);
1934 this.timerId = null;
1935 }
1936 this.queue = [];
1937 };
1938 AsyncQueue.prototype.startQueue = function () {
1939 var _this = this;
1940 if (this.timerId) {
1941 return;
1942 }
1943 this.timerId = requestAnimationFrame(function () {
1944 _this.timerId = null;
1945 var start = Date.now();
1946 var cb;
1947 while ((cb = _this.queue.shift())) {
1948 cb();
1949 if (Date.now() - start >= _this.frameDuration) {
1950 _this.startQueue();
1951 break;
1952 }
1953 }
1954 });
1955 };
1956 return AsyncQueue;
1957 }());
1958
1959 var imageManager = new AsyncQueue();
1960 function getImageDetails(url) {
1961 return __awaiter(this, void 0, void 0, function () {
1962 var _this = this;
1963 return __generator(this, function (_a) {
1964 return [2, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1965 var dataURL, error_1, image_1, error_2;
1966 return __generator(this, function (_a) {
1967 switch (_a.label) {
1968 case 0:
1969 if (!url.startsWith('data:')) return [3, 1];
1970 dataURL = url;
1971 return [3, 4];
1972 case 1:
1973 _a.trys.push([1, 3, , 4]);
1974 return [4, getImageDataURL(url)];
1975 case 2:
1976 dataURL = _a.sent();
1977 return [3, 4];
1978 case 3:
1979 error_1 = _a.sent();
1980 reject(error_1);
1981 return [2];
1982 case 4:
1983 _a.trys.push([4, 6, , 7]);
1984 return [4, urlToImage(dataURL)];
1985 case 5:
1986 image_1 = _a.sent();
1987 imageManager.addToQueue(function () {
1988 resolve(__assign({ src: url, dataURL: dataURL, width: image_1.naturalWidth, height: image_1.naturalHeight }, analyzeImage(image_1)));
1989 });
1990 return [3, 7];
1991 case 6:
1992 error_2 = _a.sent();
1993 reject(error_2);
1994 return [3, 7];
1995 case 7: return [2];
1996 }
1997 });
1998 }); })];
1999 });
2000 });
2001 }
2002 function getImageDataURL(url) {
2003 return __awaiter(this, void 0, void 0, function () {
2004 var parsedURL;
2005 return __generator(this, function (_a) {
2006 switch (_a.label) {
2007 case 0:
2008 parsedURL = new URL(url);
2009 if (!(parsedURL.origin === location.origin)) return [3, 2];
2010 return [4, loadAsDataURL(url)];
2011 case 1: return [2, _a.sent()];
2012 case 2: return [4, bgFetch({ url: url, responseType: 'data-url' })];
2013 case 3: return [2, _a.sent()];
2014 }
2015 });
2016 });
2017 }
2018 function urlToImage(url) {
2019 return __awaiter(this, void 0, void 0, function () {
2020 return __generator(this, function (_a) {
2021 return [2, new Promise(function (resolve, reject) {
2022 var image = new Image();
2023 image.onload = function () { return resolve(image); };
2024 image.onerror = function () { return reject("Unable to load image ".concat(url)); };
2025 image.src = url;
2026 })];
2027 });
2028 });
2029 }
2030 var MAX_ANALIZE_PIXELS_COUNT = 32 * 32;
2031 var canvas;
2032 var context;
2033 function createCanvas() {
2034 var maxWidth = MAX_ANALIZE_PIXELS_COUNT;
2035 var maxHeight = MAX_ANALIZE_PIXELS_COUNT;
2036 canvas = document.createElement('canvas');
2037 canvas.width = maxWidth;
2038 canvas.height = maxHeight;
2039 context = canvas.getContext('2d');
2040 context.imageSmoothingEnabled = false;
2041 }
2042 function removeCanvas() {
2043 canvas = null;
2044 context = null;
2045 }
2046 var MAX_IMAGE_SIZE = 5 * 1024 * 1024;
2047 function analyzeImage(image) {
2048 if (!canvas) {
2049 createCanvas();
2050 }
2051 var naturalWidth = image.naturalWidth, naturalHeight = image.naturalHeight;
2052 if (naturalHeight === 0 || naturalWidth === 0) {
2053 logWarn("logWarn(Image is empty ".concat(image.currentSrc, ")"));
2054 return null;
2055 }
2056 var size = naturalWidth * naturalHeight * 4;
2057 if (size > MAX_IMAGE_SIZE) {
2058 logInfo('Skipped large image analyzing(Larger than 5mb in memory)');
2059 return {
2060 isDark: false,
2061 isLight: false,
2062 isTransparent: false,
2063 isLarge: false,
2064 isTooLarge: true,
2065 };
2066 }
2067 var naturalPixelsCount = naturalWidth * naturalHeight;
2068 var k = Math.min(1, Math.sqrt(MAX_ANALIZE_PIXELS_COUNT / naturalPixelsCount));
2069 var width = Math.ceil(naturalWidth * k);
2070 var height = Math.ceil(naturalHeight * k);
2071 context.clearRect(0, 0, width, height);
2072 context.drawImage(image, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);
2073 var imageData = context.getImageData(0, 0, width, height);
2074 var d = imageData.data;
2075 var TRANSPARENT_ALPHA_THRESHOLD = 0.05;
2076 var DARK_LIGHTNESS_THRESHOLD = 0.4;
2077 var LIGHT_LIGHTNESS_THRESHOLD = 0.7;
2078 var transparentPixelsCount = 0;
2079 var darkPixelsCount = 0;
2080 var lightPixelsCount = 0;
2081 var i, x, y;
2082 var r, g, b, a;
2083 var l;
2084 for (y = 0; y < height; y++) {
2085 for (x = 0; x < width; x++) {
2086 i = 4 * (y * width + x);
2087 r = d[i + 0];
2088 g = d[i + 1];
2089 b = d[i + 2];
2090 a = d[i + 3];
2091 if (a / 255 < TRANSPARENT_ALPHA_THRESHOLD) {
2092 transparentPixelsCount++;
2093 }
2094 else {
2095 l = getSRGBLightness(r, g, b);
2096 if (l < DARK_LIGHTNESS_THRESHOLD) {
2097 darkPixelsCount++;
2098 }
2099 if (l > LIGHT_LIGHTNESS_THRESHOLD) {
2100 lightPixelsCount++;
2101 }
2102 }
2103 }
2104 }
2105 var totalPixelsCount = width * height;
2106 var opaquePixelsCount = totalPixelsCount - transparentPixelsCount;
2107 var DARK_IMAGE_THRESHOLD = 0.7;
2108 var LIGHT_IMAGE_THRESHOLD = 0.7;
2109 var TRANSPARENT_IMAGE_THRESHOLD = 0.1;
2110 var LARGE_IMAGE_PIXELS_COUNT = 800 * 600;
2111 return {
2112 isDark: ((darkPixelsCount / opaquePixelsCount) >= DARK_IMAGE_THRESHOLD),
2113 isLight: ((lightPixelsCount / opaquePixelsCount) >= LIGHT_IMAGE_THRESHOLD),
2114 isTransparent: ((transparentPixelsCount / totalPixelsCount) >= TRANSPARENT_IMAGE_THRESHOLD),
2115 isLarge: (naturalPixelsCount >= LARGE_IMAGE_PIXELS_COUNT),
2116 isTooLarge: false,
2117 };
2118 }
2119 function getFilteredImageDataURL(_a, theme) {
2120 var dataURL = _a.dataURL, width = _a.width, height = _a.height;
2121 var matrix = getSVGFilterMatrixValue(theme);
2122 var svg = [
2123 "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"".concat(width, "\" height=\"").concat(height, "\">"),
2124 '<defs>',
2125 '<filter id="darkreader-image-filter">',
2126 "<feColorMatrix type=\"matrix\" values=\"".concat(matrix, "\" />"),
2127 '</filter>',
2128 '</defs>',
2129 "<image width=\"".concat(width, "\" height=\"").concat(height, "\" filter=\"url(#darkreader-image-filter)\" xlink:href=\"").concat(dataURL, "\" />"),
2130 '</svg>',
2131 ].join('');
2132 return "data:image/svg+xml;base64,".concat(btoa(svg));
2133 }
2134 function cleanImageProcessingCache() {
2135 imageManager && imageManager.stopQueue();
2136 removeCanvas();
2137 }
2138
2139 var gradientLength = 'gradient'.length;
2140 var conicGradient = 'conic-';
2141 var conicGradientLength = conicGradient.length;
2142 var radialGradient = 'radial-';
2143 var linearGradient = 'linear-';
2144 function parseGradient(value) {
2145 var result = [];
2146 var index = 0;
2147 var startIndex = conicGradient.length;
2148 var _loop_1 = function () {
2149 var typeGradient;
2150 [linearGradient, radialGradient, conicGradient].find(function (possibleType) {
2151 if (index - possibleType.length >= 0) {
2152 var possibleGradient = value.substring(index - possibleType.length, index);
2153 if (possibleGradient === possibleType) {
2154 if (value.slice(index - possibleType.length - 10, index - possibleType.length - 1) === 'repeating') {
2155 typeGradient = "repeating-".concat(possibleType, "gradient");
2156 return true;
2157 }
2158 if (value.slice(index - possibleType.length - 8, index - possibleType.length - 1) === '-webkit') {
2159 typeGradient = "-webkit-".concat(possibleType, "gradient");
2160 return true;
2161 }
2162 typeGradient = "".concat(possibleType, "gradient");
2163 return true;
2164 }
2165 }
2166 });
2167 if (!typeGradient) {
2168 return "break";
2169 }
2170 var _a = getParenthesesRange(value, index + gradientLength), start = _a.start, end = _a.end;
2171 var match = value.substring(start + 1, end - 1);
2172 startIndex = end + 1 + conicGradientLength;
2173 result.push({
2174 typeGradient: typeGradient,
2175 match: match,
2176 offset: typeGradient.length + 2,
2177 index: index - typeGradient.length + gradientLength,
2178 hasComma: true,
2179 });
2180 };
2181 while ((index = value.indexOf('gradient', startIndex)) !== -1) {
2182 var state_1 = _loop_1();
2183 if (state_1 === "break")
2184 break;
2185 }
2186 if (result.length) {
2187 result[result.length - 1].hasComma = false;
2188 }
2189 return result;
2190 }
2191
2192 function getPriority(ruleStyle, property) {
2193 return Boolean(ruleStyle && ruleStyle.getPropertyPriority(property));
2194 }
2195 function getModifiableCSSDeclaration(property, value, rule, variablesStore, ignoreImageSelectors, isCancelled) {
2196 if (property.startsWith('--')) {
2197 var modifier = getVariableModifier(variablesStore, property, value, rule, ignoreImageSelectors, isCancelled);
2198 if (modifier) {
2199 return { property: property, value: modifier, important: getPriority(rule.style, property), sourceValue: value };
2200 }
2201 }
2202 else if (value.includes('var(')) {
2203 var modifier = getVariableDependantModifier(variablesStore, property, value);
2204 if (modifier) {
2205 return { property: property, value: modifier, important: getPriority(rule.style, property), sourceValue: value };
2206 }
2207 }
2208 else if ((property.includes('color') && property !== '-webkit-print-color-adjust') ||
2209 property === 'fill' ||
2210 property === 'stroke' ||
2211 property === 'stop-color') {
2212 var modifier = getColorModifier(property, value);
2213 if (modifier) {
2214 return { property: property, value: modifier, important: getPriority(rule.style, property), sourceValue: value };
2215 }
2216 }
2217 else if (property === 'background-image' || property === 'list-style-image') {
2218 var modifier = getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled);
2219 if (modifier) {
2220 return { property: property, value: modifier, important: getPriority(rule.style, property), sourceValue: value };
2221 }
2222 }
2223 else if (property.includes('shadow')) {
2224 var modifier = getShadowModifier(value);
2225 if (modifier) {
2226 return { property: property, value: modifier, important: getPriority(rule.style, property), sourceValue: value };
2227 }
2228 }
2229 return null;
2230 }
2231 function joinSelectors() {
2232 var selectors = [];
2233 for (var _i = 0; _i < arguments.length; _i++) {
2234 selectors[_i] = arguments[_i];
2235 }
2236 return selectors.filter(Boolean).join(', ');
2237 }
2238 function getModifiedUserAgentStyle(theme, isIFrame, styleSystemControls) {
2239 var lines = [];
2240 if (!isIFrame) {
2241 lines.push('html {');
2242 lines.push(" background-color: ".concat(modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme), " !important;"));
2243 lines.push('}');
2244 }
2245 if (isCSSColorSchemePropSupported) {
2246 lines.push('html {');
2247 lines.push(" color-scheme: ".concat(theme.mode === 1 ? 'dark' : 'dark light', " !important;"));
2248 lines.push('}');
2249 }
2250 var bgSelectors = joinSelectors(isIFrame ? '' : 'html, body', styleSystemControls ? 'input, textarea, select, button' : '');
2251 if (bgSelectors) {
2252 lines.push("".concat(bgSelectors, " {"));
2253 lines.push(" background-color: ".concat(modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme), ";"));
2254 lines.push('}');
2255 }
2256 lines.push("".concat(joinSelectors('html, body', styleSystemControls ? 'input, textarea, select, button' : ''), " {"));
2257 lines.push(" border-color: ".concat(modifyBorderColor({ r: 76, g: 76, b: 76 }, theme), ";"));
2258 lines.push(" color: ".concat(modifyForegroundColor({ r: 0, g: 0, b: 0 }, theme), ";"));
2259 lines.push('}');
2260 lines.push('a {');
2261 lines.push(" color: ".concat(modifyForegroundColor({ r: 0, g: 64, b: 255 }, theme), ";"));
2262 lines.push('}');
2263 lines.push('table {');
2264 lines.push(" border-color: ".concat(modifyBorderColor({ r: 128, g: 128, b: 128 }, theme), ";"));
2265 lines.push('}');
2266 lines.push('::placeholder {');
2267 lines.push(" color: ".concat(modifyForegroundColor({ r: 169, g: 169, b: 169 }, theme), ";"));
2268 lines.push('}');
2269 lines.push('input:-webkit-autofill,');
2270 lines.push('textarea:-webkit-autofill,');
2271 lines.push('select:-webkit-autofill {');
2272 lines.push(" background-color: ".concat(modifyBackgroundColor({ r: 250, g: 255, b: 189 }, theme), " !important;"));
2273 lines.push(" color: ".concat(modifyForegroundColor({ r: 0, g: 0, b: 0 }, theme), " !important;"));
2274 lines.push('}');
2275 if (theme.scrollbarColor) {
2276 lines.push(getModifiedScrollbarStyle(theme));
2277 }
2278 if (theme.selectionColor) {
2279 lines.push(getModifiedSelectionStyle(theme));
2280 }
2281 return lines.join('\n');
2282 }
2283 function getSelectionColor(theme) {
2284 var backgroundColorSelection;
2285 var foregroundColorSelection;
2286 if (theme.selectionColor === 'auto') {
2287 backgroundColorSelection = modifyBackgroundColor({ r: 0, g: 96, b: 212 }, __assign(__assign({}, theme), { grayscale: 0 }));
2288 foregroundColorSelection = modifyForegroundColor({ r: 255, g: 255, b: 255 }, __assign(__assign({}, theme), { grayscale: 0 }));
2289 }
2290 else {
2291 var rgb = parse(theme.selectionColor);
2292 var hsl = rgbToHSL(rgb);
2293 backgroundColorSelection = theme.selectionColor;
2294 if (hsl.l < 0.5) {
2295 foregroundColorSelection = '#FFF';
2296 }
2297 else {
2298 foregroundColorSelection = '#000';
2299 }
2300 }
2301 return { backgroundColorSelection: backgroundColorSelection, foregroundColorSelection: foregroundColorSelection };
2302 }
2303 function getModifiedSelectionStyle(theme) {
2304 var lines = [];
2305 var modifiedSelectionColor = getSelectionColor(theme);
2306 var backgroundColorSelection = modifiedSelectionColor.backgroundColorSelection;
2307 var foregroundColorSelection = modifiedSelectionColor.foregroundColorSelection;
2308 ['::selection', '::-moz-selection'].forEach(function (selection) {
2309 lines.push("".concat(selection, " {"));
2310 lines.push(" background-color: ".concat(backgroundColorSelection, " !important;"));
2311 lines.push(" color: ".concat(foregroundColorSelection, " !important;"));
2312 lines.push('}');
2313 });
2314 return lines.join('\n');
2315 }
2316 function getModifiedScrollbarStyle(theme) {
2317 var lines = [];
2318 var colorTrack;
2319 var colorIcons;
2320 var colorThumb;
2321 var colorThumbHover;
2322 var colorThumbActive;
2323 var colorCorner;
2324 if (theme.scrollbarColor === 'auto') {
2325 colorTrack = modifyBackgroundColor({ r: 241, g: 241, b: 241 }, theme);
2326 colorIcons = modifyForegroundColor({ r: 96, g: 96, b: 96 }, theme);
2327 colorThumb = modifyBackgroundColor({ r: 176, g: 176, b: 176 }, theme);
2328 colorThumbHover = modifyBackgroundColor({ r: 144, g: 144, b: 144 }, theme);
2329 colorThumbActive = modifyBackgroundColor({ r: 96, g: 96, b: 96 }, theme);
2330 colorCorner = modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme);
2331 }
2332 else {
2333 var rgb = parse(theme.scrollbarColor);
2334 var hsl_1 = rgbToHSL(rgb);
2335 var isLight = hsl_1.l > 0.5;
2336 var lighten = function (lighter) { return (__assign(__assign({}, hsl_1), { l: clamp(hsl_1.l + lighter, 0, 1) })); };
2337 var darken = function (darker) { return (__assign(__assign({}, hsl_1), { l: clamp(hsl_1.l - darker, 0, 1) })); };
2338 colorTrack = hslToString(darken(0.4));
2339 colorIcons = hslToString(isLight ? darken(0.4) : lighten(0.4));
2340 colorThumb = hslToString(hsl_1);
2341 colorThumbHover = hslToString(lighten(0.1));
2342 colorThumbActive = hslToString(lighten(0.2));
2343 }
2344 lines.push('::-webkit-scrollbar {');
2345 lines.push(" background-color: ".concat(colorTrack, ";"));
2346 lines.push(" color: ".concat(colorIcons, ";"));
2347 lines.push('}');
2348 lines.push('::-webkit-scrollbar-thumb {');
2349 lines.push(" background-color: ".concat(colorThumb, ";"));
2350 lines.push('}');
2351 lines.push('::-webkit-scrollbar-thumb:hover {');
2352 lines.push(" background-color: ".concat(colorThumbHover, ";"));
2353 lines.push('}');
2354 lines.push('::-webkit-scrollbar-thumb:active {');
2355 lines.push(" background-color: ".concat(colorThumbActive, ";"));
2356 lines.push('}');
2357 lines.push('::-webkit-scrollbar-corner {');
2358 lines.push(" background-color: ".concat(colorCorner, ";"));
2359 lines.push('}');
2360 if (isFirefox) {
2361 lines.push('* {');
2362 lines.push(" scrollbar-color: ".concat(colorThumb, " ").concat(colorTrack, ";"));
2363 lines.push('}');
2364 }
2365 return lines.join('\n');
2366 }
2367 function getModifiedFallbackStyle(filter, _a) {
2368 var strict = _a.strict;
2369 var lines = [];
2370 var isMicrosoft = location.hostname.endsWith('microsoft.com');
2371 lines.push("html, body, ".concat(strict ? "body :not(iframe)".concat(isMicrosoft ? ':not(div[style^="position:absolute;top:0;left:-"]' : '') : 'body > :not(iframe)', " {"));
2372 lines.push(" background-color: ".concat(modifyBackgroundColor({ r: 255, g: 255, b: 255 }, filter), " !important;"));
2373 lines.push(" border-color: ".concat(modifyBorderColor({ r: 64, g: 64, b: 64 }, filter), " !important;"));
2374 lines.push(" color: ".concat(modifyForegroundColor({ r: 0, g: 0, b: 0 }, filter), " !important;"));
2375 lines.push('}');
2376 return lines.join('\n');
2377 }
2378 var unparsableColors = new Set([
2379 'inherit',
2380 'transparent',
2381 'initial',
2382 'currentcolor',
2383 'none',
2384 'unset',
2385 ]);
2386 var colorParseCache = new Map();
2387 function parseColorWithCache($color) {
2388 $color = $color.trim();
2389 if (colorParseCache.has($color)) {
2390 return colorParseCache.get($color);
2391 }
2392 if ($color.includes('calc(')) {
2393 $color = lowerCalcExpression($color);
2394 }
2395 var color = parse($color);
2396 colorParseCache.set($color, color);
2397 return color;
2398 }
2399 function tryParseColor($color) {
2400 try {
2401 return parseColorWithCache($color);
2402 }
2403 catch (err) {
2404 return null;
2405 }
2406 }
2407 function getColorModifier(prop, value) {
2408 if (unparsableColors.has(value.toLowerCase())) {
2409 return value;
2410 }
2411 try {
2412 var rgb_1 = parseColorWithCache(value);
2413 if (prop.includes('background')) {
2414 return function (filter) { return modifyBackgroundColor(rgb_1, filter); };
2415 }
2416 if (prop.includes('border') || prop.includes('outline')) {
2417 return function (filter) { return modifyBorderColor(rgb_1, filter); };
2418 }
2419 return function (filter) { return modifyForegroundColor(rgb_1, filter); };
2420 }
2421 catch (err) {
2422 logWarn('Color parse error', err);
2423 return null;
2424 }
2425 }
2426 var imageDetailsCache = new Map();
2427 var awaitingForImageLoading = new Map();
2428 function shouldIgnoreImage(selectorText, selectors) {
2429 if (!selectorText || selectors.length === 0) {
2430 return false;
2431 }
2432 if (selectors.some(function (s) { return s === '*'; })) {
2433 return true;
2434 }
2435 var ruleSelectors = selectorText.split(/,\s*/g);
2436 var _loop_1 = function (i) {
2437 var ignoredSelector = selectors[i];
2438 if (ruleSelectors.some(function (s) { return s === ignoredSelector; })) {
2439 return { value: true };
2440 }
2441 };
2442 for (var i = 0; i < selectors.length; i++) {
2443 var state_1 = _loop_1(i);
2444 if (typeof state_1 === "object")
2445 return state_1.value;
2446 }
2447 return false;
2448 }
2449 function getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled) {
2450 var _this = this;
2451 try {
2452 var gradients = parseGradient(value);
2453 var urls = getMatches(cssURLRegex, value);
2454 if (urls.length === 0 && gradients.length === 0) {
2455 return value;
2456 }
2457 var getIndices = function (matches) {
2458 var index = 0;
2459 return matches.map(function (match) {
2460 var valueIndex = value.indexOf(match, index);
2461 index = valueIndex + match.length;
2462 return { match: match, index: valueIndex };
2463 });
2464 };
2465 var matches_1 = gradients.map(function (i) { return (__assign({ type: 'gradient' }, i)); })
2466 .concat(getIndices(urls).map(function (i) { return (__assign({ type: 'url', offset: 0 }, i)); }))
2467 .sort(function (a, b) { return a.index > b.index ? 1 : -1; });
2468 var getGradientModifier_1 = function (gradient) {
2469 var typeGradient = gradient.typeGradient, match = gradient.match, hasComma = gradient.hasComma;
2470 var partsRegex = /([^\(\),]+(\([^\(\)]*(\([^\(\)]*\)*[^\(\)]*)?\))?[^\(\),]*),?/g;
2471 var colorStopRegex = /^(from|color-stop|to)\(([^\(\)]*?,\s*)?(.*?)\)$/;
2472 var parts = getMatches(partsRegex, match, 1).map(function (part) {
2473 part = part.trim();
2474 var rgb = tryParseColor(part);
2475 if (rgb) {
2476 return function (filter) { return modifyGradientColor(rgb, filter); };
2477 }
2478 var space = part.lastIndexOf(' ');
2479 rgb = tryParseColor(part.substring(0, space));
2480 if (rgb) {
2481 return function (filter) { return "".concat(modifyGradientColor(rgb, filter), " ").concat(part.substring(space + 1)); };
2482 }
2483 var colorStopMatch = part.match(colorStopRegex);
2484 if (colorStopMatch) {
2485 rgb = tryParseColor(colorStopMatch[3]);
2486 if (rgb) {
2487 return function (filter) { return "".concat(colorStopMatch[1], "(").concat(colorStopMatch[2] ? "".concat(colorStopMatch[2], ", ") : '').concat(modifyGradientColor(rgb, filter), ")"); };
2488 }
2489 }
2490 return function () { return part; };
2491 });
2492 return function (filter) {
2493 return "".concat(typeGradient, "(").concat(parts.map(function (modify) { return modify(filter); }).join(', '), ")").concat(hasComma ? ', ' : '');
2494 };
2495 };
2496 var getURLModifier_1 = function (urlValue) {
2497 var _a;
2498 if (shouldIgnoreImage(rule.selectorText, ignoreImageSelectors)) {
2499 return null;
2500 }
2501 var url = getCSSURLValue(urlValue);
2502 var parentStyleSheet = rule.parentStyleSheet;
2503 var baseURL = (parentStyleSheet && parentStyleSheet.href) ?
2504 getCSSBaseBath(parentStyleSheet.href) :
2505 ((_a = parentStyleSheet.ownerNode) === null || _a === void 0 ? void 0 : _a.baseURI) || location.origin;
2506 url = getAbsoluteURL(baseURL, url);
2507 var absoluteValue = "url(\"".concat(url, "\")");
2508 return function (filter) { return __awaiter(_this, void 0, void 0, function () {
2509 var imageDetails, awaiters_1, err_1, bgImageValue;
2510 return __generator(this, function (_a) {
2511 switch (_a.label) {
2512 case 0:
2513 if (!imageDetailsCache.has(url)) return [3, 1];
2514 imageDetails = imageDetailsCache.get(url);
2515 return [3, 7];
2516 case 1:
2517 _a.trys.push([1, 6, , 7]);
2518 if (!awaitingForImageLoading.has(url)) return [3, 3];
2519 awaiters_1 = awaitingForImageLoading.get(url);
2520 return [4, new Promise(function (resolve) { return awaiters_1.push(resolve); })];
2521 case 2:
2522 imageDetails = _a.sent();
2523 if (!imageDetails) {
2524 return [2, null];
2525 }
2526 return [3, 5];
2527 case 3:
2528 awaitingForImageLoading.set(url, []);
2529 return [4, getImageDetails(url)];
2530 case 4:
2531 imageDetails = _a.sent();
2532 imageDetailsCache.set(url, imageDetails);
2533 awaitingForImageLoading.get(url).forEach(function (resolve) { return resolve(imageDetails); });
2534 awaitingForImageLoading.delete(url);
2535 _a.label = 5;
2536 case 5:
2537 if (isCancelled()) {
2538 return [2, null];
2539 }
2540 return [3, 7];
2541 case 6:
2542 err_1 = _a.sent();
2543 logWarn(err_1);
2544 if (awaitingForImageLoading.has(url)) {
2545 awaitingForImageLoading.get(url).forEach(function (resolve) { return resolve(null); });
2546 awaitingForImageLoading.delete(url);
2547 }
2548 return [2, absoluteValue];
2549 case 7:
2550 bgImageValue = getBgImageValue_1(imageDetails, filter) || absoluteValue;
2551 return [2, bgImageValue];
2552 }
2553 });
2554 }); };
2555 };
2556 var getBgImageValue_1 = function (imageDetails, filter) {
2557 var isDark = imageDetails.isDark, isLight = imageDetails.isLight, isTransparent = imageDetails.isTransparent, isLarge = imageDetails.isLarge, isTooLarge = imageDetails.isTooLarge, width = imageDetails.width;
2558 var result;
2559 if (isTooLarge) {
2560 result = "url(\"".concat(imageDetails.src, "\")");
2561 }
2562 else if (isDark && isTransparent && filter.mode === 1 && !isLarge && width > 2) {
2563 logInfo("Inverting dark image ".concat(imageDetails.src));
2564 var inverted = getFilteredImageDataURL(imageDetails, __assign(__assign({}, filter), { sepia: clamp(filter.sepia + 10, 0, 100) }));
2565 result = "url(\"".concat(inverted, "\")");
2566 }
2567 else if (isLight && !isTransparent && filter.mode === 1) {
2568 if (isLarge) {
2569 result = 'none';
2570 }
2571 else {
2572 logInfo("Dimming light image ".concat(imageDetails.src));
2573 var dimmed = getFilteredImageDataURL(imageDetails, filter);
2574 result = "url(\"".concat(dimmed, "\")");
2575 }
2576 }
2577 else if (filter.mode === 0 && isLight && !isLarge) {
2578 logInfo("Applying filter to image ".concat(imageDetails.src));
2579 var filtered = getFilteredImageDataURL(imageDetails, __assign(__assign({}, filter), { brightness: clamp(filter.brightness - 10, 5, 200), sepia: clamp(filter.sepia + 10, 0, 100) }));
2580 result = "url(\"".concat(filtered, "\")");
2581 }
2582 else {
2583 result = null;
2584 }
2585 return result;
2586 };
2587 var modifiers_1 = [];
2588 var matchIndex_1 = 0;
2589 matches_1.forEach(function (_a, i) {
2590 var type = _a.type, match = _a.match, index = _a.index, typeGradient = _a.typeGradient, hasComma = _a.hasComma, offset = _a.offset;
2591 var matchStart = index;
2592 var prefixStart = matchIndex_1;
2593 var matchEnd = matchStart + match.length + offset;
2594 matchIndex_1 = matchEnd;
2595 prefixStart !== matchStart && modifiers_1.push(function () { return value.substring(prefixStart, matchStart); });
2596 if (type === 'url') {
2597 modifiers_1.push(getURLModifier_1(match));
2598 }
2599 else if (type === 'gradient') {
2600 modifiers_1.push(getGradientModifier_1({ match: match, index: index, typeGradient: typeGradient, hasComma: hasComma, offset: offset }));
2601 }
2602 if (i === matches_1.length - 1) {
2603 modifiers_1.push(function () { return value.substring(matchEnd); });
2604 }
2605 });
2606 return function (filter) {
2607 var results = modifiers_1.filter(Boolean).map(function (modify) { return modify(filter); });
2608 if (results.some(function (r) { return r instanceof Promise; })) {
2609 return Promise.all(results).then(function (asyncResults) {
2610 return asyncResults.filter(Boolean).join('');
2611 });
2612 }
2613 return results.join('');
2614 };
2615 }
2616 catch (err) {
2617 logWarn("Unable to parse gradient ".concat(value), err);
2618 return null;
2619 }
2620 }
2621 function getShadowModifierWithInfo(value) {
2622 try {
2623 var index_1 = 0;
2624 var colorMatches_1 = getMatches(/(^|\s)(?!calc)([a-z]+\(.+?\)|#[0-9a-f]+|[a-z]+)(.*?(inset|outset)?($|,))/ig, value, 2);
2625 var notParsed_1 = 0;
2626 var modifiers_2 = colorMatches_1.map(function (match, i) {
2627 var prefixIndex = index_1;
2628 var matchIndex = value.indexOf(match, index_1);
2629 var matchEnd = matchIndex + match.length;
2630 index_1 = matchEnd;
2631 var rgb = tryParseColor(match);
2632 if (!rgb) {
2633 notParsed_1++;
2634 return function () { return value.substring(prefixIndex, matchEnd); };
2635 }
2636 return function (filter) { return "".concat(value.substring(prefixIndex, matchIndex)).concat(modifyShadowColor(rgb, filter)).concat(i === colorMatches_1.length - 1 ? value.substring(matchEnd) : ''); };
2637 });
2638 return function (filter) {
2639 var modified = modifiers_2.map(function (modify) { return modify(filter); }).join('');
2640 return {
2641 matchesLength: colorMatches_1.length,
2642 unparseableMatchesLength: notParsed_1,
2643 result: modified,
2644 };
2645 };
2646 }
2647 catch (err) {
2648 logWarn("Unable to parse shadow ".concat(value), err);
2649 return null;
2650 }
2651 }
2652 function getShadowModifier(value) {
2653 var shadowModifier = getShadowModifierWithInfo(value);
2654 if (!shadowModifier) {
2655 return null;
2656 }
2657 return function (theme) { return shadowModifier(theme).result; };
2658 }
2659 function getVariableModifier(variablesStore, prop, value, rule, ignoredImgSelectors, isCancelled) {
2660 return variablesStore.getModifierForVariable({
2661 varName: prop,
2662 sourceValue: value,
2663 rule: rule,
2664 ignoredImgSelectors: ignoredImgSelectors,
2665 isCancelled: isCancelled,
2666 });
2667 }
2668 function getVariableDependantModifier(variablesStore, prop, value) {
2669 return variablesStore.getModifierForVarDependant(prop, value);
2670 }
2671 function cleanModificationCache() {
2672 colorParseCache.clear();
2673 clearColorModificationCache();
2674 imageDetailsCache.clear();
2675 cleanImageProcessingCache();
2676 awaitingForImageLoading.clear();
2677 }
2678
2679 var VAR_TYPE_BGCOLOR = 1 << 0;
2680 var VAR_TYPE_TEXTCOLOR = 1 << 1;
2681 var VAR_TYPE_BORDERCOLOR = 1 << 2;
2682 var VAR_TYPE_BGIMG = 1 << 3;
2683 var VariablesStore = (function () {
2684 function VariablesStore() {
2685 this.varTypes = new Map();
2686 this.rulesQueue = [];
2687 this.definedVars = new Set();
2688 this.varRefs = new Map();
2689 this.unknownColorVars = new Set();
2690 this.unknownBgVars = new Set();
2691 this.undefinedVars = new Set();
2692 this.initialVarTypes = new Map();
2693 this.changedTypeVars = new Set();
2694 this.typeChangeSubscriptions = new Map();
2695 this.unstableVarValues = new Map();
2696 }
2697 VariablesStore.prototype.clear = function () {
2698 this.varTypes.clear();
2699 this.rulesQueue.splice(0);
2700 this.definedVars.clear();
2701 this.varRefs.clear();
2702 this.unknownColorVars.clear();
2703 this.unknownBgVars.clear();
2704 this.undefinedVars.clear();
2705 this.initialVarTypes.clear();
2706 this.changedTypeVars.clear();
2707 this.typeChangeSubscriptions.clear();
2708 this.unstableVarValues.clear();
2709 };
2710 VariablesStore.prototype.isVarType = function (varName, typeNum) {
2711 return (this.varTypes.has(varName) &&
2712 (this.varTypes.get(varName) & typeNum) > 0);
2713 };
2714 VariablesStore.prototype.addRulesForMatching = function (rules) {
2715 this.rulesQueue.push(rules);
2716 };
2717 VariablesStore.prototype.matchVariablesAndDependants = function () {
2718 var _this = this;
2719 this.changedTypeVars.clear();
2720 this.initialVarTypes = new Map(this.varTypes);
2721 this.collectRootVariables();
2722 this.collectVariablesAndVarDep(this.rulesQueue);
2723 this.rulesQueue.splice(0);
2724 this.collectRootVarDependants();
2725 this.varRefs.forEach(function (refs, v) {
2726 refs.forEach(function (r) {
2727 if (_this.varTypes.has(v)) {
2728 _this.resolveVariableType(r, _this.varTypes.get(v));
2729 }
2730 });
2731 });
2732 this.unknownColorVars.forEach(function (v) {
2733 if (_this.unknownBgVars.has(v)) {
2734 _this.unknownColorVars.delete(v);
2735 _this.unknownBgVars.delete(v);
2736 _this.resolveVariableType(v, VAR_TYPE_BGCOLOR);
2737 }
2738 else if (_this.isVarType(v, VAR_TYPE_BGCOLOR | VAR_TYPE_TEXTCOLOR | VAR_TYPE_BORDERCOLOR)) {
2739 _this.unknownColorVars.delete(v);
2740 }
2741 else {
2742 _this.undefinedVars.add(v);
2743 }
2744 });
2745 this.unknownBgVars.forEach(function (v) {
2746 var hasColor = _this.findVarRef(v, function (ref) {
2747 return (_this.unknownColorVars.has(ref) ||
2748 _this.isVarType(ref, VAR_TYPE_TEXTCOLOR | VAR_TYPE_BORDERCOLOR));
2749 }) != null;
2750 if (hasColor) {
2751 _this.itarateVarRefs(v, function (ref) {
2752 _this.resolveVariableType(ref, VAR_TYPE_BGCOLOR);
2753 });
2754 }
2755 else if (_this.isVarType(v, VAR_TYPE_BGCOLOR | VAR_TYPE_BGIMG)) {
2756 _this.unknownBgVars.delete(v);
2757 }
2758 else {
2759 _this.undefinedVars.add(v);
2760 }
2761 });
2762 this.changedTypeVars.forEach(function (varName) {
2763 if (_this.typeChangeSubscriptions.has(varName)) {
2764 _this.typeChangeSubscriptions
2765 .get(varName)
2766 .forEach(function (callback) {
2767 callback();
2768 });
2769 }
2770 });
2771 this.changedTypeVars.clear();
2772 };
2773 VariablesStore.prototype.getModifierForVariable = function (options) {
2774 var _this = this;
2775 return function (theme) {
2776 var varName = options.varName, sourceValue = options.sourceValue, rule = options.rule, ignoredImgSelectors = options.ignoredImgSelectors, isCancelled = options.isCancelled;
2777 var getDeclarations = function () {
2778 var declarations = [];
2779 var addModifiedValue = function (typeNum, varNameWrapper, colorModifier) {
2780 if (!_this.isVarType(varName, typeNum)) {
2781 return;
2782 }
2783 var property = varNameWrapper(varName);
2784 var modifiedValue;
2785 if (isVarDependant(sourceValue)) {
2786 if (isConstructedColorVar(sourceValue)) {
2787 var value = insertVarValues(sourceValue, _this.unstableVarValues);
2788 if (!value) {
2789 value = typeNum === VAR_TYPE_BGCOLOR ? '#ffffff' : '#000000';
2790 }
2791 modifiedValue = colorModifier(value, theme);
2792 }
2793 else {
2794 modifiedValue = replaceCSSVariablesNames(sourceValue, function (v) { return varNameWrapper(v); }, function (fallback) { return colorModifier(fallback, theme); });
2795 }
2796 }
2797 else {
2798 modifiedValue = colorModifier(sourceValue, theme);
2799 }
2800 declarations.push({
2801 property: property,
2802 value: modifiedValue,
2803 });
2804 };
2805 addModifiedValue(VAR_TYPE_BGCOLOR, wrapBgColorVariableName, tryModifyBgColor);
2806 addModifiedValue(VAR_TYPE_TEXTCOLOR, wrapTextColorVariableName, tryModifyTextColor);
2807 addModifiedValue(VAR_TYPE_BORDERCOLOR, wrapBorderColorVariableName, tryModifyBorderColor);
2808 if (_this.isVarType(varName, VAR_TYPE_BGIMG)) {
2809 var property = wrapBgImgVariableName(varName);
2810 var modifiedValue = sourceValue;
2811 if (isVarDependant(sourceValue)) {
2812 modifiedValue = replaceCSSVariablesNames(sourceValue, function (v) { return wrapBgColorVariableName(v); }, function (fallback) { return tryModifyBgColor(fallback, theme); });
2813 }
2814 var bgModifier = getBgImageModifier(modifiedValue, rule, ignoredImgSelectors, isCancelled);
2815 modifiedValue = typeof bgModifier === 'function' ? bgModifier(theme) : bgModifier;
2816 declarations.push({
2817 property: property,
2818 value: modifiedValue,
2819 });
2820 }
2821 return declarations;
2822 };
2823 var callbacks = new Set();
2824 var addListener = function (onTypeChange) {
2825 var callback = function () {
2826 var decs = getDeclarations();
2827 onTypeChange(decs);
2828 };
2829 callbacks.add(callback);
2830 _this.subscribeForVarTypeChange(varName, callback);
2831 };
2832 var removeListeners = function () {
2833 callbacks.forEach(function (callback) {
2834 _this.unsubscribeFromVariableTypeChanges(varName, callback);
2835 });
2836 };
2837 return {
2838 declarations: getDeclarations(),
2839 onTypeChange: { addListener: addListener, removeListeners: removeListeners },
2840 };
2841 };
2842 };
2843 VariablesStore.prototype.getModifierForVarDependant = function (property, sourceValue) {
2844 var _this = this;
2845 if (sourceValue.match(/^\s*(rgb|hsl)a?\(/)) {
2846 var isBg_1 = property.startsWith('background');
2847 var isText_1 = (property === 'color' || property === 'caret-color');
2848 return function (theme) {
2849 var value = insertVarValues(sourceValue, _this.unstableVarValues);
2850 if (!value) {
2851 value = isBg_1 ? '#ffffff' : '#000000';
2852 }
2853 var modifier = isBg_1 ? tryModifyBgColor : isText_1 ? tryModifyTextColor : tryModifyBorderColor;
2854 return modifier(value, theme);
2855 };
2856 }
2857 if (property === 'background-color') {
2858 return function (theme) {
2859 return replaceCSSVariablesNames(sourceValue, function (v) { return wrapBgColorVariableName(v); }, function (fallback) { return tryModifyBgColor(fallback, theme); });
2860 };
2861 }
2862 if (property === 'color' || property === 'caret-color') {
2863 return function (theme) {
2864 return replaceCSSVariablesNames(sourceValue, function (v) { return wrapTextColorVariableName(v); }, function (fallback) { return tryModifyTextColor(fallback, theme); });
2865 };
2866 }
2867 if (property === 'background' || property === 'background-image' || property === 'box-shadow') {
2868 return function (theme) {
2869 var unknownVars = new Set();
2870 var modify = function () {
2871 var variableReplaced = replaceCSSVariablesNames(sourceValue, function (v) {
2872 if (_this.isVarType(v, VAR_TYPE_BGCOLOR)) {
2873 return wrapBgColorVariableName(v);
2874 }
2875 if (_this.isVarType(v, VAR_TYPE_BGIMG)) {
2876 return wrapBgImgVariableName(v);
2877 }
2878 unknownVars.add(v);
2879 return v;
2880 }, function (fallback) { return tryModifyBgColor(fallback, theme); });
2881 if (property === 'box-shadow') {
2882 var shadowModifier = getShadowModifierWithInfo(variableReplaced);
2883 var modifiedShadow = shadowModifier(theme);
2884 if (modifiedShadow.unparseableMatchesLength !== modifiedShadow.matchesLength) {
2885 return modifiedShadow.result;
2886 }
2887 }
2888 return variableReplaced;
2889 };
2890 var modified = modify();
2891 if (unknownVars.size > 0) {
2892 return new Promise(function (resolve) {
2893 var firstUnknownVar = unknownVars.values().next().value;
2894 var callback = function () {
2895 _this.unsubscribeFromVariableTypeChanges(firstUnknownVar, callback);
2896 var newValue = modify();
2897 resolve(newValue);
2898 };
2899 _this.subscribeForVarTypeChange(firstUnknownVar, callback);
2900 });
2901 }
2902 return modified;
2903 };
2904 }
2905 if (property.startsWith('border') || property.startsWith('outline')) {
2906 return function (theme) {
2907 return replaceCSSVariablesNames(sourceValue, function (v) { return wrapBorderColorVariableName(v); }, function (fallback) { return tryModifyBorderColor(fallback, theme); });
2908 };
2909 }
2910 return null;
2911 };
2912 VariablesStore.prototype.subscribeForVarTypeChange = function (varName, callback) {
2913 if (!this.typeChangeSubscriptions.has(varName)) {
2914 this.typeChangeSubscriptions.set(varName, new Set());
2915 }
2916 var rootStore = this.typeChangeSubscriptions.get(varName);
2917 if (!rootStore.has(callback)) {
2918 rootStore.add(callback);
2919 }
2920 };
2921 VariablesStore.prototype.unsubscribeFromVariableTypeChanges = function (varName, callback) {
2922 if (this.typeChangeSubscriptions.has(varName)) {
2923 this.typeChangeSubscriptions.get(varName).delete(callback);
2924 }
2925 };
2926 VariablesStore.prototype.collectVariablesAndVarDep = function (ruleList) {
2927 var _this = this;
2928 ruleList.forEach(function (rules) {
2929 iterateCSSRules(rules, function (rule) {
2930 rule.style && iterateCSSDeclarations(rule.style, function (property, value) {
2931 if (isVariable(property)) {
2932 _this.inspectVariable(property, value);
2933 }
2934 if (isVarDependant(value)) {
2935 _this.inspectVarDependant(property, value);
2936 }
2937 });
2938 });
2939 });
2940 };
2941 VariablesStore.prototype.collectRootVariables = function () {
2942 var _this = this;
2943 iterateCSSDeclarations(document.documentElement.style, function (property, value) {
2944 if (isVariable(property)) {
2945 _this.inspectVariable(property, value);
2946 }
2947 });
2948 };
2949 VariablesStore.prototype.inspectVariable = function (varName, value) {
2950 this.unstableVarValues.set(varName, value);
2951 if (isVarDependant(value) && isConstructedColorVar(value)) {
2952 this.unknownColorVars.add(varName);
2953 this.definedVars.add(varName);
2954 }
2955 if (this.definedVars.has(varName)) {
2956 return;
2957 }
2958 this.definedVars.add(varName);
2959 var color = tryParseColor(value);
2960 if (color) {
2961 this.unknownColorVars.add(varName);
2962 }
2963 else if (value.includes('url(') ||
2964 value.includes('linear-gradient(') ||
2965 value.includes('radial-gradient(')) {
2966 this.resolveVariableType(varName, VAR_TYPE_BGIMG);
2967 }
2968 };
2969 VariablesStore.prototype.resolveVariableType = function (varName, typeNum) {
2970 var initialType = this.initialVarTypes.get(varName) || 0;
2971 var currentType = this.varTypes.get(varName) || 0;
2972 var newType = currentType | typeNum;
2973 this.varTypes.set(varName, newType);
2974 if (newType !== initialType || this.undefinedVars.has(varName)) {
2975 this.changedTypeVars.add(varName);
2976 this.undefinedVars.delete(varName);
2977 }
2978 this.unknownColorVars.delete(varName);
2979 this.unknownBgVars.delete(varName);
2980 };
2981 VariablesStore.prototype.collectRootVarDependants = function () {
2982 var _this = this;
2983 iterateCSSDeclarations(document.documentElement.style, function (property, value) {
2984 if (isVarDependant(value)) {
2985 _this.inspectVarDependant(property, value);
2986 }
2987 });
2988 };
2989 VariablesStore.prototype.inspectVarDependant = function (property, value) {
2990 var _this = this;
2991 if (isVariable(property)) {
2992 this.iterateVarDeps(value, function (ref) {
2993 if (!_this.varRefs.has(property)) {
2994 _this.varRefs.set(property, new Set());
2995 }
2996 _this.varRefs.get(property).add(ref);
2997 });
2998 }
2999 else if (property === 'background-color' || property === 'box-shadow') {
3000 this.iterateVarDeps(value, function (v) { return _this.resolveVariableType(v, VAR_TYPE_BGCOLOR); });
3001 }
3002 else if (property === 'color' || property === 'caret-color') {
3003 this.iterateVarDeps(value, function (v) { return _this.resolveVariableType(v, VAR_TYPE_TEXTCOLOR); });
3004 }
3005 else if (property.startsWith('border') || property.startsWith('outline')) {
3006 this.iterateVarDeps(value, function (v) { return _this.resolveVariableType(v, VAR_TYPE_BORDERCOLOR); });
3007 }
3008 else if (property === 'background' || property === 'background-image') {
3009 this.iterateVarDeps(value, function (v) {
3010 if (_this.isVarType(v, VAR_TYPE_BGCOLOR | VAR_TYPE_BGIMG)) {
3011 return;
3012 }
3013 var isBgColor = _this.findVarRef(v, function (ref) {
3014 return (_this.unknownColorVars.has(ref) ||
3015 _this.isVarType(ref, VAR_TYPE_TEXTCOLOR | VAR_TYPE_BORDERCOLOR));
3016 }) != null;
3017 _this.itarateVarRefs(v, function (ref) {
3018 if (isBgColor) {
3019 _this.resolveVariableType(ref, VAR_TYPE_BGCOLOR);
3020 }
3021 else {
3022 _this.unknownBgVars.add(ref);
3023 }
3024 });
3025 });
3026 }
3027 };
3028 VariablesStore.prototype.iterateVarDeps = function (value, iterator) {
3029 var varDeps = new Set();
3030 iterateVarDependencies(value, function (v) { return varDeps.add(v); });
3031 varDeps.forEach(function (v) { return iterator(v); });
3032 };
3033 VariablesStore.prototype.findVarRef = function (varName, iterator, stack) {
3034 var e_1, _a;
3035 if (stack === void 0) { stack = new Set(); }
3036 if (stack.has(varName)) {
3037 return null;
3038 }
3039 stack.add(varName);
3040 var result = iterator(varName);
3041 if (result) {
3042 return varName;
3043 }
3044 var refs = this.varRefs.get(varName);
3045 if (!refs || refs.size === 0) {
3046 return null;
3047 }
3048 try {
3049 for (var refs_1 = __values(refs), refs_1_1 = refs_1.next(); !refs_1_1.done; refs_1_1 = refs_1.next()) {
3050 var ref = refs_1_1.value;
3051 var found = this.findVarRef(ref, iterator, stack);
3052 if (found) {
3053 return found;
3054 }
3055 }
3056 }
3057 catch (e_1_1) { e_1 = { error: e_1_1 }; }
3058 finally {
3059 try {
3060 if (refs_1_1 && !refs_1_1.done && (_a = refs_1.return)) _a.call(refs_1);
3061 }
3062 finally { if (e_1) throw e_1.error; }
3063 }
3064 return null;
3065 };
3066 VariablesStore.prototype.itarateVarRefs = function (varName, iterator) {
3067 this.findVarRef(varName, function (ref) {
3068 iterator(ref);
3069 return false;
3070 });
3071 };
3072 VariablesStore.prototype.setOnRootVariableChange = function (callback) {
3073 this.onRootVariableDefined = callback;
3074 };
3075 VariablesStore.prototype.putRootVars = function (styleElement, theme) {
3076 var e_2, _a;
3077 var _this = this;
3078 var sheet = styleElement.sheet;
3079 if (sheet.cssRules.length > 0) {
3080 sheet.deleteRule(0);
3081 }
3082 var declarations = new Map();
3083 iterateCSSDeclarations(document.documentElement.style, function (property, value) {
3084 if (isVariable(property)) {
3085 if (_this.isVarType(property, VAR_TYPE_BGCOLOR)) {
3086 declarations.set(wrapBgColorVariableName(property), tryModifyBgColor(value, theme));
3087 }
3088 if (_this.isVarType(property, VAR_TYPE_TEXTCOLOR)) {
3089 declarations.set(wrapTextColorVariableName(property), tryModifyTextColor(value, theme));
3090 }
3091 if (_this.isVarType(property, VAR_TYPE_BORDERCOLOR)) {
3092 declarations.set(wrapBorderColorVariableName(property), tryModifyBorderColor(value, theme));
3093 }
3094 _this.subscribeForVarTypeChange(property, _this.onRootVariableDefined);
3095 }
3096 });
3097 var cssLines = [];
3098 cssLines.push(':root {');
3099 try {
3100 for (var declarations_1 = __values(declarations), declarations_1_1 = declarations_1.next(); !declarations_1_1.done; declarations_1_1 = declarations_1.next()) {
3101 var _b = __read(declarations_1_1.value, 2), property = _b[0], value = _b[1];
3102 cssLines.push(" ".concat(property, ": ").concat(value, ";"));
3103 }
3104 }
3105 catch (e_2_1) { e_2 = { error: e_2_1 }; }
3106 finally {
3107 try {
3108 if (declarations_1_1 && !declarations_1_1.done && (_a = declarations_1.return)) _a.call(declarations_1);
3109 }
3110 finally { if (e_2) throw e_2.error; }
3111 }
3112 cssLines.push('}');
3113 var cssText = cssLines.join('\n');
3114 sheet.insertRule(cssText);
3115 };
3116 return VariablesStore;
3117 }());
3118 var variablesStore = new VariablesStore();
3119 function getVariableRange(input, searchStart) {
3120 if (searchStart === void 0) { searchStart = 0; }
3121 var start = input.indexOf('var(', searchStart);
3122 if (start >= 0) {
3123 var range = getParenthesesRange(input, start + 3);
3124 if (range) {
3125 return { start: start, end: range.end };
3126 }
3127 return null;
3128 }
3129 }
3130 function getVariablesMatches(input) {
3131 var ranges = [];
3132 var i = 0;
3133 var range;
3134 while ((range = getVariableRange(input, i))) {
3135 var start = range.start, end = range.end;
3136 ranges.push({ start: start, end: end, value: input.substring(start, end) });
3137 i = range.end + 1;
3138 }
3139 return ranges;
3140 }
3141 function replaceVariablesMatches(input, replacer) {
3142 var matches = getVariablesMatches(input);
3143 var matchesCount = matches.length;
3144 if (matchesCount === 0) {
3145 return input;
3146 }
3147 var inputLength = input.length;
3148 var replacements = matches.map(function (m) { return replacer(m.value); });
3149 var parts = [];
3150 parts.push(input.substring(0, matches[0].start));
3151 for (var i = 0; i < matchesCount; i++) {
3152 parts.push(replacements[i]);
3153 var start = matches[i].end;
3154 var end = i < matchesCount - 1 ? matches[i + 1].start : inputLength;
3155 parts.push(input.substring(start, end));
3156 }
3157 return parts.join('');
3158 }
3159 function getVariableNameAndFallback(match) {
3160 var commaIndex = match.indexOf(',');
3161 var name;
3162 var fallback;
3163 if (commaIndex >= 0) {
3164 name = match.substring(4, commaIndex).trim();
3165 fallback = match.substring(commaIndex + 1, match.length - 1).trim();
3166 }
3167 else {
3168 name = match.substring(4, match.length - 1).trim();
3169 fallback = '';
3170 }
3171 return { name: name, fallback: fallback };
3172 }
3173 function replaceCSSVariablesNames(value, nameReplacer, fallbackReplacer) {
3174 var matchReplacer = function (match) {
3175 var _a = getVariableNameAndFallback(match), name = _a.name, fallback = _a.fallback;
3176 var newName = nameReplacer(name);
3177 if (!fallback) {
3178 return "var(".concat(newName, ")");
3179 }
3180 var newFallback;
3181 if (isVarDependant(fallback)) {
3182 newFallback = replaceCSSVariablesNames(fallback, nameReplacer, fallbackReplacer);
3183 }
3184 else if (fallbackReplacer) {
3185 newFallback = fallbackReplacer(fallback);
3186 }
3187 else {
3188 newFallback = fallback;
3189 }
3190 return "var(".concat(newName, ", ").concat(newFallback, ")");
3191 };
3192 return replaceVariablesMatches(value, matchReplacer);
3193 }
3194 function iterateVarDependencies(value, iterator) {
3195 replaceCSSVariablesNames(value, function (varName) {
3196 iterator(varName);
3197 return varName;
3198 });
3199 }
3200 function wrapBgColorVariableName(name) {
3201 return "--darkreader-bg".concat(name);
3202 }
3203 function wrapTextColorVariableName(name) {
3204 return "--darkreader-text".concat(name);
3205 }
3206 function wrapBorderColorVariableName(name) {
3207 return "--darkreader-border".concat(name);
3208 }
3209 function wrapBgImgVariableName(name) {
3210 return "--darkreader-bgimg".concat(name);
3211 }
3212 function isVariable(property) {
3213 return property.startsWith('--');
3214 }
3215 function isVarDependant(value) {
3216 return value.includes('var(');
3217 }
3218 function isConstructedColorVar(value) {
3219 return value.match(/^\s*(rgb|hsl)a?\(/);
3220 }
3221 var rawValueRegex = /^\d{1,3}, ?\d{1,3}, ?\d{1,3}$/;
3222 function parseRawValue(color) {
3223 if (rawValueRegex.test(color)) {
3224 var splitted = color.split(',');
3225 var resultInRGB_1 = 'rgb(';
3226 splitted.forEach(function (number) {
3227 resultInRGB_1 += "".concat(number.trim(), ", ");
3228 });
3229 resultInRGB_1 = resultInRGB_1.substring(0, resultInRGB_1.length - 2);
3230 resultInRGB_1 += ')';
3231 return { isRaw: true, color: resultInRGB_1 };
3232 }
3233 return { isRaw: false, color: color };
3234 }
3235 function handleRawValue(color, theme, modifyFunction) {
3236 var _a = parseRawValue(color), isRaw = _a.isRaw, newColor = _a.color;
3237 var rgb = tryParseColor(newColor);
3238 if (rgb) {
3239 var outputColor = modifyFunction(rgb, theme);
3240 if (isRaw) {
3241 var outputInRGB = tryParseColor(outputColor);
3242 return outputInRGB ? "".concat(outputInRGB.r, ", ").concat(outputInRGB.g, ", ").concat(outputInRGB.b) : outputColor;
3243 }
3244 return outputColor;
3245 }
3246 return newColor;
3247 }
3248 function tryModifyBgColor(color, theme) {
3249 return handleRawValue(color, theme, modifyBackgroundColor);
3250 }
3251 function tryModifyTextColor(color, theme) {
3252 return handleRawValue(color, theme, modifyForegroundColor);
3253 }
3254 function tryModifyBorderColor(color, theme) {
3255 return handleRawValue(color, theme, modifyBorderColor);
3256 }
3257 function insertVarValues(source, varValues, stack) {
3258 if (stack === void 0) { stack = new Set(); }
3259 var containsUnresolvedVar = false;
3260 var matchReplacer = function (match) {
3261 var _a = getVariableNameAndFallback(match), name = _a.name, fallback = _a.fallback;
3262 if (stack.has(name)) {
3263 containsUnresolvedVar = true;
3264 return null;
3265 }
3266 stack.add(name);
3267 var varValue = varValues.get(name) || fallback;
3268 var inserted = null;
3269 if (varValue) {
3270 if (isVarDependant(varValue)) {
3271 inserted = insertVarValues(varValue, varValues, stack);
3272 }
3273 else {
3274 inserted = varValue;
3275 }
3276 }
3277 if (!inserted) {
3278 containsUnresolvedVar = true;
3279 return null;
3280 }
3281 return inserted;
3282 };
3283 var replaced = replaceVariablesMatches(source, matchReplacer);
3284 if (containsUnresolvedVar) {
3285 return null;
3286 }
3287 return replaced;
3288 }
3289
3290 var overrides = {
3291 'background-color': {
3292 customProp: '--darkreader-inline-bgcolor',
3293 cssProp: 'background-color',
3294 dataAttr: 'data-darkreader-inline-bgcolor',
3295 },
3296 'background-image': {
3297 customProp: '--darkreader-inline-bgimage',
3298 cssProp: 'background-image',
3299 dataAttr: 'data-darkreader-inline-bgimage',
3300 },
3301 'border-color': {
3302 customProp: '--darkreader-inline-border',
3303 cssProp: 'border-color',
3304 dataAttr: 'data-darkreader-inline-border',
3305 },
3306 'border-bottom-color': {
3307 customProp: '--darkreader-inline-border-bottom',
3308 cssProp: 'border-bottom-color',
3309 dataAttr: 'data-darkreader-inline-border-bottom',
3310 },
3311 'border-left-color': {
3312 customProp: '--darkreader-inline-border-left',
3313 cssProp: 'border-left-color',
3314 dataAttr: 'data-darkreader-inline-border-left',
3315 },
3316 'border-right-color': {
3317 customProp: '--darkreader-inline-border-right',
3318 cssProp: 'border-right-color',
3319 dataAttr: 'data-darkreader-inline-border-right',
3320 },
3321 'border-top-color': {
3322 customProp: '--darkreader-inline-border-top',
3323 cssProp: 'border-top-color',
3324 dataAttr: 'data-darkreader-inline-border-top',
3325 },
3326 'box-shadow': {
3327 customProp: '--darkreader-inline-boxshadow',
3328 cssProp: 'box-shadow',
3329 dataAttr: 'data-darkreader-inline-boxshadow',
3330 },
3331 'color': {
3332 customProp: '--darkreader-inline-color',
3333 cssProp: 'color',
3334 dataAttr: 'data-darkreader-inline-color',
3335 },
3336 'fill': {
3337 customProp: '--darkreader-inline-fill',
3338 cssProp: 'fill',
3339 dataAttr: 'data-darkreader-inline-fill',
3340 },
3341 'stroke': {
3342 customProp: '--darkreader-inline-stroke',
3343 cssProp: 'stroke',
3344 dataAttr: 'data-darkreader-inline-stroke',
3345 },
3346 'outline-color': {
3347 customProp: '--darkreader-inline-outline',
3348 cssProp: 'outline-color',
3349 dataAttr: 'data-darkreader-inline-outline',
3350 },
3351 'stop-color': {
3352 customProp: '--darkreader-inline-stopcolor',
3353 cssProp: 'stop-color',
3354 dataAttr: 'data-darkreader-inline-stopcolor',
3355 },
3356 };
3357 var overridesList = Object.values(overrides);
3358 var normalizedPropList = {};
3359 overridesList.forEach(function (_a) {
3360 var cssProp = _a.cssProp, customProp = _a.customProp;
3361 return normalizedPropList[customProp] = cssProp;
3362 });
3363 var INLINE_STYLE_ATTRS = ['style', 'fill', 'stop-color', 'stroke', 'bgcolor', 'color'];
3364 var INLINE_STYLE_SELECTOR = INLINE_STYLE_ATTRS.map(function (attr) { return "[".concat(attr, "]"); }).join(', ');
3365 function getInlineOverrideStyle() {
3366 return overridesList.map(function (_a) {
3367 var dataAttr = _a.dataAttr, customProp = _a.customProp, cssProp = _a.cssProp;
3368 return [
3369 "[".concat(dataAttr, "] {"),
3370 " ".concat(cssProp, ": var(").concat(customProp, ") !important;"),
3371 '}',
3372 ].join('\n');
3373 }).join('\n');
3374 }
3375 function getInlineStyleElements(root) {
3376 var results = [];
3377 if (root instanceof Element && root.matches(INLINE_STYLE_SELECTOR)) {
3378 results.push(root);
3379 }
3380 if (root instanceof Element || (isShadowDomSupported && root instanceof ShadowRoot) || root instanceof Document) {
3381 push(results, root.querySelectorAll(INLINE_STYLE_SELECTOR));
3382 }
3383 return results;
3384 }
3385 var treeObservers = new Map();
3386 var attrObservers = new Map();
3387 function watchForInlineStyles(elementStyleDidChange, shadowRootDiscovered) {
3388 deepWatchForInlineStyles(document, elementStyleDidChange, shadowRootDiscovered);
3389 iterateShadowHosts(document.documentElement, function (host) {
3390 deepWatchForInlineStyles(host.shadowRoot, elementStyleDidChange, shadowRootDiscovered);
3391 });
3392 }
3393 function deepWatchForInlineStyles(root, elementStyleDidChange, shadowRootDiscovered) {
3394 if (treeObservers.has(root)) {
3395 treeObservers.get(root).disconnect();
3396 attrObservers.get(root).disconnect();
3397 }
3398 var discoveredNodes = new WeakSet();
3399 function discoverNodes(node) {
3400 getInlineStyleElements(node).forEach(function (el) {
3401 if (discoveredNodes.has(el)) {
3402 return;
3403 }
3404 discoveredNodes.add(el);
3405 elementStyleDidChange(el);
3406 });
3407 iterateShadowHosts(node, function (n) {
3408 if (discoveredNodes.has(node)) {
3409 return;
3410 }
3411 discoveredNodes.add(node);
3412 shadowRootDiscovered(n.shadowRoot);
3413 deepWatchForInlineStyles(n.shadowRoot, elementStyleDidChange, shadowRootDiscovered);
3414 });
3415 }
3416 var treeObserver = createOptimizedTreeObserver(root, {
3417 onMinorMutations: function (_a) {
3418 var additions = _a.additions;
3419 additions.forEach(function (added) { return discoverNodes(added); });
3420 },
3421 onHugeMutations: function () {
3422 discoverNodes(root);
3423 },
3424 });
3425 treeObservers.set(root, treeObserver);
3426 var attemptCount = 0;
3427 var start = null;
3428 var ATTEMPTS_INTERVAL = getDuration({ seconds: 10 });
3429 var RETRY_TIMEOUT = getDuration({ seconds: 2 });
3430 var MAX_ATTEMPTS_COUNT = 50;
3431 var cache = [];
3432 var timeoutId = null;
3433 var handleAttributeMutations = throttle(function (mutations) {
3434 mutations.forEach(function (m) {
3435 if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
3436 elementStyleDidChange(m.target);
3437 }
3438 });
3439 });
3440 var attrObserver = new MutationObserver(function (mutations) {
3441 if (timeoutId) {
3442 cache.push.apply(cache, __spreadArray([], __read(mutations), false));
3443 return;
3444 }
3445 attemptCount++;
3446 var now = Date.now();
3447 if (start == null) {
3448 start = now;
3449 }
3450 else if (attemptCount >= MAX_ATTEMPTS_COUNT) {
3451 if (now - start < ATTEMPTS_INTERVAL) {
3452 timeoutId = setTimeout(function () {
3453 start = null;
3454 attemptCount = 0;
3455 timeoutId = null;
3456 var attributeCache = cache;
3457 cache = [];
3458 handleAttributeMutations(attributeCache);
3459 }, RETRY_TIMEOUT);
3460 cache.push.apply(cache, __spreadArray([], __read(mutations), false));
3461 return;
3462 }
3463 start = now;
3464 attemptCount = 1;
3465 }
3466 handleAttributeMutations(mutations);
3467 });
3468 attrObserver.observe(root, {
3469 attributes: true,
3470 attributeFilter: INLINE_STYLE_ATTRS.concat(overridesList.map(function (_a) {
3471 var dataAttr = _a.dataAttr;
3472 return dataAttr;
3473 })),
3474 subtree: true,
3475 });
3476 attrObservers.set(root, attrObserver);
3477 }
3478 function stopWatchingForInlineStyles() {
3479 treeObservers.forEach(function (o) { return o.disconnect(); });
3480 attrObservers.forEach(function (o) { return o.disconnect(); });
3481 treeObservers.clear();
3482 attrObservers.clear();
3483 }
3484 var inlineStyleCache = new WeakMap();
3485 var filterProps = ['brightness', 'contrast', 'grayscale', 'sepia', 'mode'];
3486 function getInlineStyleCacheKey(el, theme) {
3487 return INLINE_STYLE_ATTRS
3488 .map(function (attr) { return "".concat(attr, "=\"").concat(el.getAttribute(attr), "\""); })
3489 .concat(filterProps.map(function (prop) { return "".concat(prop, "=\"").concat(theme[prop], "\""); }))
3490 .join(' ');
3491 }
3492 function shouldIgnoreInlineStyle(element, selectors) {
3493 for (var i = 0, len = selectors.length; i < len; i++) {
3494 var ingnoredSelector = selectors[i];
3495 if (element.matches(ingnoredSelector)) {
3496 return true;
3497 }
3498 }
3499 return false;
3500 }
3501 function overrideInlineStyle(element, theme, ignoreInlineSelectors, ignoreImageSelectors) {
3502 var cacheKey = getInlineStyleCacheKey(element, theme);
3503 if (cacheKey === inlineStyleCache.get(element)) {
3504 return;
3505 }
3506 var unsetProps = new Set(Object.keys(overrides));
3507 function setCustomProp(targetCSSProp, modifierCSSProp, cssVal) {
3508 var isPropertyVariable = targetCSSProp.startsWith('--');
3509 var _a = isPropertyVariable ? {} : overrides[targetCSSProp], customProp = _a.customProp, dataAttr = _a.dataAttr;
3510 var mod = getModifiableCSSDeclaration(modifierCSSProp, cssVal, {}, variablesStore, ignoreImageSelectors, null);
3511 if (!mod) {
3512 return;
3513 }
3514 var value = mod.value;
3515 if (typeof value === 'function') {
3516 value = value(theme);
3517 }
3518 if (isPropertyVariable && typeof value === 'object') {
3519 var typedValue = value;
3520 typedValue.declarations.forEach(function (_a) {
3521 var property = _a.property, value = _a.value;
3522 !(value instanceof Promise) && element.style.setProperty(property, value);
3523 });
3524 }
3525 else {
3526 element.style.setProperty(customProp, value);
3527 if (!element.hasAttribute(dataAttr)) {
3528 element.setAttribute(dataAttr, '');
3529 }
3530 unsetProps.delete(targetCSSProp);
3531 }
3532 }
3533 if (ignoreInlineSelectors.length > 0) {
3534 if (shouldIgnoreInlineStyle(element, ignoreInlineSelectors)) {
3535 unsetProps.forEach(function (cssProp) {
3536 element.removeAttribute(overrides[cssProp].dataAttr);
3537 });
3538 return;
3539 }
3540 }
3541 if (element.hasAttribute('bgcolor')) {
3542 var value = element.getAttribute('bgcolor');
3543 if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
3544 value = "#".concat(value);
3545 }
3546 setCustomProp('background-color', 'background-color', value);
3547 }
3548 if (element.hasAttribute('color') && element.rel !== 'mask-icon') {
3549 var value = element.getAttribute('color');
3550 if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
3551 value = "#".concat(value);
3552 }
3553 setCustomProp('color', 'color', value);
3554 }
3555 if (element instanceof SVGElement) {
3556 if (element.hasAttribute('fill')) {
3557 var SMALL_SVG_LIMIT_1 = 32;
3558 var value_1 = element.getAttribute('fill');
3559 if (value_1 !== 'none') {
3560 if (!(element instanceof SVGTextElement)) {
3561 var handleSVGElement = function () {
3562 var _a = element.getBoundingClientRect(), width = _a.width, height = _a.height;
3563 var isBg = (width > SMALL_SVG_LIMIT_1 || height > SMALL_SVG_LIMIT_1);
3564 setCustomProp('fill', isBg ? 'background-color' : 'color', value_1);
3565 };
3566 if (isReadyStateComplete()) {
3567 handleSVGElement();
3568 }
3569 else {
3570 addReadyStateCompleteListener(handleSVGElement);
3571 }
3572 }
3573 else {
3574 setCustomProp('fill', 'color', value_1);
3575 }
3576 }
3577 }
3578 if (element.hasAttribute('stop-color')) {
3579 setCustomProp('stop-color', 'background-color', element.getAttribute('stop-color'));
3580 }
3581 }
3582 if (element.hasAttribute('stroke')) {
3583 var value = element.getAttribute('stroke');
3584 setCustomProp('stroke', element instanceof SVGLineElement || element instanceof SVGTextElement ? 'border-color' : 'color', value);
3585 }
3586 element.style && iterateCSSDeclarations(element.style, function (property, value) {
3587 if (property === 'background-image' && value.includes('url')) {
3588 return;
3589 }
3590 if (overrides.hasOwnProperty(property) || (property.startsWith('--') && !normalizedPropList[property])) {
3591 setCustomProp(property, property, value);
3592 }
3593 else {
3594 var overridenProp = normalizedPropList[property];
3595 if (overridenProp &&
3596 (!element.style.getPropertyValue(overridenProp) && !element.hasAttribute(overridenProp))) {
3597 if (overridenProp === 'background-color' && element.hasAttribute('bgcolor')) {
3598 return;
3599 }
3600 element.style.setProperty(property, '');
3601 }
3602 }
3603 });
3604 if (element.style && element instanceof SVGTextElement && element.style.fill) {
3605 setCustomProp('fill', 'color', element.style.getPropertyValue('fill'));
3606 }
3607 forEach(unsetProps, function (cssProp) {
3608 element.removeAttribute(overrides[cssProp].dataAttr);
3609 });
3610 inlineStyleCache.set(element, getInlineStyleCacheKey(element, theme));
3611 }
3612
3613 var metaThemeColorName = 'theme-color';
3614 var metaThemeColorSelector = "meta[name=\"".concat(metaThemeColorName, "\"]");
3615 var srcMetaThemeColor = null;
3616 var observer = null;
3617 function changeMetaThemeColor(meta, theme) {
3618 srcMetaThemeColor = srcMetaThemeColor || meta.content;
3619 try {
3620 var color = parse(srcMetaThemeColor);
3621 meta.content = modifyBackgroundColor(color, theme);
3622 }
3623 catch (err) {
3624 logWarn(err);
3625 }
3626 }
3627 function changeMetaThemeColorWhenAvailable(theme) {
3628 var meta = document.querySelector(metaThemeColorSelector);
3629 if (meta) {
3630 changeMetaThemeColor(meta, theme);
3631 }
3632 else {
3633 if (observer) {
3634 observer.disconnect();
3635 }
3636 observer = new MutationObserver(function (mutations) {
3637 loop: for (var i = 0; i < mutations.length; i++) {
3638 var addedNodes = mutations[i].addedNodes;
3639 for (var j = 0; j < addedNodes.length; j++) {
3640 var node = addedNodes[j];
3641 if (node instanceof HTMLMetaElement && node.name === metaThemeColorName) {
3642 observer.disconnect();
3643 observer = null;
3644 changeMetaThemeColor(node, theme);
3645 break loop;
3646 }
3647 }
3648 }
3649 });
3650 observer.observe(document.head, { childList: true });
3651 }
3652 }
3653 function restoreMetaThemeColor() {
3654 if (observer) {
3655 observer.disconnect();
3656 observer = null;
3657 }
3658 var meta = document.querySelector(metaThemeColorSelector);
3659 if (meta && srcMetaThemeColor) {
3660 meta.content = srcMetaThemeColor;
3661 }
3662 }
3663
3664 var themeCacheKeys = [
3665 'mode',
3666 'brightness',
3667 'contrast',
3668 'grayscale',
3669 'sepia',
3670 'darkSchemeBackgroundColor',
3671 'darkSchemeTextColor',
3672 'lightSchemeBackgroundColor',
3673 'lightSchemeTextColor',
3674 ];
3675 function getThemeKey(theme) {
3676 var resultKey = '';
3677 themeCacheKeys.forEach(function (key) {
3678 resultKey += "".concat(key, ":").concat(theme[key], ";");
3679 });
3680 return resultKey;
3681 }
3682 var asyncQueue = createAsyncTasksQueue();
3683 function createStyleSheetModifier() {
3684 var renderId = 0;
3685 var rulesTextCache = new Set();
3686 var rulesModCache = new Map();
3687 var varTypeChangeCleaners = new Set();
3688 var prevFilterKey = null;
3689 var hasNonLoadedLink = false;
3690 var wasRebuilt = false;
3691 function shouldRebuildStyle() {
3692 return hasNonLoadedLink && !wasRebuilt;
3693 }
3694 function modifySheet(options) {
3695 var rules = options.sourceCSSRules;
3696 var theme = options.theme, ignoreImageAnalysis = options.ignoreImageAnalysis, force = options.force, prepareSheet = options.prepareSheet, isAsyncCancelled = options.isAsyncCancelled;
3697 var rulesChanged = (rulesModCache.size === 0);
3698 var notFoundCacheKeys = new Set(rulesModCache.keys());
3699 var themeKey = getThemeKey(theme);
3700 var themeChanged = (themeKey !== prevFilterKey);
3701 if (hasNonLoadedLink) {
3702 wasRebuilt = true;
3703 }
3704 var modRules = [];
3705 iterateCSSRules(rules, function (rule) {
3706 var cssText = rule.cssText;
3707 var textDiffersFromPrev = false;
3708 notFoundCacheKeys.delete(cssText);
3709 if (rule.parentRule instanceof CSSMediaRule) {
3710 cssText += ";".concat(rule.parentRule.media.mediaText);
3711 }
3712 if (!rulesTextCache.has(cssText)) {
3713 rulesTextCache.add(cssText);
3714 textDiffersFromPrev = true;
3715 }
3716 if (textDiffersFromPrev) {
3717 rulesChanged = true;
3718 }
3719 else {
3720 modRules.push(rulesModCache.get(cssText));
3721 return;
3722 }
3723 var modDecs = [];
3724 rule.style && iterateCSSDeclarations(rule.style, function (property, value) {
3725 var mod = getModifiableCSSDeclaration(property, value, rule, variablesStore, ignoreImageAnalysis, isAsyncCancelled);
3726 if (mod) {
3727 modDecs.push(mod);
3728 }
3729 });
3730 var modRule = null;
3731 if (modDecs.length > 0) {
3732 var parentRule = rule.parentRule;
3733 modRule = { selector: rule.selectorText, declarations: modDecs, parentRule: parentRule };
3734 modRules.push(modRule);
3735 }
3736 rulesModCache.set(cssText, modRule);
3737 }, function () {
3738 hasNonLoadedLink = true;
3739 });
3740 notFoundCacheKeys.forEach(function (key) {
3741 rulesTextCache.delete(key);
3742 rulesModCache.delete(key);
3743 });
3744 prevFilterKey = themeKey;
3745 if (!force && !rulesChanged && !themeChanged) {
3746 return;
3747 }
3748 renderId++;
3749 function setRule(target, index, rule) {
3750 var selector = rule.selector, declarations = rule.declarations;
3751 var getDeclarationText = function (dec) {
3752 var property = dec.property, value = dec.value, important = dec.important, sourceValue = dec.sourceValue;
3753 return "".concat(property, ": ").concat(value == null ? sourceValue : value).concat(important ? ' !important' : '', ";");
3754 };
3755 var cssRulesText = '';
3756 declarations.forEach(function (declarations) {
3757 cssRulesText += "".concat(getDeclarationText(declarations), " ");
3758 });
3759 var ruleText = "".concat(selector, " { ").concat(cssRulesText, " }");
3760 target.insertRule(ruleText, index);
3761 }
3762 var asyncDeclarations = new Map();
3763 var varDeclarations = new Map();
3764 var asyncDeclarationCounter = 0;
3765 var varDeclarationCounter = 0;
3766 var rootReadyGroup = { rule: null, rules: [], isGroup: true };
3767 var groupRefs = new WeakMap();
3768 function getGroup(rule) {
3769 if (rule == null) {
3770 return rootReadyGroup;
3771 }
3772 if (groupRefs.has(rule)) {
3773 return groupRefs.get(rule);
3774 }
3775 var group = { rule: rule, rules: [], isGroup: true };
3776 groupRefs.set(rule, group);
3777 var parentGroup = getGroup(rule.parentRule);
3778 parentGroup.rules.push(group);
3779 return group;
3780 }
3781 varTypeChangeCleaners.forEach(function (clear) { return clear(); });
3782 varTypeChangeCleaners.clear();
3783 modRules.filter(function (r) { return r; }).forEach(function (_a) {
3784 var selector = _a.selector, declarations = _a.declarations, parentRule = _a.parentRule;
3785 var group = getGroup(parentRule);
3786 var readyStyleRule = { selector: selector, declarations: [], isGroup: false };
3787 var readyDeclarations = readyStyleRule.declarations;
3788 group.rules.push(readyStyleRule);
3789 function handleAsyncDeclaration(property, modified, important, sourceValue) {
3790 var asyncKey = ++asyncDeclarationCounter;
3791 var asyncDeclaration = { property: property, value: null, important: important, asyncKey: asyncKey, sourceValue: sourceValue };
3792 readyDeclarations.push(asyncDeclaration);
3793 var currentRenderId = renderId;
3794 modified.then(function (asyncValue) {
3795 if (!asyncValue || isAsyncCancelled() || currentRenderId !== renderId) {
3796 return;
3797 }
3798 asyncDeclaration.value = asyncValue;
3799 asyncQueue.add(function () {
3800 if (isAsyncCancelled() || currentRenderId !== renderId) {
3801 return;
3802 }
3803 rebuildAsyncRule(asyncKey);
3804 });
3805 });
3806 }
3807 function handleVarDeclarations(property, modified, important, sourceValue) {
3808 var _a = modified, varDecs = _a.declarations, onTypeChange = _a.onTypeChange;
3809 var varKey = ++varDeclarationCounter;
3810 var currentRenderId = renderId;
3811 var initialIndex = readyDeclarations.length;
3812 var oldDecs = [];
3813 if (varDecs.length === 0) {
3814 var tempDec = { property: property, value: sourceValue, important: important, sourceValue: sourceValue, varKey: varKey };
3815 readyDeclarations.push(tempDec);
3816 oldDecs = [tempDec];
3817 }
3818 varDecs.forEach(function (mod) {
3819 if (mod.value instanceof Promise) {
3820 handleAsyncDeclaration(mod.property, mod.value, important, sourceValue);
3821 }
3822 else {
3823 var readyDec = { property: mod.property, value: mod.value, important: important, sourceValue: sourceValue, varKey: varKey };
3824 readyDeclarations.push(readyDec);
3825 oldDecs.push(readyDec);
3826 }
3827 });
3828 onTypeChange.addListener(function (newDecs) {
3829 if (isAsyncCancelled() || currentRenderId !== renderId) {
3830 return;
3831 }
3832 var readyVarDecs = newDecs.map(function (mod) {
3833 return { property: mod.property, value: mod.value, important: important, sourceValue: sourceValue, varKey: varKey };
3834 });
3835 var index = readyDeclarations.indexOf(oldDecs[0], initialIndex);
3836 readyDeclarations.splice.apply(readyDeclarations, __spreadArray([index, oldDecs.length], __read(readyVarDecs), false));
3837 oldDecs = readyVarDecs;
3838 rebuildVarRule(varKey);
3839 });
3840 varTypeChangeCleaners.add(function () { return onTypeChange.removeListeners(); });
3841 }
3842 declarations.forEach(function (_a) {
3843 var property = _a.property, value = _a.value, important = _a.important, sourceValue = _a.sourceValue;
3844 if (typeof value === 'function') {
3845 var modified = value(theme);
3846 if (modified instanceof Promise) {
3847 handleAsyncDeclaration(property, modified, important, sourceValue);
3848 }
3849 else if (property.startsWith('--')) {
3850 handleVarDeclarations(property, modified, important, sourceValue);
3851 }
3852 else {
3853 readyDeclarations.push({ property: property, value: modified, important: important, sourceValue: sourceValue });
3854 }
3855 }
3856 else {
3857 readyDeclarations.push({ property: property, value: value, important: important, sourceValue: sourceValue });
3858 }
3859 });
3860 });
3861 var sheet = prepareSheet();
3862 function buildStyleSheet() {
3863 function createTarget(group, parent) {
3864 var rule = group.rule;
3865 if (rule instanceof CSSMediaRule) {
3866 var media = rule.media;
3867 var index = parent.cssRules.length;
3868 parent.insertRule("@media ".concat(media.mediaText, " {}"), index);
3869 return parent.cssRules[index];
3870 }
3871 return parent;
3872 }
3873 function iterateReadyRules(group, target, styleIterator) {
3874 group.rules.forEach(function (r) {
3875 if (r.isGroup) {
3876 var t = createTarget(r, target);
3877 iterateReadyRules(r, t, styleIterator);
3878 }
3879 else {
3880 styleIterator(r, target);
3881 }
3882 });
3883 }
3884 iterateReadyRules(rootReadyGroup, sheet, function (rule, target) {
3885 var index = target.cssRules.length;
3886 rule.declarations.forEach(function (_a) {
3887 var asyncKey = _a.asyncKey, varKey = _a.varKey;
3888 if (asyncKey != null) {
3889 asyncDeclarations.set(asyncKey, { rule: rule, target: target, index: index });
3890 }
3891 if (varKey != null) {
3892 varDeclarations.set(varKey, { rule: rule, target: target, index: index });
3893 }
3894 });
3895 setRule(target, index, rule);
3896 });
3897 }
3898 function rebuildAsyncRule(key) {
3899 var _a = asyncDeclarations.get(key), rule = _a.rule, target = _a.target, index = _a.index;
3900 target.deleteRule(index);
3901 setRule(target, index, rule);
3902 asyncDeclarations.delete(key);
3903 }
3904 function rebuildVarRule(key) {
3905 var _a = varDeclarations.get(key), rule = _a.rule, target = _a.target, index = _a.index;
3906 target.deleteRule(index);
3907 setRule(target, index, rule);
3908 }
3909 buildStyleSheet();
3910 }
3911 return { modifySheet: modifySheet, shouldRebuildStyle: shouldRebuildStyle };
3912 }
3913
3914 var STYLE_SELECTOR = 'style, link[rel*="stylesheet" i]:not([disabled])';
3915 function shouldManageStyle(element) {
3916 return (((element instanceof HTMLStyleElement) ||
3917 (element instanceof SVGStyleElement) ||
3918 (element instanceof HTMLLinkElement &&
3919 element.rel &&
3920 element.rel.toLowerCase().includes('stylesheet') &&
3921 !element.disabled &&
3922 (isFirefox ? !element.href.startsWith('moz-extension://') : true) &&
3923 !element.href.startsWith('https://fonts.googleapis.com'))) &&
3924 !element.classList.contains('darkreader') &&
3925 element.media.toLowerCase() !== 'print' &&
3926 !element.classList.contains('stylus'));
3927 }
3928 function getManageableStyles(node, results, deep) {
3929 if (results === void 0) { results = []; }
3930 if (deep === void 0) { deep = true; }
3931 if (shouldManageStyle(node)) {
3932 results.push(node);
3933 }
3934 else if (node instanceof Element || (isShadowDomSupported && node instanceof ShadowRoot) || node === document) {
3935 forEach(node.querySelectorAll(STYLE_SELECTOR), function (style) { return getManageableStyles(style, results, false); });
3936 if (deep) {
3937 iterateShadowHosts(node, function (host) { return getManageableStyles(host.shadowRoot, results, false); });
3938 }
3939 }
3940 return results;
3941 }
3942 var syncStyleSet = new WeakSet();
3943 var corsStyleSet = new WeakSet();
3944 var canOptimizeUsingProxy$1 = false;
3945 document.addEventListener('__darkreader__inlineScriptsAllowed', function () {
3946 canOptimizeUsingProxy$1 = true;
3947 });
3948 var loadingLinkCounter = 0;
3949 var rejectorsForLoadingLinks = new Map();
3950 function cleanLoadingLinks() {
3951 rejectorsForLoadingLinks.clear();
3952 }
3953 function manageStyle(element, _a) {
3954 var update = _a.update, loadingStart = _a.loadingStart, loadingEnd = _a.loadingEnd;
3955 var prevStyles = [];
3956 var next = element;
3957 while ((next = next.nextElementSibling) && next.matches('.darkreader')) {
3958 prevStyles.push(next);
3959 }
3960 var corsCopy = prevStyles.find(function (el) { return el.matches('.darkreader--cors') && !corsStyleSet.has(el); }) || null;
3961 var syncStyle = prevStyles.find(function (el) { return el.matches('.darkreader--sync') && !syncStyleSet.has(el); }) || null;
3962 var corsCopyPositionWatcher = null;
3963 var syncStylePositionWatcher = null;
3964 var cancelAsyncOperations = false;
3965 var isOverrideEmpty = true;
3966 var sheetModifier = createStyleSheetModifier();
3967 var observer = new MutationObserver(function () {
3968 update();
3969 });
3970 var observerOptions = { attributes: true, childList: true, subtree: true, characterData: true };
3971 function containsCSSImport() {
3972 return element instanceof HTMLStyleElement && element.textContent.trim().match(cssImportRegex);
3973 }
3974 function hasImports(cssRules, checkCrossOrigin) {
3975 var result = false;
3976 if (cssRules) {
3977 var rule = void 0;
3978 cssRulesLoop: for (var i = 0, len = cssRules.length; i < len; i++) {
3979 rule = cssRules[i];
3980 if (rule.href) {
3981 if (checkCrossOrigin) {
3982 if (rule.href.startsWith('http') && !rule.href.startsWith(location.origin)) {
3983 result = true;
3984 break cssRulesLoop;
3985 }
3986 }
3987 else {
3988 result = true;
3989 break cssRulesLoop;
3990 }
3991 }
3992 }
3993 }
3994 return result;
3995 }
3996 function getRulesSync() {
3997 if (corsCopy) {
3998 logInfo('[getRulesSync] Using cors-copy.');
3999 return corsCopy.sheet.cssRules;
4000 }
4001 if (containsCSSImport()) {
4002 logInfo('[getRulesSync] CSSImport detected.');
4003 return null;
4004 }
4005 var cssRules = safeGetSheetRules();
4006 if (element instanceof HTMLLinkElement &&
4007 !isRelativeHrefOnAbsolutePath(element.href) &&
4008 hasImports(cssRules, false)) {
4009 logInfo('[getRulesSync] CSSImportRule detected on non-local href.');
4010 return null;
4011 }
4012 if (hasImports(cssRules, true)) {
4013 logInfo('[getRulesSync] Cross-Origin CSSImportRule detected.');
4014 return null;
4015 }
4016 logInfo('[getRulesSync] Using cssRules.');
4017 !cssRules && logWarn('[getRulesSync] cssRules is null, trying again.');
4018 return cssRules;
4019 }
4020 function insertStyle() {
4021 if (corsCopy) {
4022 if (element.nextSibling !== corsCopy) {
4023 element.parentNode.insertBefore(corsCopy, element.nextSibling);
4024 }
4025 if (corsCopy.nextSibling !== syncStyle) {
4026 element.parentNode.insertBefore(syncStyle, corsCopy.nextSibling);
4027 }
4028 }
4029 else if (element.nextSibling !== syncStyle) {
4030 element.parentNode.insertBefore(syncStyle, element.nextSibling);
4031 }
4032 }
4033 function createSyncStyle() {
4034 syncStyle = element instanceof SVGStyleElement ?
4035 document.createElementNS('http://www.w3.org/2000/svg', 'style') :
4036 document.createElement('style');
4037 syncStyle.classList.add('darkreader');
4038 syncStyle.classList.add('darkreader--sync');
4039 syncStyle.media = 'screen';
4040 if (element.title) {
4041 syncStyle.title = element.title;
4042 }
4043 syncStyleSet.add(syncStyle);
4044 }
4045 var isLoadingRules = false;
4046 var wasLoadingError = false;
4047 var loadingLinkId = ++loadingLinkCounter;
4048 function getRulesAsync() {
4049 return __awaiter(this, void 0, void 0, function () {
4050 var cssText, cssBasePath, _a, cssRules, accessError, err_1, fullCSSText, err_2;
4051 var _b;
4052 return __generator(this, function (_c) {
4053 switch (_c.label) {
4054 case 0:
4055 if (!(element instanceof HTMLLinkElement)) return [3, 7];
4056 _a = __read(getRulesOrError(), 2), cssRules = _a[0], accessError = _a[1];
4057 if (accessError) {
4058 logWarn(accessError);
4059 }
4060 if (!((!cssRules && !accessError && !isSafari) ||
4061 (isSafari && !element.sheet) ||
4062 isStillLoadingError(accessError))) return [3, 5];
4063 _c.label = 1;
4064 case 1:
4065 _c.trys.push([1, 3, , 4]);
4066 logInfo("Linkelement ".concat(loadingLinkId, " is not loaded yet and thus will be await for"), element);
4067 return [4, linkLoading(element, loadingLinkId)];
4068 case 2:
4069 _c.sent();
4070 return [3, 4];
4071 case 3:
4072 err_1 = _c.sent();
4073 logWarn(err_1);
4074 wasLoadingError = true;
4075 return [3, 4];
4076 case 4:
4077 if (cancelAsyncOperations) {
4078 return [2, null];
4079 }
4080 _b = __read(getRulesOrError(), 2), cssRules = _b[0], accessError = _b[1];
4081 if (accessError) {
4082 logWarn(accessError);
4083 }
4084 _c.label = 5;
4085 case 5:
4086 if (cssRules) {
4087 if (!hasImports(cssRules, false)) {
4088 return [2, cssRules];
4089 }
4090 }
4091 return [4, loadText(element.href)];
4092 case 6:
4093 cssText = _c.sent();
4094 cssBasePath = getCSSBaseBath(element.href);
4095 if (cancelAsyncOperations) {
4096 return [2, null];
4097 }
4098 return [3, 8];
4099 case 7:
4100 if (containsCSSImport()) {
4101 cssText = element.textContent.trim();
4102 cssBasePath = getCSSBaseBath(location.href);
4103 }
4104 else {
4105 return [2, null];
4106 }
4107 _c.label = 8;
4108 case 8:
4109 if (!cssText) return [3, 13];
4110 _c.label = 9;
4111 case 9:
4112 _c.trys.push([9, 11, , 12]);
4113 return [4, replaceCSSImports(cssText, cssBasePath)];
4114 case 10:
4115 fullCSSText = _c.sent();
4116 corsCopy = createCORSCopy(element, fullCSSText);
4117 return [3, 12];
4118 case 11:
4119 err_2 = _c.sent();
4120 logWarn(err_2);
4121 return [3, 12];
4122 case 12:
4123 if (corsCopy) {
4124 corsCopyPositionWatcher = watchForNodePosition(corsCopy, 'prev-sibling');
4125 return [2, corsCopy.sheet.cssRules];
4126 }
4127 _c.label = 13;
4128 case 13: return [2, null];
4129 }
4130 });
4131 });
4132 }
4133 function details(options) {
4134 var rules = getRulesSync();
4135 if (!rules) {
4136 if (options.secondRound) {
4137 logWarn('Detected dead-lock at details(), returning early to prevent it.');
4138 return null;
4139 }
4140 if (isLoadingRules || wasLoadingError) {
4141 return null;
4142 }
4143 isLoadingRules = true;
4144 loadingStart();
4145 getRulesAsync().then(function (results) {
4146 isLoadingRules = false;
4147 loadingEnd();
4148 if (results) {
4149 update();
4150 }
4151 }).catch(function (err) {
4152 logWarn(err);
4153 isLoadingRules = false;
4154 loadingEnd();
4155 });
4156 return null;
4157 }
4158 return { rules: rules };
4159 }
4160 var forceRenderStyle = false;
4161 function render(theme, ignoreImageAnalysis) {
4162 var rules = getRulesSync();
4163 if (!rules) {
4164 return;
4165 }
4166 cancelAsyncOperations = false;
4167 function removeCSSRulesFromSheet(sheet) {
4168 for (var i = sheet.cssRules.length - 1; i >= 0; i--) {
4169 sheet.deleteRule(i);
4170 }
4171 }
4172 function prepareOverridesSheet() {
4173 if (!syncStyle) {
4174 createSyncStyle();
4175 }
4176 syncStylePositionWatcher && syncStylePositionWatcher.stop();
4177 insertStyle();
4178 if (syncStyle.sheet == null) {
4179 syncStyle.textContent = '';
4180 }
4181 var sheet = syncStyle.sheet;
4182 removeCSSRulesFromSheet(sheet);
4183 if (syncStylePositionWatcher) {
4184 syncStylePositionWatcher.run();
4185 }
4186 else {
4187 syncStylePositionWatcher = watchForNodePosition(syncStyle, 'prev-sibling', function () {
4188 forceRenderStyle = true;
4189 buildOverrides();
4190 });
4191 }
4192 return syncStyle.sheet;
4193 }
4194 function buildOverrides() {
4195 var force = forceRenderStyle;
4196 forceRenderStyle = false;
4197 sheetModifier.modifySheet({
4198 prepareSheet: prepareOverridesSheet,
4199 sourceCSSRules: rules,
4200 theme: theme,
4201 ignoreImageAnalysis: ignoreImageAnalysis,
4202 force: force,
4203 isAsyncCancelled: function () { return cancelAsyncOperations; },
4204 });
4205 isOverrideEmpty = syncStyle.sheet.cssRules.length === 0;
4206 if (sheetModifier.shouldRebuildStyle()) {
4207 addReadyStateCompleteListener(function () { return update(); });
4208 }
4209 }
4210 buildOverrides();
4211 }
4212 function getRulesOrError() {
4213 try {
4214 if (element.sheet == null) {
4215 return [null, null];
4216 }
4217 return [element.sheet.cssRules, null];
4218 }
4219 catch (err) {
4220 return [null, err];
4221 }
4222 }
4223 function isStillLoadingError(error) {
4224 return error && error.message && error.message.includes('loading');
4225 }
4226 function safeGetSheetRules() {
4227 var _a = __read(getRulesOrError(), 2), cssRules = _a[0], err = _a[1];
4228 if (err) {
4229 logWarn(err);
4230 return null;
4231 }
4232 return cssRules;
4233 }
4234 function watchForSheetChanges() {
4235 watchForSheetChangesUsingProxy();
4236 if (!isThunderbird && !(canOptimizeUsingProxy$1 && element.sheet)) {
4237 watchForSheetChangesUsingRAF();
4238 }
4239 }
4240 var rulesChangeKey = null;
4241 var rulesCheckFrameId = null;
4242 function getRulesChangeKey() {
4243 var rules = safeGetSheetRules();
4244 return rules ? rules.length : null;
4245 }
4246 function didRulesKeyChange() {
4247 return getRulesChangeKey() !== rulesChangeKey;
4248 }
4249 function watchForSheetChangesUsingRAF() {
4250 rulesChangeKey = getRulesChangeKey();
4251 stopWatchingForSheetChangesUsingRAF();
4252 var checkForUpdate = function () {
4253 if (didRulesKeyChange()) {
4254 rulesChangeKey = getRulesChangeKey();
4255 update();
4256 }
4257 if (canOptimizeUsingProxy$1 && element.sheet) {
4258 stopWatchingForSheetChangesUsingRAF();
4259 return;
4260 }
4261 rulesCheckFrameId = requestAnimationFrame(checkForUpdate);
4262 };
4263 checkForUpdate();
4264 }
4265 function stopWatchingForSheetChangesUsingRAF() {
4266 cancelAnimationFrame(rulesCheckFrameId);
4267 }
4268 var areSheetChangesPending = false;
4269 function onSheetChange() {
4270 canOptimizeUsingProxy$1 = true;
4271 stopWatchingForSheetChangesUsingRAF();
4272 if (areSheetChangesPending) {
4273 return;
4274 }
4275 function handleSheetChanges() {
4276 areSheetChangesPending = false;
4277 if (cancelAsyncOperations) {
4278 return;
4279 }
4280 update();
4281 }
4282 areSheetChangesPending = true;
4283 if (typeof queueMicrotask === 'function') {
4284 queueMicrotask(handleSheetChanges);
4285 }
4286 else {
4287 requestAnimationFrame(handleSheetChanges);
4288 }
4289 }
4290 function watchForSheetChangesUsingProxy() {
4291 element.addEventListener('__darkreader__updateSheet', onSheetChange);
4292 }
4293 function stopWatchingForSheetChangesUsingProxy() {
4294 element.removeEventListener('__darkreader__updateSheet', onSheetChange);
4295 }
4296 function stopWatchingForSheetChanges() {
4297 stopWatchingForSheetChangesUsingProxy();
4298 stopWatchingForSheetChangesUsingRAF();
4299 }
4300 function pause() {
4301 observer.disconnect();
4302 cancelAsyncOperations = true;
4303 corsCopyPositionWatcher && corsCopyPositionWatcher.stop();
4304 syncStylePositionWatcher && syncStylePositionWatcher.stop();
4305 stopWatchingForSheetChanges();
4306 }
4307 function destroy() {
4308 pause();
4309 removeNode(corsCopy);
4310 removeNode(syncStyle);
4311 loadingEnd();
4312 if (rejectorsForLoadingLinks.has(loadingLinkId)) {
4313 var reject = rejectorsForLoadingLinks.get(loadingLinkId);
4314 rejectorsForLoadingLinks.delete(loadingLinkId);
4315 reject && reject();
4316 }
4317 }
4318 function watch() {
4319 observer.observe(element, observerOptions);
4320 if (element instanceof HTMLStyleElement) {
4321 watchForSheetChanges();
4322 }
4323 }
4324 var maxMoveCount = 10;
4325 var moveCount = 0;
4326 function restore() {
4327 if (!syncStyle) {
4328 return;
4329 }
4330 moveCount++;
4331 if (moveCount > maxMoveCount) {
4332 logWarn('Style sheet was moved multiple times', element);
4333 return;
4334 }
4335 logWarn('Restore style', syncStyle, element);
4336 insertStyle();
4337 corsCopyPositionWatcher && corsCopyPositionWatcher.skip();
4338 syncStylePositionWatcher && syncStylePositionWatcher.skip();
4339 if (!isOverrideEmpty) {
4340 forceRenderStyle = true;
4341 update();
4342 }
4343 }
4344 return {
4345 details: details,
4346 render: render,
4347 pause: pause,
4348 destroy: destroy,
4349 watch: watch,
4350 restore: restore,
4351 };
4352 }
4353 function linkLoading(link, loadingId) {
4354 return __awaiter(this, void 0, void 0, function () {
4355 return __generator(this, function (_a) {
4356 return [2, new Promise(function (resolve, reject) {
4357 var cleanUp = function () {
4358 link.removeEventListener('load', onLoad);
4359 link.removeEventListener('error', onError);
4360 rejectorsForLoadingLinks.delete(loadingId);
4361 };
4362 var onLoad = function () {
4363 cleanUp();
4364 logInfo("Linkelement ".concat(loadingId, " has been loaded"));
4365 resolve();
4366 };
4367 var onError = function () {
4368 cleanUp();
4369 reject("Linkelement ".concat(loadingId, " couldn't be loaded. ").concat(link.href));
4370 };
4371 rejectorsForLoadingLinks.set(loadingId, function () {
4372 cleanUp();
4373 reject();
4374 });
4375 link.addEventListener('load', onLoad);
4376 link.addEventListener('error', onError);
4377 if (!link.href) {
4378 onError();
4379 }
4380 })];
4381 });
4382 });
4383 }
4384 function getCSSImportURL(importDeclaration) {
4385 return getCSSURLValue(importDeclaration.substring(7).trim().replace(/;$/, '').replace(/screen$/, ''));
4386 }
4387 function loadText(url) {
4388 return __awaiter(this, void 0, void 0, function () {
4389 return __generator(this, function (_a) {
4390 switch (_a.label) {
4391 case 0:
4392 if (!url.startsWith('data:')) return [3, 3];
4393 return [4, fetch(url)];
4394 case 1: return [4, (_a.sent()).text()];
4395 case 2: return [2, _a.sent()];
4396 case 3: return [4, bgFetch({ url: url, responseType: 'text', mimeType: 'text/css', origin: window.location.origin })];
4397 case 4: return [2, _a.sent()];
4398 }
4399 });
4400 });
4401 }
4402 function replaceCSSImports(cssText, basePath, cache) {
4403 if (cache === void 0) { cache = new Map(); }
4404 return __awaiter(this, void 0, void 0, function () {
4405 var importMatches, importMatches_1, importMatches_1_1, match, importURL, absoluteURL, importedCSS, err_3, e_1_1;
4406 var e_1, _a;
4407 return __generator(this, function (_b) {
4408 switch (_b.label) {
4409 case 0:
4410 cssText = removeCSSComments(cssText);
4411 cssText = replaceCSSFontFace(cssText);
4412 cssText = replaceCSSRelativeURLsWithAbsolute(cssText, basePath);
4413 importMatches = getMatches(cssImportRegex, cssText);
4414 _b.label = 1;
4415 case 1:
4416 _b.trys.push([1, 10, 11, 12]);
4417 importMatches_1 = __values(importMatches), importMatches_1_1 = importMatches_1.next();
4418 _b.label = 2;
4419 case 2:
4420 if (!!importMatches_1_1.done) return [3, 9];
4421 match = importMatches_1_1.value;
4422 importURL = getCSSImportURL(match);
4423 absoluteURL = getAbsoluteURL(basePath, importURL);
4424 importedCSS = void 0;
4425 if (!cache.has(absoluteURL)) return [3, 3];
4426 importedCSS = cache.get(absoluteURL);
4427 return [3, 7];
4428 case 3:
4429 _b.trys.push([3, 6, , 7]);
4430 return [4, loadText(absoluteURL)];
4431 case 4:
4432 importedCSS = _b.sent();
4433 cache.set(absoluteURL, importedCSS);
4434 return [4, replaceCSSImports(importedCSS, getCSSBaseBath(absoluteURL), cache)];
4435 case 5:
4436 importedCSS = _b.sent();
4437 return [3, 7];
4438 case 6:
4439 err_3 = _b.sent();
4440 logWarn(err_3);
4441 importedCSS = '';
4442 return [3, 7];
4443 case 7:
4444 cssText = cssText.split(match).join(importedCSS);
4445 _b.label = 8;
4446 case 8:
4447 importMatches_1_1 = importMatches_1.next();
4448 return [3, 2];
4449 case 9: return [3, 12];
4450 case 10:
4451 e_1_1 = _b.sent();
4452 e_1 = { error: e_1_1 };
4453 return [3, 12];
4454 case 11:
4455 try {
4456 if (importMatches_1_1 && !importMatches_1_1.done && (_a = importMatches_1.return)) _a.call(importMatches_1);
4457 }
4458 finally { if (e_1) throw e_1.error; }
4459 return [7];
4460 case 12:
4461 cssText = cssText.trim();
4462 return [2, cssText];
4463 }
4464 });
4465 });
4466 }
4467 function createCORSCopy(srcElement, cssText) {
4468 if (!cssText) {
4469 return null;
4470 }
4471 var cors = document.createElement('style');
4472 cors.classList.add('darkreader');
4473 cors.classList.add('darkreader--cors');
4474 cors.media = 'screen';
4475 cors.textContent = cssText;
4476 srcElement.parentNode.insertBefore(cors, srcElement.nextSibling);
4477 cors.sheet.disabled = true;
4478 corsStyleSet.add(cors);
4479 return cors;
4480 }
4481
4482 var observers = [];
4483 var observedRoots;
4484 var undefinedGroups = new Map();
4485 var elementsDefinitionCallback;
4486 function collectUndefinedElements(root) {
4487 if (!isDefinedSelectorSupported) {
4488 return;
4489 }
4490 forEach(root.querySelectorAll(':not(:defined)'), function (el) {
4491 var tag = el.tagName.toLowerCase();
4492 if (!tag.includes('-')) {
4493 var extendedTag = el.getAttribute('is');
4494 if (extendedTag) {
4495 tag = extendedTag;
4496 }
4497 else {
4498 return;
4499 }
4500 }
4501 if (!undefinedGroups.has(tag)) {
4502 undefinedGroups.set(tag, new Set());
4503 customElementsWhenDefined(tag).then(function () {
4504 if (elementsDefinitionCallback) {
4505 var elements = undefinedGroups.get(tag);
4506 undefinedGroups.delete(tag);
4507 elementsDefinitionCallback(Array.from(elements));
4508 }
4509 });
4510 }
4511 undefinedGroups.get(tag).add(el);
4512 });
4513 }
4514 var canOptimizeUsingProxy = false;
4515 document.addEventListener('__darkreader__inlineScriptsAllowed', function () {
4516 canOptimizeUsingProxy = true;
4517 });
4518 var resolvers = new Map();
4519 function handleIsDefined(e) {
4520 canOptimizeUsingProxy = true;
4521 if (resolvers.has(e.detail.tag)) {
4522 var resolve = resolvers.get(e.detail.tag);
4523 resolve();
4524 }
4525 }
4526 function customElementsWhenDefined(tag) {
4527 return __awaiter(this, void 0, void 0, function () {
4528 return __generator(this, function (_a) {
4529 return [2, new Promise(function (resolve) {
4530 if (window.customElements && typeof customElements.whenDefined === 'function') {
4531 customElements.whenDefined(tag).then(function () { return resolve(); });
4532 }
4533 else if (canOptimizeUsingProxy) {
4534 resolvers.set(tag, resolve);
4535 document.dispatchEvent(new CustomEvent('__darkreader__addUndefinedResolver', { detail: { tag: tag } }));
4536 }
4537 else {
4538 var checkIfDefined_1 = function () {
4539 var elements = undefinedGroups.get(tag);
4540 if (elements && elements.size > 0) {
4541 if (elements.values().next().value.matches(':defined')) {
4542 resolve();
4543 }
4544 else {
4545 requestAnimationFrame(checkIfDefined_1);
4546 }
4547 }
4548 };
4549 requestAnimationFrame(checkIfDefined_1);
4550 }
4551 })];
4552 });
4553 });
4554 }
4555 function watchWhenCustomElementsDefined(callback) {
4556 elementsDefinitionCallback = callback;
4557 }
4558 function unsubscribeFromDefineCustomElements() {
4559 elementsDefinitionCallback = null;
4560 undefinedGroups.clear();
4561 document.removeEventListener('__darkreader__isDefined', handleIsDefined);
4562 }
4563 function watchForStyleChanges(currentStyles, update, shadowRootDiscovered) {
4564 stopWatchingForStyleChanges();
4565 var prevStyles = new Set(currentStyles);
4566 var prevStyleSiblings = new WeakMap();
4567 var nextStyleSiblings = new WeakMap();
4568 function saveStylePosition(style) {
4569 prevStyleSiblings.set(style, style.previousElementSibling);
4570 nextStyleSiblings.set(style, style.nextElementSibling);
4571 }
4572 function forgetStylePosition(style) {
4573 prevStyleSiblings.delete(style);
4574 nextStyleSiblings.delete(style);
4575 }
4576 function didStylePositionChange(style) {
4577 return (style.previousElementSibling !== prevStyleSiblings.get(style) ||
4578 style.nextElementSibling !== nextStyleSiblings.get(style));
4579 }
4580 currentStyles.forEach(saveStylePosition);
4581 function handleStyleOperations(operations) {
4582 var createdStyles = operations.createdStyles, removedStyles = operations.removedStyles, movedStyles = operations.movedStyles;
4583 createdStyles.forEach(function (s) { return saveStylePosition(s); });
4584 movedStyles.forEach(function (s) { return saveStylePosition(s); });
4585 removedStyles.forEach(function (s) { return forgetStylePosition(s); });
4586 createdStyles.forEach(function (s) { return prevStyles.add(s); });
4587 removedStyles.forEach(function (s) { return prevStyles.delete(s); });
4588 if (createdStyles.size + removedStyles.size + movedStyles.size > 0) {
4589 update({
4590 created: Array.from(createdStyles),
4591 removed: Array.from(removedStyles),
4592 moved: Array.from(movedStyles),
4593 updated: [],
4594 });
4595 }
4596 }
4597 function handleMinorTreeMutations(_a) {
4598 var additions = _a.additions, moves = _a.moves, deletions = _a.deletions;
4599 var createdStyles = new Set();
4600 var removedStyles = new Set();
4601 var movedStyles = new Set();
4602 additions.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return createdStyles.add(style); }); });
4603 deletions.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return removedStyles.add(style); }); });
4604 moves.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return movedStyles.add(style); }); });
4605 handleStyleOperations({ createdStyles: createdStyles, removedStyles: removedStyles, movedStyles: movedStyles });
4606 additions.forEach(function (n) {
4607 iterateShadowHosts(n, subscribeForShadowRootChanges);
4608 collectUndefinedElements(n);
4609 });
4610 }
4611 function handleHugeTreeMutations(root) {
4612 var styles = new Set(getManageableStyles(root));
4613 var createdStyles = new Set();
4614 var removedStyles = new Set();
4615 var movedStyles = new Set();
4616 styles.forEach(function (s) {
4617 if (!prevStyles.has(s)) {
4618 createdStyles.add(s);
4619 }
4620 });
4621 prevStyles.forEach(function (s) {
4622 if (!styles.has(s)) {
4623 removedStyles.add(s);
4624 }
4625 });
4626 styles.forEach(function (s) {
4627 if (!createdStyles.has(s) && !removedStyles.has(s) && didStylePositionChange(s)) {
4628 movedStyles.add(s);
4629 }
4630 });
4631 handleStyleOperations({ createdStyles: createdStyles, removedStyles: removedStyles, movedStyles: movedStyles });
4632 iterateShadowHosts(root, subscribeForShadowRootChanges);
4633 collectUndefinedElements(root);
4634 }
4635 function handleAttributeMutations(mutations) {
4636 var updatedStyles = new Set();
4637 var removedStyles = new Set();
4638 mutations.forEach(function (m) {
4639 var target = m.target;
4640 if (target.isConnected) {
4641 if (shouldManageStyle(target)) {
4642 updatedStyles.add(target);
4643 }
4644 else if (target instanceof HTMLLinkElement && target.disabled) {
4645 removedStyles.add(target);
4646 }
4647 }
4648 });
4649 if (updatedStyles.size + removedStyles.size > 0) {
4650 update({
4651 updated: Array.from(updatedStyles),
4652 created: [],
4653 removed: Array.from(removedStyles),
4654 moved: [],
4655 });
4656 }
4657 }
4658 function observe(root) {
4659 var treeObserver = createOptimizedTreeObserver(root, {
4660 onMinorMutations: handleMinorTreeMutations,
4661 onHugeMutations: handleHugeTreeMutations,
4662 });
4663 var attrObserver = new MutationObserver(handleAttributeMutations);
4664 attrObserver.observe(root, { attributes: true, attributeFilter: ['rel', 'disabled', 'media'], subtree: true });
4665 observers.push(treeObserver, attrObserver);
4666 observedRoots.add(root);
4667 }
4668 function subscribeForShadowRootChanges(node) {
4669 var shadowRoot = node.shadowRoot;
4670 if (shadowRoot == null || observedRoots.has(shadowRoot)) {
4671 return;
4672 }
4673 observe(shadowRoot);
4674 shadowRootDiscovered(shadowRoot);
4675 }
4676 observe(document);
4677 iterateShadowHosts(document.documentElement, subscribeForShadowRootChanges);
4678 watchWhenCustomElementsDefined(function (hosts) {
4679 var newStyles = [];
4680 hosts.forEach(function (host) { return push(newStyles, getManageableStyles(host.shadowRoot)); });
4681 update({ created: newStyles, updated: [], removed: [], moved: [] });
4682 hosts.forEach(function (host) {
4683 var shadowRoot = host.shadowRoot;
4684 if (shadowRoot == null) {
4685 return;
4686 }
4687 subscribeForShadowRootChanges(host);
4688 iterateShadowHosts(shadowRoot, subscribeForShadowRootChanges);
4689 collectUndefinedElements(shadowRoot);
4690 });
4691 });
4692 document.addEventListener('__darkreader__isDefined', handleIsDefined);
4693 collectUndefinedElements(document);
4694 }
4695 function resetObservers() {
4696 observers.forEach(function (o) { return o.disconnect(); });
4697 observers.splice(0, observers.length);
4698 observedRoots = new WeakSet();
4699 }
4700 function stopWatchingForStyleChanges() {
4701 resetObservers();
4702 unsubscribeFromDefineCustomElements();
4703 }
4704
4705 function hexify(number) {
4706 return ((number < 16 ? '0' : '') + number.toString(16));
4707 }
4708 function generateUID() {
4709 if ('randomUUID' in crypto) {
4710 var uuid = crypto.randomUUID();
4711 return uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23) + uuid.substring(24);
4712 }
4713 return Array.from(crypto.getRandomValues(new Uint8Array(16))).map(function (x) { return hexify(x); }).join('');
4714 }
4715
4716 var adoptedStyleOverrides = new WeakMap();
4717 var overrideList = new WeakSet();
4718 function createAdoptedStyleSheetOverride(node) {
4719 var cancelAsyncOperations = false;
4720 function injectSheet(sheet, override) {
4721 var newSheets = __spreadArray([], __read(node.adoptedStyleSheets), false);
4722 var sheetIndex = newSheets.indexOf(sheet);
4723 var existingIndex = newSheets.indexOf(override);
4724 if (sheetIndex === existingIndex - 1) {
4725 return;
4726 }
4727 if (existingIndex >= 0) {
4728 newSheets.splice(existingIndex, 1);
4729 }
4730 newSheets.splice(sheetIndex + 1, 0, override);
4731 node.adoptedStyleSheets = newSheets;
4732 }
4733 function destroy() {
4734 cancelAsyncOperations = true;
4735 var newSheets = __spreadArray([], __read(node.adoptedStyleSheets), false);
4736 node.adoptedStyleSheets.forEach(function (adoptedStyleSheet) {
4737 if (overrideList.has(adoptedStyleSheet)) {
4738 var existingIndex = newSheets.indexOf(adoptedStyleSheet);
4739 if (existingIndex >= 0) {
4740 newSheets.splice(existingIndex, 1);
4741 }
4742 adoptedStyleOverrides.delete(adoptedStyleSheet);
4743 overrideList.delete(adoptedStyleSheet);
4744 }
4745 });
4746 node.adoptedStyleSheets = newSheets;
4747 }
4748 function render(theme, ignoreImageAnalysis) {
4749 node.adoptedStyleSheets.forEach(function (sheet) {
4750 if (overrideList.has(sheet)) {
4751 return;
4752 }
4753 var rules = sheet.rules;
4754 var override = new CSSStyleSheet();
4755 function prepareOverridesSheet() {
4756 for (var i = override.cssRules.length - 1; i >= 0; i--) {
4757 override.deleteRule(i);
4758 }
4759 injectSheet(sheet, override);
4760 adoptedStyleOverrides.set(sheet, override);
4761 overrideList.add(override);
4762 return override;
4763 }
4764 var sheetModifier = createStyleSheetModifier();
4765 sheetModifier.modifySheet({
4766 prepareSheet: prepareOverridesSheet,
4767 sourceCSSRules: rules,
4768 theme: theme,
4769 ignoreImageAnalysis: ignoreImageAnalysis,
4770 force: false,
4771 isAsyncCancelled: function () { return cancelAsyncOperations; },
4772 });
4773 });
4774 }
4775 return {
4776 render: render,
4777 destroy: destroy
4778 };
4779 }
4780
4781 function injectProxy(enableStyleSheetsProxy) {
4782 document.dispatchEvent(new CustomEvent('__darkreader__inlineScriptsAllowed'));
4783 var addRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'addRule');
4784 var insertRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'insertRule');
4785 var deleteRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'deleteRule');
4786 var removeRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'removeRule');
4787 var documentStyleSheetsDescriptor = enableStyleSheetsProxy ?
4788 Object.getOwnPropertyDescriptor(Document.prototype, 'styleSheets') : null;
4789 var shouldWrapHTMLElement = location.hostname.endsWith('baidu.com');
4790 var getElementsByTagNameDescriptor = shouldWrapHTMLElement ?
4791 Object.getOwnPropertyDescriptor(Element.prototype, 'getElementsByTagName') : null;
4792 var cleanUp = function () {
4793 Object.defineProperty(CSSStyleSheet.prototype, 'addRule', addRuleDescriptor);
4794 Object.defineProperty(CSSStyleSheet.prototype, 'insertRule', insertRuleDescriptor);
4795 Object.defineProperty(CSSStyleSheet.prototype, 'deleteRule', deleteRuleDescriptor);
4796 Object.defineProperty(CSSStyleSheet.prototype, 'removeRule', removeRuleDescriptor);
4797 document.removeEventListener('__darkreader__cleanUp', cleanUp);
4798 document.removeEventListener('__darkreader__addUndefinedResolver', addUndefinedResolver);
4799 if (enableStyleSheetsProxy) {
4800 Object.defineProperty(Document.prototype, 'styleSheets', documentStyleSheetsDescriptor);
4801 }
4802 if (shouldWrapHTMLElement) {
4803 Object.defineProperty(Element.prototype, 'getElementsByTagName', getElementsByTagNameDescriptor);
4804 }
4805 };
4806 var addUndefinedResolver = function (e) {
4807 customElements.whenDefined(e.detail.tag).then(function () {
4808 document.dispatchEvent(new CustomEvent('__darkreader__isDefined', { detail: { tag: e.detail.tag } }));
4809 });
4810 };
4811 document.addEventListener('__darkreader__cleanUp', cleanUp);
4812 document.addEventListener('__darkreader__addUndefinedResolver', addUndefinedResolver);
4813 var updateSheetEvent = new Event('__darkreader__updateSheet');
4814 function proxyAddRule(selector, style, index) {
4815 addRuleDescriptor.value.call(this, selector, style, index);
4816 if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
4817 this.ownerNode.dispatchEvent(updateSheetEvent);
4818 }
4819 return -1;
4820 }
4821 function proxyInsertRule(rule, index) {
4822 var returnValue = insertRuleDescriptor.value.call(this, rule, index);
4823 if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
4824 this.ownerNode.dispatchEvent(updateSheetEvent);
4825 }
4826 return returnValue;
4827 }
4828 function proxyDeleteRule(index) {
4829 deleteRuleDescriptor.value.call(this, index);
4830 if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
4831 this.ownerNode.dispatchEvent(updateSheetEvent);
4832 }
4833 }
4834 function proxyRemoveRule(index) {
4835 removeRuleDescriptor.value.call(this, index);
4836 if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
4837 this.ownerNode.dispatchEvent(updateSheetEvent);
4838 }
4839 }
4840 function proxyDocumentStyleSheets() {
4841 var _this = this;
4842 var getCurrentValue = function () {
4843 var docSheets = documentStyleSheetsDescriptor.get.call(_this);
4844 var filteredSheets = __spreadArray([], __read(docSheets), false).filter(function (styleSheet) {
4845 return !styleSheet.ownerNode.classList.contains('darkreader');
4846 });
4847 filteredSheets.item = function (item) {
4848 return filteredSheets[item];
4849 };
4850 return Object.setPrototypeOf(filteredSheets, StyleSheetList.prototype);
4851 };
4852 var elements = getCurrentValue();
4853 var styleSheetListBehavior = {
4854 get: function (_, property) {
4855 return getCurrentValue()[property];
4856 }
4857 };
4858 elements = new Proxy(elements, styleSheetListBehavior);
4859 return elements;
4860 }
4861 function proxyGetElementsByTagName(tagName) {
4862 var _this = this;
4863 if (tagName !== 'style') {
4864 return getElementsByTagNameDescriptor.value.call(this, tagName);
4865 }
4866 var getCurrentElementValue = function () {
4867 var elements = getElementsByTagNameDescriptor.value.call(_this, tagName);
4868 return Object.setPrototypeOf(__spreadArray([], __read(elements), false).filter(function (element) {
4869 return !element.classList.contains('darkreader');
4870 }), NodeList.prototype);
4871 };
4872 var elements = getCurrentElementValue();
4873 var nodeListBehavior = {
4874 get: function (_, property) {
4875 return getCurrentElementValue()[Number(property) || property];
4876 }
4877 };
4878 elements = new Proxy(elements, nodeListBehavior);
4879 return elements;
4880 }
4881 Object.defineProperty(CSSStyleSheet.prototype, 'addRule', Object.assign({}, addRuleDescriptor, { value: proxyAddRule }));
4882 Object.defineProperty(CSSStyleSheet.prototype, 'insertRule', Object.assign({}, insertRuleDescriptor, { value: proxyInsertRule }));
4883 Object.defineProperty(CSSStyleSheet.prototype, 'deleteRule', Object.assign({}, deleteRuleDescriptor, { value: proxyDeleteRule }));
4884 Object.defineProperty(CSSStyleSheet.prototype, 'removeRule', Object.assign({}, removeRuleDescriptor, { value: proxyRemoveRule }));
4885 if (enableStyleSheetsProxy) {
4886 Object.defineProperty(Document.prototype, 'styleSheets', Object.assign({}, documentStyleSheetsDescriptor, { get: proxyDocumentStyleSheets }));
4887 }
4888 if (shouldWrapHTMLElement) {
4889 Object.defineProperty(Element.prototype, 'getElementsByTagName', Object.assign({}, getElementsByTagNameDescriptor, { value: proxyGetElementsByTagName }));
4890 }
4891 }
4892
4893 var INSTANCE_ID = generateUID();
4894 var styleManagers = new Map();
4895 var adoptedStyleManagers = [];
4896 var filter = null;
4897 var fixes = null;
4898 var isIFrame$1 = null;
4899 var ignoredImageAnalysisSelectors = null;
4900 var ignoredInlineSelectors = null;
4901 function createOrUpdateStyle(className, root) {
4902 if (root === void 0) { root = document.head || document; }
4903 var element = root.querySelector(".".concat(className));
4904 if (!element) {
4905 element = document.createElement('style');
4906 element.classList.add('darkreader');
4907 element.classList.add(className);
4908 element.media = 'screen';
4909 element.textContent = '';
4910 }
4911 return element;
4912 }
4913 function createOrUpdateScript(className, root) {
4914 if (root === void 0) { root = document.head || document; }
4915 var element = root.querySelector(".".concat(className));
4916 if (!element) {
4917 element = document.createElement('script');
4918 element.classList.add('darkreader');
4919 element.classList.add(className);
4920 }
4921 return element;
4922 }
4923 var nodePositionWatchers = new Map();
4924 function setupNodePositionWatcher(node, alias) {
4925 nodePositionWatchers.has(alias) && nodePositionWatchers.get(alias).stop();
4926 nodePositionWatchers.set(alias, watchForNodePosition(node, 'parent'));
4927 }
4928 function stopStylePositionWatchers() {
4929 forEach(nodePositionWatchers.values(), function (watcher) { return watcher.stop(); });
4930 nodePositionWatchers.clear();
4931 }
4932 function createStaticStyleOverrides() {
4933 var fallbackStyle = createOrUpdateStyle('darkreader--fallback', document);
4934 fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: true });
4935 document.head.insertBefore(fallbackStyle, document.head.firstChild);
4936 setupNodePositionWatcher(fallbackStyle, 'fallback');
4937 var userAgentStyle = createOrUpdateStyle('darkreader--user-agent');
4938 userAgentStyle.textContent = getModifiedUserAgentStyle(filter, isIFrame$1, filter.styleSystemControls);
4939 document.head.insertBefore(userAgentStyle, fallbackStyle.nextSibling);
4940 setupNodePositionWatcher(userAgentStyle, 'user-agent');
4941 var textStyle = createOrUpdateStyle('darkreader--text');
4942 if (filter.useFont || filter.textStroke > 0) {
4943 textStyle.textContent = createTextStyle(filter);
4944 }
4945 else {
4946 textStyle.textContent = '';
4947 }
4948 document.head.insertBefore(textStyle, fallbackStyle.nextSibling);
4949 setupNodePositionWatcher(textStyle, 'text');
4950 var invertStyle = createOrUpdateStyle('darkreader--invert');
4951 if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {
4952 invertStyle.textContent = [
4953 "".concat(fixes.invert.join(', '), " {"),
4954 " filter: ".concat(getCSSFilterValue(__assign(__assign({}, filter), { contrast: filter.mode === 0 ? filter.contrast : clamp(filter.contrast - 10, 0, 100) })), " !important;"),
4955 '}',
4956 ].join('\n');
4957 }
4958 else {
4959 invertStyle.textContent = '';
4960 }
4961 document.head.insertBefore(invertStyle, textStyle.nextSibling);
4962 setupNodePositionWatcher(invertStyle, 'invert');
4963 var inlineStyle = createOrUpdateStyle('darkreader--inline');
4964 inlineStyle.textContent = getInlineOverrideStyle();
4965 document.head.insertBefore(inlineStyle, invertStyle.nextSibling);
4966 setupNodePositionWatcher(inlineStyle, 'inline');
4967 var overrideStyle = createOrUpdateStyle('darkreader--override');
4968 overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : '';
4969 document.head.appendChild(overrideStyle);
4970 setupNodePositionWatcher(overrideStyle, 'override');
4971 var variableStyle = createOrUpdateStyle('darkreader--variables');
4972 var selectionColors = getSelectionColor(filter);
4973 var darkSchemeBackgroundColor = filter.darkSchemeBackgroundColor, darkSchemeTextColor = filter.darkSchemeTextColor, lightSchemeBackgroundColor = filter.lightSchemeBackgroundColor, lightSchemeTextColor = filter.lightSchemeTextColor, mode = filter.mode;
4974 var schemeBackgroundColor = mode === 0 ? lightSchemeBackgroundColor : darkSchemeBackgroundColor;
4975 var schemeTextColor = mode === 0 ? lightSchemeTextColor : darkSchemeTextColor;
4976 schemeBackgroundColor = modifyBackgroundColor(parse(schemeBackgroundColor), filter);
4977 schemeTextColor = modifyForegroundColor(parse(schemeTextColor), filter);
4978 variableStyle.textContent = [
4979 ":root {",
4980 " --darkreader-neutral-background: ".concat(schemeBackgroundColor, ";"),
4981 " --darkreader-neutral-text: ".concat(schemeTextColor, ";"),
4982 " --darkreader-selection-background: ".concat(selectionColors.backgroundColorSelection, ";"),
4983 " --darkreader-selection-text: ".concat(selectionColors.foregroundColorSelection, ";"),
4984 "}"
4985 ].join('\n');
4986 document.head.insertBefore(variableStyle, inlineStyle.nextSibling);
4987 setupNodePositionWatcher(variableStyle, 'variables');
4988 var rootVarsStyle = createOrUpdateStyle('darkreader--root-vars');
4989 document.head.insertBefore(rootVarsStyle, variableStyle.nextSibling);
4990 var proxyScript = createOrUpdateScript('darkreader--proxy');
4991 proxyScript.append("(".concat(injectProxy, ")(!").concat(fixes && fixes.disableStyleSheetsProxy, ")"));
4992 document.head.insertBefore(proxyScript, rootVarsStyle.nextSibling);
4993 proxyScript.remove();
4994 }
4995 var shadowRootsWithOverrides = new Set();
4996 function createShadowStaticStyleOverrides(root) {
4997 var inlineStyle = createOrUpdateStyle('darkreader--inline', root);
4998 inlineStyle.textContent = getInlineOverrideStyle();
4999 root.insertBefore(inlineStyle, root.firstChild);
5000 var overrideStyle = createOrUpdateStyle('darkreader--override', root);
5001 overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : '';
5002 root.insertBefore(overrideStyle, inlineStyle.nextSibling);
5003 var invertStyle = createOrUpdateStyle('darkreader--invert', root);
5004 if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {
5005 invertStyle.textContent = [
5006 "".concat(fixes.invert.join(', '), " {"),
5007 " filter: ".concat(getCSSFilterValue(__assign(__assign({}, filter), { contrast: filter.mode === 0 ? filter.contrast : clamp(filter.contrast - 10, 0, 100) })), " !important;"),
5008 '}',
5009 ].join('\n');
5010 }
5011 else {
5012 invertStyle.textContent = '';
5013 }
5014 root.insertBefore(invertStyle, overrideStyle.nextSibling);
5015 shadowRootsWithOverrides.add(root);
5016 }
5017 function replaceCSSTemplates($cssText) {
5018 return $cssText.replace(/\${(.+?)}/g, function (_, $color) {
5019 var color = tryParseColor($color);
5020 if (color) {
5021 return modifyColor(color, filter);
5022 }
5023 logWarn("Couldn't parse CSSTemplate's color.");
5024 return $color;
5025 });
5026 }
5027 function cleanFallbackStyle() {
5028 var fallback = document.querySelector('.darkreader--fallback');
5029 if (fallback) {
5030 fallback.textContent = '';
5031 }
5032 }
5033 function createDynamicStyleOverrides() {
5034 cancelRendering();
5035 var allStyles = getManageableStyles(document);
5036 var newManagers = allStyles
5037 .filter(function (style) { return !styleManagers.has(style); })
5038 .map(function (style) { return createManager(style); });
5039 newManagers
5040 .map(function (manager) { return manager.details({ secondRound: false }); })
5041 .filter(function (detail) { return detail && detail.rules.length > 0; })
5042 .forEach(function (detail) {
5043 variablesStore.addRulesForMatching(detail.rules);
5044 });
5045 variablesStore.matchVariablesAndDependants();
5046 variablesStore.setOnRootVariableChange(function () {
5047 variablesStore.putRootVars(document.head.querySelector('.darkreader--root-vars'), filter);
5048 });
5049 variablesStore.putRootVars(document.head.querySelector('.darkreader--root-vars'), filter);
5050 styleManagers.forEach(function (manager) { return manager.render(filter, ignoredImageAnalysisSelectors); });
5051 if (loadingStyles.size === 0) {
5052 cleanFallbackStyle();
5053 }
5054 newManagers.forEach(function (manager) { return manager.watch(); });
5055 var inlineStyleElements = toArray(document.querySelectorAll(INLINE_STYLE_SELECTOR));
5056 iterateShadowHosts(document.documentElement, function (host) {
5057 createShadowStaticStyleOverrides(host.shadowRoot);
5058 var elements = host.shadowRoot.querySelectorAll(INLINE_STYLE_SELECTOR);
5059 if (elements.length > 0) {
5060 push(inlineStyleElements, elements);
5061 }
5062 });
5063 inlineStyleElements.forEach(function (el) { return overrideInlineStyle(el, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors); });
5064 handleAdoptedStyleSheets(document);
5065 }
5066 var loadingStylesCounter = 0;
5067 var loadingStyles = new Set();
5068 function createManager(element) {
5069 var loadingStyleId = ++loadingStylesCounter;
5070 logInfo("New manager for element, with loadingStyleID ".concat(loadingStyleId), element);
5071 function loadingStart() {
5072 if (!isDOMReady() || !didDocumentShowUp) {
5073 loadingStyles.add(loadingStyleId);
5074 logInfo("Current amount of styles loading: ".concat(loadingStyles.size));
5075 var fallbackStyle = document.querySelector('.darkreader--fallback');
5076 if (!fallbackStyle.textContent) {
5077 fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: false });
5078 }
5079 }
5080 }
5081 function loadingEnd() {
5082 loadingStyles.delete(loadingStyleId);
5083 logInfo("Removed loadingStyle ".concat(loadingStyleId, ", now awaiting: ").concat(loadingStyles.size));
5084 logInfo("To-do to be loaded", loadingStyles);
5085 if (loadingStyles.size === 0 && isDOMReady()) {
5086 cleanFallbackStyle();
5087 }
5088 }
5089 function update() {
5090 var details = manager.details({ secondRound: true });
5091 if (!details) {
5092 return;
5093 }
5094 variablesStore.addRulesForMatching(details.rules);
5095 variablesStore.matchVariablesAndDependants();
5096 manager.render(filter, ignoredImageAnalysisSelectors);
5097 }
5098 var manager = manageStyle(element, { update: update, loadingStart: loadingStart, loadingEnd: loadingEnd });
5099 styleManagers.set(element, manager);
5100 return manager;
5101 }
5102 function removeManager(element) {
5103 var manager = styleManagers.get(element);
5104 if (manager) {
5105 manager.destroy();
5106 styleManagers.delete(element);
5107 }
5108 }
5109 var throttledRenderAllStyles = throttle(function (callback) {
5110 styleManagers.forEach(function (manager) { return manager.render(filter, ignoredImageAnalysisSelectors); });
5111 adoptedStyleManagers.forEach(function (manager) { return manager.render(filter, ignoredImageAnalysisSelectors); });
5112 callback && callback();
5113 });
5114 var cancelRendering = function () {
5115 throttledRenderAllStyles.cancel();
5116 };
5117 function onDOMReady() {
5118 if (loadingStyles.size === 0) {
5119 cleanFallbackStyle();
5120 return;
5121 }
5122 logWarn("DOM is ready, but still have styles being loaded.", loadingStyles);
5123 }
5124 var documentVisibilityListener = null;
5125 var didDocumentShowUp = !document.hidden;
5126 function watchForDocumentVisibility(callback) {
5127 var alreadyWatching = Boolean(documentVisibilityListener);
5128 documentVisibilityListener = function () {
5129 if (!document.hidden) {
5130 stopWatchingForDocumentVisibility();
5131 callback();
5132 didDocumentShowUp = true;
5133 }
5134 };
5135 if (!alreadyWatching) {
5136 document.addEventListener('visibilitychange', documentVisibilityListener);
5137 }
5138 }
5139 function stopWatchingForDocumentVisibility() {
5140 document.removeEventListener('visibilitychange', documentVisibilityListener);
5141 documentVisibilityListener = null;
5142 }
5143 function createThemeAndWatchForUpdates() {
5144 createStaticStyleOverrides();
5145 function runDynamicStyle() {
5146 createDynamicStyleOverrides();
5147 watchForUpdates();
5148 }
5149 if (document.hidden && !filter.immediateModify) {
5150 watchForDocumentVisibility(runDynamicStyle);
5151 }
5152 else {
5153 runDynamicStyle();
5154 }
5155 changeMetaThemeColorWhenAvailable(filter);
5156 }
5157 function handleAdoptedStyleSheets(node) {
5158 try {
5159 if (Array.isArray(node.adoptedStyleSheets)) {
5160 if (node.adoptedStyleSheets.length > 0) {
5161 var newManger = createAdoptedStyleSheetOverride(node);
5162 adoptedStyleManagers.push(newManger);
5163 newManger.render(filter, ignoredImageAnalysisSelectors);
5164 }
5165 }
5166 }
5167 catch (err) {
5168 logWarn('Error occured in handleAdoptedStyleSheets: ', err);
5169 }
5170 }
5171 function watchForUpdates() {
5172 var managedStyles = Array.from(styleManagers.keys());
5173 watchForStyleChanges(managedStyles, function (_a) {
5174 var created = _a.created, updated = _a.updated, removed = _a.removed, moved = _a.moved;
5175 var stylesToRemove = removed;
5176 var stylesToManage = created.concat(updated).concat(moved)
5177 .filter(function (style) { return !styleManagers.has(style); });
5178 var stylesToRestore = moved
5179 .filter(function (style) { return styleManagers.has(style); });
5180 logInfo("Styles to be removed:", stylesToRemove);
5181 stylesToRemove.forEach(function (style) { return removeManager(style); });
5182 var newManagers = stylesToManage
5183 .map(function (style) { return createManager(style); });
5184 newManagers
5185 .map(function (manager) { return manager.details({ secondRound: false }); })
5186 .filter(function (detail) { return detail && detail.rules.length > 0; })
5187 .forEach(function (detail) {
5188 variablesStore.addRulesForMatching(detail.rules);
5189 });
5190 variablesStore.matchVariablesAndDependants();
5191 newManagers.forEach(function (manager) { return manager.render(filter, ignoredImageAnalysisSelectors); });
5192 newManagers.forEach(function (manager) { return manager.watch(); });
5193 stylesToRestore.forEach(function (style) { return styleManagers.get(style).restore(); });
5194 }, function (shadowRoot) {
5195 createShadowStaticStyleOverrides(shadowRoot);
5196 handleAdoptedStyleSheets(shadowRoot);
5197 });
5198 watchForInlineStyles(function (element) {
5199 overrideInlineStyle(element, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors);
5200 if (element === document.documentElement) {
5201 var styleAttr = element.getAttribute('style') || '';
5202 if (styleAttr.includes('--')) {
5203 variablesStore.matchVariablesAndDependants();
5204 variablesStore.putRootVars(document.head.querySelector('.darkreader--root-vars'), filter);
5205 }
5206 }
5207 }, function (root) {
5208 createShadowStaticStyleOverrides(root);
5209 var inlineStyleElements = root.querySelectorAll(INLINE_STYLE_SELECTOR);
5210 if (inlineStyleElements.length > 0) {
5211 forEach(inlineStyleElements, function (el) { return overrideInlineStyle(el, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors); });
5212 }
5213 });
5214 addDOMReadyListener(onDOMReady);
5215 }
5216 function stopWatchingForUpdates() {
5217 styleManagers.forEach(function (manager) { return manager.pause(); });
5218 stopStylePositionWatchers();
5219 stopWatchingForStyleChanges();
5220 stopWatchingForInlineStyles();
5221 removeDOMReadyListener(onDOMReady);
5222 cleanReadyStateCompleteListeners();
5223 }
5224 function createDarkReaderInstanceMarker() {
5225 var metaElement = document.createElement('meta');
5226 metaElement.name = 'darkreader';
5227 metaElement.content = INSTANCE_ID;
5228 document.head.appendChild(metaElement);
5229 }
5230 function isAnotherDarkReaderInstanceActive() {
5231 var meta = document.querySelector('meta[name="darkreader"]');
5232 if (meta) {
5233 if (meta.content !== INSTANCE_ID) {
5234 return true;
5235 }
5236 return false;
5237 }
5238 createDarkReaderInstanceMarker();
5239 return false;
5240 }
5241 function createOrUpdateDynamicTheme(filterConfig, dynamicThemeFixes, iframe) {
5242 filter = filterConfig;
5243 fixes = dynamicThemeFixes;
5244 if (fixes) {
5245 ignoredImageAnalysisSelectors = Array.isArray(fixes.ignoreImageAnalysis) ? fixes.ignoreImageAnalysis : [];
5246 ignoredInlineSelectors = Array.isArray(fixes.ignoreInlineStyle) ? fixes.ignoreInlineStyle : [];
5247 }
5248 else {
5249 ignoredImageAnalysisSelectors = [];
5250 ignoredInlineSelectors = [];
5251 }
5252 if (filter.immediateModify) {
5253 setIsDOMReady(function () {
5254 return true;
5255 });
5256 }
5257 isIFrame$1 = iframe;
5258 if (document.head) {
5259 if (isAnotherDarkReaderInstanceActive()) {
5260 return;
5261 }
5262 document.documentElement.setAttribute('data-darkreader-mode', 'dynamic');
5263 document.documentElement.setAttribute('data-darkreader-scheme', filter.mode ? 'dark' : 'dimmed');
5264 createThemeAndWatchForUpdates();
5265 }
5266 else {
5267 if (!isFirefox) {
5268 var fallbackStyle = createOrUpdateStyle('darkreader--fallback');
5269 document.documentElement.appendChild(fallbackStyle);
5270 fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: true });
5271 }
5272 var headObserver_1 = new MutationObserver(function () {
5273 if (document.head) {
5274 headObserver_1.disconnect();
5275 if (isAnotherDarkReaderInstanceActive()) {
5276 removeDynamicTheme();
5277 return;
5278 }
5279 createThemeAndWatchForUpdates();
5280 }
5281 });
5282 headObserver_1.observe(document, { childList: true, subtree: true });
5283 }
5284 }
5285 function removeProxy() {
5286 document.dispatchEvent(new CustomEvent('__darkreader__cleanUp'));
5287 removeNode(document.head.querySelector('.darkreader--proxy'));
5288 }
5289 function removeDynamicTheme() {
5290 document.documentElement.removeAttribute("data-darkreader-mode");
5291 document.documentElement.removeAttribute("data-darkreader-scheme");
5292 cleanDynamicThemeCache();
5293 removeNode(document.querySelector('.darkreader--fallback'));
5294 if (document.head) {
5295 restoreMetaThemeColor();
5296 removeNode(document.head.querySelector('.darkreader--user-agent'));
5297 removeNode(document.head.querySelector('.darkreader--text'));
5298 removeNode(document.head.querySelector('.darkreader--invert'));
5299 removeNode(document.head.querySelector('.darkreader--inline'));
5300 removeNode(document.head.querySelector('.darkreader--override'));
5301 removeNode(document.head.querySelector('.darkreader--variables'));
5302 removeNode(document.head.querySelector('.darkreader--root-vars'));
5303 removeNode(document.head.querySelector('meta[name="darkreader"]'));
5304 removeProxy();
5305 }
5306 shadowRootsWithOverrides.forEach(function (root) {
5307 removeNode(root.querySelector('.darkreader--inline'));
5308 removeNode(root.querySelector('.darkreader--override'));
5309 });
5310 shadowRootsWithOverrides.clear();
5311 forEach(styleManagers.keys(), function (el) { return removeManager(el); });
5312 loadingStyles.clear();
5313 cleanLoadingLinks();
5314 forEach(document.querySelectorAll('.darkreader'), removeNode);
5315 adoptedStyleManagers.forEach(function (manager) {
5316 manager.destroy();
5317 });
5318 adoptedStyleManagers.splice(0);
5319 }
5320 function cleanDynamicThemeCache() {
5321 variablesStore.clear();
5322 parsedURLCache.clear();
5323 stopWatchingForDocumentVisibility();
5324 cancelRendering();
5325 stopWatchingForUpdates();
5326 cleanModificationCache();
5327 }
5328
5329 var blobRegex = /url\(\"(blob\:.*?)\"\)/g;
5330 function replaceBlobs(text) {
5331 return __awaiter(this, void 0, void 0, function () {
5332 var promises, data;
5333 return __generator(this, function (_a) {
5334 switch (_a.label) {
5335 case 0:
5336 promises = [];
5337 getMatches(blobRegex, text, 1).forEach(function (url) {
5338 var promise = loadAsDataURL(url);
5339 promises.push(promise);
5340 });
5341 return [4, Promise.all(promises)];
5342 case 1:
5343 data = _a.sent();
5344 return [2, text.replace(blobRegex, function () { return "url(\"".concat(data.shift(), "\")"); })];
5345 }
5346 });
5347 });
5348 }
5349 var banner = "/*\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/master/LICENSE */\n";
5350 function collectCSS() {
5351 return __awaiter(this, void 0, void 0, function () {
5352 function addStaticCSS(selector, comment) {
5353 var staticStyle = document.querySelector(selector);
5354 if (staticStyle && staticStyle.textContent) {
5355 css.push("/* ".concat(comment, " */"));
5356 css.push(staticStyle.textContent);
5357 css.push('');
5358 }
5359 }
5360 var css, modifiedCSS, formattedCSS, _a, _b;
5361 return __generator(this, function (_c) {
5362 switch (_c.label) {
5363 case 0:
5364 css = [banner];
5365 addStaticCSS('.darkreader--fallback', 'Fallback Style');
5366 addStaticCSS('.darkreader--user-agent', 'User-Agent Style');
5367 addStaticCSS('.darkreader--text', 'Text Style');
5368 addStaticCSS('.darkreader--invert', 'Invert Style');
5369 addStaticCSS('.darkreader--variables', 'Variables Style');
5370 modifiedCSS = [];
5371 document.querySelectorAll('.darkreader--sync').forEach(function (element) {
5372 forEach(element.sheet.cssRules, function (rule) {
5373 rule && rule.cssText && modifiedCSS.push(rule.cssText);
5374 });
5375 });
5376 if (!modifiedCSS.length) return [3, 2];
5377 formattedCSS = formatCSS(modifiedCSS.join('\n'));
5378 css.push('/* Modified CSS */');
5379 _b = (_a = css).push;
5380 return [4, replaceBlobs(formattedCSS)];
5381 case 1:
5382 _b.apply(_a, [_c.sent()]);
5383 css.push('');
5384 _c.label = 2;
5385 case 2:
5386 addStaticCSS('.darkreader--override', 'Override Style');
5387 return [2, css.join('\n')];
5388 }
5389 });
5390 });
5391 }
5392
5393 var isDarkReaderEnabled = false;
5394 var isIFrame = (function () {
5395 try {
5396 return window.self !== window.top;
5397 }
5398 catch (err) {
5399 console.warn(err);
5400 return true;
5401 }
5402 })();
5403 function enable(themeOptions, fixes) {
5404 if (themeOptions === void 0) { themeOptions = {}; }
5405 if (fixes === void 0) { fixes = null; }
5406 var theme = __assign(__assign({}, DEFAULT_THEME), themeOptions);
5407 if (theme.engine !== ThemeEngines.dynamicTheme) {
5408 throw new Error('Theme engine is not supported.');
5409 }
5410 createOrUpdateDynamicTheme(theme, fixes, isIFrame);
5411 isDarkReaderEnabled = true;
5412 }
5413 function isEnabled() {
5414 return isDarkReaderEnabled;
5415 }
5416 function disable() {
5417 removeDynamicTheme();
5418 isDarkReaderEnabled = false;
5419 }
5420 var darkScheme = matchMedia('(prefers-color-scheme: dark)');
5421 var store = {
5422 themeOptions: null,
5423 fixes: null,
5424 };
5425 function handleColorScheme() {
5426 if (darkScheme.matches) {
5427 enable(store.themeOptions, store.fixes);
5428 }
5429 else {
5430 disable();
5431 }
5432 }
5433 function auto(themeOptions, fixes) {
5434 if (themeOptions === void 0) { themeOptions = {}; }
5435 if (fixes === void 0) { fixes = null; }
5436 if (themeOptions) {
5437 store = { themeOptions: themeOptions, fixes: fixes };
5438 handleColorScheme();
5439 if (isMatchMediaChangeEventListenerSupported) {
5440 darkScheme.addEventListener('change', handleColorScheme);
5441 }
5442 else {
5443 darkScheme.addListener(handleColorScheme);
5444 }
5445 }
5446 else {
5447 if (isMatchMediaChangeEventListenerSupported) {
5448 darkScheme.removeEventListener('change', handleColorScheme);
5449 }
5450 else {
5451 darkScheme.removeListener(handleColorScheme);
5452 }
5453 disable();
5454 }
5455 }
5456 function exportGeneratedCSS() {
5457 return __awaiter(this, void 0, void 0, function () {
5458 return __generator(this, function (_a) {
5459 switch (_a.label) {
5460 case 0: return [4, collectCSS()];
5461 case 1: return [2, _a.sent()];
5462 }
5463 });
5464 });
5465 }
5466 var setFetchMethod = setFetchMethod$1;
5467
5468 exports.auto = auto;
5469 exports.disable = disable;
5470 exports.enable = enable;
5471 exports.exportGeneratedCSS = exportGeneratedCSS;
5472 exports.isEnabled = isEnabled;
5473 exports.setFetchMethod = setFetchMethod;
5474
5475 Object.defineProperty(exports, '__esModule', { value: true });
5476
5477}));