/*******************************************************************************

    uBlock Origin - a browser extension to block requests.
    Copyright (C) 2019-present Raymond Hill

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see {http://www.gnu.org/licenses/}.

    Home: https://github.com/gorhill/uBlock

    The scriptlets below are meant to be injected only into a
    web page context.
*/

// The lines below are skipped by the resource parser. Purpose is clean
// jshinting.
(function() {
// >>>> start of private namespace
'use strict';

/// abort-current-script.js
/// alias acs.js
/// alias abort-current-inline-script.js
/// alias acis.js
(function() {
    const target = '{{1}}';
    if ( target === '' || target === '{{1}}' ) { return; }
    const reRegexEscape = /[.*+?^${}()|[\]\\]/g;
    const needle = '{{2}}';
    const reNeedle = (( ) => {
        if ( needle === '' || needle === '{{2}}' ) { return /^/; }
        if ( /^\/.+\/$/.test(needle) ) {
            return new RegExp(needle.slice(1,-1));
        }
        return new RegExp(needle.replace(reRegexEscape, '\\$&'));
    })();
    const context = '{{3}}';
    const reContext = (( ) => {
        if ( context === '' || context === '{{3}}' ) { return /^$/; }
        if ( /^\/.+\/$/.test(context) ) {
            return new RegExp(context.slice(1,-1));
        }
        return new RegExp(context.replace(reRegexEscape, '\\$&'));
    })();
    const thisScript = document.currentScript;
    const chain = target.split('.');
    let owner = window;
    let prop;
    for (;;) {
        prop = chain.shift();
        if ( chain.length === 0 ) { break; }
        owner = owner[prop];
        if ( owner instanceof Object === false ) { return; }
    }
    let value;
    let desc = Object.getOwnPropertyDescriptor(owner, prop);
    if (
        desc instanceof Object === false ||
        desc.get instanceof Function === false
    ) {
        value = owner[prop];
        desc = undefined;
    }
    const magic = String.fromCharCode(Date.now() % 26 + 97) +
                  Math.floor(Math.random() * 982451653 + 982451653).toString(36);
    const scriptTexts = new WeakMap();
    const getScriptText = elem => {
        let text = elem.textContent;
        if ( text.trim() !== '' ) { return text; }
        if ( scriptTexts.has(elem) ) { return scriptTexts.get(elem); }
        const [ , mime, content ] =
            /^data:([^,]*),(.+)$/.exec(elem.src.trim()) ||
            [ '', '', '' ];
        try {
            switch ( true ) {
            case mime.endsWith(';base64'):
                text = self.atob(content);
                break;
            default:
                text = self.decodeURIComponent(content);
                break;
            }
        } catch(ex) {
        }
        scriptTexts.set(elem, text);
        return text;
    };
    const validate = ( ) => {
        const e = document.currentScript;
        if ( e instanceof HTMLScriptElement === false ) { return; }
        if ( reContext.test(e.src) === false ) { return; }
        if ( e === thisScript ) { return; }
        if ( reNeedle.test(getScriptText(e)) === false ) { return; }
        throw new ReferenceError(magic);
    };
    Object.defineProperty(owner, prop, {
        get: function() {
            validate();
            return desc instanceof Object
                ? desc.get.call(owner)
                : value;
        },
        set: function(a) {
            validate();
            if ( desc instanceof Object ) {
                desc.set.call(owner, a);
            } else {
                value = a;
            }
        }
    });
    const oe = window.onerror;
    window.onerror = function(msg) {
        if ( typeof msg === 'string' && msg.includes(magic) ) {
            return true;
        }
        if ( oe instanceof Function ) {
            return oe.apply(this, arguments);
        }
    }.bind();
})();

/// abort-on-property-read.js
/// alias aopr.js
(function() {
    const magic = String.fromCharCode(Date.now() % 26 + 97) +
                  Math.floor(Math.random() * 982451653 + 982451653).toString(36);
    const abort = function() {
        throw new ReferenceError(magic);
    };
    const makeProxy = function(owner, chain) {
        const pos = chain.indexOf('.');
        if ( pos === -1 ) {
            const desc = Object.getOwnPropertyDescriptor(owner, chain);
            if ( !desc || desc.get !== abort ) {
                Object.defineProperty(owner, chain, {
                    get: abort,
                    set: function(){}
                });
            }
            return;
        }
        const prop = chain.slice(0, pos);
        let v = owner[prop];
        chain = chain.slice(pos + 1);
        if ( v ) {
            makeProxy(v, chain);
            return;
        }
        const desc = Object.getOwnPropertyDescriptor(owner, prop);
        if ( desc && desc.set !== undefined ) { return; }
        Object.defineProperty(owner, prop, {
            get: function() { return v; },
            set: function(a) {
                v = a;
                if ( a instanceof Object ) {
                    makeProxy(a, chain);
                }
            }
        });
    };
    const owner = window;
    let chain = '{{1}}';
    makeProxy(owner, chain);
    const oe = window.onerror;
    window.onerror = function(msg, src, line, col, error) {
        if ( typeof msg === 'string' && msg.indexOf(magic) !== -1 ) {
            return true;
        }
        if ( oe instanceof Function ) {
            return oe(msg, src, line, col, error);
        }
    }.bind();
})();

/// abort-on-property-write.js
/// alias aopw.js
(function() {
    const magic = String.fromCharCode(Date.now() % 26 + 97) +
                  Math.floor(Math.random() * 982451653 + 982451653).toString(36);
    let prop = '{{1}}';
    let owner = window;
    for (;;) {
        const pos = prop.indexOf('.');
        if ( pos === -1 ) { break; }
        owner = owner[prop.slice(0, pos)];
        if ( owner instanceof Object === false ) { return; }
        prop = prop.slice(pos + 1);
    }
    delete owner[prop];
    Object.defineProperty(owner, prop, {
        set: function() {
            throw new ReferenceError(magic);
        }
    });
    const oe = window.onerror;
    window.onerror = function(msg, src, line, col, error) {
        if ( typeof msg === 'string' && msg.indexOf(magic) !== -1 ) {
            return true;
        }
        if ( oe instanceof Function ) {
            return oe(msg, src, line, col, error);
        }
    }.bind();
})();

/// abort-on-stack-trace.js
/// alias aost.js
// Status is currently experimental
(function() {
    let chain = '{{1}}';
    let needle = '{{2}}';
    let logLevel = '{{3}}';
    const reRegexEscape = /[.*+?^${}()|[\]\\]/g;
    if ( needle === '' || needle === '{{2}}' ) {
        needle = '^';
    } else if ( /^\/.+\/$/.test(needle) ) {
        needle = needle.slice(1,-1);
    } else {
        needle = needle.replace(reRegexEscape, '\\$&');
    }
    const reNeedle = new RegExp(needle);
    const magic = String.fromCharCode(Math.random() * 26 + 97) +
        Math.floor(
            (0.25 + Math.random() * 0.75) * Number.MAX_SAFE_INTEGER
        ).toString(36).slice(-8);
    const log = console.log.bind(console);
    const ErrorCtor = self.Error;
    const mustAbort = function(err) {
        let docURL = self.location.href;
        const pos = docURL.indexOf('#');
        if ( pos !== -1 ) {
            docURL = docURL.slice(0, pos);
        }
        // Normalize stack trace
        const lines = [];
        for ( let line of err.stack.split(/[\n\r]+/) ) {
            if ( line.includes(magic) ) { continue; }
            line = line.trim();
            let match = /(.*?@)?(\S+)(:\d+):\d+\)?$/.exec(line);
            if ( match === null ) { continue; }
            let url = match[2];
            if ( url.startsWith('(') ) { url = url.slice(1); }
            if ( url === docURL ) {
                url = 'inlineScript';
            } else if ( url.startsWith('<anonymous>') ) {
                url = 'injectedScript';
            }
            let fn = match[1] !== undefined
                ? match[1].slice(0, -1)
                : line.slice(0, match.index).trim();
            if ( fn.startsWith('at') ) { fn = fn.slice(2).trim(); }
            let rowcol = match[3];
            lines.push(' ' + `${fn} ${url}${rowcol}:1`.trim());
        }
        lines[0] = `stackDepth:${lines.length-1}`;
        const stack = lines.join('\t');
        const r = reNeedle.test(stack);
        if (
            logLevel === '1' ||
            logLevel === '2' && r ||
            logLevel === '3' && !r
        ) {
            log(stack.replace(/\t/g, '\n'));
        }
        return r;
    };
    const makeProxy = function(owner, chain) {
        const pos = chain.indexOf('.');
        if ( pos === -1 ) {
            let v = owner[chain];
            Object.defineProperty(owner, chain, {
                get: function() {
                    if ( mustAbort(new ErrorCtor(magic)) ) {
                        throw new ReferenceError(magic);
                    }
                    return v;
                },
                set: function(a) {
                    if ( mustAbort(new ErrorCtor(magic)) ) {
                        throw new ReferenceError(magic);
                    }
                    v = a;
                },
            });
            return;
        }
        const prop = chain.slice(0, pos);
        let v = owner[prop];
        chain = chain.slice(pos + 1);
        if ( v ) {
            makeProxy(v, chain);
            return;
        }
        const desc = Object.getOwnPropertyDescriptor(owner, prop);
        if ( desc && desc.set !== undefined ) { return; }
        Object.defineProperty(owner, prop, {
            get: function() { return v; },
            set: function(a) {
                v = a;
                if ( a instanceof Object ) {
                    makeProxy(a, chain);
                }
            }
        });
    };
    const owner = window;
    makeProxy(owner, chain);
    const oe = window.onerror;
    window.onerror = function(msg, src, line, col, error) {
        if ( typeof msg === 'string' && msg.indexOf(magic) !== -1 ) {
            return true;
        }
        if ( oe instanceof Function ) {
            return oe(msg, src, line, col, error);
        }
    }.bind();
})();

/// addEventListener-defuser.js
/// alias aeld.js
// https://github.com/uBlockOrigin/uAssets/issues/9123#issuecomment-848255120
(function() {
    let needle1 = '{{1}}';
    if ( needle1 === '' || needle1 === '{{1}}' ) {
        needle1 = '.?';
    } else if ( /^\/.+\/$/.test(needle1) ) {
        needle1 = needle1.slice(1,-1);
    } else {
        needle1 = needle1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    needle1 = new RegExp(needle1);
    let needle2 = '{{2}}';
    if ( needle2 === '' || needle2 === '{{2}}' ) {
        needle2 = '.?';
    } else if ( /^\/.+\/$/.test(needle2) ) {
        needle2 = needle2.slice(1,-1);
    } else {
        needle2 = needle2.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    needle2 = new RegExp(needle2);
    self.EventTarget.prototype.addEventListener = new Proxy(
        self.EventTarget.prototype.addEventListener,
        {
            apply: function(target, thisArg, args) {
                let type, handler;
                try {
                    type = String(args[0]);
                    handler = String(args[1]);
                } catch(ex) {
                }
                if (
                    needle1.test(type) === false ||
                    needle2.test(handler) === false
                ) {
                    return target.apply(thisArg, args);
                }
            }
        }
    );
})();

/// addEventListener-logger.js
/// alias aell.js
// https://github.com/uBlockOrigin/uAssets/issues/9123#issuecomment-848255120
(function() {
    const log = console.log.bind(console);
    self.EventTarget.prototype.addEventListener = new Proxy(
        self.EventTarget.prototype.addEventListener,
        {
            apply: function(target, thisArg, args) {
                let type, handler;
                try {
                    type = String(args[0]);
                    handler = String(args[1]);
                } catch(ex) {
                }
                log('uBO: addEventListener("%s", %s)', type, handler);
                return target.apply(thisArg, args);
            }
        }
    );
})();

/// json-prune.js
//
//  When no "prune paths" argument is provided, the scriptlet is
//  used for logging purpose and the "needle paths" argument is
//  used to filter logging output.
//
//  https://github.com/uBlockOrigin/uBlock-issues/issues/1545
//  - Add support for "remove everything if needle matches" case
//
(function() {
    const rawPrunePaths = '{{1}}';
    const rawNeedlePaths = '{{2}}';
    const prunePaths = rawPrunePaths !== '{{1}}' && rawPrunePaths !== ''
        ? rawPrunePaths.split(/ +/)
        : [];
    let needlePaths;
    let log, reLogNeedle;
    if ( prunePaths.length !== 0 ) {
        needlePaths = prunePaths.length !== 0 &&
                      rawNeedlePaths !== '{{2}}' && rawNeedlePaths !== ''
            ? rawNeedlePaths.split(/ +/)
            : [];
    } else {
        log = console.log.bind(console);
        let needle;
        if ( rawNeedlePaths === '' || rawNeedlePaths === '{{2}}' ) {
            needle = '.?';
        } else if ( rawNeedlePaths.charAt(0) === '/' && rawNeedlePaths.slice(-1) === '/' ) {
            needle = rawNeedlePaths.slice(1, -1);
        } else {
            needle = rawNeedlePaths.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        reLogNeedle = new RegExp(needle);
    }
    const findOwner = function(root, path, prune = false) {
        let owner = root;
        let chain = path;
        for (;;) {
            if ( typeof owner !== 'object' || owner === null  ) {
                return false;
            }
            const pos = chain.indexOf('.');
            if ( pos === -1 ) {
                if ( prune === false ) {
                    return owner.hasOwnProperty(chain);
                }
                if ( chain === '*' ) {
                    for ( const key in owner ) {
                        if ( owner.hasOwnProperty(key) === false ) { continue; }
                        delete owner[key];
                    }
                } else if ( owner.hasOwnProperty(chain) ) {
                    delete owner[chain];
                }
                return true;
            }
            const prop = chain.slice(0, pos);
            if (
                prop === '[]' && Array.isArray(owner) ||
                prop === '*' && owner instanceof Object
            ) {
                const next = chain.slice(pos + 1);
                let found = false;
                for ( const key of Object.keys(owner) ) {
                    found = findOwner(owner[key], next, prune) || found;
                }
                return found;
            }
            if ( owner.hasOwnProperty(prop) === false ) { return false; }
            owner = owner[prop];
            chain = chain.slice(pos + 1);
        }
    };
    const mustProcess = function(root) {
        for ( const needlePath of needlePaths ) {
            if ( findOwner(root, needlePath) === false ) {
                return false;
            }
        }
        return true;
    };
    const pruner = function(o) {
        if ( log !== undefined ) {
            const json = JSON.stringify(o, null, 2);
            if ( reLogNeedle.test(json) ) {
                log('uBO:', location.hostname, json);
            }
            return o;
        }
        if ( mustProcess(o) === false ) { return o; }
        for ( const path of prunePaths ) {
            findOwner(o, path, true);
        }
        return o;
    };
    JSON.parse = new Proxy(JSON.parse, {
        apply: function() {
            return pruner(Reflect.apply(...arguments));
        },
    });
    Response.prototype.json = new Proxy(Response.prototype.json, {
        apply: function() {
            return Reflect.apply(...arguments).then(o => pruner(o));
        },
    });
})();

// Imported from:
// https://github.com/NanoAdblocker/NanoFilters/blob/1f3be7211bb0809c5106996f52564bf10c4525f7/NanoFiltersSource/NanoResources.txt#L126
//
// Speed up or down setInterval, 3 optional arguments.
//      The payload matcher, a string literal or a JavaScript RegExp, defaults
//      to match all.
// delayMatcher
//      The delay matcher, an integer, defaults to 1000.
//      Use `*` to match any delay.
// boostRatio - The delay multiplier when there is a match, 0.5 speeds up by
//      2 times and 2 slows down by 2 times, defaults to 0.05 or speed up
//      20 times. Speed up and down both cap at 50 times.
/// nano-setInterval-booster.js
/// alias nano-sib.js
(function() {
    let needleArg = '{{1}}';
    if ( needleArg === '{{1}}' ) { needleArg = ''; }
    let delayArg = '{{2}}';
    if ( delayArg === '{{2}}' ) { delayArg = ''; }
    let boostArg = '{{3}}';
    if ( boostArg === '{{3}}' ) { boostArg = ''; }
    if ( needleArg === '' ) {
        needleArg = '.?';
    } else if ( needleArg.charAt(0) === '/' && needleArg.slice(-1) === '/' ) {
        needleArg = needleArg.slice(1, -1);
    } else {
        needleArg = needleArg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    const reNeedle = new RegExp(needleArg);
    let delay = delayArg !== '*' ? parseInt(delayArg, 10) : -1;
    if ( isNaN(delay) || isFinite(delay) === false ) { delay = 1000; }
    let boost = parseFloat(boostArg);
    boost = isNaN(boost) === false && isFinite(boost)
        ? Math.min(Math.max(boost, 0.02), 50)
        : 0.05;
    self.setInterval = new Proxy(self.setInterval, {
        apply: function(target, thisArg, args) {
            const [ a, b ] = args;
            if (
                (delay === -1 || b === delay) &&
                reNeedle.test(a.toString())
            ) {
                args[1] = b * boost;
            }
            return target.apply(thisArg, args);
        }
    });
})();

// Imported from:
// https://github.com/NanoAdblocker/NanoFilters/blob/1f3be7211bb0809c5106996f52564bf10c4525f7/NanoFiltersSource/NanoResources.txt#L82
//
// Speed up or down setTimeout, 3 optional arguments.
// funcMatcher
//      The payload matcher, a string literal or a JavaScript RegExp, defaults
//      to match all.
// delayMatcher
//      The delay matcher, an integer, defaults to 1000.
//      Use `*` to match any delay.
// boostRatio - The delay multiplier when there is a match, 0.5 speeds up by
//      2 times and 2 slows down by 2 times, defaults to 0.05 or speed up
//      20 times. Speed up and down both cap at 50 times.
/// nano-setTimeout-booster.js
/// alias nano-stb.js
(function() {
    let needleArg = '{{1}}';
    if ( needleArg === '{{1}}' ) { needleArg = ''; }
    let delayArg = '{{2}}';
    if ( delayArg === '{{2}}' ) { delayArg = ''; }
    let boostArg = '{{3}}';
    if ( boostArg === '{{3}}' ) { boostArg = ''; }
    if ( needleArg === '' ) {
        needleArg = '.?';
    } else if ( needleArg.charAt(0) === '/' && needleArg.slice(-1) === '/' ) {
        needleArg = needleArg.slice(1, -1);
    } else {
        needleArg = needleArg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    const reNeedle = new RegExp(needleArg);
    let delay = delayArg !== '*' ? parseInt(delayArg, 10) : -1;
    if ( isNaN(delay) || isFinite(delay) === false ) { delay = 1000; }
    let boost = parseFloat(boostArg);
    boost = isNaN(boost) === false && isFinite(boost)
        ? Math.min(Math.max(boost, 0.02), 50)
        : 0.05;
    self.setTimeout = new Proxy(self.setTimeout, {
        apply: function(target, thisArg, args) {
            const [ a, b ] = args;
            if (
                (delay === -1 || b === delay) &&
                reNeedle.test(a.toString())
            ) {
                args[1] = b * boost;
            }
            return target.apply(thisArg, args);
        }
    });
})();

/// noeval-if.js
(function() {
    let needle = '{{1}}';
    if ( needle === '' || needle === '{{1}}' ) {
        needle = '.?';
    } else if ( needle.slice(0,1) === '/' && needle.slice(-1) === '/' ) {
        needle = needle.slice(1,-1);
    } else {
        needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    needle = new RegExp(needle);
    window.eval = new Proxy(window.eval, {          // jshint ignore: line
        apply: function(target, thisArg, args) {
            const a = args[0];
            if ( needle.test(a.toString()) === false ) {
                return target.apply(thisArg, args);
            }
        }
    });
})();

/// no-fetch-if.js
(function() {
    let arg1 = '{{1}}';
    if ( arg1 === '{{1}}' ) { arg1 = ''; }
    const needles = [];
    for ( const condition of arg1.split(/\s+/) ) {
        if ( condition === '' ) { continue; }
        const pos = condition.indexOf(':');
        let key, value;
        if ( pos !== -1 ) {
            key = condition.slice(0, pos);
            value = condition.slice(pos + 1);
        } else {
            key = 'url';
            value = condition;
        }
        if ( value === '' ) {
            value = '^';
        } else if ( value.startsWith('/') && value.endsWith('/') ) {
            value = value.slice(1, -1);
        } else {
            value = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        needles.push({ key, re: new RegExp(value) });
    }
    const log = needles.length === 0 ? console.log.bind(console) : undefined;
    self.fetch = new Proxy(self.fetch, {
        apply: function(target, thisArg, args) {
            let proceed = true;
            try {
                let details;
                if ( args[0] instanceof self.Request ) {
                    details = args[0];
                } else {
                    details = Object.assign({ url: args[0] }, args[1]);
                }
                const props = new Map();
                for ( const prop in details ) {
                    let v = details[prop];
                    if ( typeof v !== 'string' ) {
                        try { v = JSON.stringify(v); }
                        catch(ex) { }
                    }
                    if ( typeof v !== 'string' ) { continue; }
                    props.set(prop, v);
                }
                if ( log !== undefined ) {
                    const out = Array.from(props)
                                     .map(a => `${a[0]}:${a[1]}`)
                                     .join(' ');
                    log(`uBO: fetch(${out})`);
                }
                proceed = needles.length === 0;
                for ( const { key, re } of needles ) {
                    if (
                        props.has(key) === false ||
                        re.test(props.get(key)) === false
                    ) {
                        proceed = true;
                        break;
                    }
                }
            } catch(ex) {
            }
            return proceed
                ? Reflect.apply(target, thisArg, args)
                : Promise.resolve(new Response());
        }
    });
})();

/// no-floc.js
//  https://github.com/uBlockOrigin/uBlock-issues/issues/1553
(function() {
    if ( Document instanceof Object === false ) { return; }
    if ( Document.prototype.interestCohort instanceof Function === false ) {
        return;
    }
    Document.prototype.interestCohort = new Proxy(
        Document.prototype.interestCohort,
        {
            apply: function() {
                return Promise.reject();
            }
        }
    );
})();

/// refresh-defuser.js
// https://www.reddit.com/r/uBlockOrigin/comments/q0frv0/while_reading_a_sports_article_i_was_redirected/hf7wo9v/
(function() {
    const arg1 = '{{1}}';
    const defuse = ( ) => {
        const meta = document.querySelector('meta[http-equiv="refresh" i][content]');
        if ( meta === null ) { return; }
        const s = arg1 === '' || arg1 === '{{1}}'
            ? meta.getAttribute('content')
            : arg1;
        const ms = Math.max(parseFloat(s) || 0, 0) * 1000;
        setTimeout(( ) => { window.stop(); }, ms);
    };
    if ( document.readyState === 'loading' ) {
        document.addEventListener('DOMContentLoaded', defuse, { once: true });
    } else {
        defuse();
    }
})();

/// remove-attr.js
/// alias ra.js
(function() {
    const token = '{{1}}';
    if ( token === '' || token === '{{1}}' ) { return; }
    const tokens = token.split(/\s*\|\s*/);
    let selector = '{{2}}';
    if ( selector === '' || selector === '{{2}}' ) {
        selector = `[${tokens.join('],[')}]`;
    }
    let behavior = '{{3}}';
    let timer;
    const rmattr = ( ) => {
        timer = undefined;
        try {
            const nodes = document.querySelectorAll(selector);
            for ( const node of nodes ) {
                for ( const attr of tokens ) {
                    node.removeAttribute(attr);
                }
            }
        } catch(ex) {
        }
    };
    const mutationHandler = mutations => {
        if ( timer !== undefined ) { return; }
        let skip = true;
        for ( let i = 0; i < mutations.length && skip; i++ ) {
            const { type, addedNodes, removedNodes } = mutations[i];
            if ( type === 'attributes' ) { skip = false; }
            for ( let j = 0; j < addedNodes.length && skip; j++ ) {
                if ( addedNodes[j].nodeType === 1 ) { skip = false; break; }
            }
            for ( let j = 0; j < removedNodes.length && skip; j++ ) {
                if ( removedNodes[j].nodeType === 1 ) { skip = false; break; }
            }
        }
        if ( skip ) { return; }
        timer = self.requestIdleCallback(rmattr, { timeout: 17 });
    };
    const start = ( ) => {
        rmattr();
        if ( /\bstay\b/.test(behavior) === false ) { return; }
        const observer = new MutationObserver(mutationHandler);
        observer.observe(document, {
            attributes: true,
            attributeFilter: tokens,
            childList: true,
            subtree: true,
        });
    };
    if ( document.readyState !== 'complete' && /\bcomplete\b/.test(behavior) ) {
        self.addEventListener('load', start, { once: true });
    } else if ( document.readyState !== 'loading' || /\basap\b/.test(behavior) ) {
        start();
    } else {
        self.addEventListener('DOMContentLoaded', start, { once: true });
    }
})();

/// remove-class.js
/// alias rc.js
(function() {
    const token = '{{1}}';
    if ( token === '' || token === '{{1}}' ) { return; }
    const tokens = token.split(/\s*\|\s*/);
    let selector = '{{2}}';
    if ( selector === '' || selector === '{{2}}' ) {
        selector = '.' + tokens.map(a => CSS.escape(a)).join(',.');
    }
    let behavior = '{{3}}';
    let timer;
    const rmclass = function() {
        timer = undefined;
        try {
            const nodes = document.querySelectorAll(selector);
            for ( const node of nodes ) {
                node.classList.remove(...tokens);
            }
        } catch(ex) {
        }
    };
    const mutationHandler = mutations => {
        if ( timer !== undefined ) { return; }
        let skip = true;
        for ( let i = 0; i < mutations.length && skip; i++ ) {
            const { type, addedNodes, removedNodes } = mutations[i];
            if ( type === 'attributes' ) { skip = false; }
            for ( let j = 0; j < addedNodes.length && skip; j++ ) {
                if ( addedNodes[j].nodeType === 1 ) { skip = false; break; }
            }
            for ( let j = 0; j < removedNodes.length && skip; j++ ) {
                if ( removedNodes[j].nodeType === 1 ) { skip = false; break; }
            }
        }
        if ( skip ) { return; }
        timer = self.requestIdleCallback(rmclass, { timeout: 67 });
    };
    const start = ( ) => {
        rmclass();
        if ( /\bstay\b/.test(behavior) === false ) { return; }
        const observer = new MutationObserver(mutationHandler);
        observer.observe(document, {
            attributes: true,
            attributeFilter: [ 'class' ],
            childList: true,
            subtree: true,
        });
    };
    if ( document.readyState !== 'complete' && /\bcomplete\b/.test(behavior) ) {
        self.addEventListener('load', start, { once: true });
    } else if ( document.readyState === 'loading' ) {
        self.addEventListener('DOMContentLoaded', start, { once: true });
    } else {
        start();
    }
})();

/// no-requestAnimationFrame-if.js
/// alias norafif.js
(function() {
    let needle = '{{1}}';
    if ( needle === '{{1}}' ) { needle = ''; }
    const needleNot = needle.charAt(0) === '!';
    if ( needleNot ) { needle = needle.slice(1); }
    if ( needle.startsWith('/') && needle.endsWith('/') ) {
        needle = needle.slice(1, -1);
    } else if ( needle !== '' ) {
        needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    const log = needleNot === false && needle === '' ? console.log : undefined;
    const reNeedle = new RegExp(needle);
    window.requestAnimationFrame = new Proxy(window.requestAnimationFrame, {
        apply: function(target, thisArg, args) {
            const a = String(args[0]);
            let defuse = false;
            if ( log !== undefined ) {
                log('uBO: requestAnimationFrame("%s")', a);
            } else {
                defuse = reNeedle.test(a) !== needleNot;
            }
            if ( defuse ) {
                args[0] = function(){};
            }
            return target.apply(thisArg, args);
        }
    });
})();

/// set-constant.js
/// alias set.js
(function() {
    const chain = '{{1}}';
    let cValue = '{{2}}';
    const thisScript = document.currentScript;
    if ( cValue === 'undefined' ) {
        cValue = undefined;
    } else if ( cValue === 'false' ) {
        cValue = false;
    } else if ( cValue === 'true' ) {
        cValue = true;
    } else if ( cValue === 'null' ) {
        cValue = null;
    } else if ( cValue === "''" ) {
        cValue = '';
    } else if ( cValue === '[]' ) {
        cValue = [];
    } else if ( cValue === '{}' ) {
        cValue = {};
    } else if ( cValue === 'noopFunc' ) {
        cValue = function(){};
    } else if ( cValue === 'trueFunc' ) {
        cValue = function(){ return true; };
    } else if ( cValue === 'falseFunc' ) {
        cValue = function(){ return false; };
    } else if ( /^\d+$/.test(cValue) ) {
        cValue = parseFloat(cValue);
        if ( isNaN(cValue) ) { return; }
        if ( Math.abs(cValue) > 0x7FFF ) { return; }
    } else {
        return;
    }
    let aborted = false;
    const mustAbort = function(v) {
        if ( aborted ) { return true; }
        aborted =
            (v !== undefined && v !== null) &&
            (cValue !== undefined && cValue !== null) &&
            (typeof v !== typeof cValue);
        return aborted;
    };
    // https://github.com/uBlockOrigin/uBlock-issues/issues/156
    //   Support multiple trappers for the same property.
    const trapProp = function(owner, prop, configurable, handler) {
        if ( handler.init(owner[prop]) === false ) { return; }
        const odesc = Object.getOwnPropertyDescriptor(owner, prop);
        let prevGetter, prevSetter;
        if ( odesc instanceof Object ) {
            owner[prop] = cValue;
            if ( odesc.get instanceof Function ) {
                prevGetter = odesc.get;
            }
            if ( odesc.set instanceof Function ) {
                prevSetter = odesc.set;
            }
        }
        try {
            Object.defineProperty(owner, prop, {
                configurable,
                get() {
                    if ( prevGetter !== undefined ) {
                        prevGetter();
                    }
                    return handler.getter(); // cValue
                },
                set(a) {
                    if ( prevSetter !== undefined ) {
                        prevSetter(a);
                    }
                    handler.setter(a);
                }
            });
        } catch(ex) {
        }
    };
    const trapChain = function(owner, chain) {
        const pos = chain.indexOf('.');
        if ( pos === -1 ) {
            trapProp(owner, chain, false, {
                v: undefined,
                init: function(v) {
                    if ( mustAbort(v) ) { return false; }
                    this.v = v;
                    return true;
                },
                getter: function() {
                    return document.currentScript === thisScript
                        ? this.v
                        : cValue;
                },
                setter: function(a) {
                    if ( mustAbort(a) === false ) { return; }
                    cValue = a;
                }
            });
            return;
        }
        const prop = chain.slice(0, pos);
        const v = owner[prop];
        chain = chain.slice(pos + 1);
        if ( v instanceof Object || typeof v === 'object' && v !== null ) {
            trapChain(v, chain);
            return;
        }
        trapProp(owner, prop, true, {
            v: undefined,
            init: function(v) {
                this.v = v;
                return true;
            },
            getter: function() {
                return this.v;
            },
            setter: function(a) {
                this.v = a;
                if ( a instanceof Object ) {
                    trapChain(a, chain);
                }
            }
        });
    };
    trapChain(window, chain);
})();

/// no-setInterval-if.js
/// alias nosiif.js
(function() {
    let needle = '{{1}}';
    const needleNot = needle.charAt(0) === '!';
    if ( needleNot ) { needle = needle.slice(1); }
    let delay = '{{2}}';
    if ( delay === '{{2}}' ) { delay = undefined; }
    let delayNot = false;
    if ( delay !== undefined ) {
        delayNot = delay.charAt(0) === '!';
        if ( delayNot ) { delay = delay.slice(1); }
        delay = parseInt(delay, 10);
    }
    if ( needle === '' || needle === '{{1}}' ) {
        needle = '';
    } else if ( needle.startsWith('/') && needle.endsWith('/') ) {
        needle = needle.slice(1,-1);
    } else {
        needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    const log = needleNot === false && needle === '' && delay === undefined
        ? console.log
        : undefined;
    const reNeedle = new RegExp(needle);
    window.setInterval = new Proxy(window.setInterval, {
        apply: function(target, thisArg, args) {
            const a = String(args[0]);
            const b = args[1];
            if ( log !== undefined ) {
                log('uBO: setInterval("%s", %s)', a, b);
            } else {
                let defuse;
                if ( needle !== '' ) {
                    defuse = reNeedle.test(a) !== needleNot;
                }
                if ( defuse !== false && delay !== undefined ) {
                    defuse = (b === delay || isNaN(b) && isNaN(delay) ) !== delayNot;
                }
                if ( defuse ) {
                    args[0] = function(){};
                }
            }
            return target.apply(thisArg, args);
        }
    });
})();

/// no-setTimeout-if.js
/// alias nostif.js
/// alias setTimeout-defuser.js
(function() {
    let needle = '{{1}}';
    const needleNot = needle.charAt(0) === '!';
    if ( needleNot ) { needle = needle.slice(1); }
    let delay = '{{2}}';
    if ( delay === '{{2}}' ) { delay = undefined; }
    let delayNot = false;
    if ( delay !== undefined ) {
        delayNot = delay.charAt(0) === '!';
        if ( delayNot ) { delay = delay.slice(1); }
        delay = parseInt(delay, 10);
    }
    if ( needle === '' || needle === '{{1}}' ) {
        needle = '';
    } else if ( needle.startsWith('/') && needle.endsWith('/') ) {
        needle = needle.slice(1,-1);
    } else {
        needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    const log = needleNot === false && needle === '' && delay === undefined
        ? console.log
        : undefined;
    const reNeedle = new RegExp(needle);
    window.setTimeout = new Proxy(window.setTimeout, {
        apply: function(target, thisArg, args) {
            const a = String(args[0]);
            const b = args[1];
            if ( log !== undefined ) {
                log('uBO: setTimeout("%s", %s)', a, b);
            } else {
                let defuse;
                if ( needle !== '' ) {
                    defuse = reNeedle.test(a) !== needleNot;
                }
                if ( defuse !== false && delay !== undefined ) {
                    defuse = (b === delay || isNaN(b) && isNaN(delay) ) !== delayNot;
                }
                if ( defuse ) {
                    args[0] = function(){};
                }
            }
            return target.apply(thisArg, args);
        }
    });
})();

/// webrtc-if.js
(function() {
    let good = '{{1}}';
    if ( good.startsWith('/') && good.endsWith('/') ) {
        good = good.slice(1, -1);
    } else {
        good = good.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    let reGood;
    try {
        reGood = new RegExp(good);
    } catch(ex) {
        return;
    }
    const rtcName = window.RTCPeerConnection
        ? 'RTCPeerConnection'
        : (window.webkitRTCPeerConnection ? 'webkitRTCPeerConnection' : '');
    if ( rtcName === '' ) { return; }
    const log = console.log.bind(console);
    const neuteredPeerConnections = new WeakSet();
    const isGoodConfig = function(instance, config) {
        if ( neuteredPeerConnections.has(instance) ) { return false; }
        if ( config instanceof Object === false ) { return true; }
        if ( Array.isArray(config.iceServers) === false ) { return true; }
        for ( const server of config.iceServers ) {
            const urls = typeof server.urls === 'string'
                ? [ server.urls ]
                : server.urls;
            if ( Array.isArray(urls) ) {
                for ( const url of urls ) {
                    if ( reGood.test(url) ) { return true; }
                }
            }
            if ( typeof server.username === 'string' ) {
                if ( reGood.test(server.username) ) { return true; }
            }
            if ( typeof server.credential === 'string' ) {
                if ( reGood.test(server.credential) ) { return true; }
            }
        }
        neuteredPeerConnections.add(instance);
        return false;
    };
    const peerConnectionCtor = window[rtcName];
    const peerConnectionProto = peerConnectionCtor.prototype;
    peerConnectionProto.createDataChannel =
        new Proxy(peerConnectionProto.createDataChannel, {
            apply: function(target, thisArg, args) {
                if ( isGoodConfig(target, args[1]) === false ) {
                    log('uBO:', args[1]);
                    return Reflect.apply(target, thisArg, args.slice(0, 1));
                }
                return Reflect.apply(target, thisArg, args);
            },
        });
    window[rtcName] =
        new Proxy(peerConnectionCtor, {
            construct: function(target, args) {
                if ( isGoodConfig(target, args[0]) === false ) {
                    log('uBO:', args[0]);
                    return Reflect.construct(target);
                }
                return Reflect.construct(target, args);
            }
        });
})();

/// no-xhr-if.js
(function() {
    const xhrInstances = new WeakMap();
    let arg1 = '{{1}}';
    if ( arg1 === '{{1}}' ) { arg1 = ''; }
    const needles = [];
    for ( const condition of arg1.split(/\s+/) ) {
        if ( condition === '' ) { continue; }
        const pos = condition.indexOf(':');
        let key, value;
        if ( pos !== -1 ) {
            key = condition.slice(0, pos);
            value = condition.slice(pos + 1);
        } else {
            key = 'url';
            value = condition;
        }
        if ( value === '' ) {
            value = '^';
        } else if ( value.startsWith('/') && value.endsWith('/') ) {
            value = value.slice(1, -1);
        } else {
            value = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        needles.push({ key, re: new RegExp(value) });
    }
    const log = needles.length === 0 ? console.log.bind(console) : undefined;
    self.XMLHttpRequest = class extends self.XMLHttpRequest {
        open(...args) {
            if ( log !== undefined ) {
                log(`uBO: xhr.open(${args.join(', ')})`);
            } else {
                const argNames = [ 'method', 'url' ];
                const haystack = new Map();
                for ( let i = 0; i < args.length && i < argNames.length; i++  ) {
                    haystack.set(argNames[i], args[i]);
                }
                if ( haystack.size !== 0 ) {
                    let matches = true;
                    for ( const { key, re } of needles ) {
                        matches = re.test(haystack.get(key) || '');
                        if ( matches === false ) { break; }
                    }
                    if ( matches ) {
                        xhrInstances.set(this, haystack);
                    }
                }
            }
            return super.open(...args);
        }
        send(...args) {
            const haystack = xhrInstances.get(this);
            if ( haystack === undefined ) {
                return super.send(...args);
            }
            Object.defineProperties(this, {
                readyState: { value: 4, writable: false },
                response: { value: '', writable: false },
                responseText: { value: '', writable: false },
                responseURL: { value: haystack.get('url'), writable: false },
                responseXML: { value: '', writable: false },
                status: { value: 200, writable: false },
                statusText: { value: 'OK', writable: false },
            });
            if ( this.onreadystatechange !== null ) {
                setTimeout(( ) => {
                    const ev = new Event('readystatechange');
                    this.onreadystatechange.call(this, ev);
                }, 1);
            }
            if ( this.onload !== null ) {
                setTimeout(( ) => {
                    const ev = new Event('load');
                    this.onload.call(this, ev);
                }, 1);
            }
        }
    };
})();

// https://github.com/uBlockOrigin/uAssets/issues/10323#issuecomment-992312847
// https://github.com/AdguardTeam/Scriptlets/issues/158
/// window-close-if.js
(function() {
    const arg1 = '{{1}}';
    let reStr;
    if ( arg1 === '{{1}}' || arg1 === '' ) {
        reStr = '^';
    } else if ( arg1.startsWith('/') && arg1.endsWith('/') ) {
        reStr = arg1.slice(1, -1);
    } else {
        reStr = arg1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    try {
        const re = new RegExp(reStr);
        if ( re.test(`${window.location.pathname}${window.location.search}`) ) {
            window.close();
        }
    } catch(ex) {
        console.log(ex);
    }
})();

// https://github.com/gorhill/uBlock/issues/1228
/// window.name-defuser
(function() {
    if ( window === window.top ) {
        window.name = '';
    }
})();

// Experimental: Generic nuisance overlay buster.
// if this works well and proves to be useful, this may end up
// as a stock tool in uBO's popup panel.
/// overlay-buster.js
(function() {
    if ( window !== window.top ) {
        return;
    }
    var tstart;
    var ttl = 30000;
    var delay = 0;
    var delayStep = 50;
    var buster = function() {
        var docEl = document.documentElement,
            bodyEl = document.body,
            vw = Math.min(docEl.clientWidth, window.innerWidth),
            vh = Math.min(docEl.clientHeight, window.innerHeight),
            tol = Math.min(vw, vh) * 0.05,
            el = document.elementFromPoint(vw/2, vh/2),
            style, rect;
        for (;;) {
            if ( el === null || el.parentNode === null || el === bodyEl ) {
                break;
            }
            style = window.getComputedStyle(el);
            if ( parseInt(style.zIndex, 10) >= 1000 || style.position === 'fixed' ) {
                rect = el.getBoundingClientRect();
                if ( rect.left <= tol && rect.top <= tol && (vw - rect.right) <= tol && (vh - rect.bottom) < tol ) {
                    el.parentNode.removeChild(el);
                    tstart = Date.now();
                    el = document.elementFromPoint(vw/2, vh/2);
                    bodyEl.style.setProperty('overflow', 'auto', 'important');
                    docEl.style.setProperty('overflow', 'auto', 'important');
                    continue;
                }
            }
            el = el.parentNode;
        }
        if ( (Date.now() - tstart) < ttl ) {
            delay = Math.min(delay + delayStep, 1000);
            setTimeout(buster, delay);
        }
    };
    var domReady = function(ev) {
        if ( ev ) {
            document.removeEventListener(ev.type, domReady);
        }
        tstart = Date.now();
        setTimeout(buster, delay);
    };
    if ( document.readyState === 'loading' ) {
        document.addEventListener('DOMContentLoaded', domReady);
    } else {
        domReady();
    }
})();

// https://github.com/uBlockOrigin/uAssets/issues/8
/// alert-buster.js
(function() {
    window.alert = function(a) {
        console.info(a);
    };
})();

// https://github.com/uBlockOrigin/uAssets/issues/58
/// gpt-defuser.js
(function() {
    const noopfn = function() {
    };
    let props = '_resetGPT resetGPT resetAndLoadGPTRecovery _resetAndLoadGPTRecovery setupGPT setupGPTuo';
    props = props.split(/\s+/);
    while ( props.length ) {
        var prop = props.pop();
        if ( typeof window[prop] === 'function' ) {
            window[prop] = noopfn;
        } else {
            Object.defineProperty(window, prop, {
                get: function() { return noopfn; },
                set: noopfn
            });
        }
    }
})();

// Prevent web pages from using RTCPeerConnection(), and report attempts in console.
/// nowebrtc.js
(function() {
    var rtcName = window.RTCPeerConnection ? 'RTCPeerConnection' : (
        window.webkitRTCPeerConnection ? 'webkitRTCPeerConnection' : ''
    );
    if ( rtcName === '' ) { return; }
    var log = console.log.bind(console);
    var pc = function(cfg) {
        log('Document tried to create an RTCPeerConnection: %o', cfg);
    };
    const noop = function() {
    };
    pc.prototype = {
        close: noop,
        createDataChannel: noop,
        createOffer: noop,
        setRemoteDescription: noop,
        toString: function() {
            return '[object RTCPeerConnection]';
        }
    };
    var z = window[rtcName];
    window[rtcName] = pc.bind(window);
    if ( z.prototype ) {
        z.prototype.createDataChannel = function() {
            return {
                close: function() {},
                send: function() {}
            };
        }.bind(null);
    }
})();

// https://github.com/uBlockOrigin/uAssets/issues/88
/// golem.de.js
(function() {
    const rael = window.addEventListener;
    window.addEventListener = function(a, b) {
        rael(...arguments);
        let haystack;
        try {
            haystack = b.toString();
        } catch(ex) {
        }
        if (
            typeof haystack === 'string' &&
            /^\s*function\s*\(\)\s*\{\s*window\.clearTimeout\(r\)\s*\}\s*$/.test(haystack)
        ) {
            b();
        }
    }.bind(window);
})();

// https://forums.lanik.us/viewtopic.php?f=64&t=32278
// https://www.reddit.com/r/chrome/comments/58eix6/ublock_origin_not_working_on_certain_sites/
/// upmanager-defuser.js
(function() {
    var onerror = window.onerror;
    window.onerror = function(msg, source, lineno, colno, error) {
        if ( typeof msg === 'string' && msg.indexOf('upManager') !== -1 ) {
            return true;
        }
        if ( onerror instanceof Function ) {
            onerror.call(window, msg, source, lineno, colno, error);
        }
    };
    Object.defineProperty(window, 'upManager', { value: function() {} });
})();

// https://github.com/uBlockOrigin/uAssets/issues/110
/// smartadserver.com.js
(function() {
    Object.defineProperties(window, {
        SmartAdObject: { value: function(){} },
        SmartAdServerAjax: { value: function(){} },
        smartAd: { value: { LoadAds: function() {}, Register: function() {} } }
    });
})();

// https://github.com/reek/anti-adblock-killer/issues/3774#issuecomment-348536138
// https://github.com/uBlockOrigin/uAssets/issues/883
/// adfly-defuser.js
(function() {
    // Based on AdsBypasser
    // License:
    //   https://github.com/adsbypasser/adsbypasser/blob/master/LICENSE
    var isDigit = /^\d$/;
    var handler = function(encodedURL) {
        var var1 = "", var2 = "", i;
        for (i = 0; i < encodedURL.length; i++) {
            if (i % 2 === 0) {
                var1 = var1 + encodedURL.charAt(i);
            } else {
                var2 = encodedURL.charAt(i) + var2;
            }
        }
        var data = (var1 + var2).split("");
        for (i = 0; i < data.length; i++) {
            if (isDigit.test(data[i])) {
                for (var ii = i + 1; ii < data.length; ii++) {
                    if (isDigit.test(data[ii])) {
                        var temp = parseInt(data[i],10) ^ parseInt(data[ii],10);
                        if (temp < 10) {
                            data[i] = temp.toString();
                        }
                        i = ii;
                        break;
                    }
                }
            }
        }
        data = data.join("");
        var decodedURL = window.atob(data).slice(16, -16);
        window.stop();
        window.onbeforeunload = null;
        window.location.href = decodedURL;
    };
    try {
        var val;
        var flag = true;
        window.Object.defineProperty(window, "ysmm", {
            configurable: false,
            set: function(value) {
                if (flag) {
                    flag = false;
                    try {
                        if (typeof value === "string") {
                            handler(value);
                        }
                    } catch (err) { }
                }
                val = value;
            },
            get: function() {
                return val;
            }
        });
    } catch (err) {
        window.console.error("Failed to set up Adfly bypasser!");
    }
})();

// https://github.com/uBlockOrigin/uAssets/issues/913
/// disable-newtab-links.js
(function() {
    document.addEventListener('click', function(ev) {
        var target = ev.target;
        while ( target !== null ) {
            if ( target.localName === 'a' && target.hasAttribute('target') ) {
                ev.stopPropagation();
                ev.preventDefault();
                break;
            }
            target = target.parentNode;
        }
    });
})();

/// damoh-defuser.js
(function() {
    const handled = new WeakSet();
    let asyncTimer;
    const cleanVideo = function() {
        asyncTimer = undefined;
        const v = document.querySelector('video');
        if ( v === null ) { return; }
        if ( handled.has(v) ) { return; }
        handled.add(v);
        v.pause();
        v.controls = true;
        let el = v.querySelector('meta[itemprop="contentURL"][content]');
        if ( el === null ) { return; }
        v.src = el.getAttribute('content');
        el = v.querySelector('meta[itemprop="thumbnailUrl"][content]');
        if ( el !== null ) { v.poster = el.getAttribute('content'); }
    };
    const cleanVideoAsync = function() {
        if ( asyncTimer !== undefined ) { return; }
        asyncTimer = window.requestAnimationFrame(cleanVideo);
    };
    const observer = new MutationObserver(cleanVideoAsync);
    observer.observe(document, { childList: true, subtree: true });
})();

/// twitch-videoad.js
// https://github.com/uBlockOrigin/uAssets/issues/5184
// https://github.com/pixeltris/TwitchAdSolutions/commit/6be4c5313035
// https://github.com/pixeltris/TwitchAdSolutions/commit/3d2883ea9e3a
// https://github.com/pixeltris/TwitchAdSolutions/commit/7233b5fd2284
// https://github.com/pixeltris/TwitchAdSolutions/commit/aad8946dab2b
(function() {
    if ( /(^|\.)twitch\.tv$/.test(document.location.hostname) === false ) { return; }
    window.fetch = new Proxy(window.fetch, {
        apply: function(target, thisArg, args) {
            const [ url, init ] = args;
            if (
                typeof url === 'string' &&
                url.includes('gql') &&
                init instanceof Object &&
                init.headers instanceof Object &&
                typeof init.body === 'string' &&
                init.body.includes('PlaybackAccessToken') &&
                init.body.includes('"isVod":true') === false
            ) {
                const { headers } = init;
                if ( typeof headers['X-Device-Id'] === 'string' ) {
                    headers['X-Device-Id'] = 'twitch-web-wall-mason';
                }
                if ( typeof headers['Device-ID'] === 'string' ) {
                    headers['Device-ID'] = 'twitch-web-wall-mason';
                }
            }
            return Reflect.apply(target, thisArg, args);
        }
    });
})();

// https://github.com/NanoAdblocker/NanoFilters/issues/149
/// cookie-remover.js
(function() {
    const needle = '{{1}}';
    let reName = /./;
    if ( /^\/.+\/$/.test(needle) ) {
        reName = new RegExp(needle.slice(1,-1));
    } else if ( needle !== '' && needle !== '{{1}}' ) {
        reName = new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
    }
    const removeCookie = function() {
        document.cookie.split(';').forEach(cookieStr => {
            let pos = cookieStr.indexOf('=');
            if ( pos === -1 ) { return; }
            let cookieName = cookieStr.slice(0, pos).trim();
            if ( !reName.test(cookieName) ) { return; }
            let part1 = cookieName + '=';
            let part2a = '; domain=' + document.location.hostname;
            let part2b = '; domain=.' + document.location.hostname;
            let part2c, part2d;
            let domain = document.domain;
            if ( domain ) {
                if ( domain !== document.location.hostname ) {
                    part2c = '; domain=.' + domain;
                }
                if ( domain.startsWith('www.') ) {
                    part2d = '; domain=' + domain.replace('www', '');
                }
            }
            let part3 = '; path=/';
            let part4 = '; Max-Age=-1000; expires=Thu, 01 Jan 1970 00:00:00 GMT';
            document.cookie = part1 + part4;
            document.cookie = part1 + part2a + part4;
            document.cookie = part1 + part2b + part4;
            document.cookie = part1 + part3 + part4;
            document.cookie = part1 + part2a + part3 + part4;
            document.cookie = part1 + part2b + part3 + part4;
            if ( part2c !== undefined ) {
                document.cookie = part1 + part2c + part3 + part4;
            }
            if ( part2d !== undefined ) {
                document.cookie = part1 + part2d + part3 + part4;
            }
        });
    };
    removeCookie();
    window.addEventListener('beforeunload', removeCookie);
})();

// These lines below are skipped by the resource parser.
// <<<< end of private namespace
})();


.vscrollable {
direction: ltr;
flex-grow: 1;
font-size: small;
overflow-x: hidden;
overflow-y: auto;
}

keep keep keep replace keep keep keep keep

@charset "UTF-8";
/* https://protocol.mozilla.org/assets/docs/css/protocol.css */
@font-face {
    font-family: Inter;
    font-style: normal;
    font-weight: normal;
    src: url('fonts/Inter/Inter-Regular.woff2') format('woff2');
}
@font-face {
    font-family: Inter;
    font-style: normal;
    font-weight: 600;
    src: url('fonts/Inter/Inter-SemiBold.woff2') format('woff2');
}
@font-face {
    font-family: Metropolis;
    font-style: normal;
    font-weight: normal;
    src: url('fonts/Metropolis/Metropolis-Regular.woff2') format('woff2');
}
@font-face {
    font-family: Metropolis;
    font-style: normal;
    font-weight: 600;
    src: url('fonts/Metropolis/Metropolis-SemiBold.woff2') format('woff2');
}

/**
    Common uBO spacing.
    Ref: https://github.com/uBlockOrigin/uBlock-issues/issues/1005
*/
:root {
    --default-gap-xlarge: 32px;
    --default-gap-large: 24px;
    --default-gap: 16px;
    --default-gap-small: 12px;
    --default-gap-xsmall: 8px;
    --default-gap-xxsmall: 4px;
    }

/* Common uBO styles */
body {
    background-color: var(--surface-1);
    border: 0;
    box-sizing: border-box;
    color: var(--ink-1);
        fill: var(--ink-1);
    font-family: var(--font-family);
    font-size: var(--font-size);
    line-height: 1.5;
    margin: 0;
    padding: 0;
    }
a {
    color: var(--link-ink);
        fill: var(--link-ink);
    }
a:hover {
    color: var(--link-hover-ink);
        fill: var(--link-hover-ink);
    }
code, .code {
    background-color: var(--surface-2);
    font-family: monospace;
    font-size: smaller;
    padding: 2px 4px;
    }
hr {
    border: 0;
    border-top: 1px solid var(--surface-2);
    margin: 1em 0;
    }
textarea {
    font-size: 90%;
    }
button {
    align-items: center;
    appearance: none;
    -moz-appearance: none;
    -webkit-appearance: none;
    border: 0;
    border-radius: var(--button-border-radius);
    background-color: var(--button-surface);
    color: var(--button-ink);
    display: inline-flex;
    fill: var(--button-ink);
    font-size: 14px;
    justify-content: center;
    min-height: 36px;
    padding: 0 var(--font-size);
    position: relative;
    vertical-align: middle;
    }
button.vflex {
    height: 100%;
    min-height: unset;
    padding-bottom: 0;
    padding-top: 0;
    }
button > .hover {
    background-color: var(--elevation-up-surface);
    border-radius: var(--button-border-radius);
    height: 100%;
    left: 0;
    opacity: 0;
    pointer-events: none;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 100;
    }
button:not(.disabled):not([disabled]):hover > .hover {
    opacity: var(--elevation-up1-opacity);
    }
button.notext:not(.disabled):not([disabled]):hover > .hover {
    opacity: var(--elevation-up2-opacity);
    }
button.active {
    }
button.disabled,
button[disabled] {
    background-color: var(--button-disabled-surface);
    color: var(--button-ink);
    fill: var(--button-ink);
    filter: var(--button-disabled-filter);
    pointer-events: none;
    }
button.preferred:not(.disabled):not([disabled]) {
    background-color: var(--button-preferred-surface);
    color: var(--button-preferred-ink);
        fill: var(--button-preferred-ink);
    }
button.preferred:not(.disabled):not([disabled]):hover > .hover {
    background-color: var(--elevation-down-surface);
    opacity: var(--elevation-down1-opacity);
    }
button.iconified.notext {
    background-color: transparent;
    }
button.iconified > .fa-icon {
    font-size: 120%;
    padding-left: 0;
    padding-right: 0;
    }
button.iconified > .fa-icon + [data-i18n] {
    padding-right: 0;
    padding-left: 0.4em;
    }
body[dir="rtl"] button.iconified > .fa-icon + [data-i18n] {
    padding-right: 0.4em;
    padding-left: 0;
    }
label {
    align-items: center;
    display: inline-flex;
    position: relative;
    }
section.notice {
    background-color: var(--notice-surface);
    box-shadow: var(--notice-surface-shadow);
    color: var(--notice-ink);
    }
:root:not(.classic) section.notice a {
    color: var(--surface-2);
    }

/**
    Checkbox design borrowed from:
    - https://material.io/components/selection-controls
    Motivation:
    - To comply with design suggestions to make uBO comply with
      Firefox Preview design guidelines.
    - To have a single checkbox design across all platforms.
*/
.checkbox {
    --margin-end: calc(var(--font-size) * 0.75);
    box-sizing: border-box;
    display: inline-flex;
    flex-shrink: 0;
    height: var(--checkbox-size);
    margin: 0;
    margin-inline-end: var(--margin-end);
    -webkit-margin-end: var(--margin-end);
    position: relative;
    width: var(--checkbox-size);
    }
.checkbox > input[type="checkbox"] {
    box-sizing: border-box;
    height: 100%;
    margin: 0;
    min-width: var(--checkbox-size);
    opacity: 0;
    position: absolute;
    width: 100%;
    }
.checkbox > input[type="checkbox"] + svg {
    background-color: transparent;
    border: 2px solid var(--checkbox-ink);
    border-radius: 2px;
    box-sizing: border-box;
    fill: none;
    height: 100%;
    pointer-events: none;
    position: absolute;
    stroke: none;
    stroke-width: 3.12px;
    width: 100%;
    }
.checkbox > input[type="checkbox"]:checked + svg {
    background-color: var(--checkbox-checked-ink);
    border-color: var(--checkbox-checked-ink);
    stroke: var(--surface-1);
    }
.checkbox[disabled],
.checkbox[disabled] ~ span {
    filter: var(--checkbox-disabled-filter);
    }

select {
    padding: 2px;
    }

.hidden {
    display: none;
    height: 0;
    visibility: hidden;
    width: 0;
    }
.subtil {
    color: var(--subtil-ink);
    cursor: default;
    opacity: 66%;
    }
.fieldset {
    margin: var(--font-size);
    }
.fieldset-header {
    color: var(--fieldset-header-ink);
    font-size: 14px;
    font-weight: 600;
    letter-spacing: 0.5px;
    }
.ul {
    margin: 1em 0;
    }
.li {
    align-items: center;
    display: flex;
    margin: calc(var(--font-size) * 0.75) 0;
    }
.liul {
    margin: 0.5em 0;
    margin-inline-start: 2em;
    -webkit-margin-start: 2em;
    }
@media (max-width: 640px) {
    button.iconified > .fa-icon {
        font-size: 1.2rem;
        padding: 0;
        }
    button.iconified > [data-i18n] {
        display: none;
        }
    }

.logo {
    align-items: center;
    display: inline-flex;
    padding: 0 0.5em;
    width: 1.25em;
    }
.logo > img {
    width: 100%;
    }

/* high dpi devices */
:root.hidpi button {
    font-family: Metropolis, sans-serif;
    font-weight: 600;
    letter-spacing: 0.5px;
    }
:root.hidpi .fieldset-header {
    font-family: Metropolis, sans-serif;
    }

/* touch-screen devices */
:root.mobile label {
    flex-grow: 1
    }


/*******************************************************************************

    uBlock Origin - a browser extension to block requests.
    Copyright (C) 2017-present Raymond Hill

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see {http://www.gnu.org/licenses/}.

    Home: https://github.com/gorhill/uBlock
*/

/* globals WebAssembly */

'use strict';

/*******************************************************************************

  The original prototype was to develop an idea I had about using jump indices
  in a TypedArray for quickly matching hostnames (or more generally strings)[1].
  Once I had a working, un-optimized prototype, I realized I had ended up
  with something formally named a "trie": <https://en.wikipedia.org/wiki/Trie>,
  hence the name. I have no idea whether the implementation here or one
  resembling it has been done elsewhere.

  "HN" in HNTrieContainer stands for "HostName", because the trie is
  specialized to deal with matching hostnames -- which is a bit more
  complicated than matching plain strings.

  For example, `www.abc.com` is deemed matching `abc.com`, because the former
  is a subdomain of the latter. The opposite is of course not true.

  The resulting read-only tries created as a result of using HNTrieContainer
  are simply just typed arrays filled with integers. The matching algorithm is
  just a matter of reading/comparing these integers, and further using them as
  indices in the array as a way to move around in the trie.

  [1] To solve <https://github.com/gorhill/uBlock/issues/3193>

  Since this trie is specialized for matching hostnames, the stored
  strings are reversed internally, because of hostname comparison logic:

  Correct matching:
    index      0123456
               abc.com
                     |
           www.abc.com
    index  01234567890

  Incorrect matching (typically used for plain strings):
    index  0123456
           abc.com
           |
           www.abc.com
    index  01234567890

  ------------------------------------------------------------------------------

  1st iteration:
    - https://github.com/gorhill/uBlock/blob/ff58107dac3a32607f8113e39ed5015584506813/src/js/hntrie.js
    - Suitable for small to medium set of hostnames
    - One buffer per trie

  2nd iteration: goal was to make matches() method wasm-able
    - https://github.com/gorhill/uBlock/blob/c3b0fd31f64bd7ffecdd282fb1208fe07aac3eb0/src/js/hntrie.js
    - Suitable for small to medium set of hostnames
    - Distinct tries all share same buffer:
      - Reduced memory footprint
        - https://stackoverflow.com/questions/45803829/memory-overhead-of-typed-arrays-vs-strings/45808835#45808835
      - Reusing needle character lookups for all tries
        - This significantly reduce the number of String.charCodeAt() calls
    - Slightly improved creation time

  This is the 3rd iteration: goal was to make add() method wasm-able and
  further improve memory/CPU efficiency.

  This 3rd iteration has the following new traits:
    - Suitable for small to large set of hostnames
    - Support multiple trie containers (instanciable)
    - Designed to hold large number of hostnames
    - Hostnames can be added at any time (instead of all at once)
      - This means pre-sorting is no longer a requirement
    - The trie is always compact
      - There is no longer a need for a `vacuum` method
      - This makes the add() method wasm-able
    - It can return the exact hostname which caused the match
    - serializable/unserializable available for fast loading
    - Distinct trie reference support the iteration protocol, thus allowing
      to extract all the hostnames in the trie

  Its primary purpose is to replace the use of Set() as a mean to hold
  large number of hostnames (ex. FilterHostnameDict in static filtering
  engine).

  A HNTrieContainer is mostly a large buffer in which distinct but related
  tries are stored. The memory layout of the buffer is as follow:

    0-254: needle being processed
      255: length of needle
  256-259: offset to start of trie data section (=> trie0)
  260-263: offset to end of trie data section (=> trie1)
  264-267: offset to start of character data section  (=> char0)
  268-271: offset to end of character data section (=> char1)
      272: start of trie data section

*/

const PAGE_SIZE   = 65536;
                                            // i32 /  i8
const TRIE0_SLOT  = 256 >>> 2;              //  64 / 256
const TRIE1_SLOT  = TRIE0_SLOT + 1;         //  65 / 260
const CHAR0_SLOT  = TRIE0_SLOT + 2;         //  66 / 264
const CHAR1_SLOT  = TRIE0_SLOT + 3;         //  67 / 268
const TRIE0_START = TRIE0_SLOT + 4 << 2;    //       272

const roundToPageSize = v => (v + PAGE_SIZE-1) & ~(PAGE_SIZE-1);

class HNTrieContainer {

    constructor() {
        const len = PAGE_SIZE * 2;
        this.buf = new Uint8Array(len);
        this.buf32 = new Uint32Array(this.buf.buffer);
        this.needle = '';
        this.buf32[TRIE0_SLOT] = TRIE0_START;
        this.buf32[TRIE1_SLOT] = this.buf32[TRIE0_SLOT];
        this.buf32[CHAR0_SLOT] = len >>> 1;
        this.buf32[CHAR1_SLOT] = this.buf32[CHAR0_SLOT];
        this.wasmMemory = null;

        this.lastStored = '';
        this.lastStoredLen = this.lastStoredIndex = 0;
    }

    //--------------------------------------------------------------------------
    // Public methods
    //--------------------------------------------------------------------------

    reset(details) {
        if (
            details instanceof Object &&
            typeof details.byteLength === 'number' &&
            typeof details.char0 === 'number'
        ) {
            if ( details.byteLength > this.buf.byteLength ) {
                this.reallocateBuf(details.byteLength);
            }
            this.buf32[CHAR0_SLOT] = details.char0;
        }
        this.buf32[TRIE1_SLOT] = this.buf32[TRIE0_SLOT];
        this.buf32[CHAR1_SLOT] = this.buf32[CHAR0_SLOT];

        this.lastStored = '';
        this.lastStoredLen = this.lastStoredIndex = 0;
    }

    setNeedle(needle) {
        if ( needle !== this.needle ) {
            const buf = this.buf;
            let i = needle.length;
            if ( i > 255 ) { i = 255; }
            buf[255] = i;
            while ( i-- ) {
                buf[i] = needle.charCodeAt(i);
            }
            this.needle = needle;
        }
        return this;
    }

    matchesJS(iroot) {
        const buf32 = this.buf32;
        const buf8 = this.buf;
        const char0 = buf32[CHAR0_SLOT];
        let ineedle = buf8[255];
        let icell = buf32[iroot+0];
        if ( icell === 0 ) { return -1; }
        let c = 0, v = 0, i0 = 0, n = 0;
        for (;;) {
            if ( ineedle === 0 ) { return -1; }
            ineedle -= 1;
            c = buf8[ineedle];
            // find first segment with a first-character match
            for (;;) {
                v = buf32[icell+2];
                i0 = char0 + (v >>> 8);
                if ( buf8[i0] === c ) { break; }
                icell = buf32[icell+0];
                if ( icell === 0 ) { return -1; }
            }
            // all characters in segment must match
            n = v & 0x7F;
            if ( n > 1 ) {
                n -= 1;
                if ( n > ineedle ) { return -1; }
                i0 += 1;
                const i1 = i0 + n;
                do {
                    ineedle -= 1;
                    if ( buf8[i0] !== buf8[ineedle] ) { return -1; }
                    i0 += 1;
                } while ( i0 < i1 );
            }
            // boundary at end of segment?
            if ( (v & 0x80) !== 0 ) {
                if ( ineedle === 0 || buf8[ineedle-1] === 0x2E /* '.' */ ) {
                    return ineedle;
                }
            }
            // next segment
            icell = buf32[icell+1];
            if ( icell === 0 ) { break; }
        }
        return -1;
    }

    createTrie() {
        // grow buffer if needed
        if ( (this.buf32[CHAR0_SLOT] - this.buf32[TRIE1_SLOT]) < 12 ) {
            this.growBuf(12, 0);
        }
        const iroot = this.buf32[TRIE1_SLOT] >>> 2;
        this.buf32[TRIE1_SLOT] += 12;
        this.buf32[iroot+0] = 0;
        this.buf32[iroot+1] = 0;
        this.buf32[iroot+2] = 0;
        return iroot;
    }

    createTrieFromIterable(hostnames) {
        const itrie = this.createTrie();
        for ( const hn of hostnames ) {
            if ( hn === '' ) { continue; }
            this.setNeedle(hn).add(itrie);
        }
        return itrie;
    }

    createTrieFromStoredDomainOpt(i, n) {
        const itrie = this.createTrie();
        const jend = i + n;
        let j = i, offset = 0, k = 0, c = 0;
        while ( j !== jend ) {
            offset = this.buf32[CHAR0_SLOT]; // Important
            k = 0;
            for (;;) {
                if ( j === jend ) { break; }
                c = this.buf[offset+j];
                j += 1;
                if ( c === 0x7C /* '|' */ ) { break; }
                if ( k === 255 ) { continue; }
                this.buf[k] = c;
                k += 1;
            }
            if ( k !== 0 ) {
                this.buf[255] = k;
                this.add(itrie);
            }
        }
        this.needle = '';   // Important
        this.buf[255] = 0;  // Important
        return itrie;
    }

    dumpTrie(iroot) {
        let hostnames = Array.from(this.trieIterator(iroot));
        if ( String.prototype.padStart instanceof Function ) {
            const maxlen = Math.min(
                hostnames.reduce((maxlen, hn) => Math.max(maxlen, hn.length), 0),
                64
            );
            hostnames = hostnames.map(hn => hn.padStart(maxlen));
        }
        for ( const hn of hostnames ) {
            console.log(hn);
        }
    }

    trieIterator(iroot) {
        return {
            value: undefined,
            done: false,
            next() {
                if ( this.icell === 0 ) {
                    if ( this.forks.length === 0 ) {
                        this.value = undefined;
                        this.done = true;
                        return this;
                    }
                    this.charPtr = this.forks.pop();
                    this.icell = this.forks.pop();
                }
                for (;;) {
                    const idown = this.container.buf32[this.icell+0];
                    if ( idown !== 0 ) {
                        this.forks.push(idown, this.charPtr);
                    }
                    const v = this.container.buf32[this.icell+2];
                    let i0 = this.container.buf32[CHAR0_SLOT] + (v >>> 8);
                    const i1 = i0 + (v & 0x7F);
                    while ( i0 < i1 ) {
                        this.charPtr -= 1;
                        this.charBuf[this.charPtr] = this.container.buf[i0];
                        i0 += 1;
                    }
                    this.icell = this.container.buf32[this.icell+1];
                    if ( (v & 0x80) !== 0 ) {
                        return this.toHostname();
                    }
                }
            },
            toHostname() {
                this.value = this.textDecoder.decode(
                    new Uint8Array(this.charBuf.buffer, this.charPtr)
                );
                return this;
            },
            container: this,
            icell: this.buf32[iroot],
            charBuf: new Uint8Array(256),
            charPtr: 256,
            forks: [],
            textDecoder: new TextDecoder(),
            [Symbol.iterator]() { return this; },
        };
    }

    // TODO:
    //   Rework code to add from a string already present in the character
    //   buffer, i.e. not having to go through setNeedle() when adding a new
    //   hostname to a trie. This will require much work though, and probably
    //   changing the order in which string segments are stored in the
    //   character buffer.
    addJS(iroot) {
        let lhnchar = this.buf[255];
        if ( lhnchar === 0 ) { return 0; }
        // grow buffer if needed
        if (
            (this.buf32[CHAR0_SLOT] - this.buf32[TRIE1_SLOT]) < 24 ||
            (this.buf.length - this.buf32[CHAR1_SLOT]) < 256
        ) {
            this.growBuf(24, 256);
        }
        let icell = this.buf32[iroot+0];
        // special case: first node in trie
        if ( icell === 0 ) {
            this.buf32[iroot+0] = this.addLeafCell(lhnchar);
            return 1;
        }
        //
        const char0 = this.buf32[CHAR0_SLOT];
        let isegchar, lsegchar, boundaryBit, inext;
        // find a matching cell: move down
        for (;;) {
            const v = this.buf32[icell+2];
            let isegchar0 = char0 + (v >>> 8);
            // if first character is no match, move to next descendant
            if ( this.buf[isegchar0] !== this.buf[lhnchar-1] ) {
                inext = this.buf32[icell+0];
                if ( inext === 0 ) {
                    this.buf32[icell+0] = this.addLeafCell(lhnchar);
                    return 1;
                }
                icell = inext;
                continue;
            }
            // 1st character was tested
            isegchar = 1;
            lhnchar -= 1;
            // find 1st mismatch in rest of segment
            lsegchar = v & 0x7F;
            if ( lsegchar !== 1 ) {
                for (;;) {
                    if ( isegchar === lsegchar ) { break; }
                    if ( lhnchar === 0 ) { break; }
                    if ( this.buf[isegchar0+isegchar] !== this.buf[lhnchar-1] ) { break; }
                    isegchar += 1;
                    lhnchar -= 1;
                }
            }
            boundaryBit = v & 0x80;
            // all segment characters matched
            if ( isegchar === lsegchar ) {
                // needle remainder: no
                if ( lhnchar === 0 ) {
                    // boundary: yes, already present
                    if ( boundaryBit !== 0 ) { return 0; }
                    // boundary: no, mark as boundary
                    this.buf32[icell+2] = v | 0x80;
                }
                // needle remainder: yes
                else {
                    // remainder is at label boundary? if yes, no need to add
                    // the rest since the shortest match is always reported
                    if ( boundaryBit !== 0 ) {
                        if ( this.buf[lhnchar-1] === 0x2E /* '.' */ ) { return -1; }
                    }
                    inext = this.buf32[icell+1];
                    if ( inext !== 0 ) {
                        icell = inext;
                        continue;
                    }
                    // add needle remainder
                    this.buf32[icell+1] = this.addLeafCell(lhnchar);
                }
            }
            // some segment characters matched
            else {
                // split current cell
                isegchar0 -= char0;
                this.buf32[icell+2] = isegchar0 << 8 | isegchar;
                inext = this.addCell(
                    0,
                    this.buf32[icell+1],
                    isegchar0 + isegchar << 8 | boundaryBit | lsegchar - isegchar
                );
                this.buf32[icell+1] = inext;
                // needle remainder: yes, need new cell for remaining characters
                if ( lhnchar !== 0 ) {
                    this.buf32[inext+0] = this.addLeafCell(lhnchar);
                }
                // needle remainder: no, need boundary cell
                else {
                    this.buf32[icell+2] |= 0x80;
                }
            }
            return 1;
        }
    }

    optimize() {
        this.shrinkBuf();
        return {
            byteLength: this.buf.byteLength,
            char0: this.buf32[CHAR0_SLOT],
        };
    }

    serialize(encoder) {
        if ( encoder instanceof Object ) {
            return encoder.encode(
                this.buf32.buffer,
                this.buf32[CHAR1_SLOT]
            );
        }
        return Array.from(
            new Uint32Array(
                this.buf32.buffer,
                0,
                this.buf32[CHAR1_SLOT] + 3 >>> 2
            )
        );
    }

    unserialize(selfie, decoder) {
        this.needle = '';
        const shouldDecode = typeof selfie === 'string';
        let byteLength = shouldDecode
            ? decoder.decodeSize(selfie)
            : selfie.length << 2;
        if ( byteLength === 0 ) { return false; }
        byteLength = roundToPageSize(byteLength);
        if ( this.wasmMemory !== null ) {
            const pageCountBefore = this.buf.length >>> 16;
            const pageCountAfter = byteLength >>> 16;
            if ( pageCountAfter > pageCountBefore ) {
                this.wasmMemory.grow(pageCountAfter - pageCountBefore);
                this.buf = new Uint8Array(this.wasmMemory.buffer);
                this.buf32 = new Uint32Array(this.buf.buffer);
            }
        } else if ( byteLength > this.buf.length ) {
            this.buf = new Uint8Array(byteLength);
            this.buf32 = new Uint32Array(this.buf.buffer);
        }
        if ( shouldDecode ) {
            decoder.decode(selfie, this.buf.buffer);
        } else {
            this.buf32.set(selfie);
        }
        return true;
    }

    // The following *Hostname() methods can be used to store hostname strings
    // outside the trie. This is useful to store/match hostnames which are
    // not part of a collection, and yet still benefit from storing the strings
    // into a trie container's character buffer.
    // TODO: WASM version of matchesHostname()

    storeHostname(hn) {
        let n = hn.length;
        if ( n > 255 ) {
            hn = hn.slice(-255);
            n = 255;
        }
        if ( n === this.lastStoredLen && hn === this.lastStored ) {
            return this.lastStoredIndex;
        }
        this.lastStored = hn;
        this.lastStoredLen = n;
        if ( (this.buf.length - this.buf32[CHAR1_SLOT]) < n ) {
            this.growBuf(0, n);
        }
        const offset = this.buf32[CHAR1_SLOT];
        this.buf32[CHAR1_SLOT] = offset + n;
        const buf8 = this.buf;
        for ( let i = 0; i < n; i++ ) {
            buf8[offset+i] = hn.charCodeAt(i);
        }
        return (this.lastStoredIndex = offset - this.buf32[CHAR0_SLOT]);
    }

    extractHostname(i, n) {
        const textDecoder = new TextDecoder();
        const offset = this.buf32[CHAR0_SLOT] + i;
        return textDecoder.decode(this.buf.subarray(offset, offset + n));
    }

    storeDomainOpt(s) {
        let n = s.length;
        if ( n === this.lastStoredLen && s === this.lastStored ) {
            return this.lastStoredIndex;
        }
        this.lastStored = s;
        this.lastStoredLen = n;
        if ( (this.buf.length - this.buf32[CHAR1_SLOT]) < n ) {
            this.growBuf(0, n);
        }
        const offset = this.buf32[CHAR1_SLOT];
        this.buf32[CHAR1_SLOT] = offset + n;
        const buf8 = this.buf;
        for ( let i = 0; i < n; i++ ) {
            buf8[offset+i] = s.charCodeAt(i);
        }
        return (this.lastStoredIndex = offset - this.buf32[CHAR0_SLOT]);
    }

    extractDomainOpt(i, n) {
        const textDecoder = new TextDecoder();
        const offset = this.buf32[CHAR0_SLOT] + i;
        return textDecoder.decode(this.buf.subarray(offset, offset + n));
    }

    matchesHostname(hn, i, n) {
        this.setNeedle(hn);
        const buf8 = this.buf;
        const hr = buf8[255];
        if ( n > hr ) { return false; }
        const hl = hr - n;
        const nl = this.buf32[CHAR0_SLOT] + i;
        for ( let j = 0; j < n; j++ ) {
            if ( buf8[nl+j] !== buf8[hl+j] ) { return false; }
        }
        return n === hr || hn.charCodeAt(hl-1) === 0x2E /* '.' */;
    }

    async enableWASM(wasmModuleFetcher, path) {
        if ( typeof WebAssembly === 'undefined' ) { return false; }
        if ( this.wasmMemory instanceof WebAssembly.Memory ) { return true; }
        const module = await getWasmModule(wasmModuleFetcher, path);
        if ( module instanceof WebAssembly.Module === false ) { return false; }
        const memory = new WebAssembly.Memory({ initial: 2 });
        const instance = await WebAssembly.instantiate(module, {
            imports: {
                memory,
                growBuf: this.growBuf.bind(this, 24, 256)
            }
        });
        if ( instance instanceof WebAssembly.Instance === false ) { return false; }
        this.wasmMemory = memory;
        const curPageCount = memory.buffer.byteLength >>> 16;
        const newPageCount = roundToPageSize(this.buf.byteLength) >>> 16;
        if ( newPageCount > curPageCount ) {
            memory.grow(newPageCount - curPageCount);
        }
        const buf = new Uint8Array(memory.buffer);
        buf.set(this.buf);
        this.buf = buf;
        this.buf32 = new Uint32Array(this.buf.buffer);
        this.matches = this.matchesWASM = instance.exports.matches;
        this.add = this.addWASM = instance.exports.add;
        return true;
    }

    dumpInfo() {
        return [
            `Buffer size (Uint8Array): ${this.buf32[CHAR1_SLOT].toLocaleString('en')}`,
            `WASM: ${this.wasmMemory === null ? 'disabled' : 'enabled'}`,
        ].join('\n');
    }

    //--------------------------------------------------------------------------
    // Private methods
    //--------------------------------------------------------------------------

    addCell(idown, iright, v) {
        let icell = this.buf32[TRIE1_SLOT];
        this.buf32[TRIE1_SLOT] = icell + 12;
        icell >>>= 2;
        this.buf32[icell+0] = idown;
        this.buf32[icell+1] = iright;
        this.buf32[icell+2] = v;
        return icell;
    }

    addLeafCell(lsegchar) {
        const r = this.buf32[TRIE1_SLOT] >>> 2;
        let i = r;
        while ( lsegchar > 127 ) {
            this.buf32[i+0] = 0;
            this.buf32[i+1] = i + 3;
            this.buf32[i+2] = this.addSegment(lsegchar, lsegchar - 127);
            lsegchar -= 127;
            i += 3;
        }
        this.buf32[i+0] = 0;
        this.buf32[i+1] = 0;
        this.buf32[i+2] = this.addSegment(lsegchar, 0) | 0x80;
        this.buf32[TRIE1_SLOT] = i + 3 << 2;
        return r;
    }

    addSegment(lsegchar, lsegend) {
        if ( lsegchar === 0 ) { return 0; }
        let char1 = this.buf32[CHAR1_SLOT];
        const isegchar = char1 - this.buf32[CHAR0_SLOT];
        let i = lsegchar;
        do {
            this.buf[char1++] = this.buf[--i];
        } while ( i !== lsegend );
        this.buf32[CHAR1_SLOT] = char1;
        return isegchar << 8 | lsegchar - lsegend;
    }

    growBuf(trieGrow, charGrow) {
        const char0 = Math.max(
            roundToPageSize(this.buf32[TRIE1_SLOT] + trieGrow),
            this.buf32[CHAR0_SLOT]
        );
        const char1 = char0 + this.buf32[CHAR1_SLOT] - this.buf32[CHAR0_SLOT];
        const bufLen = Math.max(
            roundToPageSize(char1 + charGrow),
            this.buf.length
        );
        this.resizeBuf(bufLen, char0);
    }

    shrinkBuf() {
        // Can't shrink WebAssembly.Memory
        if ( this.wasmMemory !== null ) { return; }
        const char0 = this.buf32[TRIE1_SLOT] + 24;
        const char1 = char0 + this.buf32[CHAR1_SLOT] - this.buf32[CHAR0_SLOT];
        const bufLen = char1 + 256;
        this.resizeBuf(bufLen, char0);
    }

    resizeBuf(bufLen, char0) {
        bufLen = roundToPageSize(bufLen);
        if ( bufLen === this.buf.length && char0 === this.buf32[CHAR0_SLOT] ) {
            return;
        }
        const charDataLen = this.buf32[CHAR1_SLOT] - this.buf32[CHAR0_SLOT];
        if ( this.wasmMemory !== null ) {
            const pageCount = (bufLen >>> 16) - (this.buf.byteLength >>> 16);
            if ( pageCount > 0 ) {
                this.wasmMemory.grow(pageCount);
                this.buf = new Uint8Array(this.wasmMemory.buffer);
                this.buf32 = new Uint32Array(this.wasmMemory.buffer);
            }
        } else if ( bufLen !== this.buf.length ) {
            const newBuf = new Uint8Array(bufLen);
            newBuf.set(
                new Uint8Array(
                    this.buf.buffer,
                    0,
                    this.buf32[TRIE1_SLOT]
                ),
                0
            );
            newBuf.set(
                new Uint8Array(
                    this.buf.buffer,
                    this.buf32[CHAR0_SLOT],
                    charDataLen
                ),
                char0
            );
            this.buf = newBuf;
            this.buf32 = new Uint32Array(this.buf.buffer);
            this.buf32[CHAR0_SLOT] = char0;
            this.buf32[CHAR1_SLOT] = char0 + charDataLen;
        }
        if ( char0 !== this.buf32[CHAR0_SLOT] ) {
            this.buf.set(
                new Uint8Array(
                    this.buf.buffer,
                    this.buf32[CHAR0_SLOT],
                    charDataLen
                ),
                char0
            );
            this.buf32[CHAR0_SLOT] = char0;
            this.buf32[CHAR1_SLOT] = char0 + charDataLen;
        }
    }

    reallocateBuf(newSize) {
        newSize = roundToPageSize(newSize);
        if ( newSize === this.buf.length ) { return; }
        if ( this.wasmMemory === null ) {
            const newBuf = new Uint8Array(newSize);
            newBuf.set(
                newBuf.length < this.buf.length
                    ? this.buf.subarray(0, newBuf.length)
                    : this.buf
            );
            this.buf = newBuf;
        } else {
            const growBy =
                ((newSize + 0xFFFF) >>> 16) - (this.buf.length >>> 16);
            if ( growBy <= 0 ) { return; }
            this.wasmMemory.grow(growBy);
            this.buf = new Uint8Array(this.wasmMemory.buffer);
        }
        this.buf32 = new Uint32Array(this.buf.buffer);
    }
}

HNTrieContainer.prototype.matches = HNTrieContainer.prototype.matchesJS;
HNTrieContainer.prototype.matchesWASM = null;

HNTrieContainer.prototype.add = HNTrieContainer.prototype.addJS;
HNTrieContainer.prototype.addWASM = null;

/******************************************************************************/

// Code below is to attempt to load a WASM module which implements:
//
// - HNTrieContainer.add()
// - HNTrieContainer.matches()
//
// The WASM module is entirely optional, the JS implementations will be
// used should the WASM module be unavailable for whatever reason.

const getWasmModule = (( ) => {
    let wasmModulePromise;

    return async function(wasmModuleFetcher, path) {
        if ( wasmModulePromise instanceof Promise ) {
            return wasmModulePromise;
        }

        // The wasm module will work only if CPU is natively little-endian,
        // as we use native uint32 array in our js code.
        const uint32s = new Uint32Array(1);
        const uint8s = new Uint8Array(uint32s.buffer);
        uint32s[0] = 1;
        if ( uint8s[0] !== 1 ) { return; }

        wasmModulePromise = wasmModuleFetcher(`${path}hntrie`).catch(reason => {
            console.info(reason);
        });

        return wasmModulePromise;
    };
})();

/******************************************************************************/

export default HNTrieContainer;


# CodeMirror

[![Build Status](https://travis-ci.org/codemirror/CodeMirror.svg)](https://travis-ci.org/codemirror/CodeMirror)
[![NPM version](https://img.shields.io/npm/v/codemirror.svg)](https://www.npmjs.org/package/codemirror)

CodeMirror is a versatile text editor implemented in JavaScript for
the browser. It is specialized for editing code, and comes with over
100 language modes and various addons that implement more advanced
editing functionality. Every language comes with fully-featured code
and syntax highlighting to help with reading and editing complex code.

A rich programming API and a CSS theming system are available for
customizing CodeMirror to fit your application, and extending it with
new functionality.

You can find more information (and the
[manual](https://codemirror.net/doc/manual.html)) on the [project
page](https://codemirror.net). For questions and discussion, use the
[discussion forum](https://discuss.codemirror.net/).

See
[CONTRIBUTING.md](https://github.com/codemirror/CodeMirror/blob/master/CONTRIBUTING.md)
for contributing guidelines.

The CodeMirror community aims to be welcoming to everybody. We use the
[Contributor Covenant
(1.1)](http://contributor-covenant.org/version/1/1/0/) as our code of
conduct.

### Installation

Either get the [zip file](https://codemirror.net/codemirror.zip) with
the latest version, or make sure you have [Node](https://nodejs.org/)
installed and run:

    npm install codemirror

**NOTE**: This is the source repository for the library, and not the
distribution channel. Cloning it is not the recommended way to install
the library, and will in fact not work unless you also run the build
step.

### Quickstart

To build the project, make sure you have Node.js installed (at least version 6)
and then `npm install`. To run, just open `index.html` in your
browser (you don't need to run a webserver). Run the tests with `npm test`.


#!/usr/bin/env bash
#
# This script assumes a linux environment

set -e

DES="dist/build/uBlock0.dig"

./tools/make-nodejs.sh $DES
./tools/make-assets.sh $DES

cp -R platform/dig/*   $DES/

cd $DES
npm run build

echo "*** uBlock0.dig: Package done."


* */
:root {
--font-size: 14px;
--font-size-smaller: 13px;
--font-family: Inter, sans-serif;
}
:root.mobile {
--font-size: 16px;
--font-size-smaller: 14px;

keep keep keep keep add keep keep keep keep keep