HyperLite Web Accelerator [NG]

АВТО-РЕЖИМ: видео-хостинги → мгновенный запуск центрального видео. Обычные сайты → текст в видимой области первым. Полная совместимость с Passkey и 2FA на ЛЮБОМ сайте + авто-отключение на grok.x.ai

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

You will need to install an extension such as Tampermonkey to install this script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         HyperLite Web Accelerator [NG]
// @name:en      HyperLite Web Accelerator [NG]
// @namespace    http://tampermonkey.net/
// @version      1.2.7
// @description  АВТО-РЕЖИМ: видео-хостинги → мгновенный запуск центрального видео. Обычные сайты → текст в видимой области первым. Полная совместимость с Passkey и 2FA на ЛЮБОМ сайте + авто-отключение на grok.x.ai
// @description:en AUTO MODE: Video sites → instant central video play. Full Passkey/2FA compatibility on ANY site + auto-skip on grok.x.ai
// @author       Qwen + Grok
// @match        *://*/*
// @grant        none
// @run-at       document-start
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    // === АВТО-ОТКЛЮЧЕНИЕ НА GROK / X.AI (чтобы passkey и 2FA работали 100%) ===
    if (location.hostname.endsWith('.x.ai') || location.hostname.includes('grok')) {
        console.log('[HyperLite] 🔥 Полностью отключён на grok.x.ai / x.ai — Passkey и 2FA теперь работают без ошибок');
        return; // ← полностью выходим, скрипт больше ничего не делает на этих доменах
    }

    // === БЕЗОПАСНЫЙ requestIdleCallback ===
    const requestIdleCallback = window.requestIdleCallback
        ? window.requestIdleCallback.bind(window)
        : (callback) => setTimeout(callback, 1);

    const CONFIG = {
        lazyImages: true,
        lazyIframes: true,
        blockAutoPlayOthers: true,
        blockTrackers: true,
        optimizeFonts: true,
        aggressivePrefetch: true,
        maxPrefetch: 12,
        rootMargin: '400px'
    };

    const TRACKER_DOMAINS = [
        'google-analytics.com', 'analytics.google.com', 'googletagmanager.com', 'doubleclick.net',
        'facebook.net', 'connect.facebook.net', 'fb.com', 'hotjar.com', 'intercom.io',
        'mc.yandex.ru', 'mc.yandex.net', 'metrika.yandex.ru', 'yandex.ru/metrika',
        'yandex.ru/adfox', 'clck.ru', 'clck.yandex.ru', 'dzen.ru', 'zen.yandex.ru',
        'pixel.', 'beacon.', 'counter.', 'stat.', 'tracker.', 'analytics.', 'ad.', 'ads.',
        'mail.ru', 't.mail.ru', 'ad.mail.ru', 'my.mail.ru/counter'
    ];

    const VIDEO_HOSTS_REGEX = /youtube|vk\.com|ok\.ru|rutube|dzen|yandex\.ru\/video|mail\.ru\/video|my\.mail\.ru\/video/i;

    // === ЗАЩИТА АУТЕНТИФИКАЦИИ НА ВСЕХ ОСТАЛЬНЫХ САЙТАХ ===
    function isAuthRelated(node) {
        if (!node || node.nodeType !== 1) return false;
        const str = (node.id || node.className || node.getAttribute('data-') || node.src || node.tagName || '').toLowerCase();
        const keywords = ['webauthn','passkey','credential','2fa','otp','mfa','totp','twofactor','verification','auth','login','session','challenge','verify','code','token','invalid_argument'];
        if (keywords.some(k => str.includes(k))) return true;

        // проверка родителей
        let parent = node.parentElement;
        while (parent) {
            const pstr = (parent.id || parent.className || parent.getAttribute('data-') || parent.src || '').toLowerCase();
            if (keywords.some(k => pstr.includes(k))) return true;
            parent = parent.parentElement;
        }
        return false;
    }

    function isCriticalIframe(iframe) {
        if (!iframe || iframe.tagName !== 'IFRAME') return false;
        const src = (iframe.src || '').toLowerCase();
        if (src.startsWith('chrome-extension:') || src.startsWith('moz-extension:') ||
            src.startsWith('ms-browser-extension:') || src.startsWith('safari-web-extension:') ||
            !src || src === 'about:blank') return true;

        if (src.includes('webauthn') || src.includes('credential') || (src.includes('auth') && src.includes('iframe'))) return true;

        const rect = iframe.getBoundingClientRect();
        const style = window.getComputedStyle(iframe);
        if (style.display === 'none' || style.visibility === 'hidden' || parseFloat(style.opacity) < 0.1 ||
            rect.width <= 4 || rect.height <= 4) return true;
        return false;
    }

    // === 1. БЛОКИРОВКА ТРЕКЕРОВ ===
    function blockTrackersInNode(node) {
        if (!node || node.nodeType !== 1 || isAuthRelated(node)) return;
        const checkElement = (el) => {
            if (!el || el.nodeType !== 1) return false;
            if (el.tagName === 'SCRIPT' || el.tagName === 'IFRAME' || el.tagName === 'IMG') {
                const src = (el.src || el.href || '').toLowerCase();
                if (TRACKER_DOMAINS.some(d => src.includes(d))) {
                    el.remove();
                    return true;
                }
            }
            return false;
        };
        checkElement(node);
        node.querySelectorAll('script[src], iframe[src], img[src]').forEach(checkElement);
    }

    // === 2. ОПТИМИЗАЦИЯ ШРИФТОВ ===
    function optimizeFonts() {
        if (!CONFIG.optimizeFonts) return;
        const style = document.createElement('style');
        style.textContent = `
            html { -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
            * { font-display: swap !important; }
            @media (prefers-reduced-motion: reduce) {
                *, ::before, ::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
            }
        `;
        document.head.appendChild(style);

        const resources = ['https://www.youtube.com','https://vk.com','https://rutube.ru','https://dzen.ru','https://ok.ru','https://mail.ru','https://my.mail.ru','https://i.ytimg.com','https://fonts.googleapis.com','https://fonts.gstatic.com'];
        resources.forEach(href => {
            const pre = document.createElement('link'); pre.rel = 'preconnect'; pre.href = href; document.head.appendChild(pre);
            const dns = document.createElement('link'); dns.rel = 'dns-prefetch'; dns.href = href; document.head.appendChild(dns);
        });
    }

    // === 3. ОБРАБОТКА МЕДИА ===
    function processMedia(node, isMainVideo = false) {
        if (!node || node.nodeType !== 1 || isAuthRelated(node)) return;

        if (CONFIG.lazyImages) {
            const images = node.tagName === 'IMG' ? [node] : node.querySelectorAll('img');
            images.forEach(img => {
                if (!img.hasAttribute('loading')) img.setAttribute('loading', 'lazy');
                img.decoding = 'async';
            });
        }

        if (CONFIG.lazyIframes) {
            const iframes = node.tagName === 'IFRAME' ? [node] : node.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                if (isCriticalIframe(iframe)) return;
                const src = iframe.src || '';
                const isVideoPlatform = VIDEO_HOSTS_REGEX.test(src);
                if (isVideoPlatform && isMainVideo) {
                    iframe.removeAttribute('loading');
                    iframe.setAttribute('preload', 'auto');
                    if (src.includes('autoplay=0')) iframe.src = src.replace('autoplay=0', 'autoplay=1');
                } else {
                    if (!iframe.hasAttribute('loading')) iframe.setAttribute('loading', 'lazy');
                    if (isVideoPlatform && src.includes('autoplay=1')) iframe.src = src.replace('autoplay=1', 'autoplay=0');
                }
            });
        }

        const videos = node.tagName === 'VIDEO' ? [node] : node.querySelectorAll('video');
        videos.forEach(video => {
            if (isMainVideo) {
                video.removeAttribute('loading');
                video.setAttribute('preload', 'auto');
                video.autoplay = true;
                video.load();
                video.setAttribute('fetchpriority', 'high');
            } else if (CONFIG.blockAutoPlayOthers) {
                video.removeAttribute('autoplay');
                video.setAttribute('preload', 'none');
            }
        });
    }

    // === 4. INTERSECTION OBSERVER ===
    let mainVideoObserver = null;
    function activateMainVideoFocus() {
        if (mainVideoObserver) mainVideoObserver.disconnect();
        mainVideoObserver = new IntersectionObserver((entries) => {
            for (const entry of entries) {
                if (entry.isIntersecting && entry.intersectionRatio > 0.65) {
                    const el = entry.target;
                    const isVideoPlatform = el.tagName === 'VIDEO' || VIDEO_HOSTS_REGEX.test(el.src || '');
                    if (isVideoPlatform) {
                        processMedia(el, true);
                        mainVideoObserver.disconnect();
                        return;
                    }
                }
            }
        }, { threshold: 0.65, rootMargin: CONFIG.rootMargin });

        document.querySelectorAll('video, iframe').forEach(el => {
            if (!isAuthRelated(el)) mainVideoObserver.observe(el);
        });
    }

    // === 5. PREFETCH ===
    let alreadyPrefetched = new Set();
    function prefetchVisibleLinks() {
        if (!CONFIG.aggressivePrefetch) return;
        requestIdleCallback(() => {
            let count = 0;
            document.querySelectorAll('a[href]').forEach(a => {
                if (count >= CONFIG.maxPrefetch) return;
                const rect = a.getBoundingClientRect();
                const href = a.href;
                if (rect.top < window.innerHeight * 1.5 && rect.bottom > -100 && href.startsWith('http') && !alreadyPrefetched.has(href)) {
                    const link = document.createElement('link');
                    link.rel = 'prefetch';
                    link.href = href;
                    document.head.appendChild(link);
                    alreadyPrefetched.add(href);
                    count++;
                }
            });
        });
    }

    // === MUTATIONOBSERVER ===
    const observer = new MutationObserver((mutations) => {
        if (document.hidden) return;
        requestIdleCallback(() => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) {
                        processMedia(node, false);
                        blockTrackersInNode(node);
                    }
                });
            });
        });
    });

    // === ИНИЦИАЛИЗАЦИЯ ===
    function init() {
        if (!document.body) { setTimeout(init, 50); return; }
        optimizeFonts();
        processMedia(document.body, false);
        blockTrackersInNode(document.body);
        observer.observe(document.documentElement, { childList: true, subtree: true });
        setTimeout(() => { activateMainVideoFocus(); prefetchVisibleLinks(); }, 400);
        setTimeout(() => { 
            if (mainVideoObserver) mainVideoObserver.disconnect();
            activateMainVideoFocus(); 
            prefetchVisibleLinks(); 
        }, 2200);
        window.addEventListener('load', prefetchVisibleLinks);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();