/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ 463:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "info": () => (/* reexport */ info)
});

// EXTERNAL MODULE: ./src/version/shared/version.ts
var version = __webpack_require__(3);
;// CONCATENATED MODULE: ./src/info/background/info.chrome.ts

const addonName = "adblockpluschrome";
const baseName = "adblockplus";
const addonVersion = "3.25.1";
let application = "";
let applicationVersion = "";
const platform = "chromium";
let platformVersion = "";
const regexp = /(\S+)\/(\S+)(?:\s*\(.*?\))?/g;
let match;
while ((match = regexp.exec(navigator.userAgent))) {
    const app = match[1];
    const ver = (0,version/* getMajorVersion */.X)(match[2]);
    if (app === "Chrome") {
        platformVersion = ver;
    }
    else if (app !== "Mozilla" && app !== "AppleWebKit" && app !== "Safari") {
        if (app === "Edg") {
            application = "edge";
        }
        else if (app === "OPR") {
            application = "opera";
        }
        else {
            application = app.toLowerCase();
        }
        applicationVersion = ver;
    }
}
if (platformVersion === "") {
    application = "unknown";
    applicationVersion = platformVersion = "0";
}
if (application === "") {
    application = "chrome";
    applicationVersion = platformVersion;
}
const info = {
    addonName,
    baseName,
    addonVersion,
    application,
    applicationVersion,
    platform,
    platformVersion
};

;// CONCATENATED MODULE: ./src/info/background/index.ts



/***/ }),

/***/ 320:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "_o": () => (/* binding */ allowlistingState),
/* harmony export */   "fm": () => (/* binding */ allowlist),
/* harmony export */   "s": () => (/* binding */ revalidateAllowlistingStates)
/* harmony export */ });
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(120);
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _messaging_port_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(305);
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(491);
/* harmony import */ var _filterConfiguration_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(311);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module allowlisting */







let allowlistedDomainRegexp = /^@@\|\|([^/:]+)\^\$document$/;
let eventEmitter = new _events_js__WEBPACK_IMPORTED_MODULE_3__/* .EventEmitter */ .v();

/**
 * @typedef {object} filtersIsAllowlistedResult
 * @property {boolean} hostname
 *   True if an allowing filter for an entire domain matches the given page.
 * @property {boolean} page
 *   True if an allowing filter _not_ for an entire domain matches the given
 *   page.
 */

/**
 * Checks if the given page is allowlisted.
 *
 * @event "filters.isAllowlisted"
 * @returns {filtersIsAllowlistedResult}
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_1__.port.on("filters.isAllowlisted", async message =>
{
  let pageAllowlisted = false;
  let hostnameAllowlisted = false;

  for (let filterText of await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.getAllowingFilters(message.tab.id))
  {
    if (allowlistedDomainRegexp.test(filterText))
      hostnameAllowlisted = true;
    else
      pageAllowlisted = true;

    if (pageAllowlisted && hostnameAllowlisted)
      break;
  }

  return {hostname: hostnameAllowlisted, page: pageAllowlisted};
});

/**
 * Allowlists the given domain or URL.
 *
 * @param {object} options
 *   Allowlisting options
 * @param {string} [options.hostname]
 *   Domain to allowlist (required unless singlePage is true)
 * @param {string} options.origin
 *   Filter origin
 * @param {boolean} [options.singlePage=false]
 *   Whether to allowlist the entire domain or a single page
 * @param {string} [options.url]
 *   URL to allowlist (required if no hostname)
 *
 * @returns {Promise}
 * @throws {Error} Either domain or valid URL required
 */
async function allowlist({hostname, origin, singlePage = false, url})
{
  let filterText;

  if (!hostname && !url)
    throw new Error("Hostname or URL required");

  if (url)
  {
    if (!(url instanceof URL))
      throw new Error("Invalid URL");

    if (singlePage)
    {
      // We generate a filter which only applies to the same protocol and
      // subdomain, but one which doesn't consider the exact query string or
      // fragment.
      // Our logic here is taken from the legacy Firefox extension.
      // See https://hg.adblockplus.org/adblockplus/file/tip/lib/ui.js#l1517
      let ending = "|";
      url.hash = "";
      if (url.search && url.search.includes("&"))
      {
        url.search = "";
        ending = "?";
      }
      filterText = `@@|${url.href}${ending}$document`;
    }
    else
    {
      hostname = url.hostname;
    }
  }

  if (!filterText)
  {
    let host = hostname.replace(/^www\./, "");
    filterText = `@@||${host}^$document`;
  }

  await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.enable([filterText]);

  const filterSubscriptions = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.getForFilter(filterText);
  if (filterSubscriptions.length == 0)
    await (0,_filterConfiguration_js__WEBPACK_IMPORTED_MODULE_2__/* .addFilter */ .KJ)(filterText, origin);
}

/**
 * Determines whether the given tab is allowlisted
 *
 * @param {number} tabId - Tab ID
 *
 * @returns {Promise<boolean>} whether the given tab is allowlisted
 */
async function isTabAllowlisted(tabId)
{
  const allowingFilters = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.getAllowingFilters(tabId);
  return allowingFilters.length > 0;
}

/**
 * Adds an allowing filter for the given page's hostname, if it is not
 * already allowlisted. Note: If a disabled allowing filter exists, we
 * enable that instead.
 *
 * @event "filters.allowlist"
 * @proper {string} [origin]
 *   String indicating where the filter originated from.
 * @property {boolean} [singlePage=false]
 *   If true we add an allowing filter for the given page's URL instead.
 * @property {object} tab
 *   Tab that contains the page to allowlist.
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_1__.port.on("filters.allowlist", async message =>
{
  let page = new ext.Page(message.tab);
  await allowlist({
    origin: message.origin,
    singlePage: message.singlePage,
    url: page.url
  });
});

/**
 * Remove any allowing filters which apply to the given page's URL.
 *
 * @event "filters.unallowlist"
 * @property {boolean} [singlePage=false]
 *   If true we only remove allowing filters which are not for an entire
 *   domain.
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_1__.port.on("filters.unallowlist", async message =>
{
  for (let filterText of await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.getAllowingFilters(message.tab.id))
  {
    if (message.singlePage && allowlistedDomainRegexp.test(filterText))
      continue;

    await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.remove([filterText]);

    const filterSubscriptions = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.getForFilter(filterText);
    if (filterSubscriptions.length != 0)
      await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.disable([filterText]);
  }
});

/**
 * @namespace
 * @static
 */
let allowlistingState = {
  /**
   * Adds a listener for the given event name.
   *
   * @param {string} name
   * @param {function} listener
   */
  addListener: eventEmitter.on.bind(eventEmitter),

  /**
   * Removes a listener for the given event name.
   *
   * @param {string} name
   * @param {function} listener
   */
  removeListener: eventEmitter.off.bind(eventEmitter)
};

async function revalidateAllowlistingState(page)
{
  const isAllowlisted = await isTabAllowlisted(page.id);
  eventEmitter.emit("changed", page, isAllowlisted);
}

async function revalidateAllowlistingStates()
{
  let tabs = await browser.tabs.query({});
  for (let tab of tabs)
    revalidateAllowlistingState(new ext.Page(tab));
}

ext.pages.onLoaded.addListener(revalidateAllowlistingState);
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onAdded.addListener(revalidateAllowlistingStates);
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onChanged.addListener(async(filter, property) =>
{
  if (property !== "enabled")
    return;

  await revalidateAllowlistingStates();
});
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onRemoved.addListener(revalidateAllowlistingStates);
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onAdded.addListener(revalidateAllowlistingStates);
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onChanged.addListener(async(subscription, property) =>
{
  if (property !== null && property !== "enabled")
    return;

  await revalidateAllowlistingStates();
});
_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onRemoved.addListener(revalidateAllowlistingStates);


/***/ }),

/***/ 820:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "c4": () => (/* binding */ setIconPath),
/* harmony export */   "k8": () => (/* binding */ setIconImageData),
/* harmony export */   "q_": () => (/* binding */ setBadge),
/* harmony export */   "qp": () => (/* binding */ toggleBadge)
/* harmony export */ });
/* harmony import */ var _storage_tab_session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(658);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module browserAction */



let badgeStateByPage = new _storage_tab_session_js__WEBPACK_IMPORTED_MODULE_0__/* .TabSessionStorage */ .H("browserAction:blockedState");
let changesByPage = new _storage_tab_session_js__WEBPACK_IMPORTED_MODULE_0__/* .TabSessionStorage */ .H("browserAction:changes");

async function setBadgeState(tabId, key, value)
{
  return badgeStateByPage.transaction(async() =>
  {
    let badgeState = await badgeStateByPage.get(tabId);

    if (!badgeState)
    {
      badgeState = {
        hiddenState: "visible",
        text: ""
      };
    }

    // We need to ignore any text changes while we're hiding the badge
    if (!(badgeState.hiddenState == "hiding" && key == "text"))
      badgeState[key] = value;

    await badgeStateByPage.set(tabId, badgeState);

    return badgeState;
  });
}

function applyChanges(tabId, changes)
{
  return Promise.all(Object.keys(changes).map(async change =>
  {
    // Firefox for Android displays the browser action not as an icon but
    // as a menu item. There is no icon, but such an option may be added
    // in the future.
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1331746
    if (change == "iconPath" && "setIcon" in browser.action)
    {
      return browser.action.setIcon({
        tabId,
        path: {
          16: changes.iconPath.replace("$size", "16"),
          20: changes.iconPath.replace("$size", "20"),
          32: changes.iconPath.replace("$size", "32"),
          40: changes.iconPath.replace("$size", "40")
        }
      });
    }

    if (change == "iconImageData" && "setIcon" in browser.action)
    {
      return browser.action.setIcon({
        tabId,
        imageData: changes.iconImageData
      });
    }

    // There is no badge on Firefox for Android; the browser action is
    // simply a menu item.
    if (change == "badgeText" && "setBadgeText" in browser.action)
    {
      // Remember changes to the badge text but don't apply them yet
      // as long as the badge is hidden.
      let badgeState = await setBadgeState(tabId, "text", changes.badgeText);
      if (badgeState.hiddenState == "hidden")
        return;

      return browser.action.setBadgeText({
        tabId,
        text: changes.badgeText
      });
    }

    // There is no badge on Firefox for Android; the browser action is
    // simply a menu item.
    if (change == "badgeColor" &&
        "setBadgeBackgroundColor" in browser.action)
    {
      return browser.action.setBadgeBackgroundColor({
        tabId,
        color: changes.badgeColor
      });
    }
  }));
}

function addChange(tabId, name, value)
{
  void changesByPage.transaction(async() =>
  {
    const changes = (await changesByPage.get(tabId)) || {};
    changes[name] = value;
    await changesByPage.set(tabId, changes);

    try
    {
      await applyChanges(tabId, changes);
      await changesByPage.delete(tabId);
    }
    catch (e)
    {
      // If the tab is prerendered, browser.action.set* fails
      // and we have to delay our changes until the currently visible tab
      // is replaced with the prerendered tab.
    }
  });
}

function onReplaced(addedTabId)
{
  void changesByPage.transaction(async() =>
  {
    const changes = await changesByPage.get(addedTabId);
    if (!changes)
      return;

    try
    {
      await applyChanges(addedTabId, changes);
    }
    catch (e)
    {
      // Ignore if we fail to apply the changes
    }

    await changesByPage.delete(addedTabId);
  });
}
// If the tab is prerendered, browser.action.set* fails
// and we have to delay our changes until the currently visible tab
// is replaced with the prerendered tab.
browser.tabs.onReplaced.addListener(onReplaced);

/**
 * Sets icon badge for given tab.
 *
 * @param {number} tabId
 * @param {object} badge
 * @param {string} badge.color
 * @param {string} badge.number
 */
function setBadge(tabId, badge)
{
  if (!badge)
  {
    addChange(tabId, "badgeText", "");
  }
  else
  {
    if ("number" in badge)
      addChange(tabId, "badgeText", badge.number.toString());

    if ("color" in badge)
      addChange(tabId, "badgeColor", badge.color);
  }
}

/**
 * Sets icon image for given tab using image data.
 *
 * @param  {number} tabId
 * @param  {object} imageData
 */
function setIconImageData(tabId, imageData)
{
  addChange(tabId, "iconImageData", imageData);
}

/**
 * Sets icon image for given tab using file path.
 *
 * @param  {number} tabId
 * @param  {string} path - expected to include "$size" placeholder
 */
function setIconPath(tabId, path)
{
  addChange(tabId, "iconPath", path);
}

/**
 * Toggles icon badge for given tab.
 *
 * @param  {number} tabId
 * @param  {boolean} shouldHide
 */
async function toggleBadge(tabId, shouldHide)
{
  if (shouldHide)
  {
    await setBadgeState(tabId, "hiddenState", "hiding");
    addChange(tabId, "badgeText", "");
    await setBadgeState(tabId, "hiddenState", "hidden");
  }
  else
  {
    let badgeState = await setBadgeState(tabId, "hiddenState", "visible");
    addChange(tabId, "badgeText", badgeState.text);
  }
}


/***/ }),

/***/ 491:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "v": () => (/* binding */ EventEmitter)
/* harmony export */ });
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */

/**
 * Registers and emits named events.
 */
class EventEmitter
{
  constructor()
  {
    this._listeners = new Map();
  }

  /**
   * Adds a listener for the specified event name.
   *
   * @param {string}   name
   * @param {function} listener
   */
  on(name, listener)
  {
    let listeners = this._listeners.get(name);
    if (listeners)
      listeners.push(listener);
    else
      this._listeners.set(name, [listener]);
  }

  /**
   * Removes a listener for the specified event name.
   *
   * @param {string}   name
   * @param {function} listener
   */
  off(name, listener)
  {
    let listeners = this._listeners.get(name);
    if (listeners)
    {
      if (listeners.length > 1)
      {
        let idx = listeners.indexOf(listener);
        if (idx != -1)
          listeners.splice(idx, 1);
      }
      else if (listeners[0] === listener)
      {
        // We must use strict equality above for compatibility with
        // Array.prototype.indexOf
        this._listeners.delete(name);
      }
    }
  }

  /**
   * Returns a copy of the array of listeners for the specified event.
   *
   * @param {string} name
   *
   * @returns {Array.<function>}
   */
  listeners(name)
  {
    let listeners = this._listeners.size > 0 ? this._listeners.get(name) : null;
    return listeners ? listeners.slice() : [];
  }

  /**
   * Checks whether there are any listeners for the specified event.
   *
   * @param {string} [name] The name of the event. If omitted, checks whether
   *   there are any listeners for any event.
   *
   * @returns {boolean}
   */
  hasListeners(name)
  {
    return this._listeners.size > 0 &&
           (typeof name == "undefined" || this._listeners.has(name));
  }

  /**
   * Calls all previously added listeners for the given event name.
   *
   * @param {string} name
   * @param {...*}   [args]
   */
  emit(name, ...args)
  {
    let listeners = this._listeners.size > 0 ? this._listeners.get(name) : null;
    if (listeners)
    {
      for (let listener of listeners.slice())
        listener(...args);
    }
  }
}


/***/ }),

/***/ 311:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "KJ": () => (/* binding */ addFilter),
  "VF": () => (/* binding */ addSubscription),
  "P0": () => (/* binding */ askConfirmSubscription),
  "k7": () => (/* binding */ initDisabledFilterCounters),
  "BL": () => (/* binding */ start)
});

// EXTERNAL MODULE: ./node_modules/@eyeo/webext-ad-filtering-solution/dist/ewe-api.js
var ewe_api = __webpack_require__(120);
// EXTERNAL MODULE: ./lib/pages/options.js
var options = __webpack_require__(262);
// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/events.js
var events = __webpack_require__(370);
// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/port.js
var port = __webpack_require__(305);
// EXTERNAL MODULE: ./src/core/api/background/index.ts + 1 modules
var background = __webpack_require__(12);
// EXTERNAL MODULE: ./adblockpluschrome/lib/events.js
var lib_events = __webpack_require__(491);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/requestBlocker.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module requestBlocker */



let filterTypes = new Set(function*()
{
  for (let type of ewe_api.reporting.contentTypesMap.values())
    yield type.toUpperCase();

  yield "SNIPPET";
}());

;// CONCATENATED MODULE: ./adblockpluschrome/lib/filterConfiguration.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */










const disabledFilterCounters = new Map();
const eventEmitter = new lib_events/* EventEmitter */.v();

async function addFilter(filterText, origin)
{
  const data = {created: Date.now()};
  if (origin)
    data.origin = origin;

  try
  {
    await ewe_api.filters.add([filterText], data);
    await ewe_api.filters.enable([filterText]);
  }
  catch (ex)
  {
    // If we add an existing filter again, we ignore the resulting error to
    // avoid showing unnecessary error messages to the user
    if (ex.type !== "storage_duplicate_filters")
      return ex;
  }

  return null;
}

async function addSubscription(details)
{
  try
  {
    await ewe_api.subscriptions.add(details.url, details);
    await ewe_api.subscriptions.sync(details.url);
  }
  catch (ex)
  {
    return false;
  }

  return true;
}

/**
 * Asks user to confirm the subscription details before it is added.
 * @param {Object} details
 */
async function askConfirmSubscription(details)
{
  await (0,options/* showOptions */.a)({
    type: "app.respond",
    action: "addSubscription",
    args: [{
      homepage: details.homepage || null,
      title: details.title || null,
      url: details.url
    }]
  });
}

function parseFilter(text)
{
  let filterText = text.trim() || null;
  let error = null;

  if (filterText)
  {
    if (filterText[0] == "[")
    {
      error = {type: "unexpected_filter_list_header"};
    }
    else
    {
      let filterError = ewe_api.filters.validate(filterText);
      if (filterError)
        error = (0,background/* toSerializableFilterError */.ZB)(filterError);
    }
  }

  return [filterText, error];
}

async function filtersAdd(text, origin)
{
  let [filterText, error] = parseFilter(text);

  if (!error && filterText)
    error = await addFilter(filterText, origin);

  return (error) ? [error] : [];
}

function filtersValidate(text)
{
  let filterTexts = [];
  let errors = [];

  let lines = text.split("\n");
  for (let i = 0; i < lines.length; i++)
  {
    let [filterText, error] = parseFilter(lines[i]);

    if (error)
    {
      // We don't treat filter headers like invalid filters,
      // instead we simply ignore them and don't show any errors
      // in order to allow pasting complete filter lists.
      // If there are no filters, we do treat it as an invalid filter
      // to inform users about it and to give them a chance to edit it.
      if (error.type === "unexpected_filter_list_header" &&
          lines.length > 1)
        continue;

      if (lines.length > 1)
        error.lineno = i + 1;

      errors.push(error);
    }
    else if (filterText)
    {
      filterTexts.push(filterText);
    }
  }

  return [filterTexts, errors];
}

async function filtersRemove(message)
{
  await ewe_api.filters.remove([message.text]);
  // in order to behave, from consumer perspective, like any other
  // method that could produce errors, return an Array, even if empty
  return [];
}

async function initDisabledFilterCounters()
{
  for (const subscription of await ewe_api.subscriptions.getSubscriptions())
  {
    let count = 0;

    for (const filter of await ewe_api.subscriptions.getFilters(subscription.url))
    {
      if (filter.enabled === false)
        count++;
    }

    if (count > 0)
    {
      disabledFilterCounters.set(subscription.url, count);
      // Core doesn't expose the subscription's disabled filters state
      // and to avoid adding new "loaded" events and behavior around it,
      // we emit a "filtersDisabled" event to trigger UI changes
      eventEmitter.emit(
        "filtersDisabled",
        subscription,
        true,
        true
      );
    }
  }
}

async function updateCounters(filterText, enabled)
{
  for (const subscription of await ewe_api.subscriptions.getForFilter(filterText))
  {
    const oldCount = disabledFilterCounters.get(subscription.url) || 0;
    const newCount = (enabled) ? oldCount - 1 : oldCount + 1;

    if (newCount === 0)
      disabledFilterCounters.delete(subscription.url);
    else
      disabledFilterCounters.set(subscription.url, newCount);

    if (oldCount === 0 || newCount === 0)
    {
      eventEmitter.emit(
        "filtersDisabled",
        subscription,
        newCount > 0,
        oldCount > 0
      );
    }
  }
}


function start()
{
  /**
   * Attempts to add the given filter, or returns an error.
   *
   * @event "filters.add"
   * @property {string} [origin] - Where the filter originated from
   * @property {string} text - The filter text to add
   * @returns {FilterError[]}
   */
  port.port.on("filters.add", (message, sender) =>
  {
    return filtersAdd(message.text, message.origin);
  });

  /**
   * Returns a serialized version of all filters in special subscriptions.
   *
   * @event "filters.get"
   * @returns {object[]}
   */
  port.port.on("filters.get", async(message, sender) =>
  {
    let filters = await ewe_api.filters.getUserFilters();
    return filters.map(background/* toSerializableFilter */.iw);
  });

  /**
   * Returns the available filter types, e.g. "FONT", "WEBSOCKET", etc.
   *
   * @event "filters.getTypes"
   * @returns {string[]}
   */
  port.port.on("filters.getTypes", (message, sender) => Array.from(filterTypes));

  /**
   * Import the given block of filter text as custom user filters.
   *
   * @event "filters.importRaw"
   * @property {string} [origin]
   *   Where the filter originated from.
   * @property {string} text
   *   The filters to add.
   * @returns {string[]} errors
   */
  port.port.on("filters.importRaw", async(message, sender) =>
  {
    let [filterTexts, errors] = filtersValidate(message.text);

    if (errors.length == 0)
    {
      const error = await ewe_api.filters.add(filterTexts);
      if (error)
        errors.push(error);
    }

    return errors;
  });

  /**
   * Remove the given filter.
   *
   * @event "filters.remove"
   * @property {string} text
   *   The text of the filter to remove.
   * @returns {string[]} errors
   */
  port.port.on("filters.remove", (message, sender) => filtersRemove(message));

  /**
   * Batch-removes the given filters.
   *
   * @event "filters.removeBatch"
   * @property {string[]} texts
   *   The texts of filters to remove.
   * @returns {string[]} errors
   */
  port.port.on("filters.removeBatch", async message =>
  {
    await ewe_api.filters.remove(message.texts);

    // in order to behave, from consumer perspective, like any other
    // method that could produce errors, return an Array, even if empty
    return [];
  });

  /**
   * Replaces one custom user filter with another.
   *
   * @event "filters.replace"
   * @property {string} new - The new filter text to add.
   * @property {string} old - The old filter text to remove.
   * @property {string} [origin] - Where the filter originated from.
   * @returns {string[]} errors
   */
  port.port.on("filters.replace", async(message, sender) =>
  {
    let errors = await filtersAdd(message.new, message.origin);
    if (errors.length)
      return errors;
    await filtersRemove({text: message.old});
    return [];
  });

  /**
   * Enabled or disables the given filter.
   *
   * @event "filters.toggle"
   * @property {string} text - The filter text.
   * @property {boolean} disabled - True to disable the filter, false to enable.
   */
  port.port.on("filters.toggle", async(message, sender) =>
  {
    if (message.disabled)
      await ewe_api.filters.disable([message.text]);
    else
      await ewe_api.filters.enable([message.text]);
  });

  /**
   * Validates the filters inside the given block of filter text.
   *
   * @event "filters.validate"
   * @property {string} text - The filters to validate
   * @returns {string[]} errors
   */
  port.port.on("filters.validate", (message, sender) =>
  {
    let [, errors] = filtersValidate(message.text);
    return errors;
  });

  /**
   * Adds a subscription, either in the background or with the user's
   * confirmation.
   *
   * @event "subscriptions.add"
   * @property {string} url
   *   The subscription's URL.
   * @property {boolean} confirm
   *   If true the user will first be asked to confirm the subscription's
   *   details before it is added.
   * @property {string} [title]
   *   The subscription's title.
   * @property {string} [homepage]
   *   The subscription's homepage.
   * @returns {?boolean}
   *   true if the subscription was added, false if the URL is invalid,
   *   null if the "confirm" property was set
   */
  port.port.on("subscriptions.add", async(message, sender) =>
  {
    if (message.confirm)
    {
      askConfirmSubscription({
        homepage: message.homepage,
        title: message.title,
        url: message.url
      });
      return null;
    }

    return addSubscription(message);
  });

  ewe_api.reporting.onSubscribeLinkClicked.addListener(message =>
  {
    askConfirmSubscription({
      title: message.title,
      url: message.url
    });
  });

  /**
   * Enables all filters from the given subscription.
   *
   * @event "subscriptions.enableAllFilters"
   * @property {string} url
   *   The subscription's URL.
   */
  port.port.on("subscriptions.enableAllFilters", async(message, sender) =>
  {
    const filters = await ewe_api.subscriptions.getFilters(message.url);
    const filterTexts = filters.map(filter => filter.text);
    await ewe_api.filters.enable(filterTexts);
  });

  /**
   * Returns a serialized version of all updatable subscriptions which meet
   * the given criteria. Optionally include the disabled filters for those
   * subscriptions.
   *
   * @event "subscriptions.get"
   * @property {boolean} ignoreDisabled
   *   Skip disabled subscriptions if true.
   * @property {boolean} disabledFilters
   *   Include a subscription's disabled filters if true.
   * @returns {object[]} subscriptions
   */
  port.port.on("subscriptions.get", async(message, sender) =>
  {
    let subscriptions = [];
    for (let s of await ewe_api.subscriptions.getSubscriptions())
    {
      if (message.ignoreDisabled && !s.enabled)
        continue;

      let subscription = (0,background/* toSerializableSubscription */.Bp)(s);
      if (message.disabledFilters)
      {
        let filters = await ewe_api.subscriptions.getFilters(s.url) || [];
        subscription.disabledFilters = filters
        .filter(f => f.enabled === false)
        .map(f => f.text);
      }
      subscriptions.push(subscription);
    }
    return subscriptions;
  });

  /**
   * Returns the amount of disabled filters contained in a subscription.
   *
   * @event "subscriptions.getDisabledFilterCount"
   * @property {string} url - The subscription's URL.
   */
  port.port.on("subscriptions.getDisabledFilterCount", (message, sender) =>
  {
    return disabledFilterCounters.get(message.url) || 0;
  });

  /**
   * Returns a list of serialised recommended subscriptions for the user.
   *
   * @event "subscriptions.getRecommendations"
   * @returns {object[]} recommendedSubscriptions
   */
  port.port.on("subscriptions.getRecommendations", async(message, sender) =>
  {
    const recommendations = await ewe_api.subscriptions.getRecommendations();
    return Array.from(recommendations, background/* toSerializableRecommendation */.uE);
  });

  /**
   * Remove the given subscription if it exists.
   *
   * @event "subscriptions.remove"
   * @property {string} url - The subscription's URL.
   */
  port.port.on("subscriptions.remove", async(message, sender) =>
  {
    await ewe_api.subscriptions.remove(message.url);
  });

  /**
   * Toggles a subscription by either enabling/disabling, or by adding/removing
   * it.
   *
   * @event "subscriptions.toggle"
   * @property {string} url
   *   The subscription's URL.
   * @property {boolean} keepInstalled
   *   If true enable/disable the subscription, otherwise add/remove.
   * @returns {boolean}
   *   true if the subscription was toggled successfully,
   *   false if it's a new subscription with an invalid URL
   */
  port.port.on("subscriptions.toggle", async(message, sender) =>
  {
    if (await ewe_api.subscriptions.has(message.url))
    {
      let subscription;
      for (let s of await ewe_api.subscriptions.getSubscriptions())
      {
        if (s.url == message.url)
        {
          subscription = s;
          break;
        }
      }

      if (subscription)
      {
        if (!subscription.enabled || message.keepInstalled)
        {
          if (subscription.enabled)
            await ewe_api.subscriptions.disable(message.url);
          else
            await ewe_api.subscriptions.enable(message.url);
        }
        else
        {
          await ewe_api.subscriptions.remove(subscription.url);
        }
        return true;
      }
    }

    return addSubscription(message);
  });

  /**
   * Trigger either the given subscription, or all subscriptions, to update.
   *
   * @event "subscriptions.update"
   * @property {string} [url]
   *   The subscription to update, if not specified all subscriptions will be
   *   updated.
   */
  port.port.on("subscriptions.update", async(message, sender) =>
  {
    await ewe_api.subscriptions.sync(message.url);
  });


  ewe_api.filters.onChanged.addListener(async(filter, property) =>
  {
    if (property !== "enabled")
      return;

    await updateCounters(filter.text, filter.enabled);
  });

  ewe_api.subscriptions.onRemoved.addListener(subscription =>
  {
    disabledFilterCounters.delete(subscription.url);
  });

  (0,events/* installHandler */.a)("filters", "added", emit =>
  {
    const onAdded = filter => emit((0,background/* toSerializableFilter */.iw)(filter));
    ewe_api.filters.onAdded.addListener(onAdded);
    return () => ewe_api.filters.onAdded.removeListener(onAdded);
  });

  (0,events/* installHandler */.a)("filters", "changed", emit =>
  {
    const onChanged = (filter, property) =>
      emit((0,background/* toSerializableFilter */.iw)(filter), property);
    ewe_api.filters.onChanged.addListener(onChanged);
    return () => ewe_api.filters.onChanged.removeListener(onChanged);
  });

  (0,events/* installHandler */.a)("filters", "removed", emit =>
  {
    const onRemoved = filter => emit((0,background/* toSerializableFilter */.iw)(filter));
    ewe_api.filters.onRemoved.addListener(onRemoved);
    return () => ewe_api.filters.onRemoved.removeListener(onRemoved);
  });

  (0,events/* installHandler */.a)("subscriptions", "added", emit =>
  {
    const onAdded = subscription =>
    {
      emit((0,background/* toSerializableSubscription */.Bp)(subscription));
    };
    ewe_api.subscriptions.onAdded.addListener(onAdded);
    return () => ewe_api.subscriptions.onAdded.removeListener(onAdded);
  });

  (0,events/* installHandler */.a)("subscriptions", "changed", emit =>
  {
    const onChanged = (subscription, property) =>
    {
      emit((0,background/* toSerializableSubscription */.Bp)(subscription), property);
    };
    ewe_api.subscriptions.onChanged.addListener(onChanged);
    return () => ewe_api.subscriptions.onChanged.removeListener(onChanged);
  });

  (0,events/* installHandler */.a)("subscriptions", "filtersDisabled", emit =>
  {
    const onFiltersDisabled = (subscription, hadFilters, hasFilters) =>
    {
      emit((0,background/* toSerializableSubscription */.Bp)(subscription), hadFilters, hasFilters);
    };
    eventEmitter.on("filtersDisabled", onFiltersDisabled);
    return () => eventEmitter.off("filtersDisabled", onFiltersDisabled);
  });

  (0,events/* installHandler */.a)("subscriptions", "removed", emit =>
  {
    const onRemoved = subscription =>
    {
      emit((0,background/* toSerializableSubscription */.Bp)(subscription));
    };
    ewe_api.subscriptions.onRemoved.addListener(onRemoved);
    return () => ewe_api.subscriptions.onRemoved.removeListener(onRemoved);
  });
}


/***/ }),

/***/ 370:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "a": () => (/* binding */ installHandler)
/* harmony export */ });
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(491);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



const cleanupByTabId = new Map();
const eventEmitter = new _events_js__WEBPACK_IMPORTED_MODULE_0__/* .EventEmitter */ .v();
const handlerByName = new Map();
const handlerTemplateByType = new Map();

/**
 * Installs a handler for lazily adding/removing event listeners depending on
 * whether someone is actively listening via the Messaging API.
 *
 * @param {string} type
 *   type of events to allow listening to
 * @param {string} [action]
 *   specific event to allow listening to
 *   null if handler applies to all events for the given type
 * @param {Function} install
 *   callback function for adding event listeners
 *   will receive emit, action, targetTabId as arguments
 *   expected to return callback function for removing event listeners
 */
function installHandler(type, action, install)
{
  const handler = {install, uninstall: null};

  // Handlers that can be used for arbitrary actions should be used as
  // templates, from which we can create handlers later
  if (!action)
  {
    handlerTemplateByType.set(type, handler);
    return;
  }

  handlerByName.set(`${type}.${action}`, handler);
}

function listen(type, actions, uiPort, targetTabId = null)
{
  const cleanups = [];

  for (const action of actions)
  {
    let name = `${type}.${action}`;
    if (targetTabId !== null)
      name = `${name}:${targetTabId}`;

    // Add message response listener
    const onResponse = (...args) =>
    {
      uiPort.postMessage({type: `${type}.respond`, action, args});
    };
    eventEmitter.on(name, onResponse);

    // Install event handler
    let handler = handlerByName.get(name);
    // If there's no handler for the given action, we should check
    // whether there's a generic handler for the type and create one from that
    if (!handler)
    {
      const template = handlerTemplateByType.get(type);
      if (template)
      {
        handler = Object.assign({}, template);
        handlerByName.set(name, handler);
      }
    }
    if (handler && !handler.uninstall)
    {
      const emit = eventEmitter.emit.bind(eventEmitter, name);
      handler.uninstall = handler.install(emit, action, targetTabId);
    }

    cleanups.push(() =>
    {
      eventEmitter.off(name, onResponse);

      // Uninstall event handler, if it's no longer needed
      if (!eventEmitter.hasListeners(name))
      {
        const actionHandler = handlerByName.get(name);
        if (actionHandler && actionHandler.uninstall)
        {
          actionHandler.uninstall();
          handler.uninstall = null;
        }
      }
    });
  }

  const cleanupAll = () =>
  {
    for (const cleanup of cleanups)
      cleanup();
  };

  // Stop listening when port disconnects (e.g. page is closed),
  // or when target tab is closed
  uiPort.onDisconnect.addListener(cleanupAll);
  if (targetTabId !== null)
    cleanupByTabId.set(targetTabId, cleanupAll);
}

function onTabRemoved(tabId)
{
  const cleanup = cleanupByTabId.get(tabId);
  if (!cleanup)
    return;

  cleanup();
  cleanupByTabId.delete(tabId);
}
browser.tabs.onRemoved.addListener(onTabRemoved);

function onConnect(uiPort)
{
  if (!ext.isTrustedSender(uiPort.sender))
    return;

  if (uiPort.name !== "ui")
    return;

  uiPort.onMessage.addListener(message =>
  {
    const [type, action] = message.type.split(".", 2);

    // For now we're only using long-lived connections
    // for handling "*.listen" messages
    // https://issues.adblockplus.org/ticket/6440/
    if (action !== "listen")
      return;

    listen(type, message.filter, uiPort, message.tabId);
  });
}
browser.runtime.onConnect.addListener(onConnect);


/***/ }),

/***/ 305:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "port": () => (/* binding */ port)
/* harmony export */ });
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(491);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/**
 * Communication port wrapping ext.onMessage to receive messages.
 *
 * @constructor
 */
class Port
{
  constructor()
  {
    this._eventEmitter = new _events_js__WEBPACK_IMPORTED_MODULE_0__/* .EventEmitter */ .v();
    this._onMessage = this._onMessage.bind(this);
    ext.onMessage.addListener(this._onMessage);
  }

  _onMessage(message, sender)
  {
    let callbacks = this._eventEmitter.listeners(message.type);

    try
    {
      let responses = callbacks.map(callback => callback(message, sender));
      return ext.getMessageResponse(responses);
    }
    catch (err)
    {
      console.error(err);
    }
  }

  /**
   * Function to be called when a particular message is received.
   *
   * @callback Port~messageCallback
   * @param {object} message
   * @param {object} sender
   * @return The callback can return undefined (no response),
   *         a value (response to be sent to sender immediately)
   *         or a promise (asynchronous response).
   */

  /**
   * Adds a callback for the specified message.
   *
   * The return value of the callback (if not undefined) is sent as response.
   * @param {string}   name
   * @param {Port~messageCallback} callback
   */
  on(name, callback)
  {
    this._eventEmitter.on(name, callback);
  }

  /**
   * Removes a callback for the specified message.
   *
   * @param {string}   name
   * @param {Port~messageCallback} callback
   */
  off(name, callback)
  {
    this._eventEmitter.off(name, callback);
  }

  /**
   * Disables the port and makes it stop listening to incoming messages.
   */
  disconnect()
  {
    ext.onMessage.removeListener(this._onMessage);
  }
}

/**
 * The default port to receive messages.
 *
 * @type {Port}
 */
let port = new Port();


/***/ }),

/***/ 968:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Prefs": () => (/* binding */ Prefs)
/* harmony export */ });
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(120);
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _messaging_events_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(370);
/* harmony import */ var _messaging_port_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(305);
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(491);
/* harmony import */ var _src_info_background__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(463);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module prefs */








const keyPrefix = "pref:";

let eventEmitter = new _events_js__WEBPACK_IMPORTED_MODULE_4__/* .EventEmitter */ .v();
let overrides = Object.create(null);

/** @lends module:prefs.Prefs */
let defaults = Object.create(null);

/**
 * Public keys used to verify authenticity of partners that are authorized to
 * use the allowlisting API.
 *
 * @type {string[]}
 */
defaults.allowlisting_authorizedKeys = [
  `MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuePfbm865kumeftXjlbt
J68DTXLTn0VeOgdSTqOcpADVqH0Kxz5hfLMaoKC/QhO3SmAu1yZwJZ1WP9Uyu3I5
EvJwEt7OHjJv54GhyYCtylMDCqSZgIIkUtB9PSXqFe3qyKAXACzwnLHmYIMMC1rx
bViqMD06+S4NKtzEh602/JsOOTHkXDJFQi5gGpd7Yn/r1YFG20JzU5lr0pf3dOEK
gNXiEwSRCuVSZ2+MHMtkFdP83/k59rTOfz5+ZThYmxECytD0JyY+bpDbso/XxQeL
fThNEEnSpbbeJRZQM5Lwf4D/f1wzSvyRrQiQz6Bo6TrA9DpL/BHqgUBv4O+DwhAu
8tFaaI+YWUmA1M6DRCL1aPQlFf3RB+aAf/TXFRU6enm8y/DFKWnwZja1YlApxTYT
MGnZ5hrsXZZImjcKBKwXi3JCtLkfV+osAHYrMAJPPAfECkch/ovrEUcdBEu4WsJ+
gKlL2C1/ZL+fTZc+H9qt38qba8my5XlQmhXmzXFKKyp+1pqNkQuYzzT0M8PUqtlh
z5aNu4gc/sOrQayusssUkkwISWm9yKc9pwOE+2Ax45iq2xNhjx0+rl9nc/chV21T
ZLfyePid/4N3Q7obmQ9a6trOBIF5ONyg16CK61RjacnG76AMKrVOoq9lzF2UufL8
Myzw9X8Wsw3VrjJyYbWhUtkCAwEAAQ==`,
  `MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwWP4dO4iYcHpcO6lVmjC
gg/jfLM4fP+wWNaoDvMke0gQ7m9smXVtgbYXb6qzEd0aDaCRX3em+eo6bWp6ps5U
+8USRxuNH4cs6ZLjGynmZnm2TXrJScixUEw4ULq8Rdexr4ZmtT1WfUjJSFQpWWwp
e69kVR0iwwiCFRq90I/7MfJWnwgHX2tkUkVBttmXt9o0wP8th/UOIdx+0VbrqhgY
wMyo3xCUvqcSpcKsHXoLkKGlpcplE96rKg2vOqhSSQzoHMr8ZrGIn7hsPI7enVsP
D/nMiJptavVowfNZjM/rd6Iv/TYfI1JOJWUeIM+aPyhZKrvWHGdC8VO2jneNkNXj
1B6tnZy6owPt4Lgdimr0u/146WvjAL+ZK1dc4CNecOLeRINn26POCIeOpYPHGhbi
N6K1UrHpC1Oon2NW5ms9dciE242O1BrQF5j/GvNzGoV74GvnbVFZ9eyBJm9MlIOU
Sd5O2iTqWPmJ03wVSXLx+6g0fgaGHEDtKtbfhuHvDG2dIoAB7q+oKBHQJ7CIFEbI
lBnPV1v+dxDLb3DdK0Ip9wM74S2+Nf9359TCjAaWgNjiTnhBw6xpwTGn/8vzNL3p
fcEVJJt8DUfuCYV9mtKPHbj06RHnLsaXQ72x6I+ocXi8TygTjldZFx13ttJqVvju
UaTE0E4KN9Mzb/2zEYTgCzcCAwEAAQ==`
];

/**
 * A unique id for this extension installation.
 *
 * @type {string}
 */
defaults.installation_id = "";
/**
 * The application version as set during initialization. Used to detect updates.
 *
 * @type {string}
 */
defaults.currentVersion = "";
/**
 * @see https://adblockplus.org/en/preferences#documentation_link
 * @type {string}
 */
defaults.documentation_link = "https://adblockplus.org/redirect?link=%LINK%&lang=%LANG%";
/**
 * The total number of requests blocked by the extension.
 *
 * @type {number}
 */
defaults.blocked_total = 0;
/**
 * Public keys used to verify authenticity of entities that are authorized to
 * use the bypass API.
 *
 * @type {string[]}
 */
defaults.bypass_authorizedKeys = [
  `MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsCtBp9/0qCM5lp0lJVSx
IAGgWZsX50xeJfBq6OkfsI+305Yj0igVfyVASOaC1fc2JRHD/uAOKk47SiPcBkiz
mPHUt9ziOtAEkW7GrU6gaVOSwp26vUbSuvg9ouut5U2m8ULOyzp+WyU8nCzTPV5o
AvCta04bK9or4UnyTRKyqADlNwz7WnH+0QiHYbgtfE/E3rowEoMEAC44C7OiawCm
rnBXAkyBJnh1oEfUVI4LurxVl/zLo8MWfzErkaJy1FpsFR3F3L9ymKXpmxbhlDdX
0rxjwnRD/2sCWW3SJOU26gfFgu/NI6LGxcWdPrucdkoOOOnNQjjDlhGYPTqqxugH
/I5r+tAeUrrwKjmFcpMdxX7dfw1LoBoZCZnShZKlGKDqXf985Dc+3StbGWcxwNn9
l9/Ho6YFA7fKpBKEED2V+SrDb4RCkScvOOiMOI1v5bwsLinUd/2yxRDrO25uwU7h
r4LqmOguqjjLGF17d2WvG5D+LIQwgusxQd9Jk/n9PRdwtVGJhSDsDc8el2nKIqk9
ofk3YJzAIbS9iHQ2LuHubuhzYjkxRLcdSbt1oONHCSHeecZn/OXwYeTvU7Po1KPW
emi3XUpyjylUe9ONlw50lynwRw117bNHQDDHwKPoVW1cjoAtRsCnviFHPWTPjQKe
A2LS9qa7eNdIonehrzG20cECAwEAAQ==`
];
/**
 * Whether to show a badge in the toolbar icon indicating the number
 * of blocked ads.
 *
 * @type {boolean}
 */
defaults.show_statsinicon = true;
/**
 * Whether to show the "Block element" context menu entry.
 *
 * @type {boolean}
 */
defaults.shouldShowBlockElementMenu = true;

/**
 * Whether to show tracking warning in options page when both
 * Acceptable Ads and subscription of type "Privacy" are enabled.
 *
 * @type {boolean}
 */
defaults.ui_warn_tracking = true;

/**
 * Whether to show the developer tools panel.
 *
 * @type {boolean}
 */
defaults.show_devtools_panel = true;

/**
 * Prevents unsolicited UI elements from showing up after installation. This
 * preference isn't set by the extension but can be pre-configured externally.
 *
 * @see https://adblockplus.org/development-builds/suppressing-the-first-run-page-on-chrome
 * @type {boolean}
 */
defaults.suppress_first_run_page = false;

/**
 * Additonal subscriptions to be automatically added when the extension is
 * loaded. This preference isn't set by the extension but can be pre-configured
 * externally.
 *
 * @type {string[]}
 */
defaults.additional_subscriptions = [];

/**
 * The version of major updates that the user is aware of. If it's too low,
 * the updates page will be shown to inform the user about intermediate changes.
 *
 * @type {number}
 */
defaults.last_updates_page_displayed = 0;

/**
 * Causes elements targeted by element hiding (and element hiding emulation)
 * to be highlighted instead of hidden.
 *
 * @type {boolean}
 */
defaults.elemhide_debug = false;

/**
 * Address of page to open on first run.
 *
 * @type {string}
 */
defaults.remote_first_run_page_url = "https://welcome.adblockplus.org/%LANG%/installed?an=%ADDON_NAME%&av=%ADDON_VERSION%&ap=%APPLICATION_NAME%&apv=%APPLICATION_VERSION%&p=%PLATFORM_NAME%&pv=%PLATFORM_VERSION%";

/**
 * Whether to recommend language filter lists to user.
 *
 * @type {boolean}
 */
defaults.recommend_language_subscriptions = false;

/**
 * Premium license
 *
 * @type {object}
 */
defaults.premium_license = {
  lv: 1,
  code: "",
  status: "expired"
};

/**
 * Origins that are trusted to open the options page
 */
defaults.options_backlink_trusted_origins = ["https://welcome.adblockplus.org", "https://adblockplus.org"];

/**
 * Origin of page to activate Premium license.
 *
 * @type {string}
 */
defaults.premium_license_activation_origin = "https://accounts.adblockplus.org";

/**
 * Timestamp indicating when to attempt the next Premium license check.
 *
 * @type {number}
 */
defaults.premium_license_nextcheck = 0;

/**
 * Premium license check API endpoint
 *
 * @type {string}
 */
defaults.premium_license_check_url = "https://myadblock.licensing.adblockplus.dev/license";

/**
 * Address of page to manage Premium account.
 *
 * @type {string}
 */
defaults.premium_manage_page_url = "https://accounts.adblockplus.org/%LANG%/manage?lic=%LICENSE_CODE%&s=%SOURCE%";

/**
 * Origin of page to trigger Premium onboarding
 *
 * @type {string}
 */
defaults.premium_onboarding_trigger_origin = "https://accounts.adblockplus.org";

/**
 * Address of page to upgrade to Premium.
 *
 * @type {string}
 */
defaults.premium_upgrade_page_url = "https://accounts.adblockplus.org/%LANG%/premium?an=%ADDON_NAME%&av=%ADDON_VERSION%&ap=%APPLICATION_NAME%&apv=%APPLICATION_VERSION%&p=%PLATFORM_NAME%&pv=%PLATFORM_VERSION%&s=%SOURCE%";

/**
 * Premium user ID
 *
 * @type {string}
 */
defaults.premium_user_id = "";

/**
 * The URL of the IPM server.
 *
 * @type {string}
 */
defaults.ipm_server_url = "https://ipm.adblockplus.dev/api/stats";

/**
 * The interval in which to ping the IPM server, in ms. Defaults to 24 hours.
 *
 * @type {number}
 */
defaults.ipm_ping_interval = 24 * 60 * 60 * 1000;

/**
 * List of user events
 *
 * @type {array}
 */
defaults.ipm_events = [];

/**
 * Map of commands
 *
 * @type {Object}
 */
defaults.ipm_commands = {};

/**
 * Default trusted origin for URLs used in IPMs. This is the base URL used when
 * a relative URL is passed.
 *
 * @type {string}
 */
defaults.ipm_default_origin = "https://adblockplus.org";

/**
 * Trusted origins for URLs used in IPMs
 *
 * @type {string}
 */
defaults.ipm_safe_origins = [
  defaults.ipm_default_origin,
  "https://accounts.adblockplus.org",
  "https://blog.adblockplus.org",
  "https://help.adblockplus.org",
  "https://new.adblockplus.org",
  "https://welcome.adblockplus.org"
];

/**
 * Minimum log level
 *
 * @type {number}
 */
defaults.logger_log_level = 3;

/**
 * Map of command stats
 *
 * @type {Object}
 */
defaults.onpage_dialog_command_stats = {};

/**
 * Whether user has interacted with YouTube wall detection dialog
 *
 * @type {boolean}
 */
defaults.ytWallDetection_dialog_interacted = false;

/**
 * Where the dialog for the YouTube wall should link users to
 *
 * @type {string}
 */
defaults.ytWallDetection_dialog_url = "https://adblockplus.org/youtube";

/**
 * Map of on-page dialog timing configurations
 *
 * @see src/onpage-dialog/background/middleware/ipm-onpage-dialog.types.ts
 * @see src/onpage-dialog/background/timing.types.ts
 *
 * @type {Object}
 */
defaults.onpage_dialog_timing_configurations = {
  after_web_allowlisting: {
    cooldownDuration: 24,
    maxAllowlistingDelay: 2,
    maxDisplayCount: 3
  },
  immediate: {
    cooldownDuration: 0,
    maxDisplayCount: 0
  },
  revisit_web_allowlisted_site: {
    cooldownDuration: 48,
    maxDisplayCount: 3,
    minAllowlistingDelay: 48 * 60
  },
  after_navigation: {
    cooldownDuration: 1,
    maxDisplayCount: 1
  }
};

/**
 * Whether to send user data as part of telemetry
 * Setting this to true will disable all IPMs
 *
 * @type {boolean}
 */
defaults.data_collection_opt_out = false;

/**
  * @namespace
  * @static
  */
let Prefs = {
  /**
   * Retrieves the given preference.
   *
   * @param {string} preference
   * @return {any}
   */
  get(preference)
  {
    // We need to temporarily force-disable data collection in Firefox, while
    // we're working on improving our data collection opt-out mechanism based
    // on Mozilla's requirements
    // https://gitlab.com/adblockinc/ext/adblockplus/adblockplus/-/issues/1621
    if (
      preference === "data_collection_opt_out" &&
      _src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.application === "firefox"
    )
      return true;

    let result = (preference in overrides ? overrides : defaults)[preference];

    // Object preferences are mutable, so we need to clone them to avoid
    // accidentally modifying the preference when modifying the object
    if (typeof result === "object")
      result = JSON.parse(JSON.stringify(result));

    return result;
  },

  /**
   * Resets the given preference to its default value.
   *
   * @param {string} preference
   * @return {Promise} A promise that resolves when the underlying
                       browser.storage.local.set/remove() operation completes
   */
  reset(preference)
  {
    return Prefs.set(preference, defaults[preference]);
  },

  /**
   * Sets the given preference.
   *
   * @param {string} preference
   * @param {any}    value
   * @return {Promise} A promise that resolves when the underlying
                       browser.storage.local.set/remove() operation completes
   */
  set(preference, value)
  {
    let defaultValue = defaults[preference];

    if (typeof value != typeof defaultValue)
      throw new Error("Attempt to change preference type");

    if (value == defaultValue)
    {
      let oldValue = overrides[preference];
      delete overrides[preference];

      // Firefox 66 fails to emit storage.local.onChanged events for falsey
      // values. https://bugzilla.mozilla.org/show_bug.cgi?id=1541449
      if (!oldValue &&
          _src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.platform == "gecko" && parseInt(_src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.platformVersion, 10) == 66)
        onStorageChanged({[prefToKey(preference)]: {oldValue}}, "local");

      return browser.storage.local.remove(prefToKey(preference));
    }

    overrides[preference] = value;
    return (customSave.get(preference) || savePref)(preference);
  },

  /**
   * Adds a callback that is called when the
   * value of a specified preference changed.
   *
   * @param {string}   preference
   * @param {function} callback
   */
  on(preference, callback)
  {
    eventEmitter.on(preference, callback);
  },

  /**
   * Removes a callback for the specified preference.
   *
   * @param {string}   preference
   * @param {function} callback
   */
  off(preference, callback)
  {
    eventEmitter.off(preference, callback);
  },

  /**
   * Reads the documentation_link preference and substitutes placeholders.
   *
   * @param {string} linkID
   * @return {string}
   */
  getDocLink(linkID)
  {
    return this.documentation_link
      .replace(/%LINK%/g, linkID)
      .replace(/%LANG%/g, browser.i18n.getUILanguage());
  },

  /**
   * A promise that is fullfilled when all preferences have been loaded.
   * Wait for this promise to be fulfilled before using preferences during
   * extension initialization.
   *
   * @type {Promise}
   */
  untilLoaded: null
};

function keyToPref(key)
{
  if (key.indexOf(keyPrefix) != 0)
    return null;

  return key.substr(keyPrefix.length);
}

function prefToKey(pref)
{
  return keyPrefix + pref;
}

function savePref(pref)
{
  return browser.storage.local.set({[prefToKey(pref)]: overrides[pref]});
}

let customSave = new Map();
if (_src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.platform == "gecko" && parseInt(_src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.platformVersion, 10) < 66)
{
  // Saving one storage value causes all others to be saved as well for
  // Firefox versions <66. Make sure that updating ad counter doesn't cause
  // the filters data to be saved frequently as a side-effect.
  let promise = null;
  customSave.set("blocked_total", pref =>
  {
    if (!promise)
    {
      promise = new Promise((resolve, reject) =>
      {
        setTimeout(
          () =>
          {
            promise = null;
            savePref(pref).then(resolve, reject);
          },
          60 * 1000
        );
      });
    }
    return promise;
  });
}

function addPreference(pref)
{
  Object.defineProperty(Prefs, pref, {
    get()
    {
      return Prefs.get(pref);
    },
    set(value)
    {
      Prefs.set(pref, value);
    },
    enumerable: true
  });
}

function onStorageChanged(changes)
{
  for (let key in changes)
  {
    let pref = keyToPref(key);
    if (pref && pref in defaults)
    {
      let change = changes[key];
      if ("newValue" in change && change.newValue != defaults[pref])
        overrides[pref] = change.newValue;
      else
        delete overrides[pref];

      eventEmitter.emit(pref);
    }
  }
}

async function init()
{
  let prefs = Object.keys(defaults);
  prefs.forEach(addPreference);

  let isEdgeChromium = _src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.application == "edge" &&
                       _src_info_background__WEBPACK_IMPORTED_MODULE_3__.info.platform == "chromium";

  // When upgrading from EdgeHTML to Edge Chromium (v79) data stored in
  // browser.storage.local gets corrupted.
  // To fix it, we have to call JSON.parse twice.
  // See: https://gitlab.com/eyeo/adblockplus/adblockpluschrome/issues/152
  if (isEdgeChromium)
  {
    let items = await browser.storage.local.get(null);

    let fixedItems = {};
    for (let key in items)
    {
      if (typeof items[key] == "string")
      {
        try
        {
          fixedItems[key] = JSON.parse(JSON.parse(items[key]));
        }
        catch (e) {}
      }
    }

    await browser.storage.local.set(fixedItems);
  }

  {
    let items = await browser.storage.local.get(prefs.map(prefToKey));
    for (let key in items)
      overrides[keyToPref(key)] = items[key];
  }

  if ("managed" in browser.storage)
  {
    try
    {
      let items = await browser.storage.managed.get(null);
      for (let key in items)
        defaults[key] = items[key];
    }
    catch (e)
    {
      // Opera doesn't support browser.storage.managed, but instead of simply
      // removing the API, it gives an asynchronous error which we ignore here.
    }
  }

  browser.storage.onChanged.addListener(onStorageChanged);

  // EWE 0.8.0 made the notifications API asynchronous, so we need to
  // cache ignored notification categories to continue to be able to
  // get/set the notifications_ignoredcategories preference synchronously
  let ignoredCategories = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.getIgnoredCategories();

  // Initialize notifications_ignoredcategories pseudo preference
  Object.defineProperty(Prefs, "notifications_ignoredcategories", {
    get()
    {
      return ignoredCategories;
    },
    set(value)
    {
      const categories = new Set(ignoredCategories);
      if (value)
        categories.add("*");
      else
        categories.delete("*");
      ignoredCategories = categories;

      void _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.toggleIgnoreCategory("*", !!value);
    },
    enumerable: true
  });

  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.on(
    "ignored-category-added",
    async() =>
    {
      ignoredCategories = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.getIgnoredCategories();
      eventEmitter.emit("notifications_ignoredcategories");
    }
  );
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.on(
    "ignored-category-removed",
    async() =>
    {
      ignoredCategories = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.getIgnoredCategories();
      eventEmitter.emit("notifications_ignoredcategories");
    }
  );
}

Prefs.untilLoaded = init();

/**
 * Returns the value of the given preference key.
 *
 * @event "prefs.get"
 * @property {string} key - The preference key.
 * @returns {string|string[]|number|boolean}
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on("prefs.get", (message, sender) => Prefs[message.key]);

/**
 * Sets the value of the given preference key to the given value.
 *
 * @event "prefs.set"
 * @property {string} key - The preference key.
 * @property {string} value - The value to set.
 * @returns {string|string[]|number|boolean|undefined}
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on(
  "prefs.set",
  async(message, sender) => Prefs[message.key] = message.value
);

/**
 * Toggles the value of the given preference key.
 *
 * @event "prefs.toggle"
 * @property {string} key - The preference key
 * @returns {?boolean}
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on("prefs.toggle", async(message, sender) =>
{
  if (message.key == "notifications_ignoredcategories")
    return _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.toggleIgnoreCategory("*");

  return Prefs[message.key] = !Prefs[message.key];
});

/**
 * Returns a link to a page on our website, in the user's locale if possible.
 *
 * @event "prefs.getDocLink"
 * @property {string} link
 *   The link ID to generate the doc link for.
 * @returns {string}
 */
_messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on("prefs.getDocLink", (message, sender) =>
{
  let {application, platform} = _src_info_background__WEBPACK_IMPORTED_MODULE_3__.info;
  if (platform == "chromium" && application != "opera" && application != "edge")
    application = "chrome";
  else if (platform == "gecko")
    application = "firefox";

  return Prefs.getDocLink(message.link.replace("{browser}", application));
});

(0,_messaging_events_js__WEBPACK_IMPORTED_MODULE_1__/* .installHandler */ .a)("prefs", null, (emit, action) =>
{
  const onChanged = () => emit(Prefs[action]);
  Prefs.on(action, onChanged);
  return () => Prefs.off(action, onChanged);
});


/***/ }),

/***/ 774:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Stats": () => (/* binding */ Stats),
/* harmony export */   "getBlockedPerPage": () => (/* binding */ getBlockedPerPage),
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(120);
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _messaging_events_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(370);
/* harmony import */ var _messaging_port_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(305);
/* harmony import */ var _storage_tab_session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(658);
/* harmony import */ var _browserAction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(820);
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(491);
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(968);
/* harmony import */ var _src_core_scheduled_event_emitter_background_scheduled_event_emitter_ts__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(621);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module stats */











const badgeColor = "#646464";
const badgeRefreshRate = 4;
const badgeUpdateTopic = "stats.badgeUpdate";

let eventEmitter = new _events_js__WEBPACK_IMPORTED_MODULE_7__/* .EventEmitter */ .v();
let blockedPerPage = new _storage_tab_session_js__WEBPACK_IMPORTED_MODULE_3__/* .TabSessionStorage */ .H("stats:blocked");

/**
 * Gets the number of requests blocked on the given page.
 *
 * @param  {Page} page
 * @return {Number}
 */
async function getBlockedPerPage(page)
{
  return (await blockedPerPage.get(page.id)) || 0;
}

let activeTabIds = new Set();
let activeTabIdByWindowId = new Map();

let badgeUpdateScheduled = false;

async function updateBadge(tabId)
{
  if (!_prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.show_statsinicon)
    return;

  for (let id of (typeof tabId == "undefined" ? activeTabIds : [tabId]))
  {
    let blockedCount = await blockedPerPage.get(id);

    (0,_browserAction_js__WEBPACK_IMPORTED_MODULE_4__/* .setBadge */ .q_)(id, blockedCount && {
      color: badgeColor,
      number: blockedCount
    });
  }
}

function scheduleBadgeUpdate(tabId)
{
  if (!badgeUpdateScheduled && _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.show_statsinicon &&
      (typeof tabId == "undefined" || activeTabIds.has(tabId)))
  {
    _src_core_scheduled_event_emitter_background_scheduled_event_emitter_ts__WEBPACK_IMPORTED_MODULE_6__.setSchedule(
      badgeUpdateTopic,
      1000 / badgeRefreshRate
    );
    badgeUpdateScheduled = true;
  }
}

async function onBlockableItem({filter, request})
{
  if (!filter || filter.type != "blocking")
    return;

  let {tabId} = request;

  await blockedPerPage.transaction(async() =>
  {
    let blocked = await blockedPerPage.get(tabId) || 0;
    ++blocked;

    await blockedPerPage.set(tabId, blocked);
    scheduleBadgeUpdate(tabId);

    eventEmitter.emit("blocked_per_page", {tabId, blocked});
  });

  // Don't update the total for incognito tabs.
  let tab = await browser.tabs.get(tabId);
  if (tab.incognito)
    return;

  // Make sure blocked_total is only read after the storage was loaded.
  await _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.untilLoaded;

  _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.blocked_total++;
  eventEmitter.emit("blocked_total", _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.blocked_total);
}

/**
  * @namespace
  * @static
  */
let Stats = {
  /**
   * Adds a callback that is called when the
   * value of a specified stat changed.
   *
   * @param {string}   stat
   * @param {function} callback
   */
  on(stat, callback)
  {
    eventEmitter.on(stat, callback);
  },

  /**
   * Removes a callback for the specified stat.
   *
   * @param {string}   stat
   * @param {function} callback
   */
  off(stat, callback)
  {
    eventEmitter.off(stat, callback);
  },

  /**
   * The total number of blocked requests on non-incognito pages.
   *
   * @type {number}
   */
  get blocked_total()
  {
    return _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.blocked_total;
  }
};

function start()
{
  _src_core_scheduled_event_emitter_background_scheduled_event_emitter_ts__WEBPACK_IMPORTED_MODULE_6__.setListener(badgeUpdateTopic, async() =>
  {
    badgeUpdateScheduled = false;
    await updateBadge();
  });

  // Once nagivation for the tab has been committed to (e.g. it's no longer
  // being prerendered) we clear its badge, or if some requests were already
  // blocked beforehand we display those on the badge now.
  browser.webNavigation.onCommitted.addListener(async details =>
  {
    if (details.frameId == 0)
      await updateBadge(details.tabId);
  });


  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.reporting.onBlockableItem.addListener(onBlockableItem);


  _prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.on("show_statsinicon", async() =>
  {
    let tabs = await browser.tabs.query({});
    for (let tab of tabs)
    {
      if (_prefs_js__WEBPACK_IMPORTED_MODULE_5__.Prefs.show_statsinicon)
        await updateBadge(tab.id);
      else
        (0,_browserAction_js__WEBPACK_IMPORTED_MODULE_4__/* .setBadge */ .q_)(tab.id, null);
    }
  });

  /**
 * Returns the number of blocked requests for the sender's page.
 *
 * @event "stats.getBlockedPerPage"
 * @returns {number}
 */
  _messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on("stats.getBlockedPerPage",
          message => getBlockedPerPage(new ext.Page(message.tab)));

  /**
* Returns the total number of blocked requests on non-incognito pages.
*
* @event "stats.getBlockedTotal"
* @returns {number}
*/
  _messaging_port_js__WEBPACK_IMPORTED_MODULE_2__.port.on("stats.getBlockedTotal", () => Stats.blocked_total);

  browser.tabs.query({active: true}).then(tabs =>
  {
    for (let tab of tabs)
    {
      activeTabIds.add(tab.id);
      activeTabIdByWindowId.set(tab.windowId, tab.id);
    }

    scheduleBadgeUpdate();
  });

  (0,_messaging_events_js__WEBPACK_IMPORTED_MODULE_1__/* .installHandler */ .a)("stats", null, (emit, action) =>
  {
    const onChanged = info => emit(info);
    Stats.on(action, onChanged);
    return () => Stats.off(action, onChanged);
  });

  browser.tabs.onActivated.addListener(tab =>
  {
    let lastActiveTabId = activeTabIdByWindowId.get(tab.windowId);
    if (typeof lastActiveTabId != "undefined")
      activeTabIds.delete(lastActiveTabId);

    activeTabIds.add(tab.tabId);
    activeTabIdByWindowId.set(tab.windowId, tab.tabId);

    scheduleBadgeUpdate();
  });

  if ("windows" in browser)
  {
    browser.windows.onRemoved.addListener(windowId =>
    {
      activeTabIds.delete(activeTabIdByWindowId.get(windowId));
      activeTabIdByWindowId.delete(windowId);
    });
  }
}


/***/ }),

/***/ 137:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "SessionStorage": () => (/* binding */ SessionStorage)
/* harmony export */ });
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * In-memory storage for use outside of service worker context.
 * @type {Map<string,any>}
 */
const memoryStorage = new Map();

/**
 * Indicates whether we need to store in-memory data using a dedicated browser
 * API. When we're running in the context of a service worker, we can no longer
 * rely on in-memory storage.
 * @type {boolean}
 */
const useMemoryStorage = !("session" in browser.storage);

/**
 * Session storage for storing in-memory data in a way that's safe to use in
 * a service worker context.
 */
class SessionStorage
{
  /**
   * Initializes session storage.
   * @param {string} namespace
   */
  constructor(namespace)
  {
    this._namespace = namespace;
    this._queue = Promise.resolve();
  }

  /**
   * Generates unique storage key for storing values globally for given key.
   * @param {string} key
   * @return {string}
   */
  _getGlobalKey(key)
  {
    return `session:${this._namespace}:${key}`;
  }

  /**
   * Deletes session storage entry for given key.
   * @param {string} key
   * @return {Promise}
   */
  async delete(key)
  {
    const globalKey = this._getGlobalKey(key);
    if (useMemoryStorage)
      return memoryStorage.delete(globalKey);

    return browser.storage.session.remove(globalKey);
  }

  /**
   * Retrieves session storage entry for given key.
   * @param {string} key
   * @return {Promise<any>}
   */
  async get(key)
  {
    const globalKey = this._getGlobalKey(key);
    if (useMemoryStorage)
      return memoryStorage.get(globalKey);

    const storage = await browser.storage.session.get(globalKey);
    return storage[globalKey];
  }

  /**
   * Sets session storage entry for given key.
   * @param {string} key
   * @param {any} value
   * @return {Promise}
   */
  async set(key, value)
  {
    const globalKey = this._getGlobalKey(key);
    if (useMemoryStorage)
    {
      memoryStorage.set(globalKey, value);
      return;
    }

    await browser.storage.session.set({[globalKey]: value});
  }

  /**
   * Executes given function as a transaction to avoid race conditions.
   * @param {Function} fn
   * @return {Promise}
   */
  async transaction(fn)
  {
    this._queue = this._queue
      // Necessary to avoid breakage of promise chain
      .catch(console.error)
      .then(fn);
    return this._queue;
  }
}


/***/ }),

/***/ 658:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "B": () => (/* binding */ start),
/* harmony export */   "H": () => (/* binding */ TabSessionStorage)
/* harmony export */ });
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);
/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(137);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */




/**
 * Session storage instance for storing tab-specific data.
 * @type {SessionStorage<number,any>}
 */
const sessionByTabId = new _session_js__WEBPACK_IMPORTED_MODULE_0__.SessionStorage("_tabs");

// We need to keep track of all tab session storage instances so that we can
// notify them about tab changes. Since we cannot iterate through a WeakSet,
// and since WeakRef is not yet available in all supported browsers, this means
// that we're adding them into memory without removing them. As long as we only
// create instances only right when the extension loads, this should not create
// a memory leak though.
/**
 * List of known tab session storage instances.
 * @type {Set<TabSessionStorage>}
 */
const tabStorages = new Set();

/**
 * Session storage for storing tab-specific in-memory data in a way that's safe
 * to use in a service worker context.
 */
class TabSessionStorage extends _events_js__WEBPACK_IMPORTED_MODULE_1__/* .EventEmitter */ .v
{
  /**
   * Initializes session storage.
   * @param {string} namespace
   */
  constructor(namespace)
  {
    super();

    this._namespace = namespace;
    this._queue = Promise.resolve();
    tabStorages.add(this);
  }

  /**
   * Deletes session storage content specific to given tab ID.
   * @param {number} tabId
   * @return {Promise}
   */
  async delete(tabId)
  {
    return sessionByTabId.transaction(async() =>
    {
      const session = await sessionByTabId.get(tabId);
      if (!session)
        return;

      delete session[this._namespace];

      if (Object.keys(session).length)
        await sessionByTabId.set(tabId, session);
      else
        await sessionByTabId.delete(tabId);
    });
  }

  /**
   * Emits session storage event relating to given tab ID.
   * @param {string} name
   * @param {number} tabId
   */
  async emit(name, tabId)
  {
    const session = await sessionByTabId.get(tabId);
    if (!session)
      return;

    super.emit(name, {
      tabId,
      value: session[this._namespace]
    });
  }

  /**
   * Retrieves session storage content specific to given tab ID.
   * @param {number} tabId
   * @return {Promise<any>}
   */
  async get(tabId)
  {
    const session = await sessionByTabId.get(tabId);
    if (!session)
      return;

    return session[this._namespace];
  }

  /**
   * Indicates whether session storage content exists specific to given tab ID.
   * @param {number} tabId
   * @return {Promise<boolean>}
   */
  async has(tabId)
  {
    const session = await sessionByTabId.get(tabId);
    return session && this._namespace in session;
  }

  /**
   * Sets session storage content specific to given tab ID.
   * @param {number} tabId
   * @param {any} value
   * @return {Promise}
   */
  async set(tabId, value)
  {
    return sessionByTabId.transaction(async() =>
    {
      const session = (await sessionByTabId.get(tabId)) || {};
      session[this._namespace] = value;
      await sessionByTabId.set(tabId, session);
    });
  }

  /**
   * Executes given function as a transaction to avoid race conditions.
   * @param {Function} fn
   * @return {Promise}
   */
  async transaction(fn)
  {
    this._queue = this._queue
      // Necessary to avoid breakage of promise chain
      .catch(console.error)
      .then(fn);
    return this._queue;
  }
}

/**
 * Clears tab-specific data.
 * @param {number} tabId
 * @return {Promise}
 */
async function clearStorage(tabId)
{
  // Provide stored data to listeners before removing it
  const session = await sessionByTabId.get(tabId);
  if (session)
  {
    for (const tabStorage of tabStorages)
      await tabStorage.emit("tab-removed", tabId);
  }

  await sessionByTabId.delete(tabId);
}

/**
 * Initializes tab-specific session storage.
 */
function start()
{
  // Clear tab-specific data when the tab's content changes
  ext.pages.onLoading.addListener(page =>
  {
    void clearStorage(page.id);
  });

  // Clear tab-specific data when the tab gets removed
  ext.pages.onRemoved.addListener(tabId =>
  {
    void clearStorage(tabId);
  });
}


/***/ }),

/***/ 821:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "isDataCorrupted": () => (/* binding */ isDataCorrupted),
  "setNotifyUserCallback": () => (/* binding */ setNotifyUserCallback),
  "start": () => (/* binding */ subscriptionInit_start)
});

;// CONCATENATED MODULE: ./node_modules/@adblockinc/rules/dist/index/adblockplus.json
const adblockplus_namespaceObject = JSON.parse('[{"id":"684A25C6-6B5D-458A-8A2B-BAC0A12B0B15","type":"ads","languages":["ar"],"title":"Liste AR+Liste FR+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=98","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","8D421590-1A68-4B68-BE50-04E17C09460E","3D60E303-1141-4775-B800-834177922876"],"url":"https://easylist-downloads.adblockplus.org/v3/full/liste_ar+liste_fr+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/liste_ar+liste_fr+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/liste_ar+liste_fr+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (fréquence des mises à jour automatiques)"},{"id":"25A31255-AB36-48A4-9086-06192DE71119","type":"ads","languages":["bn","gu","hi","pa","as","mr","ml","te","kn","or","ne","si"],"title":"IndianList+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","9FAA2906-CD5C-4520-BDC4-4E098B7EA228"],"url":"https://easylist-downloads.adblockplus.org/v3/full/indianlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/indianlist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/indianlist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"E22C3B40-DC90-49D7-8BF5-E60904AB159A","type":"ads","languages":["bg"],"title":"Bulgarian list+EasyList","homepage":"https://stanev.org/abp/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","1638B159-F64A-4307-84E7-16AB08ED409E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/bulgarian_list+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/bulgarian_list+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/bulgarian_list+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"EF6F4884-47DB-46A5-AAF8-8EB819D8D4D8","type":"ads","languages":["th","el","sl","hr","sr","bs"],"title":"Global Filters+EasyList","homepage":"https://gitlab.com/eyeo/filterlists/globalfilters","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","02F537E7-0B47-4DBA-BFFA-AE4182E4C31C"],"url":"https://easylist-downloads.adblockplus.org/v3/full/global-filters+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/global-filters+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/global-filters+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"4B6CE485-30AB-4213-AD17-504B3F2D2825","type":"ads","languages":["cs","sk"],"title":"EasyList Czech and Slovak+EasyList","homepage":"https://adblock.sk/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","2D8C4D88-34A0-4259-9098-30D28BA674BC"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistczechslovak+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistczechslovak+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistczechslovak+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"96932CD9-6DDF-4D97-B92F-FDF747B6FAA2","type":"ads","languages":["no","nb","nn","da","is","fo","kl","sv","fi"],"title":"Dandelion Sprout\'s Nordic Filters+EasyList","homepage":"https://github.com/DandelionSprout/adfilt","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","6D489E8D-E61C-444C-BBC5-44741773ADC2"],"url":"https://easylist-downloads.adblockplus.org/v3/full/dandelion_sprouts_nordic_filters+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/dandelion_sprouts_nordic_filters+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/dandelion_sprouts_nordic_filters+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"0CD3D105-D3B3-4652-8489-94163DE9A08F","type":"ads","languages":["de"],"title":"EasyList Germany+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","4337FB2B-A95C-44D5-B78D-11AD40F7711B"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistgermany+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistgermany+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistgermany+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"8C13E995-8F06-4927-BEA7-6C845FB7EEBF","type":"ads","languages":["en"],"title":"EasyList","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"C3D13A19-3E8D-41F5-AD64-0F3B36DDE128","type":"ads","languages":["es"],"title":"EasyList Spanish+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","C8C1AA76-15B4-4CA3-8A9C-AD38D6AFCAEC"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistspanish+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistspanish+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistspanish+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"2CEA1481-C29C-44F1-A084-A2A019533797","type":"ads","languages":["fr"],"title":"Liste FR+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=98","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","8D421590-1A68-4B68-BE50-04E17C09460E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/liste_fr+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/liste_fr+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/liste_fr+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"07549D8B-F06F-4D9D-A567-929AA59E9D1D","type":"ads","languages":["he"],"title":"EasyList Hebrew+EasyList","homepage":"https://github.com/easylist/EasyListHebrew","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","AE0D9320-665E-407D-B692-1A85AE481F34"],"url":"https://easylist-downloads.adblockplus.org/v3/full/israellist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/israellist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/israellist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"88D3F7EA-D99E-43C6-92E0-D89C8A0E7EA9","type":"ads","languages":["hu"],"title":"Hufilter Basic+EasyList","homepage":"https://github.com/hufilter/hufilter/wiki","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","EFA20F90-0490-46A4-B105-BD173F7950AA"],"url":"https://easylist-downloads.adblockplus.org/v3/full/hufilter+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/hufilter+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/hufilter+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"B7D76369-DD19-4602-80E8-2E32DDB490AC","type":"ads","languages":["id","ms"],"title":"ABPindo+EasyList","homepage":"http://abpindo.blogspot.com/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","A4A32212-E6BD-45F6-AD0F-E0FD18E8537B"],"url":"https://easylist-downloads.adblockplus.org/v3/full/abpindo+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abpindo+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/abpindo+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"BBC07C05-66F1-42EC-BD4D-7AD495FAC84B","type":"ads","languages":["it"],"title":"EasyList Italy+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","2F0A4F0D-DF16-40D0-B0E0-5EB6791EC119"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistitaly+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistitaly+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistitaly+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"361001BD-8F57-4736-97B1-F332C3D79E5D","type":"ads","languages":["ja"],"title":"Japanese Filters+EasyList","homepage":"https://gitlab.com/eyeo/filterlists/japanesefilters","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","7FCD16F0-6505-4A59-90CD-B49849481B0B"],"url":"https://easylist-downloads.adblockplus.org/v3/full/japanese-filters+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/japanese-filters+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/japanese-filters+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"2708BCB7-2E45-41BC-B517-1730CF532F89","type":"ads","languages":["ko"],"title":"KoreanList+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","BCE2062F-0D99-4861-A1F7-E3DFEA6DAB69"],"url":"https://easylist-downloads.adblockplus.org/v3/full/koreanlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/koreanlist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/koreanlist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"CBE50FA2-DE3F-480C-B1D7-04289391C033","type":"ads","languages":["lt"],"title":"EasyList Lithuania+EasyList","homepage":"https://github.com/EasyList-Lithuania/easylist_lithuania","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","E89B3C08-2DED-40EA-8EE1-339B90D7B451"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistlithuania+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistlithuania+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistlithuania+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"950C88EA-2DD1-42E3-B2A2-2DF2ED15563A","type":"ads","languages":["lv"],"title":"Latvian List+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=99-latvian-list","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","51893C6C-F39E-43C5-A2EF-9545E388A2CE"],"url":"https://easylist-downloads.adblockplus.org/v3/full/latvianlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/latvianlist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/latvianlist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"A4B88FB6-E5E5-417F-8A49-20B8244995FD","type":"ads","languages":["nl"],"title":"EasyList Dutch+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","CB94E27D-6CD1-4DB9-83D9-6B7F1A3555F6"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistdutch+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistdutch+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistdutch+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"3D2C09D0-DF1C-4C8E-9947-A23DCEAF8F8B","type":"ads","languages":["pl"],"title":"EasyList Polish+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","9F743FCD-801B-41D0-830F-5A4EA995216E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistpolish+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistpolish+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistpolish+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"14DF7BE6-9675-4E07-987A-D8A1000F9FEF","type":"ads","languages":["pt"],"title":"EasyList Portuguese+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","A41441EE-BF7C-4A48-9A43-42CCEA2B2A1D"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistportuguese+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistportuguese+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistportuguese+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"EEEF75EC-B2B4-49F4-BC49-17B08266F334","type":"ads","languages":["ro"],"title":"ROList+EasyList","homepage":"https://zoso.ro/rolist/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","99166908-5FDA-4F9E-8C4C-70BB4DEEFC08"],"url":"https://easylist-downloads.adblockplus.org/v3/full/rolist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/rolist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/rolist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"1B5F78CA-8B30-4BDF-B0A3-451CB2202984","type":"ads","languages":["ru","uk","uz","kk"],"title":"RU, UA, UZ, KZ+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=102","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","879ECB9D-8935-4506-939E-5BBB7DD09402"],"url":"https://easylist-downloads.adblockplus.org/v3/full/ruadlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/ruadlist+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/ruadlist+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"D99D3350-7F11-43E1-87CB-FDE0C78E8CD6","type":"ads","languages":["tr"],"title":"Turkish Filters+EasyList","homepage":"https://gitlab.com/eyeo/filterlists/turkishfilters","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","C5238877-8B59-4CC5-AE7F-F8714A5452D1"],"url":"https://easylist-downloads.adblockplus.org/v3/full/turkish-filters+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/turkish-filters+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/turkish-filters+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"1C571EC7-6E52-47CC-B04A-4B3008D0AEBE","type":"ads","languages":["vi"],"title":"ABPVN List+EasyList","homepage":"http://abpvn.com/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","03648752-31EE-4FD0-85C1-20B07C5551C3"],"url":"https://easylist-downloads.adblockplus.org/v3/full/abpvn+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abpvn+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/abpvn+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"9BD3EA2F-889D-4CC3-B680-CF484F2BD1B9","type":"ads","languages":["zh"],"title":"EasyList China+EasyList","homepage":"https://github.com/easylist/easylistchina/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","1D7F590C-B752-4BA0-9473-6A26DE1326B1"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistchina+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easylistchina+easylist/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"0798B6A2-94A4-4ADF-89ED-BEC112FC4C7F","type":"allowing","title":"Allow nonintrusive advertising","homepage":"https://acceptableads.com/","url":"https://easylist-downloads.adblockplus.org/v3/full/exceptionrules.txt","mv2_url":"https://easylist-downloads.adblockplus.org/exceptionrules.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/exceptionrules/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days"},{"id":"F12E0801-A00B-49DE-B1E3-52C9C4F90C8C","type":"allowing","title":"Allow nonintrusive advertising without third-party tracking","homepage":"https://acceptableads.com/","url":"https://easylist-downloads.adblockplus.org/v3/full/exceptionrules-privacy-friendly.txt","mv2_url":"https://easylist-downloads.adblockplus.org/exceptionrules-privacy-friendly.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/exceptionrules-privacy-friendly/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days"},{"id":"CDAD4CF5-2706-42CB-B404-F5B9B61B8CAA","type":"annoyances","title":"Premium - Distraction Control","includes":["D5561090-9ADB-4EEE-AA81-101B645D9F4F","8E2D687A-3B44-46E1-BE68-2FE5441A788E","3B85CD3F-553A-45D1-AA38-6288E1C4C7B9","1E7A240E-CD85-493D-BEEF-C68A6AEA1225"],"url":"https://easylist-downloads.adblockplus.org/v3/full/adblock_premium.txt","mv2_url":"https://easylist-downloads.adblockplus.org/adblock_premium.txt","privileged":true,"diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/adblock_premium/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"D4028CDD-3D39-4624-ACC7-8140F4EC3238","type":"circumvention","title":"ABP filters","homepage":"https://github.com/abp-filters/abp-filters-anti-cv","url":"https://easylist-downloads.adblockplus.org/v3/full/abp-filters-anti-cv.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abp-filters-anti-cv.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/abp-filters-anti-cv/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 hours (update frequency)"},{"id":"2090F374-29D9-4202-B2CE-139D6492D95E","type":"cookies","title":"I don\'t care about cookies","homepage":"https://www.i-dont-care-about-cookies.eu/","url":"https://easylist-downloads.adblockplus.org/v3/full/i_dont_care_about_cookies.txt","mv2_url":"https://easylist-downloads.adblockplus.org/i_dont_care_about_cookies.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/i_dont_care_about_cookies/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"588470E8-E163-4CD9-A909-521B2A3BE73F","type":"cookies-premium","title":"Premium - Block cookie consent pop-ups","url":"https://easylist-downloads.adblockplus.org/v3/full/cookie-filter-list.txt","mv2_url":"https://easylist-downloads.adblockplus.org/cookie-filter-list.txt","privileged":true,"diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/cookie-filter-list/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"5BD2BB73-459D-4A74-AF9D-A10157268350","type":"notifications","title":"Fanboy\'s Notifications Blocking List","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/fanboy-notifications.txt","mv2_url":"https://easylist-downloads.adblockplus.org/fanboy-notifications.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/fanboy-notifications/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"D72B6F06-52B2-4FED-96A2-1BF59CDD7AEC","type":"privacy","title":"EasyPrivacy","homepage":"https://easylist.to/","requires":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easyprivacy.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easyprivacy.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/easyprivacy/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"},{"id":"0A679439-445F-4DE7-84B9-88341F6DA520","type":"social","title":"Fanboy\'s Social Blocking List","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/fanboy-social.txt","mv2_url":"https://easylist-downloads.adblockplus.org/fanboy-social.txt","diff_url":"https://easylist-downloads.adblockplus.org/v3/diff/fanboy-social/b9294f90a42df444a3476ebe51317dacb065431f.json","expires":"1 days (update frequency)"}]');
// EXTERNAL MODULE: ./node_modules/@eyeo/webext-ad-filtering-solution/dist/ewe-api.js
var ewe_api = __webpack_require__(120);
// EXTERNAL MODULE: ./src/ipm/background/index.ts + 3 modules
var background = __webpack_require__(386);
// EXTERNAL MODULE: ./src/premium/background/index.ts + 1 modules
var premium_background = __webpack_require__(282);
// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
;// CONCATENATED MODULE: ./src/options/background/link-to-options.ts

function startOptionLinkListener() {
    const trustedOrigins = prefs.Prefs.get("options_backlink_trusted_origins");
    if (!Array.isArray(trustedOrigins)) {
        return;
    }
    trustedOrigins.forEach((trustedOrigin) => {
        ext.addTrustedMessageTypes(trustedOrigin, ["options.open"]);
    });
}

;// CONCATENATED MODULE: ./src/options/background/index.ts


// EXTERNAL MODULE: ./src/info/background/index.ts + 1 modules
var info_background = __webpack_require__(463);
// EXTERNAL MODULE: ./src/testing/ready-state/background/index.ts + 2 modules
var ready_state_background = __webpack_require__(351);
// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/port.js
var port = __webpack_require__(305);
// EXTERNAL MODULE: ./adblockpluschrome/lib/allowlisting.js
var allowlisting = __webpack_require__(320);
// EXTERNAL MODULE: ./adblockpluschrome/lib/filterConfiguration.js + 1 modules
var filterConfiguration = __webpack_require__(311);
// EXTERNAL MODULE: ./lib/notifications.js
var notifications = __webpack_require__(954);
// EXTERNAL MODULE: ./lib/pages/options.js
var options = __webpack_require__(262);
// EXTERNAL MODULE: ./adblockpluschrome/lib/storage/session.js
var session = __webpack_require__(137);
// EXTERNAL MODULE: ./adblockpluschrome/lib/storage/tab-session.js
var tab_session = __webpack_require__(658);
// EXTERNAL MODULE: ./adblockpluschrome/lib/browserAction.js
var browserAction = __webpack_require__(820);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/icon.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module icon */






const ANIMATION_LOOPS = 3;
const FRAME_IN_MS = 100;

let frameOpacities = calculateFrameOpacities(9, 7);
let frameOpacitiesCritical = calculateFrameOpacities(5, 3);

let stopRequested = false;
let canUpdateIcon = true;
let notRunning = Promise.resolve();
let allowlistedState = new tab_session/* TabSessionStorage */.H("icon:allowlistedState");

let icons = [null, null];

function easeOut(progress)
{
  // This is merely an approximation to the built-in ease-out timing function
  // https://css-tricks.com/emulating-css-timing-functions-javascript/
  return 1 - Math.pow(1 - progress, 1.675);
}

function calculateFrameOpacities(keyframeFrames, transitionFrames)
{
  let opacities = [];

  // Show second half of first keyframe
  // Omit first frame because it's only shown after the first timeout
  for (let i = 0; i < keyframeFrames / 2 - 1; i++)
    opacities.push(0);
  // Transition from first to second keyframe
  for (let i = 0; i < transitionFrames; i++)
    opacities.push(easeOut((i + 1) / (transitionFrames + 1)));
  // Show second keyframe
  for (let i = 0; i < keyframeFrames; i++)
    opacities.push(1);
  // Transition from second to first keyframe
  for (let i = 0; i < transitionFrames; i++)
    opacities.push(easeOut((transitionFrames - i) / (transitionFrames + 1)));
  // Show first half of first keyframe
  // Omit last frame due to an additional timeout that resets the icon
  for (let i = 0; i < keyframeFrames / 2 - 1; i++)
    opacities.push(0);

  return opacities;
}

async function loadImage(url)
{
  let response = await fetch(url);
  let blob = await response.blob();
  return createImageBitmap(blob);
}

async function renderIcons()
{
  let paths = [
    "icons/abp-16.png", "icons/abp-16-allowlisted.png",
    "icons/abp-32.png", "icons/abp-32-allowlisted.png"
  ];

  for (let path of paths)
  {
    let image = await loadImage(path);
    let [, size, allowlisted] = /\/abp-(16|32)(-allowlisted)?\./.exec(path);

    let canvas = new OffscreenCanvas(size, size);
    let context = canvas.getContext("2d");
    let imageData = icons[!!allowlisted | 0] || {};

    context.globalAlpha = 1;
    context.drawImage(image, 0, 0);
    imageData[size] = context.getImageData(0, 0, size, size);

    icons[!!allowlisted | 0] = imageData;
  }
}

async function setIcon(page, opacity, frames)
{
  opacity = opacity || 0;
  let allowlisted = !!(await allowlistedState.get(page.id));

  if (!frames)
  {
    if (opacity > 0.5)
    {
      (0,browserAction/* setIconPath */.c4)(
        page.id,
        "/icons/abp-$size-notification.png"
      );
    }
    else if (icons[allowlisted | 0])
    {
      (0,browserAction/* setIconImageData */.k8)(page.id, icons[allowlisted | 0]);
    }
    else
    {
      (0,browserAction/* setIconPath */.c4)(
        page.id,
        "/icons/abp-$size" + (allowlisted ? "-allowlisted" : "") + ".png"
      );
    }
  }
  else
  {
    browser.action.setIcon({
      tabId: page.id,
      imageData: frames["" + opacity + allowlisted]
    });
  }
}

allowlisting/* allowlistingState.addListener */._o.addListener("changed", (page, isAllowlisted) =>
{
  void allowlistedState.transaction(async() =>
  {
    const wasAllowlisted = await allowlistedState.get(page.id);
    if (wasAllowlisted === isAllowlisted)
      return;

    await allowlistedState.set(page.id, isAllowlisted);
    if (canUpdateIcon)
      await setIcon(page);
  });
});

async function renderFrames(opacities)
{
  let images = await Promise.all([
    loadImage("icons/abp-16.png"),
    loadImage("icons/abp-16-allowlisted.png"),
    loadImage("icons/abp-16-notification.png"),
    loadImage("icons/abp-20.png"),
    loadImage("icons/abp-20-allowlisted.png"),
    loadImage("icons/abp-20-notification.png"),
    loadImage("icons/abp-32.png"),
    loadImage("icons/abp-32-allowlisted.png"),
    loadImage("icons/abp-32-notification.png"),
    loadImage("icons/abp-40.png"),
    loadImage("icons/abp-40-allowlisted.png"),
    loadImage("icons/abp-40-notification.png")
  ]);

  opacities = new Set(opacities);
  let imageMap = {
    16: {base: [images[0], images[1]], overlay: images[2]},
    20: {base: [images[3], images[4]], overlay: images[5]},
    32: {base: [images[6], images[7]], overlay: images[8]},
    40: {base: [images[9], images[10]], overlay: images[11]}
  };

  let frames = {};
  let canvas = new OffscreenCanvas(0, 0);
  let context = canvas.getContext("2d");

  for (let allowlisted of [false, true])
  {
    for (let opacity of opacities)
    {
      let imageData = {};
      let sizes = [16, 20, 32, 40];
      for (let size of sizes)
      {
        canvas.width = size;
        canvas.height = size;
        context.globalAlpha = 1;
        context.drawImage(imageMap[size]["base"][allowlisted | 0], 0, 0);
        context.globalAlpha = opacity;
        context.drawImage(imageMap[size]["overlay"], 0, 0);
        imageData[size] = context.getImageData(0, 0, size, size);
      }
      frames["" + opacity + allowlisted] = imageData;
    }
  }

  return frames;
}

async function animateIcon(opacities, frames)
{
  let tabs = await browser.tabs.query({active: true});
  let pages = tabs.map(tab => new ext.Page(tab));

  let animationLoop = 0;
  let animationStep = 0;
  let numberOfFrames = opacities.length;
  let opacity = 0;

  let onActivated = async page =>
  {
    pages.push(page);
    await setIcon(page, opacity, frames);
    (0,browserAction/* toggleBadge */.qp)(page.id, true);
  };
  ext.pages.onActivated.addListener(onActivated);

  canUpdateIcon = false;
  for (let page of pages)
    (0,browserAction/* toggleBadge */.qp)(page.id, true);
  return new Promise((resolve, reject) =>
  {
    let interval = setInterval(async() =>
    {
      let oldOpacity = opacity;
      opacity = opacities[animationStep++];

      if (opacity != oldOpacity)
      {
        for (let page of pages)
        {
          if (await allowlistedState.has(page.id))
            await setIcon(page, opacity, frames);
        }
      }

      if (animationStep > numberOfFrames)
      {
        if (++animationLoop > ANIMATION_LOOPS - 1 || stopRequested)
        {
          clearInterval(interval);
          ext.pages.onActivated.removeListener(onActivated);
          for (let page of pages)
            (0,browserAction/* toggleBadge */.qp)(page.id, false);
          canUpdateIcon = true;
          resolve();
        }
        else
        {
          animationStep = 0;
        }
      }
    }, FRAME_IN_MS);
  });
}

/**
 * Stops to animate the browser action icon
 * after the current interval has been finished.
 *
 * @return {Promise} A promise that is fullfilled when
 *                   the icon animation has been stopped.
 */
async function stopIconAnimation()
{
  stopRequested = true;
  await notRunning;
  stopRequested = false;
}

/**
 * Starts to animate the browser action icon to indicate a pending notifcation.
 * If the icon is already animated, it replaces the previous
 * animation as soon as the current interval has been finished.
 *
 * @param {string} type  The notification type (i.e: "information" or
 *                       "critical".)
 */
function startIconAnimation(type)
{
  let opacities = frameOpacities;
  if (type == "critical")
    opacities = frameOpacitiesCritical;

  notRunning = Promise.all([renderFrames(opacities), stopIconAnimation()])
    .then(results =>
    {
      if (stopRequested)
        return;

      let frames = results[0];
      return animateIcon(opacities, frames);
    });
}


// Pre-render icons on Chromium (#7253).
if (info_background.info.platform == "chromium")
  renderIcons();

// EXTERNAL MODULE: ./adblockpluschrome/lib/stats.js
var stats = __webpack_require__(774);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/notificationHelper.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module notificationHelper */














/**
 * The active notification is (if any) the most recent currently displayed
 * notification. Once a notification is clicked or is superseded by another
 * notification we no longer consider it active.
 *
 * @typedef {Object} ActiveNotification
 */

/**
 * Key to store/retrieve the [active notification]{@link ActiveNotification}
 */
const activeNotificationKey = "activeNotification";

/**
 * When a notification button is clicked we need to look up what should
 * happen. This can be both for the active notification, and also for
 * notifications stashed in the notification center.
 *
 * @typedef {Object[]} NotificationButtons
 */

/**
 * Gets the key to store/retrieve the [buttons]{@link NotificationButtons} for
 * the notification with the given ID.
 *
 * @param {string} notificationId - Notification ID
 * @returns {string} Key for storing/retrieving notification buttons
 */
const getButtonsKey = notificationId => `buttons:${notificationId}`;

const notificationHelper_session = new session.SessionStorage("notificationHelper");

/**
 * Maps notification types to display methods.
 */
const displayMethods = new Map([
  ["critical", ["icon", "notification", "popup"]],
  ["newtab", ["newtab"]],
  ["normal", ["notification"]],
  ["relentless", ["notification"]],
  ["information", ["icon", "popup"]]
]);
const defaultDisplayMethods = ["popup"];

const linkPlaceholders = [
  ["LANG", () => browser.i18n.getUILanguage().replace("-", "_")],
  ["ADDON_NAME", () => info_background.info.addonName],
  ["ADDON_VERSION", () => info_background.info.addonVersion],
  ["APPLICATION_NAME", () => info_background.info.application],
  ["APPLICATION_VERSION", () => info_background.info.applicationVersion],
  ["PLATFORM_NAME", () => info_background.info.platform],
  ["PLATFORM_VERSION", () => info_background.info.platformVersion]
];

// We must hard code any "abp:" prefixed notification links here, otherwise
// notifications linking to them will not be displayed at all.
const localNotificationPages = new Map([
  ["abp:day1", "/day1.html"],
  ["abp:problem", "/problem.html"],
  ["abp:updates", "/updates.html"]
]);

// We animate the ABP icon while some kinds of notifications are active, to help
// catch the user's attention.
let notificationIconAnimationPlaying = false;

// Opera < 57 and Firefox (tested up to 68.0.1) do not support notifications
// being created with buttons. Opera added button support with >= 57, however
// the button click handlers have broken with >= 60 (tested up to 62). Until
// Opera fixes that bug (reference DNAWIZ-70332) we unfortunately can't use
// feature detection when deciding if notification buttons should be displayed.
const browserNotificationButtonsSupported = info_background.info.platform == "chromium" &&
                                            info_background.info.application != "opera";

// As of August 2019, only Chrome supports this flag and, since Firefox
// throws on unsupported options (tested with version 69), we need to
// explicitly set it only for supported browsers.
const browserNotificationRequireInteractionSupported = (
  info_background.info.platform == "chromium" && parseInt(info_background.info.platformVersion, 10) >= 50
);

function matchesDisplayMethod(method, {type})
{
  let methods = displayMethods.get(type) || defaultDisplayMethods;
  return methods.includes(method);
}

function playNotificationIconAnimation(notification)
{
  if (matchesDisplayMethod("icon", notification))
  {
    startIconAnimation(notification.type);
    notificationIconAnimationPlaying = true;
  }
}

function getNotificationButtons({type: notificationType, links}, message)
{
  let buttons = [];
  let linkCount = 0;
  let regex = /<a>(.*?)<\/a>/g;
  let match;
  while (match = regex.exec(message))
  {
    buttons.push({
      type: "link",
      title: match[1],
      link: links[linkCount++]
    });
  }

  // We allow the user to disable non-essential notifications, and we add a
  // button to those notifications to make that easier to do.
  let addConfigureButton = isOptional(notificationType);

  // Chrome only allows two notification buttons so we need to fall back
  // to a single button to open all links if there are more than two.
  let maxButtons = addConfigureButton ? 1 : 2;
  if (buttons.length > maxButtons)
  {
    buttons = [
      {
        type: "open-all",
        title: browser.i18n.getMessage("notification_open_all"),
        links
      }
    ];
  }
  if (addConfigureButton)
  {
    buttons.push({
      type: "configure",
      title: browser.i18n.getMessage("notification_configure")
    });
  }

  return buttons;
}

function openNotificationLink(link)
{
  if (link.startsWith("abp:subscribe:"))
  {
    let [,, type, locale] = link.split(":", 4);
    for (let recommendation of ewe_api.subscriptions.getRecommendations())
    {
      if (recommendation.type != type ||
          !recommendation.languages.includes(locale))
        continue;

      (0,filterConfiguration/* askConfirmSubscription */.P0)({
        homepage: recommendation.homepage,
        title: recommendation.title,
        url: recommendation.url
      });
      return;
    }

    console.error("No recommended subscription found");
    return;
  }

  let url;
  if (link.startsWith("abp:"))
    url = localNotificationPages.get(link);
  else
    url = prefs.Prefs.getDocLink(link);

  browser.tabs.create({url});
}

function getButtonLinks(buttons)
{
  let links = [];

  for (let button of buttons)
  {
    if (button.type == "link" && button.link)
      links.push(button.link);
    else if (button.type == "open-all" && button.links)
      links = links.concat(button.links);
  }
  return links;
}

async function openNotificationLinks(notificationId)
{
  let buttons = await notificationHelper_session.get(getButtonsKey(notificationId)) || [];
  for (let link of getButtonLinks(buttons))
    openNotificationLink(link);
}

async function notificationButtonClick(notificationId, buttonIndex)
{
  let buttons = await notificationHelper_session.get(getButtonsKey(notificationId));

  if (!(buttons && buttonIndex in buttons))
    return;

  let button = buttons[buttonIndex];

  switch (button.type)
  {
    case "link":
      openNotificationLink(button.link);
      break;
    case "open-all":
      await openNotificationLinks(notificationId);
      break;
    case "configure":
      await (0,options/* showOptions */.a)({
        type: "app.respond",
        action: "focusSection",
        args: ["notifications"]
      });
      break;
  }
}

/**
 * Tidy up after a notification has been dismissed.
 *
 * @param {string} notificationId
 * @param {bool} isStashed
 *   If the given notification is (or might be) stashed in the notification
 *   center, we must take care to remember what its buttons do. Leave as true
 *   unless you're sure!
 */
async function notificationDismissed(notificationId, isStashed)
{
  const activeNotification = await notificationHelper_session.get(activeNotificationKey);
  if (activeNotification && activeNotification.id == notificationId)
  {
    await notificationHelper_session.delete(activeNotificationKey);

    if (notificationIconAnimationPlaying)
    {
      stopIconAnimation();
      notificationIconAnimationPlaying = false;
    }
  }

  if (!isStashed)
    await notificationHelper_session.delete(getButtonsKey(notificationId));
}

function openNotificationInNewTab(notification)
{
  let tabIds = new Set();
  let [url] = notification.links;
  for (let [key, getValue] of linkPlaceholders)
    url = url.replace(`%${key}%`, encodeURIComponent(getValue()));

  function openNotificationTab()
  {
    browser.tabs.onCreated.removeListener(onCreated);
    browser.tabs.onRemoved.removeListener(onRemoved);
    browser.tabs.onUpdated.removeListener(onUpdated);

    browser.tabs.create({url});
    void ewe_api.notifications.markAsShown(notification.id);
    void notificationDismissed(notification.id);
  }

  let onCreated = tab =>
  {
    // Firefox loads its New Tab Page immediately and doesn't notify us
    // when it's complete so we need to open our new tab already here.
    if (tab.url == "about:newtab")
    {
      openNotificationTab();
      return;
    }

    tabIds.add(tab.id);
  };

  let onRemoved = tabId =>
  {
    tabIds.delete(tabId);
  };

  let onUpdated = (tabId, changeInfo, tab) =>
  {
    // Only look at tabs that have been opened since we started listening
    // and that have completed loading.
    if (!tabIds.has(tabId) || !("status" in changeInfo) ||
        changeInfo.status != "complete")
      return;

    tabIds.delete(tabId);

    // Open our own new tab only when a new tab gets opened
    // that isn't part of the user browsing the web.
    if (/^https?:/.test(tab.url))
      return;

    openNotificationTab();
  };

  browser.tabs.onCreated.addListener(onCreated);
  browser.tabs.onRemoved.addListener(onRemoved);
  browser.tabs.onUpdated.addListener(onUpdated);
}

/**
 * Shows the given notification. Will not re-show the currently active
 * notification.
 *
 * @param {object} notification - The notification to show
 */
async function showNotification(notification)
{
  const activeNotification = await notificationHelper_session.get(activeNotificationKey);
  if (activeNotification && activeNotification.id == notification.id)
    return;

  let texts = ewe_api.notifications.getLocalizedTexts(notification);
  let buttons = getNotificationButtons(notification, texts.message);

  // Don't display notifications at all if they contain a link to a local
  // notification page which we don't have.
  for (let link of getButtonLinks(buttons))
  {
    if (link.startsWith("abp:") &&
        !link.startsWith("abp:subscribe:") &&
        !localNotificationPages.has(link))
      return;
  }

  // We take a note of the notification's buttons even if notification buttons
  // are not supported by this browser. That way, if the user clicks the
  // (buttonless) notification we can still open all the links.
  await notificationHelper_session.set(getButtonsKey(notification.id), buttons);

  await notificationHelper_session.set(activeNotificationKey, notification);
  if (matchesDisplayMethod("notification", notification))
  {
    let notificationTitle = texts.title || "";
    let message = (texts.message || "").replace(/<\/?(a|strong)>/g, "");
    let iconUrl = browser.runtime.getURL("icons/logo/abp-128.png");

    let notificationOptions = {
      type: "basic",
      title: notificationTitle,
      iconUrl,
      message,
      // We use the highest priority to prevent the notification
      // from closing automatically, for browsers that don't support the
      // requireInteraction flag.
      priority: 2
    };

    if (browserNotificationButtonsSupported)
      notificationOptions.buttons = buttons.map(({title}) => ({title}));

    if (browserNotificationRequireInteractionSupported)
      notificationOptions.requireInteraction = true;

    browser.notifications.create(notification.id, notificationOptions);
  }

  playNotificationIconAnimation(notification);

  // Unlike other notifications, we cannot mark newtab-type notifications
  // as shown right away because they're not shown immediately.
  if (matchesDisplayMethod("newtab", notification))
  {
    const {installType} = await browser.management.getSelf();
    const {isActive: isPremiumUser} = (0,premium_background/* getPremiumState */.rh)();

    // Newtab notifications can be quite obtrusive and managed users may
    // see them more frequently than others so we shouldn't show such
    // notifications to them.

    // Because "newtab" notifications could potentially also contain upgrade
    // campaigns, we don't want to show them to premium users.

    if (installType === "admin" || isPremiumUser || navigator.webdriver)
    {
      void ewe_api.notifications.markAsShown(notification.id);
      void notificationDismissed(notification.id);
      return;
    }

    openNotificationInNewTab(notification);
  }
  else
  {
    void ewe_api.notifications.markAsShown(notification.id);
  }
}

/**
 * Initializes the notification system.
 *
 * @param {bool} firstRun
 */
async function initNotifications(firstRun)
{
  let onClick = async(notificationId, buttonIndex) =>
  {
    if (typeof buttonIndex == "number")
      await notificationButtonClick(notificationId, buttonIndex);
    else if (!browserNotificationButtonsSupported)
      await openNotificationLinks(notificationId);

    // Chrome hides notifications in the notification center when clicked,
    // so we need to clear them.
    browser.notifications.clear(notificationId);

    // But onClosed isn't triggered when we clear the notification, so we need
    // to take care to clear our record of it here too.
    await notificationDismissed(notificationId, false);
  };
  browser.notifications.onButtonClicked.addListener(onClick);
  browser.notifications.onClicked.addListener(onClick);

  let onClosed = async(notificationId, byUser) =>
  {
    // Despite using the highest priority for our notifications, Windows 10
    // will still hide them after a few seconds and stash them in the
    // notification center. We still consider the notification active when
    // this happens, in order to continue animating the ABP icon and/or
    // displaying the notification details in our popup window.
    // Note: Even if the notification was closed by the user, it still might
    //       be stashed in the notification center.
    if (byUser)
      await notificationDismissed(notificationId, true);
  };
  browser.notifications.onClosed.addListener(onClosed);

  ewe_api.notifications.locale = browser.i18n.getUILanguage();
  ewe_api.notifications.numBlocked = stats.Stats.blocked_total;
  await ewe_api.notifications.start();

  // If there is an active notification of the "newtab" type on startup, call
  // openNotificationInNewTab() to activate it again. If we don't do this,
  // the notification tab will not be opened when the user opens a new tab.
  notificationHelper_session.get(activeNotificationKey).then(notification =>
  {
    if (!notification || !matchesDisplayMethod("newtab", notification))
      return;

    openNotificationInNewTab(notification);
  });

  if (firstRun)
    (0,notifications.initDay1Notification)();
}

/**
 * If the given notification type is of vital importance return false,
 * true otherwise.
 *
 * @param {string} notificationType
 * @return {boolean}
 */
function isOptional(notificationType)
{
  return !["critical", "relentless"].includes(notificationType);
}

/**
 * Sent when a popup notification is clicked. If link is specified, that is
 * opened, otherwise the notification is dismissed.
 *
 * @event "notifications.clicked"
 * @property {number} id - ID of the clicked notification
 * @property {string} [link] - Notification link to open
 */
port.port.on("notifications.clicked", async(message, sender) =>
{
  if (message.link)
    openNotificationLink(message.link);

  // While clicking on a desktop notification's button dismisses the
  // notification, clicking on a popup window notification's link does not.
  if (!message.link || message.link.startsWith("abp:subscribe:"))
  {
    browser.notifications.clear(message.id);
    await notificationDismissed(message.id, true);
  }
});

/**
 * Returns the active notification if there is one and if it applies to the
 * given url and/or display method.
 *
 * @event "notifications.get"
 * @property {string} [displayMethod]
 *   Display method to check that the active notification matches.
 *   For example "popup" or "icon".
 * @returns {?object}
 */
port.port.on("notifications.get", async(message, sender) =>
{
  const activeNotification = await notificationHelper_session.get(activeNotificationKey);
  if (!activeNotification)
    return;

  if ("displayMethod" in message &&
      !matchesDisplayMethod(message.displayMethod, activeNotification))
    return;

  let texts = ewe_api.notifications.getLocalizedTexts(activeNotification);
  return Object.assign({texts}, activeNotification);
});

/**
 * Sent when a popup notification was shown to the user. Stops icon animation.
 *
 * @event "notifications.seen"
 */
port.port.on("notifications.seen", async(message, sender) =>
{
  const activeNotification = await notificationHelper_session.get(activeNotificationKey);
  if (!activeNotification)
    return;

  if (matchesDisplayMethod("popup", activeNotification) &&
      matchesDisplayMethod("icon", activeNotification))
    stopIconAnimation();
});

stats.Stats.on("blocked_total", () =>
{
  ewe_api.notifications.numBlocked = stats.Stats.blocked_total;
  void ewe_api.notifications.showNext();
});

ewe_api.notifications.addShowListener(showNotification);

// EXTERNAL MODULE: ./src/core/api/shared/api.ts
var api = __webpack_require__(808);
;// CONCATENATED MODULE: ./src/unload-cleanup/shared/unload-cleanup.ts

function isGetClassNameMessage(candidate) {
    return ((0,api/* isMessage */.c)(candidate) && candidate.type === "unload-cleanup.getClassName");
}

;// CONCATENATED MODULE: ./src/unload-cleanup/shared/unload-cleanup.types.ts
var DisplayValue;
(function (DisplayValue) {
    DisplayValue["block"] = "block";
})(DisplayValue || (DisplayValue = {}));
const displayValueList = Object.values(DisplayValue);

;// CONCATENATED MODULE: ./src/unload-cleanup/shared/index.ts



;// CONCATENATED MODULE: ./src/unload-cleanup/background/unload-cleanup.types.ts
const className = "__adblockplus__injected";

;// CONCATENATED MODULE: ./src/unload-cleanup/background/unload-cleanup.ts




const css = displayValueList.map((displayValue) => `.${className}--${displayValue} {display: ${displayValue} !important;}`)
    .join("\n");
async function handleMessage(message, sender) {
    if (!isGetClassNameMessage(message)) {
        return;
    }
    if (info_background.info.application !== "firefox" || typeof sender.page === "undefined") {
        return;
    }
    await browser.tabs.insertCSS(sender.page.id, {
        code: css,
        frameId: sender.frame.id,
        runAt: "document_start"
    });
    return className;
}
function start() {
    port.port.on("unload-cleanup.getClassName", handleMessage);
    ext.addTrustedMessageTypes(null, ["unload-cleanup.getClassName"]);
}

;// CONCATENATED MODULE: ./src/unload-cleanup/background/index.ts


// EXTERNAL MODULE: ./src/ipm/background/telemetry.ts + 2 modules
var telemetry = __webpack_require__(887);
;// CONCATENATED MODULE: ./src/testing/ping-ipm/background/ping-ipm.ts



function ping_ipm_start() {
    port.port.on("testing.ping_ipm_server", async () => {
        await prefs.Prefs.untilLoaded;
        void (0,telemetry/* sendPing */._)();
    });
}

;// CONCATENATED MODULE: ./src/testing/ping-ipm/background/index.ts


;// CONCATENATED MODULE: ./adblockpluschrome/lib/subscriptionInit.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module subscriptionInit */

















const defaultSubscriptionIds = [
  "8C13E995-8F06-4927-BEA7-6C845FB7EEBF",
  "0798B6A2-94A4-4ADF-89ED-BEC112FC4C7F",
  "D4028CDD-3D39-4624-ACC7-8140F4EC3238"
];

let firstRun;
let userNotificationCallback = null;
let reinitialized = false;
let dataCorrupted = false;

/**
 * If there aren't any filters, the default subscriptions are added.
 * However, if patterns.ini already did exist and/or any preference
 * is set to a non-default value, this indicates that this isn't the
 * first run, but something went wrong.
 *
 * This function detects the first run, and makes sure that the user
 * gets notified (on the first run page) if the data appears incomplete
 * and therefore will be reinitialized.
 *
 * @param {boolean} foundSubscriptions
 * @param {boolean} foundStorage
 *
 * @return {Promise}
 */
async function detectFirstRun(foundSubscriptions, foundStorage)
{
  let userFilters = await ewe_api.filters.getUserFilters();
  firstRun = !foundSubscriptions && !userFilters.length;

  if (firstRun && (foundStorage || prefs.Prefs.currentVersion))
    reinitialized = true;

  prefs.Prefs.currentVersion = info_background.info.addonVersion;
}

/**
 * In case of data corruption, we don't want to show users
 * any non-essential notifications so we need to instruct
 * the notification manager to ignore them.
 *
 * @param {boolean} value
 */
function setDataCorrupted(value)
{
  dataCorrupted = value;
  ewe_api.notifications.ignored = value;
}

async function addSubscriptionsAndNotifyUser()
{
  if (firstRun || reinitialized)
  {
    try
    {
      await ewe_api.subscriptions.addDefaults();
    }
    catch (ex)
    {
      console.error("Failed to add default filter lists:", ex);

      // We don't want to keep the extension in a broken state, so we
      // try to individually add default subscriptions ourselves
      const recommendations = ewe_api.subscriptions.getRecommendations();
      for (const recommendation of recommendations)
      {
        if (!defaultSubscriptionIds.includes(recommendation.id))
          continue;

        await ewe_api.subscriptions.add(recommendation.url);
      }
    }
  }

  for (let url of prefs.Prefs.additional_subscriptions)
  {
    try
    {
      await ewe_api.subscriptions.add(url);
      await ewe_api.subscriptions.sync(url);
    }
    catch (ex)
    {
      console.error(`Failed to add additional subscription: ${url}`);
    }
  }

  if (userNotificationCallback)
    userNotificationCallback({dataCorrupted, firstRun, reinitialized});
}

/**
 * We need to check whether we can safely write to/read from storage
 * before we start relying on it for storing preferences.
 */
async function testStorage()
{
  let testKey = "readwrite_test";
  let testValue = Math.random();

  try
  {
    await browser.storage.local.set({[testKey]: testValue});
    let result = await browser.storage.local.get(testKey);
    if (result[testKey] != testValue)
      throw new Error("Storage test: Failed to read and write value");
  }
  finally
  {
    await browser.storage.local.remove(testKey);
  }
}

function initElementHidingDebugMode()
{
  prefs.Prefs.on("elemhide_debug", () =>
  {
    void ewe_api.debugging.setElementHidingDebugMode(prefs.Prefs.elemhide_debug);
  });

  void ewe_api.debugging.setElementHidingDebugMode(prefs.Prefs.elemhide_debug);
  void ewe_api.debugging.setElementHidingDebugStyle(
    [
      ["background", "#e67370"],
      ["outline", "solid #f00"]
    ],
    [
      ["background", `
        repeating-linear-gradient(
          to bottom,
          #e67370 0,
          #e67370 9px,
          #fff 9px,
          #fff 10px
        )
      `],
      ["outline", "solid #f00"]
    ]
  );
}

async function subscriptionInit_start()
{
  const [eweFirstRun] = await Promise.all([
    ewe_api.start({
      bundledSubscriptions: adblockplus_namespaceObject,
      bundledSubscriptionsPath: "/data/rules/abp",
      name: info_background.info.addonName,
      version: info_background.info.addonVersion
    }),
    prefs.Prefs.untilLoaded["catch"](() => { setDataCorrupted(true); }),
    testStorage().catch(() => { setDataCorrupted(true); })
  ]);

  (await ewe_api.filters.getMigrationErrors()).forEach(console.error);
  (await ewe_api.subscriptions.getMigrationErrors()).forEach(console.error);
  eweFirstRun.warnings.forEach(console.warn);
  await detectFirstRun(
    eweFirstRun.foundSubscriptions,
    eweFirstRun.foundStorage
  );
  await addSubscriptionsAndNotifyUser();
  (0,allowlisting/* revalidateAllowlistingStates */.s)();

  // We have to require the "uninstall" module on demand,
  // as the "uninstall" module in turn requires this module.
  await (await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 581))).setUninstallURL();

  await (0,filterConfiguration/* initDisabledFilterCounters */.k7)();
  initElementHidingDebugMode();
  await initNotifications(firstRun);
  premium_background/* start */.BL();
  startOptionLinkListener();
  void (0,background/* startTelemetry */.VL)();
  start();
  ping_ipm_start();
  (0,ready_state_background/* setReadyState */.PL)(ready_state_background/* ReadyState.started */.kQ.started);

  /**
   * @typedef {object} subscriptionsGetInitIssuesResult
   * @property {boolean} dataCorrupted
   *   true if it appears that the user's extension data was corrupted.
   * @property {boolean} reinitialized
   *   true if we have reset the user's settings due to data corruption.
   */

  /**
   * Returns an Object with boolean flags for any subscription initialization
   * issues.
   *
   * @event "subscriptions.getInitIssues"
   * @returns {subscriptionsGetInitIssuesResult}
   */
  port.port.on("subscriptions.getInitIssues", (message, sender) => ({
    dataCorrupted,
    reinitialized
  }));
}

/**
 * Gets a value indicating whether a data corruption was detected.
 *
 * @return {boolean}
 */
function isDataCorrupted()
{
  return dataCorrupted;
}

/**
 * Sets a callback that is called with environment information after
 * initialization to notify users.
 *
 * @param {function} callback
 */
function setNotifyUserCallback(callback)
{
  userNotificationCallback = callback;
}


/***/ }),

/***/ 581:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "setUninstallURL": () => (/* binding */ setUninstallURL),
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(120);
/* harmony import */ var _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(968);
/* harmony import */ var _subscriptionInit_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(821);
/* harmony import */ var _src_info_background__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(463);
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module uninstall */







const abbreviations = [
  ["an", "addonName"],
  ["ap", "application"],
  ["apv", "applicationVersion"],
  ["av", "addonVersion"],
  ["c", "corrupted"],
  ["fv", "firstVersion"],
  ["ndc", "notificationDownloadCount"],
  ["p", "platform"],
  ["pv", "platformVersion"],
  ["s", "subscriptions"],
  ["wafc", "webAllowlistingFilterCount"]
];

/**
 * Returns the number of currently active filters that have been added using
 * the experimental allowlisting functionality (i.e. that originated in the
 * web, and not in the extension popup).
 *
 * @returns {number} The filter count
 */
async function getWebAllowlistingFilterCount()
{
  // get all allowlisting filters that are enabled
  const filters = (await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.getUserFilters()).filter(
    filter => filter.type === "allowing" && filter.enabled
  );

  // collect their metadata
  const filtersMetadata = await Promise.all(
    filters.map(async filter => await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.getMetadata(filter.text))
  );

  // count the ones that originated in the web
  return filtersMetadata.filter(data => data && data.origin === "web").length;
}

/**
 * Retrieves set of URLs of recommended ad blocking filter lists
 *
 * @return {Set}
 */
function getAdsSubscriptions()
{
  let subscriptions = new Set();
  for (let subscription of _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.getRecommendations())
  {
    if (subscription.type == "ads")
      subscriptions.add(subscription.url);
  }
  return subscriptions;
}

/**
 * Determines whether any of the given subscriptions are installed and enabled
 *
 * @param {Set} urls
 *
 * @return {boolean}
 */
async function isAnySubscriptionActive(urls)
{
  for (let subscription of await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.getSubscriptions())
  {
    if (subscription.enabled && urls.has(subscription.url))
      return true;
  }

  return false;
}

/**
 * Sets (or updates) the URL that is openend when the extension is uninstalled.
 *
 * Must be called after prefs got initialized and a data corruption
 * if any was detected, as well when notification data change.
 */
async function setUninstallURL()
{
  let search = [];
  let params = Object.create(_src_info_background__WEBPACK_IMPORTED_MODULE_3__.info);

  params.corrupted = (0,_subscriptionInit_js__WEBPACK_IMPORTED_MODULE_2__.isDataCorrupted)() ? "1" : "0";
  params.firstVersion = _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.reporting.getFirstVersion();

  let notificationDownloadCount = await _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.getDownloadCount();
  if (notificationDownloadCount < 5)
    params.notificationDownloadCount = notificationDownloadCount;
  else if (notificationDownloadCount < 8)
    params.notificationDownloadCount = "5-7";
  else if (notificationDownloadCount < 30)
    params.notificationDownloadCount = "8-29";
  else if (notificationDownloadCount < 90)
    params.notificationDownloadCount = "30-89";
  else if (notificationDownloadCount < 180)
    params.notificationDownloadCount = "90-179";
  else
    params.notificationDownloadCount = "180+";

  let aaSubscriptions = new Set([_eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.ACCEPTABLE_ADS_URL]);
  let adsSubscriptions = getAdsSubscriptions();
  let isAcceptableAdsActive = await isAnySubscriptionActive(aaSubscriptions);
  let isAdBlockingActive = await isAnySubscriptionActive(adsSubscriptions);
  params.subscriptions = (isAcceptableAdsActive << 1) | isAdBlockingActive;

  params.webAllowlistingFilterCount = await getWebAllowlistingFilterCount();

  for (let [abbreviation, key] of abbreviations)
    search.push(abbreviation + "=" + encodeURIComponent(params[key]));

  browser.runtime.setUninstallURL(_prefs_js__WEBPACK_IMPORTED_MODULE_1__.Prefs.getDocLink("uninstalled") + "&" +
                                  search.join("&"));
}

function start()
{
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.notifications.on("downloaded", setUninstallURL);

  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onAdded.addListener(setUninstallURL);
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onChanged.addListener(setUninstallURL);
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.filters.onRemoved.addListener(setUninstallURL);

  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onAdded.addListener(setUninstallURL);
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onChanged.addListener(async(subscription, property) =>
  {
    if (property !== "enabled")
      return;

    await setUninstallURL();
  });
  _eyeo_webext_ad_filtering_solution__WEBPACK_IMPORTED_MODULE_0__.subscriptions.onRemoved.addListener(setUninstallURL);
}


/***/ }),

/***/ 997:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



const {info} = __webpack_require__(463);
const {Prefs} = __webpack_require__(968);
const {setNotifyUserCallback} = __webpack_require__(821);

const {
  showProblemNotification,
  showUpdatesNotification
} = __webpack_require__(954);
const {updatesVersion} = __webpack_require__(578);

const localFirstRunPageUrl = browser.runtime.getURL("first-run.html");
const urlPlaceholders = new Set([
  ["LANG", () => browser.i18n.getUILanguage().replace("-", "_")],
  ["ADDON_NAME", () => info.addonName],
  ["ADDON_VERSION", () => info.addonVersion],
  ["APPLICATION_NAME", () => info.application],
  ["APPLICATION_VERSION", () => info.applicationVersion],
  ["PLATFORM_NAME", () => info.platform],
  ["PLATFORM_VERSION", () => info.platformVersion]
]);

function listenForRemotePage(checkIsFirstRunTab)
{
  let stop = () => {};

  const promise = new Promise((resolve, reject) =>
  {
    let timeout = null;

    function removeListeners()
    {
      clearTimeout(timeout);
      browser.webNavigation.onDOMContentLoaded.removeListener(
        onNavigationCompleted
      );
      browser.webNavigation.onErrorOccurred.removeListener(onErrorOccurred);
      browser.webRequest.onCompleted.removeListener(onRequestCompleted);
    }
    stop = removeListeners;

    function onErrorOccurred(details)
    {
      if (!checkIsFirstRunTab(details.tabId))
        return;

      console.warn(`Failed to open first-run page: ${details.error}`);
      removeListeners();
      reject();
    }
    browser.webNavigation.onErrorOccurred.addListener(onErrorOccurred);

    function onNavigationCompleted(details)
    {
      if (!checkIsFirstRunTab(details.tabId))
        return;

      removeListeners();
      resolve();
    }
    browser.webNavigation.onDOMContentLoaded.addListener(onNavigationCompleted);

    function onRequestCompleted(details)
    {
      if (!checkIsFirstRunTab(details.tabId))
        return;

      const {statusCode} = details;
      if (statusCode < 200 || statusCode > 399)
      {
        console.warn(`Failed to open first-run page: HTTP ${statusCode}`);
        removeListeners();
        reject();
      }
    }
    browser.webRequest.onCompleted.addListener(
      onRequestCompleted,
      {
        types: ["main_frame"],
        urls: ["https://*/*"]
      }
    );

    function onTimeout()
    {
      console.warn("Failed to open first-run page: Timed out");
      removeListeners();
      reject();
    }
    timeout = setTimeout(onTimeout, 30000);
  });

  return {promise, stop};
}

async function wait(time)
{
  return new Promise((resolve) =>
  {
    setTimeout(resolve, time);
  });
}

async function updateTab(tabId, url)
{
  // Chrome doesn't reliably update the tab and fails silently so we need to
  // retry repeatedly and check whether it worked.
  for (let i = 0; i < 10; i++)
  {
    await browser.tabs.update(tabId, {url});
    await wait(250);

    const tab = await browser.tabs.get(tabId);
    if (tab.url === url)
      return;
  }

  throw new Error("Failed to update tab");
}

async function openFirstRunPage(shouldShowWarning = false, forceLocal = false)
{
  const showLocal = shouldShowWarning || forceLocal;

  let firstRunTabId = null;
  let waitForRemotePage = Promise.resolve();
  let url = localFirstRunPageUrl;

  if (!showLocal)
  {
    url = Prefs.remote_first_run_page_url;
    for (const [key, getValue] of urlPlaceholders)
    {
      const value = (typeof getValue === "function") ? getValue() : null;
      url = url.replace(`%${key}%`, encodeURIComponent(value));
    }
    waitForRemotePage = listenForRemotePage((tabId) => tabId === firstRunTabId);
  }

  try
  {
    // Users with corrupted browser data may see this page each time their
    // browser starts. We avoid focusing the page for those users, in the
    // hope to make the situation less intrusive.
    const tab = await browser.tabs.create({
      active: !shouldShowWarning,
      url
    });
    firstRunTabId = tab.id;

    try
    {
      await waitForRemotePage.promise;
    }
    catch (ex)
    {
      waitForRemotePage.stop();

      // If remote page fails to load, replace it with local page
      await updateTab(firstRunTabId, localFirstRunPageUrl);
    }
  }
  catch (ex)
  {
    waitForRemotePage.stop();

    // Open local page if we failed to open remote page or replace tab,
    // unless we've already tried
    if (!showLocal)
      openFirstRunPage(shouldShowWarning, true);
  }
}

async function onNotifyUser(state)
{
  const {firstRun, reinitialized} = state;
  let {dataCorrupted} = state;

  // Show first run page, update notification or problem notification.
  // The update notification is only shown if the user hasn't been notified
  // of the latest major update yet.
  if (firstRun || updatesVersion > Prefs.last_updates_page_displayed ||
    dataCorrupted || reinitialized)
  {
    try
    {
      await Prefs.set("last_updates_page_displayed", updatesVersion);
    }
    catch (ex)
    {
      dataCorrupted = true;
    }

    const platformInfo = await browser.runtime.getPlatformInfo();
    const canShowNotification = platformInfo.os !== "android";
    const shouldShowWarning = dataCorrupted || reinitialized;

    // Show a notification if a data corruption was detected (either through
    // failure of reading from or writing to storage.local).
    if (shouldShowWarning && canShowNotification)
    {
      showProblemNotification();
      return;
    }

    if (!Prefs.suppress_first_run_page)
    {
      // Always show the first run page if a data corruption was detected
      // but we cannot show a notification. The first run page notifies the
      // user about the data corruption.
      if (firstRun || shouldShowWarning)
      {
        const locale = browser.i18n.getUILanguage();
        openFirstRunPage(
          shouldShowWarning,
          // Force local page for certain languages
          /^de\b/.test(locale)
        );
        return;
      }

      // Show a notification to inform the user about the latest major update.
      showUpdatesNotification();
    }
  }
}

exports.B = () =>
{
  setNotifyUserCallback(onNotifyUser);
};



/***/ }),

/***/ 954:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



const {Prefs} = __webpack_require__(968);
const {Stats} = __webpack_require__(774);

const ewe = __webpack_require__(120);

const {coreLocales} = __webpack_require__(16);
const scheduledEventEmitter = __webpack_require__(
  621
);

const DELAY_IN_MS = 30 * 60 * 1000;
const MIN_BLOCKED = 55;

const day1Topic = "notifications.day1";

async function isAndroid()
{
  const platformInfo = await browser.runtime.getPlatformInfo();
  return platformInfo.os == "android";
}

exports.initDay1Notification = async function initDay1Notification()
{
  if ((await isAndroid()) || Prefs.suppress_first_run_page)
    return;

  scheduledEventEmitter.setSchedule(day1Topic, DELAY_IN_MS);
};

scheduledEventEmitter.setListener(day1Topic, () =>
{
  // We don't know what exactly the blocked count will be when
  // the notification will be shown but we expect it to be shown
  // immediately after it surpasses the threshold
  let blockedCount = Stats.blocked_total;
  if (blockedCount < MIN_BLOCKED)
  {
    blockedCount = MIN_BLOCKED;
  }

  const notification = {
    id: "day1",
    type: "normal",
    title: browser.i18n.getMessage("notification_day1_title", [blockedCount]),
    message: browser.i18n.getMessage("notification_day1_message"),
    links: ["abp:day1"],
    targets: [
      {blockedTotalMin: MIN_BLOCKED}
    ]
  };

  ewe.notifications.addNotification(notification);
  void ewe.notifications.showNext();
});

exports.showProblemNotification = async() =>
{
  if (await isAndroid())
    return;

  const locale = browser.i18n.getUILanguage();

  // Due to a race condition, we cannot reliably target the notification to
  // only certain locales. Therefore we have to implement this check ourselves.
  // https://gitlab.com/eyeo/adblockplus/adblockpluschrome/issues/135
  void ewe.notifications.showNotification({
    id: "problem",
    type: /^(?:de|fr)\b/.test(locale) ? "information" : null,
    message: browser.i18n.getMessage("notification_problem_message"),
    links: ["abp:problem"]
  });
};

exports.showUpdatesNotification = async() =>
{
  if (await isAndroid())
    return;

  const locale = browser.i18n.getUILanguage();
  // Due to a race condition, we cannot reliably target the notification to
  // only certain locales. Therefore we have to implement this check ourselves.
  // https://gitlab.com/eyeo/adblockplus/adblockpluschrome/issues/135
  if (!coreLocales.includes(locale))
  {
    // That specific locale may not be part of our core languages. However,
    // the language it belongs to may be. Therefore we are able to show the
    // updates page with those translations instead.
    const [language] = locale.split("-");
    if (!coreLocales.includes(language))
      return;
  }

  void ewe.notifications.showNotification({
    id: "updates",
    type: "information",
    title: browser.i18n.getMessage("notification_updates_title"),
    message: browser.i18n.getMessage("notification_updates_message"),
    links: ["abp:updates"]
  }, {ignorable: true});
};


/***/ }),

/***/ 262:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module options */



const ewe = __webpack_require__(120);

const {
  port: messagingPort
} = __webpack_require__(305);
const {
  SessionStorage
} = __webpack_require__(137);

/**
 * Key to store/retrieve an optional message to send to the options page after
 * it opens.
 */
const optionsMessageKey = "optionsMessage";

let optionsPort = null;

// Firefox won't let us query for moz-extension:// pages, though
// starting with Firefox 56 an extension can query for its own URLs:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1271354
const optionsUrl = browser.runtime.getURL(
  browser.runtime.getManifest().options_ui.page
);

const session = new SessionStorage("options");

async function onMessage(message, port)
{
  if (message.type != "app.listen")
    return;

  const optionsMessage = await session.get(optionsMessageKey);
  if (!optionsMessage)
    return;

  await session.delete(optionsMessageKey);

  port.postMessage(optionsMessage);
}

async function onConnect(port)
{
  if (!ext.isTrustedSender(port.sender))
    return;

  if (port.name != "ui")
    return;

  if (!port.sender.tab || port.sender.tab.url !== optionsUrl)
    return;

  optionsPort = port;
  optionsPort.onDisconnect.addListener(() =>
  {
    optionsPort = null;
  });
  optionsPort.onMessage.addListener(onMessage);
}
browser.runtime.onConnect.addListener(onConnect);

/**
 * Opens the options page, or switches to its existing tab.
 * @param {Object} [message] - Message to send to options page
 */
async function showOptions(message)
{
  await session.delete(optionsMessageKey);

  // If the options page is already open, focus its tab manually to avoid
  // potentially opening it again, due to browser.runtime.openOptionsPage()
  // behaving differently across browsers
  if (optionsPort)
  {
    // Firefox for Android doesn't support browser.windows
    if ("windows" in browser)
    {
      await browser.windows.update(
        optionsPort.sender.tab.windowId,
        {focused: true}
      );
    }

    await browser.tabs.update(optionsPort.sender.tab.id, {active: true});

    // Send message after focusing options page
    if (message)
    {
      optionsPort.postMessage(message);
    }
  }
  else
  {
    // Send message after initializing options page
    if (message)
    {
      await session.set(optionsMessageKey, message);
    }

    await browser.runtime.openOptionsPage();
  }
}
module.exports.a = showOptions;

// We need to clear the popup URL on Firefox for Android in order for the
// options page to open instead of the bubble. Unfortunately there's a bug[1]
// which prevents us from doing that, so we must avoid setting the URL on
// Firefox from the manifest at all, instead setting it here only for
// non-mobile.
// [1] - https://bugzilla.mozilla.org/show_bug.cgi?id=1414613
Promise.all([browser.action.getPopup({}),
             browser.runtime.getPlatformInfo()]).then(
  ([popup, platformInfo]) =>
  {
    if (!popup && platformInfo.os != "android")
      browser.action.setPopup({popup: "popup.html"});
  }
);

// On Firefox for Android, open the options page directly when the browser
// action is clicked.
browser.action.onClicked.addListener(async() =>
{
  const [tab] = await browser.tabs.query({active: true});
  const currentPage = new ext.Page(tab);

  let message = null;
  if (/^https?:$/.test(currentPage.url.protocol))
  {
    const isAllowlisted = await ewe.filters.isResourceAllowlisted(
      currentPage.url,
      "document",
      currentPage.id
    );
    message = {
      type: "app.respond",
      action: "showPageOptions",
      args: [
        {
          host: currentPage.url.hostname.replace(/^www\./, ""),
          allowlisted: isAllowlisted
        }
      ]
    };
  }

  await showOptions(message);
});

/**
 * Opens the options page in a new tab and waits for it to load, or switches to
 * the existing tab if the options page is already open.
 *
 * @event "options.open"
 */
messagingPort.on("options.open", async(message, sender) =>
{
  await showOptions(message && message.followUpMessage);
});


/***/ }),

/***/ 578:
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/**
 * The version of major updates that the user should be aware of. Should be
 * incremented with every new iteration of the updates page.
 * See also Prefs.last_updates_page_displayed
 *
 * @type {number}
 */
exports.updatesVersion = 6;


/***/ }),

/***/ 398:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



const ewe = __webpack_require__(120);

const {SessionStorage} = __webpack_require__(137);
const {info} = __webpack_require__(463);
const {Prefs} = __webpack_require__(968);

/**
 * Rolling list of websites the user visited most recently
 *
 * @typedef {Object[]} LastVisits
 */

/**
 * Key to store/retrieve the [list of last visited websites]{@link LastVisits}
 */
const lastVisitsKey = "lastVisits";

const session = new SessionStorage("recommendLanguage");

let promisedLanguages;
let recommendationByLocale;
let recommendationUrls;

async function addVisit(url, locale)
{
  const domain = new URL(url).hostname;
  const visit = {domain, locale};

  const lastVisits = await session.get(lastVisitsKey) || [];
  if (lastVisits.length === 10)
  {
    lastVisits.shift();
  }
  lastVisits.push(visit);
  await session.set(lastVisitsKey, lastVisits);

  const distinctDomains = new Set();
  for (const prevVisit of lastVisits)
  {
    if (prevVisit.locale !== locale)
      continue;

    distinctDomains.add(prevVisit.domain);
  }
  return distinctDomains.size;
}

function normalizeLocale(locale)
{
  const match = /^[a-z]+/.exec(locale.toLowerCase());
  if (!match)
    return null;

  return match[0];
}

async function getExplicitTabLanguage(tabId)
{
  // We need to use both browser.tabs.executeScript and
  // browser.scripting.executeScript because they're exclusive to
  // Manifest v2 and v3 respectively
  if (browser.scripting)
  {
    const [frameResult] = await browser.scripting.executeScript({
      target: {tabId},
      func: () => document.documentElement.lang
    });
    return frameResult.result;
  }

  const [lang] = await browser.tabs.executeScript(
    tabId,
    {code: "document.documentElement.lang"}
  );
  return lang;
}

async function getTabLanguage(tabId)
{
  try
  {
    let [explicit, implicit] = await Promise.all([
      getExplicitTabLanguage(tabId),
      browser.tabs.detectLanguage(tabId)
    ]);

    // We're only interested in the language, not the specific locale, and
    // the language codes may also be in a different format
    explicit = normalizeLocale(explicit);
    implicit = normalizeLocale(implicit);

    // We want both sources to agree to be sure we got it right
    if (!explicit || !implicit || explicit != implicit)
      return null;

    return explicit;
  }
  catch (ex)
  {
    // We cannot run our script on certain pages (e.g. Chrome Web Store)
    return null;
  }
}

async function getInstalledRecommendationsCount()
{
  let count = 0;

  for (const subscription of await ewe.subscriptions.getSubscriptions())
  {
    if (!recommendationUrls.has(subscription.url))
      continue;

    count++;
  }

  return count;
}

async function onNavigation(details)
{
  // User opted out so nothing to do
  if (!Prefs.recommend_language_subscriptions)
    return;

  // Ignore subframes
  if (details.frameId !== 0)
    return;

  // Ignore non-HTTP(S) pages (e.g. New Tab Page)
  if (!/^https?:/.test(details.url))
    return;

  // Support for English is already included in all language filter lists
  // so we don't need to recommend adding another list
  const locale = await getTabLanguage(details.tabId);
  if (!locale || locale === "en")
    return;

  // We don't want to recommend filter lists right away but only after
  // visiting related websites a couple of times
  if (await addVisit(details.url, locale) < 3)
    return;

  // Does recommended filter list exist for given language?
  const subscriptionUrl = recommendationByLocale.get(locale);
  if (!subscriptionUrl)
    return;

  // Is filter list already installed?
  if (await ewe.subscriptions.has(subscriptionUrl))
    return;

  // Are enough recommended filter lists already installed?
  const installedCount = await getInstalledRecommendationsCount();
  if (installedCount > 2)
    return;

  // We need to know the name of the language in order to display
  // the notification properly
  const languages = await promisedLanguages;
  const languageName = languages.nativeNames[locale];
  if (!languageName)
    return;

  // Show notification
  ewe.notifications.addNotification({
    id: `reclang-${locale}`,
    type: "information",
    message: browser.i18n.getMessage(
      "notification_recommendLanguage_message",
      [languageName]
    ),
    links: [`abp:subscribe:ads:${locale}`]
  });
  void ewe.notifications.showNext();
}

function initRecommendations()
{
  recommendationByLocale = new Map();
  recommendationUrls = new Set();

  for (const recommendation of ewe.subscriptions.getRecommendations())
  {
    if (recommendation.type !== "ads")
      continue;

    const locales = recommendation.languages;
    if (!locales)
      continue;

    recommendationUrls.add(recommendation.url);
    for (const locale of locales)
    {
      recommendationByLocale.set(locale, recommendation.url);
    }
  }
}

exports.B = async() =>
{
  // Don't initiate language recommendation feature for Opera users
  // due to problems with its language detection
  // https://gitlab.com/adblockinc/ext/adblockplus/adblockplus/-/issues/960
  if (info.application === "opera")
    return;

  const uiLanguage = browser.i18n.getUILanguage();
  if (/^(?:de|fr)\b/.test(uiLanguage))
    return;

  const platformInfo = await browser.runtime.getPlatformInfo();
  if (platformInfo.os === "android")
    return;

  promisedLanguages = fetch("data/locales.json")
    .then((resp) => resp.json());
  initRecommendations();

  browser.webNavigation.onCompleted.addListener(onNavigation);
};


/***/ }),

/***/ 935:
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else { var mod; }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (module) {
  /* webextension-polyfill - v0.8.0 - Tue Apr 20 2021 11:27:38 */

  /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */

  /* vim: set sts=2 sw=2 et tw=80: */

  /* This Source Code Form is subject to the terms of the Mozilla Public
   * License, v. 2.0. If a copy of the MPL was not distributed with this
   * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  "use strict";

  if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) {
    const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received.";
    const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; // Wrapping the bulk of this polyfill in a one-time-use function is a minor
    // optimization for Firefox. Since Spidermonkey does not fully parse the
    // contents of a function until the first time it's called, and since it will
    // never actually need to be called, this allows the polyfill to be included
    // in Firefox nearly for free.

    const wrapAPIs = extensionAPIs => {
      // NOTE: apiMetadata is associated to the content of the api-metadata.json file
      // at build time by replacing the following "include" with the content of the
      // JSON file.
      const apiMetadata = {
        "alarms": {
          "clear": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "clearAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "get": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "bookmarks": {
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getChildren": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getRecent": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getSubTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTree": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "browserAction": {
          "disable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "enable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "getBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getBadgeText": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "openPopup": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setBadgeText": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "browsingData": {
          "remove": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "removeCache": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCookies": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeDownloads": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFormData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeHistory": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeLocalStorage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePasswords": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePluginData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "settings": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "commands": {
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "contextMenus": {
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "cookies": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAllCookieStores": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "set": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "devtools": {
          "inspectedWindow": {
            "eval": {
              "minArgs": 1,
              "maxArgs": 2,
              "singleCallbackArg": false
            }
          },
          "panels": {
            "create": {
              "minArgs": 3,
              "maxArgs": 3,
              "singleCallbackArg": true
            },
            "elements": {
              "createSidebarPane": {
                "minArgs": 1,
                "maxArgs": 1
              }
            }
          }
        },
        "downloads": {
          "cancel": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "download": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "erase": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFileIcon": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "open": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "pause": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFile": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "resume": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "extension": {
          "isAllowedFileSchemeAccess": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "isAllowedIncognitoAccess": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "history": {
          "addUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "deleteRange": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getVisits": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "i18n": {
          "detectLanguage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAcceptLanguages": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "identity": {
          "launchWebAuthFlow": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "idle": {
          "queryState": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "management": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getSelf": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setEnabled": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "uninstallSelf": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "notifications": {
          "clear": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPermissionLevel": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "pageAction": {
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "hide": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "permissions": {
          "contains": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "request": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "runtime": {
          "getBackgroundPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPlatformInfo": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "openOptionsPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "requestUpdateCheck": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "sendMessage": {
            "minArgs": 1,
            "maxArgs": 3
          },
          "sendNativeMessage": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "setUninstallURL": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "sessions": {
          "getDevices": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getRecentlyClosed": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "restore": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "storage": {
          "local": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          },
          "managed": {
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            }
          },
          "sync": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          }
        },
        "tabs": {
          "captureVisibleTab": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "detectLanguage": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "discard": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "duplicate": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "executeScript": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getZoom": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getZoomSettings": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goBack": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goForward": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "highlight": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "insertCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "query": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "reload": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "sendMessage": {
            "minArgs": 2,
            "maxArgs": 3
          },
          "setZoom": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "setZoomSettings": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "update": {
            "minArgs": 1,
            "maxArgs": 2
          }
        },
        "topSites": {
          "get": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "webNavigation": {
          "getAllFrames": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFrame": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "webRequest": {
          "handlerBehaviorChanged": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "windows": {
          "create": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getLastFocused": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        }
      };

      if (Object.keys(apiMetadata).length === 0) {
        throw new Error("api-metadata.json has not been included in browser-polyfill");
      }
      /**
       * A WeakMap subclass which creates and stores a value for any key which does
       * not exist when accessed, but behaves exactly as an ordinary WeakMap
       * otherwise.
       *
       * @param {function} createItem
       *        A function which will be called in order to create the value for any
       *        key which does not exist, the first time it is accessed. The
       *        function receives, as its only argument, the key being created.
       */


      class DefaultWeakMap extends WeakMap {
        constructor(createItem, items = undefined) {
          super(items);
          this.createItem = createItem;
        }

        get(key) {
          if (!this.has(key)) {
            this.set(key, this.createItem(key));
          }

          return super.get(key);
        }

      }
      /**
       * Returns true if the given object is an object with a `then` method, and can
       * therefore be assumed to behave as a Promise.
       *
       * @param {*} value The value to test.
       * @returns {boolean} True if the value is thenable.
       */


      const isThenable = value => {
        return value && typeof value === "object" && typeof value.then === "function";
      };
      /**
       * Creates and returns a function which, when called, will resolve or reject
       * the given promise based on how it is called:
       *
       * - If, when called, `chrome.runtime.lastError` contains a non-null object,
       *   the promise is rejected with that value.
       * - If the function is called with exactly one argument, the promise is
       *   resolved to that value.
       * - Otherwise, the promise is resolved to an array containing all of the
       *   function's arguments.
       *
       * @param {object} promise
       *        An object containing the resolution and rejection functions of a
       *        promise.
       * @param {function} promise.resolve
       *        The promise's resolution function.
       * @param {function} promise.reject
       *        The promise's rejection function.
       * @param {object} metadata
       *        Metadata about the wrapped method which has created the callback.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function}
       *        The generated callback function.
       */


      const makeCallback = (promise, metadata) => {
        return (...callbackArgs) => {
          if (extensionAPIs.runtime.lastError) {
            promise.reject(new Error(extensionAPIs.runtime.lastError.message));
          } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) {
            promise.resolve(callbackArgs[0]);
          } else {
            promise.resolve(callbackArgs);
          }
        };
      };

      const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments";
      /**
       * Creates a wrapper function for a method with the given name and metadata.
       *
       * @param {string} name
       *        The name of the method which is being wrapped.
       * @param {object} metadata
       *        Metadata about the method being wrapped.
       * @param {integer} metadata.minArgs
       *        The minimum number of arguments which must be passed to the
       *        function. If called with fewer than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {integer} metadata.maxArgs
       *        The maximum number of arguments which may be passed to the
       *        function. If called with more than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function(object, ...*)}
       *       The generated wrapper function.
       */


      const wrapAsyncFunction = (name, metadata) => {
        return function asyncFunctionWrapper(target, ...args) {
          if (args.length < metadata.minArgs) {
            throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
          }

          if (args.length > metadata.maxArgs) {
            throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
          }

          return new Promise((resolve, reject) => {
            if (metadata.fallbackToNoCallback) {
              // This API method has currently no callback on Chrome, but it return a promise on Firefox,
              // and so the polyfill will try to call it with a callback first, and it will fallback
              // to not passing the callback if the first call fails.
              try {
                target[name](...args, makeCallback({
                  resolve,
                  reject
                }, metadata));
              } catch (cbError) {
                console.warn(`${name} API method doesn't seem to support the callback parameter, ` + "falling back to call it without a callback: ", cbError);
                target[name](...args); // Update the API method metadata, so that the next API calls will not try to
                // use the unsupported callback anymore.

                metadata.fallbackToNoCallback = false;
                metadata.noCallback = true;
                resolve();
              }
            } else if (metadata.noCallback) {
              target[name](...args);
              resolve();
            } else {
              target[name](...args, makeCallback({
                resolve,
                reject
              }, metadata));
            }
          });
        };
      };
      /**
       * Wraps an existing method of the target object, so that calls to it are
       * intercepted by the given wrapper function. The wrapper function receives,
       * as its first argument, the original `target` object, followed by each of
       * the arguments passed to the original method.
       *
       * @param {object} target
       *        The original target object that the wrapped method belongs to.
       * @param {function} method
       *        The method being wrapped. This is used as the target of the Proxy
       *        object which is created to wrap the method.
       * @param {function} wrapper
       *        The wrapper function which is called in place of a direct invocation
       *        of the wrapped method.
       *
       * @returns {Proxy<function>}
       *        A Proxy object for the given method, which invokes the given wrapper
       *        method in its place.
       */


      const wrapMethod = (target, method, wrapper) => {
        return new Proxy(method, {
          apply(targetMethod, thisObj, args) {
            return wrapper.call(thisObj, target, ...args);
          }

        });
      };

      let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
      /**
       * Wraps an object in a Proxy which intercepts and wraps certain methods
       * based on the given `wrappers` and `metadata` objects.
       *
       * @param {object} target
       *        The target object to wrap.
       *
       * @param {object} [wrappers = {}]
       *        An object tree containing wrapper functions for special cases. Any
       *        function present in this object tree is called in place of the
       *        method in the same location in the `target` object tree. These
       *        wrapper methods are invoked as described in {@see wrapMethod}.
       *
       * @param {object} [metadata = {}]
       *        An object tree containing metadata used to automatically generate
       *        Promise-based wrapper functions for asynchronous. Any function in
       *        the `target` object tree which has a corresponding metadata object
       *        in the same location in the `metadata` tree is replaced with an
       *        automatically-generated wrapper function, as described in
       *        {@see wrapAsyncFunction}
       *
       * @returns {Proxy<object>}
       */

      const wrapObject = (target, wrappers = {}, metadata = {}) => {
        let cache = Object.create(null);
        let handlers = {
          has(proxyTarget, prop) {
            return prop in target || prop in cache;
          },

          get(proxyTarget, prop, receiver) {
            if (prop in cache) {
              return cache[prop];
            }

            if (!(prop in target)) {
              return undefined;
            }

            let value = target[prop];

            if (typeof value === "function") {
              // This is a method on the underlying object. Check if we need to do
              // any wrapping.
              if (typeof wrappers[prop] === "function") {
                // We have a special-case wrapper for this method.
                value = wrapMethod(target, target[prop], wrappers[prop]);
              } else if (hasOwnProperty(metadata, prop)) {
                // This is an async method that we have metadata for. Create a
                // Promise wrapper for it.
                let wrapper = wrapAsyncFunction(prop, metadata[prop]);
                value = wrapMethod(target, target[prop], wrapper);
              } else {
                // This is a method that we don't know or care about. Return the
                // original method, bound to the underlying object.
                value = value.bind(target);
              }
            } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) {
              // This is an object that we need to do some wrapping for the children
              // of. Create a sub-object wrapper for it with the appropriate child
              // metadata.
              value = wrapObject(value, wrappers[prop], metadata[prop]);
            } else if (hasOwnProperty(metadata, "*")) {
              // Wrap all properties in * namespace.
              value = wrapObject(value, wrappers[prop], metadata["*"]);
            } else {
              // We don't need to do any wrapping for this property,
              // so just forward all access to the underlying object.
              Object.defineProperty(cache, prop, {
                configurable: true,
                enumerable: true,

                get() {
                  return target[prop];
                },

                set(value) {
                  target[prop] = value;
                }

              });
              return value;
            }

            cache[prop] = value;
            return value;
          },

          set(proxyTarget, prop, value, receiver) {
            if (prop in cache) {
              cache[prop] = value;
            } else {
              target[prop] = value;
            }

            return true;
          },

          defineProperty(proxyTarget, prop, desc) {
            return Reflect.defineProperty(cache, prop, desc);
          },

          deleteProperty(proxyTarget, prop) {
            return Reflect.deleteProperty(cache, prop);
          }

        }; // Per contract of the Proxy API, the "get" proxy handler must return the
        // original value of the target if that value is declared read-only and
        // non-configurable. For this reason, we create an object with the
        // prototype set to `target` instead of using `target` directly.
        // Otherwise we cannot return a custom object for APIs that
        // are declared read-only and non-configurable, such as `chrome.devtools`.
        //
        // The proxy handlers themselves will still use the original `target`
        // instead of the `proxyTarget`, so that the methods and properties are
        // dereferenced via the original targets.

        let proxyTarget = Object.create(target);
        return new Proxy(proxyTarget, handlers);
      };
      /**
       * Creates a set of wrapper functions for an event object, which handles
       * wrapping of listener functions that those messages are passed.
       *
       * A single wrapper is created for each listener function, and stored in a
       * map. Subsequent calls to `addListener`, `hasListener`, or `removeListener`
       * retrieve the original wrapper, so that  attempts to remove a
       * previously-added listener work as expected.
       *
       * @param {DefaultWeakMap<function, function>} wrapperMap
       *        A DefaultWeakMap object which will create the appropriate wrapper
       *        for a given listener function when one does not exist, and retrieve
       *        an existing one when it does.
       *
       * @returns {object}
       */


      const wrapEvent = wrapperMap => ({
        addListener(target, listener, ...args) {
          target.addListener(wrapperMap.get(listener), ...args);
        },

        hasListener(target, listener) {
          return target.hasListener(wrapperMap.get(listener));
        },

        removeListener(target, listener) {
          target.removeListener(wrapperMap.get(listener));
        }

      });

      const onRequestFinishedWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }
        /**
         * Wraps an onRequestFinished listener function so that it will return a
         * `getContent()` property which returns a `Promise` rather than using a
         * callback API.
         *
         * @param {object} req
         *        The HAR entry object representing the network request.
         */


        return function onRequestFinished(req) {
          const wrappedReq = wrapObject(req, {}
          /* wrappers */
          , {
            getContent: {
              minArgs: 0,
              maxArgs: 0
            }
          });
          listener(wrappedReq);
        };
      }); // Keep track if the deprecation warning has been logged at least once.

      let loggedSendResponseDeprecationWarning = false;
      const onMessageWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }
        /**
         * Wraps a message listener function so that it may send responses based on
         * its return value, rather than by returning a sentinel value and calling a
         * callback. If the listener function returns a Promise, the response is
         * sent when the promise either resolves or rejects.
         *
         * @param {*} message
         *        The message sent by the other end of the channel.
         * @param {object} sender
         *        Details about the sender of the message.
         * @param {function(*)} sendResponse
         *        A callback which, when called with an arbitrary argument, sends
         *        that value as a response.
         * @returns {boolean}
         *        True if the wrapped listener returned a Promise, which will later
         *        yield a response. False otherwise.
         */


        return function onMessage(message, sender, sendResponse) {
          let didCallSendResponse = false;
          let wrappedSendResponse;
          let sendResponsePromise = new Promise(resolve => {
            wrappedSendResponse = function (response) {
              if (!loggedSendResponseDeprecationWarning) {
                console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack);
                loggedSendResponseDeprecationWarning = true;
              }

              didCallSendResponse = true;
              resolve(response);
            };
          });
          let result;

          try {
            result = listener(message, sender, wrappedSendResponse);
          } catch (err) {
            result = Promise.reject(err);
          }

          const isResultThenable = result !== true && isThenable(result); // If the listener didn't returned true or a Promise, or called
          // wrappedSendResponse synchronously, we can exit earlier
          // because there will be no response sent from this listener.

          if (result !== true && !isResultThenable && !didCallSendResponse) {
            return false;
          } // A small helper to send the message if the promise resolves
          // and an error if the promise rejects (a wrapped sendMessage has
          // to translate the message into a resolved promise or a rejected
          // promise).


          const sendPromisedResult = promise => {
            promise.then(msg => {
              // send the message value.
              sendResponse(msg);
            }, error => {
              // Send a JSON representation of the error if the rejected value
              // is an instance of error, or the object itself otherwise.
              let message;

              if (error && (error instanceof Error || typeof error.message === "string")) {
                message = error.message;
              } else {
                message = "An unexpected error occurred";
              }

              sendResponse({
                __mozWebExtensionPolyfillReject__: true,
                message
              });
            }).catch(err => {
              // Print an error on the console if unable to send the response.
              console.error("Failed to send onMessage rejected reply", err);
            });
          }; // If the listener returned a Promise, send the resolved value as a
          // result, otherwise wait the promise related to the wrappedSendResponse
          // callback to resolve and send it as a response.


          if (isResultThenable) {
            sendPromisedResult(result);
          } else {
            sendPromisedResult(sendResponsePromise);
          } // Let Chrome know that the listener is replying.


          return true;
        };
      });

      const wrappedSendMessageCallback = ({
        reject,
        resolve
      }, reply) => {
        if (extensionAPIs.runtime.lastError) {
          // Detect when none of the listeners replied to the sendMessage call and resolve
          // the promise to undefined as in Firefox.
          // See https://github.com/mozilla/webextension-polyfill/issues/130
          if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) {
            resolve();
          } else {
            reject(new Error(extensionAPIs.runtime.lastError.message));
          }
        } else if (reply && reply.__mozWebExtensionPolyfillReject__) {
          // Convert back the JSON representation of the error into
          // an Error instance.
          reject(new Error(reply.message));
        } else {
          resolve(reply);
        }
      };

      const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => {
        if (args.length < metadata.minArgs) {
          throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
        }

        if (args.length > metadata.maxArgs) {
          throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
        }

        return new Promise((resolve, reject) => {
          const wrappedCb = wrappedSendMessageCallback.bind(null, {
            resolve,
            reject
          });
          args.push(wrappedCb);
          apiNamespaceObj.sendMessage(...args);
        });
      };

      const staticWrappers = {
        devtools: {
          network: {
            onRequestFinished: wrapEvent(onRequestFinishedWrappers)
          }
        },
        runtime: {
          onMessage: wrapEvent(onMessageWrappers),
          onMessageExternal: wrapEvent(onMessageWrappers),
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 1,
            maxArgs: 3
          })
        },
        tabs: {
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 2,
            maxArgs: 3
          })
        }
      };
      const settingMetadata = {
        clear: {
          minArgs: 1,
          maxArgs: 1
        },
        get: {
          minArgs: 1,
          maxArgs: 1
        },
        set: {
          minArgs: 1,
          maxArgs: 1
        }
      };
      apiMetadata.privacy = {
        network: {
          "*": settingMetadata
        },
        services: {
          "*": settingMetadata
        },
        websites: {
          "*": settingMetadata
        }
      };
      return wrapObject(extensionAPIs, staticWrappers, apiMetadata);
    };

    if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) {
      throw new Error("This script should only be loaded in a browser extension.");
    } // The build process adds a UMD wrapper around this file, which makes the
    // `module` variable available.


    module.exports = wrapAPIs(chrome);
  } else {
    module.exports = browser;
  }
});


/***/ }),

/***/ 12:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "UV": () => (/* reexport */ toSerializableBlockableItem),
  "iw": () => (/* reexport */ toSerializableFilter),
  "ZB": () => (/* reexport */ toSerializableFilterError),
  "uE": () => (/* reexport */ toSerializableRecommendation),
  "Bp": () => (/* reexport */ toSerializableSubscription)
});

// EXTERNAL MODULE: ./node_modules/@eyeo/webext-ad-filtering-solution/dist/ewe-api.js
var ewe_api = __webpack_require__(120);
;// CONCATENATED MODULE: ./src/core/api/background/serializable.ts

const requestMethods = new Set(["allowing", "header", "request"]);
function toSerializableBlockableItem(item) {
    const { filter, matchInfo, request } = item;
    const isFrame = !requestMethods.has(matchInfo.method);
    let type;
    if (matchInfo.method === "request") {
        type = ewe_api.reporting.contentTypesMap.get(request.type);
    }
    else if (matchInfo.method === "allowing") {
        type = matchInfo.allowingReason;
    }
    else if (filter !== null) {
        type = matchInfo.method;
    }
    else {
        type = ewe_api.reporting.contentTypesMap.get(request.type);
    }
    if (typeof type !== "string") {
        type = "other";
    }
    return {
        docDomain: matchInfo.docDomain,
        isFrame,
        rewrittenUrl: matchInfo.rewrittenUrl,
        type: type.toUpperCase(),
        url: request.url
    };
}
function toSerializableFilter(filter) {
    const { csp, enabled, selector, slow, text, type } = filter;
    const serializable = {
        csp,
        selector,
        slow,
        text,
        type
    };
    if (typeof enabled === "boolean") {
        serializable.disabled = !enabled;
    }
    return serializable;
}
function toSerializableFilterError(filterError) {
    const { option, reason, type } = filterError;
    return {
        option,
        reason,
        type
    };
}
function toSerializableRecommendation(recommendation) {
    const { languages, title, type, url } = recommendation;
    return {
        languages,
        title,
        type,
        url
    };
}
function toSerializableSubscription(subscription) {
    const { downloading, downloadStatus, enabled, expires, homepage, lastDownload, lastSuccess, softExpiration, title, updatable, url, version } = subscription;
    return {
        disabled: !enabled,
        downloading,
        downloadStatus,
        expires,
        homepage,
        lastDownload,
        lastSuccess,
        softExpiration,
        title,
        updatable,
        url,
        version
    };
}

;// CONCATENATED MODULE: ./src/core/api/background/index.ts




/***/ }),

/***/ 808:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "c": () => (/* binding */ isMessage),
/* harmony export */   "g": () => (/* binding */ isPremiumActivateOptions)
/* harmony export */ });
function isMessage(candidate) {
    return (candidate !== null && typeof candidate === "object" && "type" in candidate);
}
function isPremiumActivateOptions(candidate) {
    return (candidate !== null && typeof candidate === "object" && "userId" in candidate);
}


/***/ }),

/***/ 621:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "hasSchedule": () => (/* binding */ hasSchedule),
/* harmony export */   "removeListener": () => (/* binding */ removeListener),
/* harmony export */   "removeSchedule": () => (/* binding */ removeSchedule),
/* harmony export */   "setListener": () => (/* binding */ setListener),
/* harmony export */   "setSchedule": () => (/* binding */ setSchedule)
/* harmony export */ });
/* harmony import */ var _scheduled_event_emitter_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(220);
/* harmony import */ var _adblockpluschrome_lib_storage_session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(137);


const storageKey = "schedules";
const storage = new _adblockpluschrome_lib_storage_session__WEBPACK_IMPORTED_MODULE_1__.SessionStorage("ScheduledEventEmitter.storage");
const initialization = initialize();
let schedules = Object.create(null);
const listeners = new Map();
async function setListener(name, listener) {
    await initialization;
    if (listeners.has(name)) {
        warn(`Overwriting already registered listener for event "${name}".`);
    }
    listeners.set(name, listener);
    activateSchedules();
}
async function setSchedule(name, time, scheduleType = _scheduled_event_emitter_types__WEBPACK_IMPORTED_MODULE_0__/* .ScheduleType.once */ .I.once) {
    await initialization;
    if (name in schedules) {
        warn(`Overwriting already registered schedule for name "${name}".`);
    }
    schedules[name] = {
        period: time,
        next: time + Date.now(),
        runOnce: scheduleType === _scheduled_event_emitter_types__WEBPACK_IMPORTED_MODULE_0__/* .ScheduleType.once */ .I.once,
        count: 0
    };
    await persistSchedules();
    activateSchedules();
}
async function removeSchedule(name) {
    await initialization;
    const schedule = schedules[name];
    if (!schedule) {
        return;
    }
    if (schedule.runOnce) {
        self.clearTimeout(schedule.activationId);
    }
    else {
        self.clearInterval(schedule.activationId);
    }
    delete schedules[name];
    await persistSchedules();
}
function hasSchedule(name) {
    return name in schedules;
}
async function removeListener(name) {
    await initialization;
    listeners.delete(name);
}
async function initialize() {
    await reviveSchedules();
}
async function persistSchedules() {
    await storage.set(storageKey, schedules);
}
async function reviveSchedules() {
    const storedSchedules = await storage.get(storageKey);
    if (Object.prototype.toString.call(storedSchedules) !== "[object Object]") {
        warn("Could not restore stored schedules.");
        return;
    }
    schedules = storedSchedules;
    Object.keys(schedules).forEach((name) => {
        delete schedules[name].activationId;
    });
}
function activateSchedules() {
    const now = Date.now();
    Object.entries(schedules).forEach(([name, schedule]) => {
        const delta = schedule.next - now;
        const isDue = delta <= 0;
        const activationKey = "activationId";
        if (activationKey in schedule) {
            return;
        }
        if (!schedule.runOnce) {
            schedule.activationId = self.setInterval(() => {
                void emitEvent(name);
            }, schedule.period);
            return;
        }
        if (!isDue) {
            schedule.activationId = self.setTimeout(() => {
                void emitEvent(name);
            }, delta);
            return;
        }
        void emitEvent(name);
    });
}
async function emitEvent(name) {
    const schedule = schedules[name];
    const listener = listeners.get(name);
    if (!schedule || !listener) {
        return;
    }
    schedule.count += 1;
    const now = Date.now();
    const callCount = schedule.count;
    listener({ callCount });
    if (schedule.runOnce) {
        await removeSchedule(name);
    }
    else {
        schedule.next = now + schedule.period;
        await persistSchedules();
    }
}
function warn(message) {
    console.warn(`[ScheduledEventEmitter]: ${message}`);
}


/***/ }),

/***/ 220:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "I": () => (/* binding */ ScheduleType)
/* harmony export */ });
var ScheduleType;
(function (ScheduleType) {
    ScheduleType["once"] = "once";
    ScheduleType["interval"] = "interval";
})(ScheduleType || (ScheduleType = {}));


/***/ }),

/***/ 88:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "I8": () => (/* binding */ extractHostFromFrame),
/* harmony export */   "Nm": () => (/* binding */ isActiveOnDomain),
/* harmony export */   "Vx": () => (/* binding */ isDomainList)
/* harmony export */ });
function parseDomains(source, separator) {
    let domains;
    if (source[0] !== "~" && !source.includes(separator)) {
        domains = new Map([
            ["", false],
            [source, true]
        ]);
    }
    else {
        domains = null;
        let hasIncludes = false;
        for (let domain of source.split(separator)) {
            if (domain === "") {
                continue;
            }
            let include;
            if (domain[0] === "~") {
                include = false;
                domain = domain.substring(1);
            }
            else {
                include = true;
                hasIncludes = true;
            }
            if (!domains) {
                domains = new Map();
            }
            domains.set(domain, include);
        }
        if (domains) {
            domains.set("", !hasIncludes);
        }
    }
    return domains;
}
function isIPAddress(hostname) {
    if (hostname[0] === "[" && hostname[hostname.length - 1] === "]") {
        return true;
    }
    return (Number(hostname[hostname.length - 1]) >= 0 &&
        /^\d+\.\d+\.\d+\.\d+$/.test(hostname));
}
function isValidIPv4Address(address) {
    return /^(((2[0-4]|1[0-9]|[1-9])?[0-9]|25[0-5])\.){4}$/.test(address + ".");
}
function isValidHostname(hostname) {
    if (isValidIPv4Address(hostname)) {
        return true;
    }
    if (hostname[0] === "[" && hostname[hostname.length - 1] === "]") {
        return true;
    }
    if (hostname[hostname.length - 1] === ".") {
        hostname = hostname.substring(0, hostname.length - 1);
    }
    if (hostname.length > 253)
        return false;
    const labels = hostname.split(".");
    for (const label of labels) {
        if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))
            return false;
    }
    if (!/\D/.test(labels[labels.length - 1]))
        return false;
    return true;
}
function* domainSuffixes(domain, includeBlank = false) {
    if (isIPAddress(domain)) {
        yield domain;
    }
    else {
        if (domain[domain.length - 1] === ".") {
            domain = domain.substring(0, domain.length - 1);
        }
        while (domain !== "") {
            yield domain;
            const dotIndex = domain.indexOf(".");
            domain = dotIndex === -1 ? "" : domain.substr(dotIndex + 1);
        }
    }
    if (includeBlank) {
        yield "";
    }
}
function isActiveOnDomain(url, domainList) {
    if (!domainList) {
        return true;
    }
    const domains = parseDomains(domainList, ",");
    if (!domains) {
        return true;
    }
    const tabURL = new URL(url);
    let tabDomain = tabURL.hostname;
    if (tabDomain === null) {
        tabDomain = "";
    }
    else if (tabDomain[tabDomain.length - 1] === ".") {
        tabDomain = tabDomain.substring(0, tabDomain.length - 1);
    }
    if (!tabDomain) {
        return !!domains.get("");
    }
    for (tabDomain of domainSuffixes(tabDomain)) {
        const isDomainIncluded = domains.get(tabDomain);
        if (typeof isDomainIncluded !== "undefined") {
            return isDomainIncluded;
        }
    }
    return !!domains.get("");
}
function isDomainList(list) {
    const domains = parseDomains(list, ",");
    if (domains === null) {
        return true;
    }
    return Array.from(domains.keys()).every((domain) => !domain || isValidHostname(domain));
}
function extractHostFromFrame(frame, originUrl) {
    for (; frame; frame = frame.parent) {
        const { hostname } = frame.url;
        if (hostname) {
            return hostname;
        }
    }
    return originUrl ? originUrl.hostname : "";
}


/***/ }),

/***/ 153:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "l": () => (/* reexport */ getInstallationId)
});

// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
;// CONCATENATED MODULE: ./src/id/shared/uuid.ts
const { crypto: uuid_crypto } = self;
function generateUUID() {
    const uuid = new Uint16Array(8);
    uuid_crypto.getRandomValues(uuid);
    uuid[3] = (uuid[3] & 0x0fff) | 0x4000;
    uuid[4] = (uuid[4] & 0x3fff) | 0x8000;
    const uuidChunks = [];
    for (let i = 0; i < uuid.length; i += 1) {
        const component = uuid[i].toString(16);
        uuidChunks.push(`000${component}`.slice(-4));
        if (i >= 1 && i <= 4)
            uuidChunks.push("-");
    }
    return uuidChunks.join("");
}
function getUUID() {
    return "randomUUID" in uuid_crypto ? uuid_crypto.randomUUID() : generateUUID();
}

;// CONCATENATED MODULE: ./src/id/shared/index.ts


;// CONCATENATED MODULE: ./src/id/background/id.ts


const installationIdStorageKey = "installation_id";
async function getInstallationId() {
    await prefs.Prefs.untilLoaded;
    let id = prefs.Prefs.get(installationIdStorageKey);
    if (id === "") {
        id = getUUID();
        void prefs.Prefs.set(installationIdStorageKey, id);
    }
    return id;
}

;// CONCATENATED MODULE: ./src/id/background/index.ts



/***/ }),

/***/ 42:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "BL": () => (/* binding */ start),
/* harmony export */   "J": () => (/* binding */ getBehavior),
/* harmony export */   "L5": () => (/* binding */ getContent),
/* harmony export */   "LE": () => (/* binding */ executeIPMCommand),
/* harmony export */   "_E": () => (/* binding */ dismissCommand),
/* harmony export */   "yA": () => (/* binding */ setCommandActor)
/* harmony export */ });
/* harmony import */ var _command_library_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(822);
/* harmony import */ var _logger_background__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(678);
/* harmony import */ var _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(968);



const knownCommandsList = Object.values(_command_library_types__WEBPACK_IMPORTED_MODULE_0__/* .CommandName */ .G7);
const commandStorageKey = "ipm_commands";
const actorByCommandName = new Map();
const unexecutableCommands = new Map();
function isCommand(candidate) {
    return (typeof candidate === "object" &&
        candidate !== null &&
        "version" in candidate &&
        "ipm_id" in candidate &&
        "command_name" in candidate);
}
function setCommandActor(commandName, actor) {
    actorByCommandName.set(commandName, actor);
    retryExecuteCommands(commandName);
}
function canProcessCommand(command) {
    return (knownCommandsList.includes(command.command_name) &&
        command.version === _command_library_types__WEBPACK_IMPORTED_MODULE_0__/* .CommandVersion */ .Pk[command.command_name]);
}
function dismissCommand(ipmId) {
    const command = getCommand(ipmId);
    if (!command) {
        return;
    }
    const commandStorage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.get(commandStorageKey);
    delete commandStorage[command.ipm_id];
    void _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.set(commandStorageKey, commandStorage);
}
function getBehavior(ipmId) {
    const command = getCommand(ipmId);
    if (!command) {
        return null;
    }
    const actor = actorByCommandName.get(command.command_name);
    if (!actor) {
        return null;
    }
    return actor.getBehavior(command);
}
function getCommand(ipmId) {
    const commandStorage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.get(commandStorageKey);
    return commandStorage[ipmId] || null;
}
function getContent(ipmId) {
    const command = getCommand(ipmId);
    if (!command) {
        return null;
    }
    const actor = actorByCommandName.get(command.command_name);
    if (!actor) {
        return null;
    }
    return actor.getContent(command);
}
function hasProcessedCommand(ipmId) {
    const commandStorage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.get(commandStorageKey);
    return ipmId in commandStorage;
}
function retryExecuteCommands(commandName) {
    for (const [command, isInitialization] of unexecutableCommands) {
        if (command.command_name !== commandName) {
            continue;
        }
        unexecutableCommands.delete(command);
        executeIPMCommand(command, isInitialization);
    }
}
function storeCommand(command) {
    const storage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.get(commandStorageKey);
    storage[command.ipm_id] = command;
    void _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.set(commandStorageKey, storage);
}
function executeIPMCommand(command, isInitialization = false) {
    if (!isCommand(command)) {
        _logger_background__WEBPACK_IMPORTED_MODULE_1__/* .error */ .vU("[ipm]: Invalid command received.");
        return;
    }
    if (!canProcessCommand(command)) {
        _logger_background__WEBPACK_IMPORTED_MODULE_1__/* .error */ .vU("[ipm]: Unknown command name received:", command.command_name);
        return;
    }
    const actor = actorByCommandName.get(command.command_name);
    if (!actor) {
        _logger_background__WEBPACK_IMPORTED_MODULE_1__/* .debug */ .fF("[ipm]: No actor found:", command.command_name);
        unexecutableCommands.set(command, isInitialization);
        return;
    }
    if (!actor.isValidCommand(command)) {
        _logger_background__WEBPACK_IMPORTED_MODULE_1__/* .error */ .vU("[ipm]: Invalid parameters received.");
        return;
    }
    if (!isInitialization) {
        if (hasProcessedCommand(command.ipm_id)) {
            _logger_background__WEBPACK_IMPORTED_MODULE_1__/* .error */ .vU("[ipm]: Campaign already processed:", command.ipm_id);
            return;
        }
        storeCommand(command);
    }
    void actor.handleCommand(command.ipm_id);
}
async function start() {
    await _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.untilLoaded;
    const commandStorage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_2__.Prefs.get(commandStorageKey);
    for (const command of Object.values(commandStorage)) {
        executeIPMCommand(command, true);
    }
}


/***/ }),

/***/ 822:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "AB": () => (/* binding */ commandLibraryVersion),
/* harmony export */   "G7": () => (/* binding */ CommandName),
/* harmony export */   "Pk": () => (/* binding */ CommandVersion)
/* harmony export */ });
const commandLibraryVersion = 1;
var CommandName;
(function (CommandName) {
    CommandName["createOnPageDialog"] = "create_on_page_dialog";
    CommandName["createTab"] = "create_tab";
})(CommandName || (CommandName = {}));
const CommandVersion = {
    [CommandName.createOnPageDialog]: 4,
    [CommandName.createTab]: 4
};


/***/ }),

/***/ 430:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "He": () => (/* binding */ getPayload),
/* harmony export */   "Ny": () => (/* binding */ recordEvent),
/* harmony export */   "QF": () => (/* binding */ clearEvents)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(935);
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(968);
/* harmony import */ var _command_library_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(822);
/* harmony import */ var _data_collection_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(385);
/* harmony import */ var _premium_background__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(282);
/* harmony import */ var _id_background__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(153);
/* harmony import */ var _info_background__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(463);







function leftPad(value) {
    return value.toString().padStart(2, "0");
}
function getLocalTimeStamp() {
    const date = new Date();
    return [
        date.getFullYear(),
        "-",
        leftPad(date.getMonth() + 1),
        "-",
        leftPad(date.getDate()),
        "T",
        leftPad(date.getHours()),
        ":",
        leftPad(date.getMinutes()),
        ":",
        leftPad(date.getSeconds())
    ].join("");
}
async function getBaseAttributes() {
    return {
        app_name: _info_background__WEBPACK_IMPORTED_MODULE_6__.info.baseName,
        browser_name: _info_background__WEBPACK_IMPORTED_MODULE_6__.info.application,
        os: (await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.getPlatformInfo()).os,
        language_tag: webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.i18n.getUILanguage(),
        app_version: _info_background__WEBPACK_IMPORTED_MODULE_6__.info.addonVersion,
        command_library_version: _command_library_types__WEBPACK_IMPORTED_MODULE_2__/* .commandLibraryVersion */ .AB,
        install_type: (await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.management.getSelf()).installType
    };
}
async function getEventData(ipmId, command, name) {
    return {
        type: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .DataType.event */ .g.event,
        device_id: await (0,_id_background__WEBPACK_IMPORTED_MODULE_5__/* .getInstallationId */ .l)(),
        action: name,
        platform: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .PlatformType.web */ .zh.web,
        app_version: _info_background__WEBPACK_IMPORTED_MODULE_6__.info.addonVersion,
        user_time: getLocalTimeStamp(),
        attributes: {
            ...(await getBaseAttributes()),
            ipm_id: ipmId,
            command_name: command,
            command_version: _command_library_types__WEBPACK_IMPORTED_MODULE_2__/* .CommandVersion */ .Pk[command]
        }
    };
}
async function getDeviceData() {
    await _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.untilLoaded;
    return {
        type: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .DataType.device */ .g.device,
        device_id: await (0,_id_background__WEBPACK_IMPORTED_MODULE_5__/* .getInstallationId */ .l)(),
        attributes: {
            ...(await getBaseAttributes()),
            blocked_total: 0,
            license_status: (0,_premium_background__WEBPACK_IMPORTED_MODULE_4__/* .getPremiumState */ .rh)().isActive
                ? _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .LicenseState.active */ .uN.active
                : _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .LicenseState.inactive */ .uN.inactive
        }
    };
}
async function getUserData() {
    return {
        type: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .DataType.customer */ .g.customer,
        platforms: [{ platform: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .PlatformType.web */ .zh.web, active: _data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .PlatformStatus["true"] */ .ag["true"] }],
        attributes: await getBaseAttributes()
    };
}
async function getPayload() {
    await _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.untilLoaded;
    const user = await getUserData();
    const device = await getDeviceData();
    const events = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.get(_data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .eventStorageKey */ .x0);
    return { user, device, events };
}
async function clearEvents() {
    await _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.untilLoaded;
    void _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.set(_data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .eventStorageKey */ .x0, []);
}
async function recordEvent(ipmId, command, name) {
    await _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.untilLoaded;
    const eventData = await getEventData(ipmId, command, name);
    const eventStorage = _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.get(_data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .eventStorageKey */ .x0);
    eventStorage.push(eventData);
    void _adblockpluschrome_lib_prefs__WEBPACK_IMPORTED_MODULE_1__.Prefs.set(_data_collection_types__WEBPACK_IMPORTED_MODULE_3__/* .eventStorageKey */ .x0, eventStorage);
}


/***/ }),

/***/ 385:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ag": () => (/* binding */ PlatformStatus),
/* harmony export */   "g": () => (/* binding */ DataType),
/* harmony export */   "uN": () => (/* binding */ LicenseState),
/* harmony export */   "x0": () => (/* binding */ eventStorageKey),
/* harmony export */   "zh": () => (/* binding */ PlatformType)
/* harmony export */ });
var DataType;
(function (DataType) {
    DataType["customer"] = "customer";
    DataType["device"] = "device";
    DataType["event"] = "event";
})(DataType || (DataType = {}));
var PlatformType;
(function (PlatformType) {
    PlatformType["web"] = "web";
})(PlatformType || (PlatformType = {}));
var LicenseState;
(function (LicenseState) {
    LicenseState["active"] = "premium";
    LicenseState["inactive"] = "free";
})(LicenseState || (LicenseState = {}));
var PlatformStatus;
(function (PlatformStatus) {
    PlatformStatus["true"] = "true";
})(PlatformStatus || (PlatformStatus = {}));
const eventStorageKey = "ipm_events";


/***/ }),

/***/ 386:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "G7": () => (/* reexport */ command_library_types/* CommandName */.G7),
  "qX": () => (/* reexport */ createSafeOriginUrl),
  "CD": () => (/* reexport */ defaultLicenseState),
  "_E": () => (/* reexport */ command_library/* dismissCommand */._E),
  "a9": () => (/* reexport */ doesLicenseStateMatch),
  "J": () => (/* reexport */ command_library/* getBehavior */.J),
  "L5": () => (/* reexport */ command_library/* getContent */.L5),
  "UE": () => (/* reexport */ isNotEmpty),
  "w6": () => (/* reexport */ isSafeUrl),
  "h8": () => (/* reexport */ isValidDomainList),
  "Bi": () => (/* reexport */ isValidLicenseStateList),
  "Ny": () => (/* reexport */ data_collection/* recordEvent */.Ny),
  "yA": () => (/* reexport */ command_library/* setCommandActor */.yA),
  "BL": () => (/* reexport */ command_library/* start */.BL),
  "VL": () => (/* reexport */ telemetry/* start */.B),
  "uU": () => (/* reexport */ validateParams)
});

// UNUSED EXPORTS: CommandVersion, DataType, LicenseState, PlatformStatus, PlatformType, clearEvents, commandLibraryVersion, eventStorageKey, executeIPMCommand, getPayload, isNumeric, isValidLicenseState

// EXTERNAL MODULE: ./src/ipm/background/command-library.ts
var command_library = __webpack_require__(42);
// EXTERNAL MODULE: ./src/ipm/background/command-library.types.ts
var command_library_types = __webpack_require__(822);
// EXTERNAL MODULE: ./src/ipm/background/data-collection.ts
var data_collection = __webpack_require__(430);
// EXTERNAL MODULE: ./src/ipm/background/data-collection.types.ts
var data_collection_types = __webpack_require__(385);
// EXTERNAL MODULE: ./src/premium/background/index.ts + 1 modules
var background = __webpack_require__(282);
;// CONCATENATED MODULE: ./src/ipm/background/license.ts


const defaultLicenseState = data_collection_types/* LicenseState.inactive */.uN.inactive;
function isValidLicenseState(candidate) {
    return (typeof candidate === "string" &&
        Object.values(data_collection_types/* LicenseState */.uN).includes(candidate));
}
async function doesLicenseStateMatch(behavior) {
    if (!behavior.licenseStateList) {
        return true;
    }
    const licenseStates = behavior.licenseStateList.split(",");
    const { isActive } = (0,background/* getPremiumState */.rh)();
    for (const licenseState of licenseStates) {
        if (licenseState === data_collection_types/* LicenseState.inactive */.uN.inactive && !isActive) {
            return true;
        }
        if (licenseState === data_collection_types/* LicenseState.active */.uN.active && isActive) {
            return true;
        }
    }
    return false;
}

// EXTERNAL MODULE: ./src/core/url/shared/url.ts
var url = __webpack_require__(88);
// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
;// CONCATENATED MODULE: ./src/ipm/background/url.ts

function createSafeOriginUrl(url) {
    const defaultOrigin = prefs.Prefs.get("ipm_default_origin");
    const safeOrigins = prefs.Prefs.get("ipm_safe_origins");
    let safeOriginUrl;
    try {
        safeOriginUrl = new URL(url, defaultOrigin);
    }
    catch (ex) {
        return null;
    }
    if (!safeOrigins.includes(safeOriginUrl.origin)) {
        return null;
    }
    return safeOriginUrl.href;
}

;// CONCATENATED MODULE: ./src/ipm/background/param-validator.ts



const isNumeric = (param) => typeof param === "number" && !Number.isNaN(param);
const isNotEmpty = (param) => typeof param === "string" && param.length > 0;
const isValidLicenseStateList = (param) => {
    if (!param) {
        return true;
    }
    if (typeof param !== "string") {
        return false;
    }
    const licenseStates = param.split(",");
    return licenseStates.every((state) => isValidLicenseState(state));
};
const isSafeUrl = (param) => {
    if (typeof param !== "string") {
        return false;
    }
    const url = createSafeOriginUrl(param);
    return typeof url === "string";
};
const isValidDomainList = (param) => {
    if (!param) {
        return true;
    }
    if (typeof param !== "string") {
        return false;
    }
    return (0,url/* isDomainList */.Vx)(param);
};
function validateParams(command, paramDefinitions) {
    return paramDefinitions
        .map((definition) => {
        const name = String(definition.name);
        const param = command[name];
        return definition.validate(param)
            ? ""
            : `Invalid value for parameter "${name}", got "${String(param)}":`;
    })
        .filter((result) => result !== "");
}

// EXTERNAL MODULE: ./src/ipm/background/telemetry.ts + 2 modules
var telemetry = __webpack_require__(887);
;// CONCATENATED MODULE: ./src/ipm/background/index.ts











/***/ }),

/***/ 887:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "_": () => (/* binding */ sendPing),
  "B": () => (/* binding */ start)
});

// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
// EXTERNAL MODULE: ./src/core/scheduled-event-emitter/background/scheduled-event-emitter.ts
var scheduled_event_emitter = __webpack_require__(621);
// EXTERNAL MODULE: ./src/core/scheduled-event-emitter/background/scheduled-event-emitter.types.ts
var scheduled_event_emitter_types = __webpack_require__(220);
;// CONCATENATED MODULE: ./src/core/scheduled-event-emitter/background/index.ts



// EXTERNAL MODULE: ./src/ipm/background/command-library.ts
var command_library = __webpack_require__(42);
// EXTERNAL MODULE: ./src/ipm/background/data-collection.ts
var data_collection = __webpack_require__(430);
// EXTERNAL MODULE: ./src/logger/background/index.ts + 2 modules
var background = __webpack_require__(678);
;// CONCATENATED MODULE: ./src/ipm/background/telemetry.types.ts
const scheduleName = "ipm_ping_schedule";
const intervalKey = "ipm_ping_interval";
const serverUrlKey = "ipm_server_url";

;// CONCATENATED MODULE: ./src/ipm/background/telemetry.ts






async function processResponse(response) {
    if (!response.ok) {
        (0,background/* error */.vU)(`[Telemetry]: Bad response status from IPM server: ${response.status}`);
        return;
    }
    const body = await response.text();
    if (body.length === 0) {
        return;
    }
    try {
        const command = JSON.parse(body);
        (0,command_library/* executeIPMCommand */.LE)(command);
    }
    catch (error) {
        (0,background/* error */.vU)("[Telemetry]: Error parsing IPM response.", error);
    }
}
async function sendPing() {
    if (prefs.Prefs.get("data_collection_opt_out") === true) {
        return;
    }
    const payload = await (0,data_collection/* getPayload */.He)();
    void (0,data_collection/* clearEvents */.QF)();
    void fetch(prefs.Prefs.get(serverUrlKey), {
        method: "POST",
        cache: "no-cache",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
    })
        .then(processResponse)
        .catch((error) => {
        (0,background/* error */.vU)("[Telemetry]: Ping sending failed with error:", error);
    });
}
async function start() {
    void (0,scheduled_event_emitter.setListener)(scheduleName, () => {
        void sendPing();
    });
    if (!(0,scheduled_event_emitter.hasSchedule)(scheduleName)) {
        await prefs.Prefs.untilLoaded;
        void sendPing();
        void (0,scheduled_event_emitter.setSchedule)(scheduleName, prefs.Prefs.get(intervalKey), scheduled_event_emitter_types/* ScheduleType.interval */.I.interval);
    }
}


/***/ }),

/***/ 678:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "fF": () => (/* reexport */ debug),
  "vU": () => (/* reexport */ error),
  "ZK": () => (/* reexport */ warn)
});

// UNUSED EXPORTS: LogLevel, info

// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
;// CONCATENATED MODULE: ./src/logger/background/logger.types.ts
var LogLevel;
(function (LogLevel) {
    LogLevel[LogLevel["debug"] = 1] = "debug";
    LogLevel[LogLevel["info"] = 2] = "info";
    LogLevel[LogLevel["warn"] = 3] = "warn";
    LogLevel[LogLevel["error"] = 4] = "error";
})(LogLevel || (LogLevel = {}));

;// CONCATENATED MODULE: ./src/logger/background/logger.ts


function log(level, fn, ...data) {
    const minLevel = prefs.Prefs.get("logger_log_level");
    if (level < minLevel) {
        return;
    }
    fn(...data);
}
const debug = log.bind(null, LogLevel.debug, console.debug);
const error = log.bind(null, LogLevel.error, console.error);
const info = log.bind(null, LogLevel.info, console.info);
const warn = log.bind(null, LogLevel.warn, console.warn);

;// CONCATENATED MODULE: ./src/logger/background/index.ts




/***/ }),

/***/ 282:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "uY": () => (/* reexport */ emitter),
  "p2": () => (/* reexport */ getAuthPayload),
  "rh": () => (/* reexport */ getPremiumState),
  "BL": () => (/* reexport */ start)
});

// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/events.js
var events = __webpack_require__(370);
// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/port.js
var port = __webpack_require__(305);
// EXTERNAL MODULE: ./adblockpluschrome/lib/events.js
var lib_events = __webpack_require__(491);
// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
// EXTERNAL MODULE: ./src/core/scheduled-event-emitter/background/scheduled-event-emitter.ts
var scheduled_event_emitter = __webpack_require__(621);
// EXTERNAL MODULE: ./src/core/api/shared/api.ts
var api = __webpack_require__(808);
// EXTERNAL MODULE: ./src/core/scheduled-event-emitter/background/scheduled-event-emitter.types.ts
var scheduled_event_emitter_types = __webpack_require__(220);
;// CONCATENATED MODULE: ./src/premium/background/license.ts







class InvalidLicenseError extends Error {
}
const emitter = new lib_events/* EventEmitter */.v();
const licenseCheckPeriod = 24 * 60 * 60 * 1000;
let licenseCheckTimeoutId = null;
const licenseCheckRetryDelay = 60 * 1000;
const licenseCheckRetryEventName = "premium.license.check.retry";
function activateLicense(oldLicense, newLicense) {
    void prefs.Prefs.set("premium_license", newLicense);
    void scheduled_event_emitter.removeSchedule(licenseCheckRetryEventName);
    if (oldLicense.status === "active") {
        emitter.emit("updated");
    }
    else {
        scheduleNextLicenseCheck(null);
        emitter.emit("activated");
    }
}
async function checkLicense(retryCount = 0) {
    if (retryCount >= 3) {
        void scheduled_event_emitter.removeSchedule(licenseCheckRetryEventName);
        if (retryCount > 3) {
            return;
        }
    }
    const userId = prefs.Prefs.get("premium_user_id");
    if (!userId) {
        return;
    }
    try {
        if (!navigator.onLine) {
            throw new Error("No network connection");
        }
        const requestData = {
            cmd: "license_check",
            u: userId,
            v: "1"
        };
        const requestUrl = prefs.Prefs.get("premium_license_check_url");
        const response = await fetch(requestUrl, {
            method: "POST",
            cache: "no-cache",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(requestData)
        });
        if (!response.ok) {
            const { status } = response;
            if (status >= 400 && status <= 499) {
                throw new Error(`Request failed (code: ${status})`);
            }
            if (status >= 500 && status <= 599) {
                throw new Error(`Received error response (code: ${status})`);
            }
            console.error(`Received unexpected response (code: ${status})`);
            return;
        }
        const oldLicense = prefs.Prefs.get("premium_license");
        const newLicense = (await response.json());
        const { lv: licenseVersion } = newLicense;
        if (licenseVersion !== 1) {
            throw new InvalidLicenseError(`Invalid license version: ${String(licenseVersion)}`);
        }
        if (oldLicense.status === "active" && newLicense.status === "expired") {
            throw new InvalidLicenseError("Expired license");
        }
        if (newLicense.status !== "active") {
            throw new InvalidLicenseError(`Unknown license status: ${newLicense.status}`);
        }
        if (!newLicense.code) {
            if (!oldLicense.code) {
                throw new InvalidLicenseError("Undefined license code");
            }
            newLicense.code = oldLicense.code;
        }
        activateLicense(oldLicense, newLicense);
    }
    catch (ex) {
        if (ex instanceof InvalidLicenseError) {
            console.error("Invalid Premium license", ex);
            deactivateLicense();
        }
        else {
            console.warn(`Premium license check failed (retries: ${retryCount})`, ex);
            if (retryCount > 0) {
                return;
            }
            void scheduled_event_emitter.setSchedule(licenseCheckRetryEventName, licenseCheckRetryDelay, scheduled_event_emitter_types/* ScheduleType.interval */.I.interval);
        }
    }
}
function deactivateLicense() {
    void prefs.Prefs.reset("premium_license");
    void prefs.Prefs.reset("premium_license_nextcheck");
    void prefs.Prefs.reset("premium_user_id");
    void scheduled_event_emitter.removeSchedule(licenseCheckRetryEventName);
    if (licenseCheckTimeoutId !== null) {
        self.clearTimeout(licenseCheckTimeoutId);
    }
    emitter.emit("deactivated");
}
function getAuthPayload() {
    if (!hasActiveLicense()) {
        return null;
    }
    const license = prefs.Prefs.get("premium_license");
    return `${license.encodedData}.${license.signature}`;
}
function getPremiumState() {
    return { isActive: hasActiveLicense() };
}
function hasActiveLicense() {
    const license = prefs.Prefs.get("premium_license");
    return license.status === "active";
}
function scheduleNextLicenseCheck(nextTimestamp) {
    if (!nextTimestamp) {
        nextTimestamp = Date.now() + licenseCheckPeriod;
        void prefs.Prefs.set("premium_license_nextcheck", nextTimestamp);
    }
    licenseCheckTimeoutId = self.setTimeout(() => {
        void checkLicense();
        scheduleNextLicenseCheck(null);
    }, nextTimestamp - Date.now());
}
function initializeLicenseChecks() {
    void scheduled_event_emitter.setListener(licenseCheckRetryEventName, (info) => {
        void checkLicense(info.callCount);
    });
    const nextCheckTimestamp = prefs.Prefs.get("premium_license_nextcheck");
    if (!nextCheckTimestamp) {
        return;
    }
    scheduleNextLicenseCheck(nextCheckTimestamp);
}
function initializeMessaging() {
    port.port.on("premium.activate", async (msg) => {
        if (!(0,api/* isPremiumActivateOptions */.g)(msg)) {
            return false;
        }
        if (!msg.userId) {
            return false;
        }
        void prefs.Prefs.set("premium_user_id", msg.userId);
        await checkLicense();
        return true;
    });
    port.port.on("premium.get", () => getPremiumState());
    (0,events/* installHandler */.a)("premium", "changed", (emit) => {
        const onChanged = () => {
            emit(getPremiumState());
        };
        emitter.on("activated", onChanged);
        emitter.on("deactivated", onChanged);
        return () => {
            emitter.off("activated", onChanged);
            emitter.off("deactivated", onChanged);
        };
    });
    ext.addTrustedMessageTypes(prefs.Prefs.get("premium_license_activation_origin"), [
        "premium.activate"
    ]);
}
function start() {
    initializeMessaging();
    initializeLicenseChecks();
}

;// CONCATENATED MODULE: ./src/premium/background/index.ts




/***/ }),

/***/ 351:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "kQ": () => (/* reexport */ ReadyState),
  "PL": () => (/* reexport */ setReadyState),
  "BL": () => (/* reexport */ start)
});

// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/port.js
var port = __webpack_require__(305);
;// CONCATENATED MODULE: ./src/testing/ready-state/background/ready-state.types.ts
var ReadyState;
(function (ReadyState) {
    ReadyState["loading"] = "loading";
    ReadyState["started"] = "started";
})(ReadyState || (ReadyState = {}));

;// CONCATENATED MODULE: ./src/testing/ready-state/background/ready-state.ts


let state = ReadyState.loading;
function setReadyState(newState) {
    state = newState;
}
function getReadyState() {
    return state;
}
function start() {
    port.port.on("testing.getReadyState", () => getReadyState());
}

;// CONCATENATED MODULE: ./src/testing/ready-state/background/index.ts




/***/ }),

/***/ 3:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "X": () => (/* binding */ getMajorVersion),
/* harmony export */   "n": () => (/* binding */ compareVersions)
/* harmony export */ });
function parseVersionComponent(comp) {
    if (comp === "*") {
        return Infinity;
    }
    const parsed = parseInt(comp, 10);
    if (Number.isNaN(parsed)) {
        return 0;
    }
    return parsed;
}
function compareVersions(v1, v2) {
    var _a, _b;
    const regexp = /^(.*?)([a-z].*)?$/i;
    const [, head1, tail1] = (_a = regexp.exec(v1)) !== null && _a !== void 0 ? _a : [];
    const [, head2, tail2] = (_b = regexp.exec(v2)) !== null && _b !== void 0 ? _b : [];
    const components1 = head1.split(".");
    const components2 = head2.split(".");
    for (let i = 0; i < components1.length || i < components2.length; i++) {
        const result = parseVersionComponent(components1[i]) -
            parseVersionComponent(components2[i]);
        if (result < 0) {
            return -1;
        }
        if (result > 0) {
            return 1;
        }
    }
    if (tail1 === tail2) {
        return 0;
    }
    if (tail1 === undefined || (tail2 !== undefined && tail1 > tail2)) {
        return 1;
    }
    return -1;
}
function getMajorVersion(version) {
    const majorVersion = version.split(".").shift();
    return typeof majorVersion === "string" ? majorVersion : "0";
}


/***/ }),

/***/ 120:
/***/ ((module) => {

(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(self, () => {
return /******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "./core/data/icannPublicSuffixList.js":
/*!********************************************!*\
  !*** ./core/data/icannPublicSuffixList.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, exports) => {

exports.icannPublicSuffixes = {
  "ac": 1,
  "com.ac": 1,
  "edu.ac": 1,
  "gov.ac": 1,
  "net.ac": 1,
  "mil.ac": 1,
  "org.ac": 1,
  "ad": 1,
  "nom.ad": 1,
  "ae": 1,
  "co.ae": 1,
  "net.ae": 1,
  "org.ae": 1,
  "sch.ae": 1,
  "ac.ae": 1,
  "gov.ae": 1,
  "mil.ae": 1,
  "aero": 1,
  "accident-investigation.aero": 1,
  "accident-prevention.aero": 1,
  "aerobatic.aero": 1,
  "aeroclub.aero": 1,
  "aerodrome.aero": 1,
  "agents.aero": 1,
  "aircraft.aero": 1,
  "airline.aero": 1,
  "airport.aero": 1,
  "air-surveillance.aero": 1,
  "airtraffic.aero": 1,
  "air-traffic-control.aero": 1,
  "ambulance.aero": 1,
  "amusement.aero": 1,
  "association.aero": 1,
  "author.aero": 1,
  "ballooning.aero": 1,
  "broker.aero": 1,
  "caa.aero": 1,
  "cargo.aero": 1,
  "catering.aero": 1,
  "certification.aero": 1,
  "championship.aero": 1,
  "charter.aero": 1,
  "civilaviation.aero": 1,
  "club.aero": 1,
  "conference.aero": 1,
  "consultant.aero": 1,
  "consulting.aero": 1,
  "control.aero": 1,
  "council.aero": 1,
  "crew.aero": 1,
  "design.aero": 1,
  "dgca.aero": 1,
  "educator.aero": 1,
  "emergency.aero": 1,
  "engine.aero": 1,
  "engineer.aero": 1,
  "entertainment.aero": 1,
  "equipment.aero": 1,
  "exchange.aero": 1,
  "express.aero": 1,
  "federation.aero": 1,
  "flight.aero": 1,
  "fuel.aero": 1,
  "gliding.aero": 1,
  "government.aero": 1,
  "groundhandling.aero": 1,
  "group.aero": 1,
  "hanggliding.aero": 1,
  "homebuilt.aero": 1,
  "insurance.aero": 1,
  "journal.aero": 1,
  "journalist.aero": 1,
  "leasing.aero": 1,
  "logistics.aero": 1,
  "magazine.aero": 1,
  "maintenance.aero": 1,
  "media.aero": 1,
  "microlight.aero": 1,
  "modelling.aero": 1,
  "navigation.aero": 1,
  "parachuting.aero": 1,
  "paragliding.aero": 1,
  "passenger-association.aero": 1,
  "pilot.aero": 1,
  "press.aero": 1,
  "production.aero": 1,
  "recreation.aero": 1,
  "repbody.aero": 1,
  "res.aero": 1,
  "research.aero": 1,
  "rotorcraft.aero": 1,
  "safety.aero": 1,
  "scientist.aero": 1,
  "services.aero": 1,
  "show.aero": 1,
  "skydiving.aero": 1,
  "software.aero": 1,
  "student.aero": 1,
  "trader.aero": 1,
  "trading.aero": 1,
  "trainer.aero": 1,
  "union.aero": 1,
  "workinggroup.aero": 1,
  "works.aero": 1,
  "af": 1,
  "gov.af": 1,
  "com.af": 1,
  "org.af": 1,
  "net.af": 1,
  "edu.af": 1,
  "ag": 1,
  "com.ag": 1,
  "org.ag": 1,
  "net.ag": 1,
  "co.ag": 1,
  "nom.ag": 1,
  "ai": 1,
  "off.ai": 1,
  "com.ai": 1,
  "net.ai": 1,
  "org.ai": 1,
  "al": 1,
  "com.al": 1,
  "edu.al": 1,
  "gov.al": 1,
  "mil.al": 1,
  "net.al": 1,
  "org.al": 1,
  "am": 1,
  "co.am": 1,
  "com.am": 1,
  "commune.am": 1,
  "net.am": 1,
  "org.am": 1,
  "ao": 1,
  "ed.ao": 1,
  "gv.ao": 1,
  "og.ao": 1,
  "co.ao": 1,
  "pb.ao": 1,
  "it.ao": 1,
  "aq": 1,
  "ar": 1,
  "bet.ar": 1,
  "com.ar": 1,
  "coop.ar": 1,
  "edu.ar": 1,
  "gob.ar": 1,
  "gov.ar": 1,
  "int.ar": 1,
  "mil.ar": 1,
  "musica.ar": 1,
  "mutual.ar": 1,
  "net.ar": 1,
  "org.ar": 1,
  "senasa.ar": 1,
  "tur.ar": 1,
  "arpa": 1,
  "e164.arpa": 1,
  "in-addr.arpa": 1,
  "ip6.arpa": 1,
  "iris.arpa": 1,
  "uri.arpa": 1,
  "urn.arpa": 1,
  "as": 1,
  "gov.as": 1,
  "asia": 1,
  "at": 1,
  "ac.at": 1,
  "co.at": 1,
  "gv.at": 1,
  "or.at": 1,
  "sth.ac.at": 1,
  "au": 1,
  "com.au": 1,
  "net.au": 1,
  "org.au": 1,
  "edu.au": 1,
  "gov.au": 1,
  "asn.au": 1,
  "id.au": 1,
  "info.au": 1,
  "conf.au": 1,
  "oz.au": 1,
  "act.au": 1,
  "nsw.au": 1,
  "nt.au": 1,
  "qld.au": 1,
  "sa.au": 1,
  "tas.au": 1,
  "vic.au": 1,
  "wa.au": 1,
  "act.edu.au": 1,
  "catholic.edu.au": 1,
  "nsw.edu.au": 1,
  "nt.edu.au": 1,
  "qld.edu.au": 1,
  "sa.edu.au": 1,
  "tas.edu.au": 1,
  "vic.edu.au": 1,
  "wa.edu.au": 1,
  "qld.gov.au": 1,
  "sa.gov.au": 1,
  "tas.gov.au": 1,
  "vic.gov.au": 1,
  "wa.gov.au": 1,
  "schools.nsw.edu.au": 1,
  "aw": 1,
  "com.aw": 1,
  "ax": 1,
  "az": 1,
  "com.az": 1,
  "net.az": 1,
  "int.az": 1,
  "gov.az": 1,
  "org.az": 1,
  "edu.az": 1,
  "info.az": 1,
  "pp.az": 1,
  "mil.az": 1,
  "name.az": 1,
  "pro.az": 1,
  "biz.az": 1,
  "ba": 1,
  "com.ba": 1,
  "edu.ba": 1,
  "gov.ba": 1,
  "mil.ba": 1,
  "net.ba": 1,
  "org.ba": 1,
  "bb": 1,
  "biz.bb": 1,
  "co.bb": 1,
  "com.bb": 1,
  "edu.bb": 1,
  "gov.bb": 1,
  "info.bb": 1,
  "net.bb": 1,
  "org.bb": 1,
  "store.bb": 1,
  "tv.bb": 1,
  "bd": 2,
  "be": 1,
  "ac.be": 1,
  "bf": 1,
  "gov.bf": 1,
  "bg": 1,
  "a.bg": 1,
  "b.bg": 1,
  "c.bg": 1,
  "d.bg": 1,
  "e.bg": 1,
  "f.bg": 1,
  "g.bg": 1,
  "h.bg": 1,
  "i.bg": 1,
  "j.bg": 1,
  "k.bg": 1,
  "l.bg": 1,
  "m.bg": 1,
  "n.bg": 1,
  "o.bg": 1,
  "p.bg": 1,
  "q.bg": 1,
  "r.bg": 1,
  "s.bg": 1,
  "t.bg": 1,
  "u.bg": 1,
  "v.bg": 1,
  "w.bg": 1,
  "x.bg": 1,
  "y.bg": 1,
  "z.bg": 1,
  "0.bg": 1,
  "1.bg": 1,
  "2.bg": 1,
  "3.bg": 1,
  "4.bg": 1,
  "5.bg": 1,
  "6.bg": 1,
  "7.bg": 1,
  "8.bg": 1,
  "9.bg": 1,
  "bh": 1,
  "com.bh": 1,
  "edu.bh": 1,
  "net.bh": 1,
  "org.bh": 1,
  "gov.bh": 1,
  "bi": 1,
  "co.bi": 1,
  "com.bi": 1,
  "edu.bi": 1,
  "or.bi": 1,
  "org.bi": 1,
  "biz": 1,
  "bj": 1,
  "africa.bj": 1,
  "agro.bj": 1,
  "architectes.bj": 1,
  "assur.bj": 1,
  "avocats.bj": 1,
  "co.bj": 1,
  "com.bj": 1,
  "eco.bj": 1,
  "econo.bj": 1,
  "edu.bj": 1,
  "info.bj": 1,
  "loisirs.bj": 1,
  "money.bj": 1,
  "net.bj": 1,
  "org.bj": 1,
  "ote.bj": 1,
  "resto.bj": 1,
  "restaurant.bj": 1,
  "tourism.bj": 1,
  "univ.bj": 1,
  "bm": 1,
  "com.bm": 1,
  "edu.bm": 1,
  "gov.bm": 1,
  "net.bm": 1,
  "org.bm": 1,
  "bn": 1,
  "com.bn": 1,
  "edu.bn": 1,
  "gov.bn": 1,
  "net.bn": 1,
  "org.bn": 1,
  "bo": 1,
  "com.bo": 1,
  "edu.bo": 1,
  "gob.bo": 1,
  "int.bo": 1,
  "org.bo": 1,
  "net.bo": 1,
  "mil.bo": 1,
  "tv.bo": 1,
  "web.bo": 1,
  "academia.bo": 1,
  "agro.bo": 1,
  "arte.bo": 1,
  "blog.bo": 1,
  "bolivia.bo": 1,
  "ciencia.bo": 1,
  "cooperativa.bo": 1,
  "democracia.bo": 1,
  "deporte.bo": 1,
  "ecologia.bo": 1,
  "economia.bo": 1,
  "empresa.bo": 1,
  "indigena.bo": 1,
  "industria.bo": 1,
  "info.bo": 1,
  "medicina.bo": 1,
  "movimiento.bo": 1,
  "musica.bo": 1,
  "natural.bo": 1,
  "nombre.bo": 1,
  "noticias.bo": 1,
  "patria.bo": 1,
  "politica.bo": 1,
  "profesional.bo": 1,
  "plurinacional.bo": 1,
  "pueblo.bo": 1,
  "revista.bo": 1,
  "salud.bo": 1,
  "tecnologia.bo": 1,
  "tksat.bo": 1,
  "transporte.bo": 1,
  "wiki.bo": 1,
  "br": 1,
  "9guacu.br": 1,
  "abc.br": 1,
  "adm.br": 1,
  "adv.br": 1,
  "agr.br": 1,
  "aju.br": 1,
  "am.br": 1,
  "anani.br": 1,
  "aparecida.br": 1,
  "app.br": 1,
  "arq.br": 1,
  "art.br": 1,
  "ato.br": 1,
  "b.br": 1,
  "barueri.br": 1,
  "belem.br": 1,
  "bhz.br": 1,
  "bib.br": 1,
  "bio.br": 1,
  "blog.br": 1,
  "bmd.br": 1,
  "boavista.br": 1,
  "bsb.br": 1,
  "campinagrande.br": 1,
  "campinas.br": 1,
  "caxias.br": 1,
  "cim.br": 1,
  "cng.br": 1,
  "cnt.br": 1,
  "com.br": 1,
  "contagem.br": 1,
  "coop.br": 1,
  "coz.br": 1,
  "cri.br": 1,
  "cuiaba.br": 1,
  "curitiba.br": 1,
  "def.br": 1,
  "des.br": 1,
  "det.br": 1,
  "dev.br": 1,
  "ecn.br": 1,
  "eco.br": 1,
  "edu.br": 1,
  "emp.br": 1,
  "enf.br": 1,
  "eng.br": 1,
  "esp.br": 1,
  "etc.br": 1,
  "eti.br": 1,
  "far.br": 1,
  "feira.br": 1,
  "flog.br": 1,
  "floripa.br": 1,
  "fm.br": 1,
  "fnd.br": 1,
  "fortal.br": 1,
  "fot.br": 1,
  "foz.br": 1,
  "fst.br": 1,
  "g12.br": 1,
  "geo.br": 1,
  "ggf.br": 1,
  "goiania.br": 1,
  "gov.br": 1,
  "ac.gov.br": 1,
  "al.gov.br": 1,
  "am.gov.br": 1,
  "ap.gov.br": 1,
  "ba.gov.br": 1,
  "ce.gov.br": 1,
  "df.gov.br": 1,
  "es.gov.br": 1,
  "go.gov.br": 1,
  "ma.gov.br": 1,
  "mg.gov.br": 1,
  "ms.gov.br": 1,
  "mt.gov.br": 1,
  "pa.gov.br": 1,
  "pb.gov.br": 1,
  "pe.gov.br": 1,
  "pi.gov.br": 1,
  "pr.gov.br": 1,
  "rj.gov.br": 1,
  "rn.gov.br": 1,
  "ro.gov.br": 1,
  "rr.gov.br": 1,
  "rs.gov.br": 1,
  "sc.gov.br": 1,
  "se.gov.br": 1,
  "sp.gov.br": 1,
  "to.gov.br": 1,
  "gru.br": 1,
  "imb.br": 1,
  "ind.br": 1,
  "inf.br": 1,
  "jab.br": 1,
  "jampa.br": 1,
  "jdf.br": 1,
  "joinville.br": 1,
  "jor.br": 1,
  "jus.br": 1,
  "leg.br": 1,
  "lel.br": 1,
  "log.br": 1,
  "londrina.br": 1,
  "macapa.br": 1,
  "maceio.br": 1,
  "manaus.br": 1,
  "maringa.br": 1,
  "mat.br": 1,
  "med.br": 1,
  "mil.br": 1,
  "morena.br": 1,
  "mp.br": 1,
  "mus.br": 1,
  "natal.br": 1,
  "net.br": 1,
  "niteroi.br": 1,
  "nom.br": 2,
  "not.br": 1,
  "ntr.br": 1,
  "odo.br": 1,
  "ong.br": 1,
  "org.br": 1,
  "osasco.br": 1,
  "palmas.br": 1,
  "poa.br": 1,
  "ppg.br": 1,
  "pro.br": 1,
  "psc.br": 1,
  "psi.br": 1,
  "pvh.br": 1,
  "qsl.br": 1,
  "radio.br": 1,
  "rec.br": 1,
  "recife.br": 1,
  "rep.br": 1,
  "ribeirao.br": 1,
  "rio.br": 1,
  "riobranco.br": 1,
  "riopreto.br": 1,
  "salvador.br": 1,
  "sampa.br": 1,
  "santamaria.br": 1,
  "santoandre.br": 1,
  "saobernardo.br": 1,
  "saogonca.br": 1,
  "seg.br": 1,
  "sjc.br": 1,
  "slg.br": 1,
  "slz.br": 1,
  "sorocaba.br": 1,
  "srv.br": 1,
  "taxi.br": 1,
  "tc.br": 1,
  "tec.br": 1,
  "teo.br": 1,
  "the.br": 1,
  "tmp.br": 1,
  "trd.br": 1,
  "tur.br": 1,
  "tv.br": 1,
  "udi.br": 1,
  "vet.br": 1,
  "vix.br": 1,
  "vlog.br": 1,
  "wiki.br": 1,
  "zlg.br": 1,
  "bs": 1,
  "com.bs": 1,
  "net.bs": 1,
  "org.bs": 1,
  "edu.bs": 1,
  "gov.bs": 1,
  "bt": 1,
  "com.bt": 1,
  "edu.bt": 1,
  "gov.bt": 1,
  "net.bt": 1,
  "org.bt": 1,
  "bv": 1,
  "bw": 1,
  "co.bw": 1,
  "org.bw": 1,
  "by": 1,
  "gov.by": 1,
  "mil.by": 1,
  "com.by": 1,
  "of.by": 1,
  "bz": 1,
  "com.bz": 1,
  "net.bz": 1,
  "org.bz": 1,
  "edu.bz": 1,
  "gov.bz": 1,
  "ca": 1,
  "ab.ca": 1,
  "bc.ca": 1,
  "mb.ca": 1,
  "nb.ca": 1,
  "nf.ca": 1,
  "nl.ca": 1,
  "ns.ca": 1,
  "nt.ca": 1,
  "nu.ca": 1,
  "on.ca": 1,
  "pe.ca": 1,
  "qc.ca": 1,
  "sk.ca": 1,
  "yk.ca": 1,
  "gc.ca": 1,
  "cat": 1,
  "cc": 1,
  "cd": 1,
  "gov.cd": 1,
  "cf": 1,
  "cg": 1,
  "ch": 1,
  "ci": 1,
  "org.ci": 1,
  "or.ci": 1,
  "com.ci": 1,
  "co.ci": 1,
  "edu.ci": 1,
  "ed.ci": 1,
  "ac.ci": 1,
  "net.ci": 1,
  "go.ci": 1,
  "asso.ci": 1,
  "xn--aroport-bya.ci": 1,
  "int.ci": 1,
  "presse.ci": 1,
  "md.ci": 1,
  "gouv.ci": 1,
  "ck": 2,
  "www.ck": 0,
  "cl": 1,
  "co.cl": 1,
  "gob.cl": 1,
  "gov.cl": 1,
  "mil.cl": 1,
  "cm": 1,
  "co.cm": 1,
  "com.cm": 1,
  "gov.cm": 1,
  "net.cm": 1,
  "cn": 1,
  "ac.cn": 1,
  "com.cn": 1,
  "edu.cn": 1,
  "gov.cn": 1,
  "net.cn": 1,
  "org.cn": 1,
  "mil.cn": 1,
  "xn--55qx5d.cn": 1,
  "xn--io0a7i.cn": 1,
  "xn--od0alg.cn": 1,
  "ah.cn": 1,
  "bj.cn": 1,
  "cq.cn": 1,
  "fj.cn": 1,
  "gd.cn": 1,
  "gs.cn": 1,
  "gz.cn": 1,
  "gx.cn": 1,
  "ha.cn": 1,
  "hb.cn": 1,
  "he.cn": 1,
  "hi.cn": 1,
  "hl.cn": 1,
  "hn.cn": 1,
  "jl.cn": 1,
  "js.cn": 1,
  "jx.cn": 1,
  "ln.cn": 1,
  "nm.cn": 1,
  "nx.cn": 1,
  "qh.cn": 1,
  "sc.cn": 1,
  "sd.cn": 1,
  "sh.cn": 1,
  "sn.cn": 1,
  "sx.cn": 1,
  "tj.cn": 1,
  "xj.cn": 1,
  "xz.cn": 1,
  "yn.cn": 1,
  "zj.cn": 1,
  "hk.cn": 1,
  "mo.cn": 1,
  "tw.cn": 1,
  "co": 1,
  "arts.co": 1,
  "com.co": 1,
  "edu.co": 1,
  "firm.co": 1,
  "gov.co": 1,
  "info.co": 1,
  "int.co": 1,
  "mil.co": 1,
  "net.co": 1,
  "nom.co": 1,
  "org.co": 1,
  "rec.co": 1,
  "web.co": 1,
  "com": 1,
  "coop": 1,
  "cr": 1,
  "ac.cr": 1,
  "co.cr": 1,
  "ed.cr": 1,
  "fi.cr": 1,
  "go.cr": 1,
  "or.cr": 1,
  "sa.cr": 1,
  "cu": 1,
  "com.cu": 1,
  "edu.cu": 1,
  "org.cu": 1,
  "net.cu": 1,
  "gov.cu": 1,
  "inf.cu": 1,
  "cv": 1,
  "com.cv": 1,
  "edu.cv": 1,
  "int.cv": 1,
  "nome.cv": 1,
  "org.cv": 1,
  "cw": 1,
  "com.cw": 1,
  "edu.cw": 1,
  "net.cw": 1,
  "org.cw": 1,
  "cx": 1,
  "gov.cx": 1,
  "cy": 1,
  "ac.cy": 1,
  "biz.cy": 1,
  "com.cy": 1,
  "ekloges.cy": 1,
  "gov.cy": 1,
  "ltd.cy": 1,
  "mil.cy": 1,
  "net.cy": 1,
  "org.cy": 1,
  "press.cy": 1,
  "pro.cy": 1,
  "tm.cy": 1,
  "cz": 1,
  "de": 1,
  "dj": 1,
  "dk": 1,
  "dm": 1,
  "com.dm": 1,
  "net.dm": 1,
  "org.dm": 1,
  "edu.dm": 1,
  "gov.dm": 1,
  "do": 1,
  "art.do": 1,
  "com.do": 1,
  "edu.do": 1,
  "gob.do": 1,
  "gov.do": 1,
  "mil.do": 1,
  "net.do": 1,
  "org.do": 1,
  "sld.do": 1,
  "web.do": 1,
  "dz": 1,
  "art.dz": 1,
  "asso.dz": 1,
  "com.dz": 1,
  "edu.dz": 1,
  "gov.dz": 1,
  "org.dz": 1,
  "net.dz": 1,
  "pol.dz": 1,
  "soc.dz": 1,
  "tm.dz": 1,
  "ec": 1,
  "com.ec": 1,
  "info.ec": 1,
  "net.ec": 1,
  "fin.ec": 1,
  "k12.ec": 1,
  "med.ec": 1,
  "pro.ec": 1,
  "org.ec": 1,
  "edu.ec": 1,
  "gov.ec": 1,
  "gob.ec": 1,
  "mil.ec": 1,
  "edu": 1,
  "ee": 1,
  "edu.ee": 1,
  "gov.ee": 1,
  "riik.ee": 1,
  "lib.ee": 1,
  "med.ee": 1,
  "com.ee": 1,
  "pri.ee": 1,
  "aip.ee": 1,
  "org.ee": 1,
  "fie.ee": 1,
  "eg": 1,
  "com.eg": 1,
  "edu.eg": 1,
  "eun.eg": 1,
  "gov.eg": 1,
  "mil.eg": 1,
  "name.eg": 1,
  "net.eg": 1,
  "org.eg": 1,
  "sci.eg": 1,
  "er": 2,
  "es": 1,
  "com.es": 1,
  "nom.es": 1,
  "org.es": 1,
  "gob.es": 1,
  "edu.es": 1,
  "et": 1,
  "com.et": 1,
  "gov.et": 1,
  "org.et": 1,
  "edu.et": 1,
  "biz.et": 1,
  "name.et": 1,
  "info.et": 1,
  "net.et": 1,
  "eu": 1,
  "fi": 1,
  "aland.fi": 1,
  "fj": 1,
  "ac.fj": 1,
  "biz.fj": 1,
  "com.fj": 1,
  "gov.fj": 1,
  "info.fj": 1,
  "mil.fj": 1,
  "name.fj": 1,
  "net.fj": 1,
  "org.fj": 1,
  "pro.fj": 1,
  "fk": 2,
  "com.fm": 1,
  "edu.fm": 1,
  "net.fm": 1,
  "org.fm": 1,
  "fm": 1,
  "fo": 1,
  "fr": 1,
  "asso.fr": 1,
  "com.fr": 1,
  "gouv.fr": 1,
  "nom.fr": 1,
  "prd.fr": 1,
  "tm.fr": 1,
  "avoues.fr": 1,
  "cci.fr": 1,
  "greta.fr": 1,
  "huissier-justice.fr": 1,
  "ga": 1,
  "gb": 1,
  "edu.gd": 1,
  "gov.gd": 1,
  "gd": 1,
  "ge": 1,
  "com.ge": 1,
  "edu.ge": 1,
  "gov.ge": 1,
  "org.ge": 1,
  "mil.ge": 1,
  "net.ge": 1,
  "pvt.ge": 1,
  "gf": 1,
  "gg": 1,
  "co.gg": 1,
  "net.gg": 1,
  "org.gg": 1,
  "gh": 1,
  "com.gh": 1,
  "edu.gh": 1,
  "gov.gh": 1,
  "org.gh": 1,
  "mil.gh": 1,
  "gi": 1,
  "com.gi": 1,
  "ltd.gi": 1,
  "gov.gi": 1,
  "mod.gi": 1,
  "edu.gi": 1,
  "org.gi": 1,
  "gl": 1,
  "co.gl": 1,
  "com.gl": 1,
  "edu.gl": 1,
  "net.gl": 1,
  "org.gl": 1,
  "gm": 1,
  "gn": 1,
  "ac.gn": 1,
  "com.gn": 1,
  "edu.gn": 1,
  "gov.gn": 1,
  "org.gn": 1,
  "net.gn": 1,
  "gov": 1,
  "gp": 1,
  "com.gp": 1,
  "net.gp": 1,
  "mobi.gp": 1,
  "edu.gp": 1,
  "org.gp": 1,
  "asso.gp": 1,
  "gq": 1,
  "gr": 1,
  "com.gr": 1,
  "edu.gr": 1,
  "net.gr": 1,
  "org.gr": 1,
  "gov.gr": 1,
  "gs": 1,
  "gt": 1,
  "com.gt": 1,
  "edu.gt": 1,
  "gob.gt": 1,
  "ind.gt": 1,
  "mil.gt": 1,
  "net.gt": 1,
  "org.gt": 1,
  "gu": 1,
  "com.gu": 1,
  "edu.gu": 1,
  "gov.gu": 1,
  "guam.gu": 1,
  "info.gu": 1,
  "net.gu": 1,
  "org.gu": 1,
  "web.gu": 1,
  "gw": 1,
  "gy": 1,
  "co.gy": 1,
  "com.gy": 1,
  "edu.gy": 1,
  "gov.gy": 1,
  "net.gy": 1,
  "org.gy": 1,
  "hk": 1,
  "com.hk": 1,
  "edu.hk": 1,
  "gov.hk": 1,
  "idv.hk": 1,
  "net.hk": 1,
  "org.hk": 1,
  "xn--55qx5d.hk": 1,
  "xn--wcvs22d.hk": 1,
  "xn--lcvr32d.hk": 1,
  "xn--mxtq1m.hk": 1,
  "xn--gmqw5a.hk": 1,
  "xn--ciqpn.hk": 1,
  "xn--gmq050i.hk": 1,
  "xn--zf0avx.hk": 1,
  "xn--io0a7i.hk": 1,
  "xn--mk0axi.hk": 1,
  "xn--od0alg.hk": 1,
  "xn--od0aq3b.hk": 1,
  "xn--tn0ag.hk": 1,
  "xn--uc0atv.hk": 1,
  "xn--uc0ay4a.hk": 1,
  "hm": 1,
  "hn": 1,
  "com.hn": 1,
  "edu.hn": 1,
  "org.hn": 1,
  "net.hn": 1,
  "mil.hn": 1,
  "gob.hn": 1,
  "hr": 1,
  "iz.hr": 1,
  "from.hr": 1,
  "name.hr": 1,
  "com.hr": 1,
  "ht": 1,
  "com.ht": 1,
  "shop.ht": 1,
  "firm.ht": 1,
  "info.ht": 1,
  "adult.ht": 1,
  "net.ht": 1,
  "pro.ht": 1,
  "org.ht": 1,
  "med.ht": 1,
  "art.ht": 1,
  "coop.ht": 1,
  "pol.ht": 1,
  "asso.ht": 1,
  "edu.ht": 1,
  "rel.ht": 1,
  "gouv.ht": 1,
  "perso.ht": 1,
  "hu": 1,
  "co.hu": 1,
  "info.hu": 1,
  "org.hu": 1,
  "priv.hu": 1,
  "sport.hu": 1,
  "tm.hu": 1,
  "2000.hu": 1,
  "agrar.hu": 1,
  "bolt.hu": 1,
  "casino.hu": 1,
  "city.hu": 1,
  "erotica.hu": 1,
  "erotika.hu": 1,
  "film.hu": 1,
  "forum.hu": 1,
  "games.hu": 1,
  "hotel.hu": 1,
  "ingatlan.hu": 1,
  "jogasz.hu": 1,
  "konyvelo.hu": 1,
  "lakas.hu": 1,
  "media.hu": 1,
  "news.hu": 1,
  "reklam.hu": 1,
  "sex.hu": 1,
  "shop.hu": 1,
  "suli.hu": 1,
  "szex.hu": 1,
  "tozsde.hu": 1,
  "utazas.hu": 1,
  "video.hu": 1,
  "id": 1,
  "ac.id": 1,
  "biz.id": 1,
  "co.id": 1,
  "desa.id": 1,
  "go.id": 1,
  "mil.id": 1,
  "my.id": 1,
  "net.id": 1,
  "or.id": 1,
  "ponpes.id": 1,
  "sch.id": 1,
  "web.id": 1,
  "ie": 1,
  "gov.ie": 1,
  "il": 1,
  "ac.il": 1,
  "co.il": 1,
  "gov.il": 1,
  "idf.il": 1,
  "k12.il": 1,
  "muni.il": 1,
  "net.il": 1,
  "org.il": 1,
  "xn--4dbrk0ce": 1,
  "xn--4dbgdty6c.xn--4dbrk0ce": 1,
  "xn--5dbhl8d.xn--4dbrk0ce": 1,
  "xn--8dbq2a.xn--4dbrk0ce": 1,
  "xn--hebda8b.xn--4dbrk0ce": 1,
  "im": 1,
  "ac.im": 1,
  "co.im": 1,
  "com.im": 1,
  "ltd.co.im": 1,
  "net.im": 1,
  "org.im": 1,
  "plc.co.im": 1,
  "tt.im": 1,
  "tv.im": 1,
  "in": 1,
  "5g.in": 1,
  "6g.in": 1,
  "ac.in": 1,
  "ai.in": 1,
  "am.in": 1,
  "bihar.in": 1,
  "biz.in": 1,
  "business.in": 1,
  "ca.in": 1,
  "cn.in": 1,
  "co.in": 1,
  "com.in": 1,
  "coop.in": 1,
  "cs.in": 1,
  "delhi.in": 1,
  "dr.in": 1,
  "edu.in": 1,
  "er.in": 1,
  "firm.in": 1,
  "gen.in": 1,
  "gov.in": 1,
  "gujarat.in": 1,
  "ind.in": 1,
  "info.in": 1,
  "int.in": 1,
  "internet.in": 1,
  "io.in": 1,
  "me.in": 1,
  "mil.in": 1,
  "net.in": 1,
  "nic.in": 1,
  "org.in": 1,
  "pg.in": 1,
  "post.in": 1,
  "pro.in": 1,
  "res.in": 1,
  "travel.in": 1,
  "tv.in": 1,
  "uk.in": 1,
  "up.in": 1,
  "us.in": 1,
  "info": 1,
  "int": 1,
  "eu.int": 1,
  "io": 1,
  "com.io": 1,
  "iq": 1,
  "gov.iq": 1,
  "edu.iq": 1,
  "mil.iq": 1,
  "com.iq": 1,
  "org.iq": 1,
  "net.iq": 1,
  "ir": 1,
  "ac.ir": 1,
  "co.ir": 1,
  "gov.ir": 1,
  "id.ir": 1,
  "net.ir": 1,
  "org.ir": 1,
  "sch.ir": 1,
  "xn--mgba3a4f16a.ir": 1,
  "xn--mgba3a4fra.ir": 1,
  "is": 1,
  "net.is": 1,
  "com.is": 1,
  "edu.is": 1,
  "gov.is": 1,
  "org.is": 1,
  "int.is": 1,
  "it": 1,
  "gov.it": 1,
  "edu.it": 1,
  "abr.it": 1,
  "abruzzo.it": 1,
  "aosta-valley.it": 1,
  "aostavalley.it": 1,
  "bas.it": 1,
  "basilicata.it": 1,
  "cal.it": 1,
  "calabria.it": 1,
  "cam.it": 1,
  "campania.it": 1,
  "emilia-romagna.it": 1,
  "emiliaromagna.it": 1,
  "emr.it": 1,
  "friuli-v-giulia.it": 1,
  "friuli-ve-giulia.it": 1,
  "friuli-vegiulia.it": 1,
  "friuli-venezia-giulia.it": 1,
  "friuli-veneziagiulia.it": 1,
  "friuli-vgiulia.it": 1,
  "friuliv-giulia.it": 1,
  "friulive-giulia.it": 1,
  "friulivegiulia.it": 1,
  "friulivenezia-giulia.it": 1,
  "friuliveneziagiulia.it": 1,
  "friulivgiulia.it": 1,
  "fvg.it": 1,
  "laz.it": 1,
  "lazio.it": 1,
  "lig.it": 1,
  "liguria.it": 1,
  "lom.it": 1,
  "lombardia.it": 1,
  "lombardy.it": 1,
  "lucania.it": 1,
  "mar.it": 1,
  "marche.it": 1,
  "mol.it": 1,
  "molise.it": 1,
  "piedmont.it": 1,
  "piemonte.it": 1,
  "pmn.it": 1,
  "pug.it": 1,
  "puglia.it": 1,
  "sar.it": 1,
  "sardegna.it": 1,
  "sardinia.it": 1,
  "sic.it": 1,
  "sicilia.it": 1,
  "sicily.it": 1,
  "taa.it": 1,
  "tos.it": 1,
  "toscana.it": 1,
  "trentin-sud-tirol.it": 1,
  "xn--trentin-sd-tirol-rzb.it": 1,
  "trentin-sudtirol.it": 1,
  "xn--trentin-sdtirol-7vb.it": 1,
  "trentin-sued-tirol.it": 1,
  "trentin-suedtirol.it": 1,
  "trentino-a-adige.it": 1,
  "trentino-aadige.it": 1,
  "trentino-alto-adige.it": 1,
  "trentino-altoadige.it": 1,
  "trentino-s-tirol.it": 1,
  "trentino-stirol.it": 1,
  "trentino-sud-tirol.it": 1,
  "xn--trentino-sd-tirol-c3b.it": 1,
  "trentino-sudtirol.it": 1,
  "xn--trentino-sdtirol-szb.it": 1,
  "trentino-sued-tirol.it": 1,
  "trentino-suedtirol.it": 1,
  "trentino.it": 1,
  "trentinoa-adige.it": 1,
  "trentinoaadige.it": 1,
  "trentinoalto-adige.it": 1,
  "trentinoaltoadige.it": 1,
  "trentinos-tirol.it": 1,
  "trentinostirol.it": 1,
  "trentinosud-tirol.it": 1,
  "xn--trentinosd-tirol-rzb.it": 1,
  "trentinosudtirol.it": 1,
  "xn--trentinosdtirol-7vb.it": 1,
  "trentinosued-tirol.it": 1,
  "trentinosuedtirol.it": 1,
  "trentinsud-tirol.it": 1,
  "xn--trentinsd-tirol-6vb.it": 1,
  "trentinsudtirol.it": 1,
  "xn--trentinsdtirol-nsb.it": 1,
  "trentinsued-tirol.it": 1,
  "trentinsuedtirol.it": 1,
  "tuscany.it": 1,
  "umb.it": 1,
  "umbria.it": 1,
  "val-d-aosta.it": 1,
  "val-daosta.it": 1,
  "vald-aosta.it": 1,
  "valdaosta.it": 1,
  "valle-aosta.it": 1,
  "valle-d-aosta.it": 1,
  "valle-daosta.it": 1,
  "valleaosta.it": 1,
  "valled-aosta.it": 1,
  "valledaosta.it": 1,
  "vallee-aoste.it": 1,
  "xn--valle-aoste-ebb.it": 1,
  "vallee-d-aoste.it": 1,
  "xn--valle-d-aoste-ehb.it": 1,
  "valleeaoste.it": 1,
  "xn--valleaoste-e7a.it": 1,
  "valleedaoste.it": 1,
  "xn--valledaoste-ebb.it": 1,
  "vao.it": 1,
  "vda.it": 1,
  "ven.it": 1,
  "veneto.it": 1,
  "ag.it": 1,
  "agrigento.it": 1,
  "al.it": 1,
  "alessandria.it": 1,
  "alto-adige.it": 1,
  "altoadige.it": 1,
  "an.it": 1,
  "ancona.it": 1,
  "andria-barletta-trani.it": 1,
  "andria-trani-barletta.it": 1,
  "andriabarlettatrani.it": 1,
  "andriatranibarletta.it": 1,
  "ao.it": 1,
  "aosta.it": 1,
  "aoste.it": 1,
  "ap.it": 1,
  "aq.it": 1,
  "aquila.it": 1,
  "ar.it": 1,
  "arezzo.it": 1,
  "ascoli-piceno.it": 1,
  "ascolipiceno.it": 1,
  "asti.it": 1,
  "at.it": 1,
  "av.it": 1,
  "avellino.it": 1,
  "ba.it": 1,
  "balsan-sudtirol.it": 1,
  "xn--balsan-sdtirol-nsb.it": 1,
  "balsan-suedtirol.it": 1,
  "balsan.it": 1,
  "bari.it": 1,
  "barletta-trani-andria.it": 1,
  "barlettatraniandria.it": 1,
  "belluno.it": 1,
  "benevento.it": 1,
  "bergamo.it": 1,
  "bg.it": 1,
  "bi.it": 1,
  "biella.it": 1,
  "bl.it": 1,
  "bn.it": 1,
  "bo.it": 1,
  "bologna.it": 1,
  "bolzano-altoadige.it": 1,
  "bolzano.it": 1,
  "bozen-sudtirol.it": 1,
  "xn--bozen-sdtirol-2ob.it": 1,
  "bozen-suedtirol.it": 1,
  "bozen.it": 1,
  "br.it": 1,
  "brescia.it": 1,
  "brindisi.it": 1,
  "bs.it": 1,
  "bt.it": 1,
  "bulsan-sudtirol.it": 1,
  "xn--bulsan-sdtirol-nsb.it": 1,
  "bulsan-suedtirol.it": 1,
  "bulsan.it": 1,
  "bz.it": 1,
  "ca.it": 1,
  "cagliari.it": 1,
  "caltanissetta.it": 1,
  "campidano-medio.it": 1,
  "campidanomedio.it": 1,
  "campobasso.it": 1,
  "carbonia-iglesias.it": 1,
  "carboniaiglesias.it": 1,
  "carrara-massa.it": 1,
  "carraramassa.it": 1,
  "caserta.it": 1,
  "catania.it": 1,
  "catanzaro.it": 1,
  "cb.it": 1,
  "ce.it": 1,
  "cesena-forli.it": 1,
  "xn--cesena-forl-mcb.it": 1,
  "cesenaforli.it": 1,
  "xn--cesenaforl-i8a.it": 1,
  "ch.it": 1,
  "chieti.it": 1,
  "ci.it": 1,
  "cl.it": 1,
  "cn.it": 1,
  "co.it": 1,
  "como.it": 1,
  "cosenza.it": 1,
  "cr.it": 1,
  "cremona.it": 1,
  "crotone.it": 1,
  "cs.it": 1,
  "ct.it": 1,
  "cuneo.it": 1,
  "cz.it": 1,
  "dell-ogliastra.it": 1,
  "dellogliastra.it": 1,
  "en.it": 1,
  "enna.it": 1,
  "fc.it": 1,
  "fe.it": 1,
  "fermo.it": 1,
  "ferrara.it": 1,
  "fg.it": 1,
  "fi.it": 1,
  "firenze.it": 1,
  "florence.it": 1,
  "fm.it": 1,
  "foggia.it": 1,
  "forli-cesena.it": 1,
  "xn--forl-cesena-fcb.it": 1,
  "forlicesena.it": 1,
  "xn--forlcesena-c8a.it": 1,
  "fr.it": 1,
  "frosinone.it": 1,
  "ge.it": 1,
  "genoa.it": 1,
  "genova.it": 1,
  "go.it": 1,
  "gorizia.it": 1,
  "gr.it": 1,
  "grosseto.it": 1,
  "iglesias-carbonia.it": 1,
  "iglesiascarbonia.it": 1,
  "im.it": 1,
  "imperia.it": 1,
  "is.it": 1,
  "isernia.it": 1,
  "kr.it": 1,
  "la-spezia.it": 1,
  "laquila.it": 1,
  "laspezia.it": 1,
  "latina.it": 1,
  "lc.it": 1,
  "le.it": 1,
  "lecce.it": 1,
  "lecco.it": 1,
  "li.it": 1,
  "livorno.it": 1,
  "lo.it": 1,
  "lodi.it": 1,
  "lt.it": 1,
  "lu.it": 1,
  "lucca.it": 1,
  "macerata.it": 1,
  "mantova.it": 1,
  "massa-carrara.it": 1,
  "massacarrara.it": 1,
  "matera.it": 1,
  "mb.it": 1,
  "mc.it": 1,
  "me.it": 1,
  "medio-campidano.it": 1,
  "mediocampidano.it": 1,
  "messina.it": 1,
  "mi.it": 1,
  "milan.it": 1,
  "milano.it": 1,
  "mn.it": 1,
  "mo.it": 1,
  "modena.it": 1,
  "monza-brianza.it": 1,
  "monza-e-della-brianza.it": 1,
  "monza.it": 1,
  "monzabrianza.it": 1,
  "monzaebrianza.it": 1,
  "monzaedellabrianza.it": 1,
  "ms.it": 1,
  "mt.it": 1,
  "na.it": 1,
  "naples.it": 1,
  "napoli.it": 1,
  "no.it": 1,
  "novara.it": 1,
  "nu.it": 1,
  "nuoro.it": 1,
  "og.it": 1,
  "ogliastra.it": 1,
  "olbia-tempio.it": 1,
  "olbiatempio.it": 1,
  "or.it": 1,
  "oristano.it": 1,
  "ot.it": 1,
  "pa.it": 1,
  "padova.it": 1,
  "padua.it": 1,
  "palermo.it": 1,
  "parma.it": 1,
  "pavia.it": 1,
  "pc.it": 1,
  "pd.it": 1,
  "pe.it": 1,
  "perugia.it": 1,
  "pesaro-urbino.it": 1,
  "pesarourbino.it": 1,
  "pescara.it": 1,
  "pg.it": 1,
  "pi.it": 1,
  "piacenza.it": 1,
  "pisa.it": 1,
  "pistoia.it": 1,
  "pn.it": 1,
  "po.it": 1,
  "pordenone.it": 1,
  "potenza.it": 1,
  "pr.it": 1,
  "prato.it": 1,
  "pt.it": 1,
  "pu.it": 1,
  "pv.it": 1,
  "pz.it": 1,
  "ra.it": 1,
  "ragusa.it": 1,
  "ravenna.it": 1,
  "rc.it": 1,
  "re.it": 1,
  "reggio-calabria.it": 1,
  "reggio-emilia.it": 1,
  "reggiocalabria.it": 1,
  "reggioemilia.it": 1,
  "rg.it": 1,
  "ri.it": 1,
  "rieti.it": 1,
  "rimini.it": 1,
  "rm.it": 1,
  "rn.it": 1,
  "ro.it": 1,
  "roma.it": 1,
  "rome.it": 1,
  "rovigo.it": 1,
  "sa.it": 1,
  "salerno.it": 1,
  "sassari.it": 1,
  "savona.it": 1,
  "si.it": 1,
  "siena.it": 1,
  "siracusa.it": 1,
  "so.it": 1,
  "sondrio.it": 1,
  "sp.it": 1,
  "sr.it": 1,
  "ss.it": 1,
  "suedtirol.it": 1,
  "xn--sdtirol-n2a.it": 1,
  "sv.it": 1,
  "ta.it": 1,
  "taranto.it": 1,
  "te.it": 1,
  "tempio-olbia.it": 1,
  "tempioolbia.it": 1,
  "teramo.it": 1,
  "terni.it": 1,
  "tn.it": 1,
  "to.it": 1,
  "torino.it": 1,
  "tp.it": 1,
  "tr.it": 1,
  "trani-andria-barletta.it": 1,
  "trani-barletta-andria.it": 1,
  "traniandriabarletta.it": 1,
  "tranibarlettaandria.it": 1,
  "trapani.it": 1,
  "trento.it": 1,
  "treviso.it": 1,
  "trieste.it": 1,
  "ts.it": 1,
  "turin.it": 1,
  "tv.it": 1,
  "ud.it": 1,
  "udine.it": 1,
  "urbino-pesaro.it": 1,
  "urbinopesaro.it": 1,
  "va.it": 1,
  "varese.it": 1,
  "vb.it": 1,
  "vc.it": 1,
  "ve.it": 1,
  "venezia.it": 1,
  "venice.it": 1,
  "verbania.it": 1,
  "vercelli.it": 1,
  "verona.it": 1,
  "vi.it": 1,
  "vibo-valentia.it": 1,
  "vibovalentia.it": 1,
  "vicenza.it": 1,
  "viterbo.it": 1,
  "vr.it": 1,
  "vs.it": 1,
  "vt.it": 1,
  "vv.it": 1,
  "je": 1,
  "co.je": 1,
  "net.je": 1,
  "org.je": 1,
  "jm": 2,
  "jo": 1,
  "com.jo": 1,
  "org.jo": 1,
  "net.jo": 1,
  "edu.jo": 1,
  "sch.jo": 1,
  "gov.jo": 1,
  "mil.jo": 1,
  "name.jo": 1,
  "jobs": 1,
  "jp": 1,
  "ac.jp": 1,
  "ad.jp": 1,
  "co.jp": 1,
  "ed.jp": 1,
  "go.jp": 1,
  "gr.jp": 1,
  "lg.jp": 1,
  "ne.jp": 1,
  "or.jp": 1,
  "aichi.jp": 1,
  "akita.jp": 1,
  "aomori.jp": 1,
  "chiba.jp": 1,
  "ehime.jp": 1,
  "fukui.jp": 1,
  "fukuoka.jp": 1,
  "fukushima.jp": 1,
  "gifu.jp": 1,
  "gunma.jp": 1,
  "hiroshima.jp": 1,
  "hokkaido.jp": 1,
  "hyogo.jp": 1,
  "ibaraki.jp": 1,
  "ishikawa.jp": 1,
  "iwate.jp": 1,
  "kagawa.jp": 1,
  "kagoshima.jp": 1,
  "kanagawa.jp": 1,
  "kochi.jp": 1,
  "kumamoto.jp": 1,
  "kyoto.jp": 1,
  "mie.jp": 1,
  "miyagi.jp": 1,
  "miyazaki.jp": 1,
  "nagano.jp": 1,
  "nagasaki.jp": 1,
  "nara.jp": 1,
  "niigata.jp": 1,
  "oita.jp": 1,
  "okayama.jp": 1,
  "okinawa.jp": 1,
  "osaka.jp": 1,
  "saga.jp": 1,
  "saitama.jp": 1,
  "shiga.jp": 1,
  "shimane.jp": 1,
  "shizuoka.jp": 1,
  "tochigi.jp": 1,
  "tokushima.jp": 1,
  "tokyo.jp": 1,
  "tottori.jp": 1,
  "toyama.jp": 1,
  "wakayama.jp": 1,
  "yamagata.jp": 1,
  "yamaguchi.jp": 1,
  "yamanashi.jp": 1,
  "xn--4pvxs.jp": 1,
  "xn--vgu402c.jp": 1,
  "xn--c3s14m.jp": 1,
  "xn--f6qx53a.jp": 1,
  "xn--8pvr4u.jp": 1,
  "xn--uist22h.jp": 1,
  "xn--djrs72d6uy.jp": 1,
  "xn--mkru45i.jp": 1,
  "xn--0trq7p7nn.jp": 1,
  "xn--8ltr62k.jp": 1,
  "xn--2m4a15e.jp": 1,
  "xn--efvn9s.jp": 1,
  "xn--32vp30h.jp": 1,
  "xn--4it797k.jp": 1,
  "xn--1lqs71d.jp": 1,
  "xn--5rtp49c.jp": 1,
  "xn--5js045d.jp": 1,
  "xn--ehqz56n.jp": 1,
  "xn--1lqs03n.jp": 1,
  "xn--qqqt11m.jp": 1,
  "xn--kbrq7o.jp": 1,
  "xn--pssu33l.jp": 1,
  "xn--ntsq17g.jp": 1,
  "xn--uisz3g.jp": 1,
  "xn--6btw5a.jp": 1,
  "xn--1ctwo.jp": 1,
  "xn--6orx2r.jp": 1,
  "xn--rht61e.jp": 1,
  "xn--rht27z.jp": 1,
  "xn--djty4k.jp": 1,
  "xn--nit225k.jp": 1,
  "xn--rht3d.jp": 1,
  "xn--klty5x.jp": 1,
  "xn--kltx9a.jp": 1,
  "xn--kltp7d.jp": 1,
  "xn--uuwu58a.jp": 1,
  "xn--zbx025d.jp": 1,
  "xn--ntso0iqx3a.jp": 1,
  "xn--elqq16h.jp": 1,
  "xn--4it168d.jp": 1,
  "xn--klt787d.jp": 1,
  "xn--rny31h.jp": 1,
  "xn--7t0a264c.jp": 1,
  "xn--5rtq34k.jp": 1,
  "xn--k7yn95e.jp": 1,
  "xn--tor131o.jp": 1,
  "xn--d5qv7z876c.jp": 1,
  "kawasaki.jp": 2,
  "kitakyushu.jp": 2,
  "kobe.jp": 2,
  "nagoya.jp": 2,
  "sapporo.jp": 2,
  "sendai.jp": 2,
  "yokohama.jp": 2,
  "city.kawasaki.jp": 0,
  "city.kitakyushu.jp": 0,
  "city.kobe.jp": 0,
  "city.nagoya.jp": 0,
  "city.sapporo.jp": 0,
  "city.sendai.jp": 0,
  "city.yokohama.jp": 0,
  "aisai.aichi.jp": 1,
  "ama.aichi.jp": 1,
  "anjo.aichi.jp": 1,
  "asuke.aichi.jp": 1,
  "chiryu.aichi.jp": 1,
  "chita.aichi.jp": 1,
  "fuso.aichi.jp": 1,
  "gamagori.aichi.jp": 1,
  "handa.aichi.jp": 1,
  "hazu.aichi.jp": 1,
  "hekinan.aichi.jp": 1,
  "higashiura.aichi.jp": 1,
  "ichinomiya.aichi.jp": 1,
  "inazawa.aichi.jp": 1,
  "inuyama.aichi.jp": 1,
  "isshiki.aichi.jp": 1,
  "iwakura.aichi.jp": 1,
  "kanie.aichi.jp": 1,
  "kariya.aichi.jp": 1,
  "kasugai.aichi.jp": 1,
  "kira.aichi.jp": 1,
  "kiyosu.aichi.jp": 1,
  "komaki.aichi.jp": 1,
  "konan.aichi.jp": 1,
  "kota.aichi.jp": 1,
  "mihama.aichi.jp": 1,
  "miyoshi.aichi.jp": 1,
  "nishio.aichi.jp": 1,
  "nisshin.aichi.jp": 1,
  "obu.aichi.jp": 1,
  "oguchi.aichi.jp": 1,
  "oharu.aichi.jp": 1,
  "okazaki.aichi.jp": 1,
  "owariasahi.aichi.jp": 1,
  "seto.aichi.jp": 1,
  "shikatsu.aichi.jp": 1,
  "shinshiro.aichi.jp": 1,
  "shitara.aichi.jp": 1,
  "tahara.aichi.jp": 1,
  "takahama.aichi.jp": 1,
  "tobishima.aichi.jp": 1,
  "toei.aichi.jp": 1,
  "togo.aichi.jp": 1,
  "tokai.aichi.jp": 1,
  "tokoname.aichi.jp": 1,
  "toyoake.aichi.jp": 1,
  "toyohashi.aichi.jp": 1,
  "toyokawa.aichi.jp": 1,
  "toyone.aichi.jp": 1,
  "toyota.aichi.jp": 1,
  "tsushima.aichi.jp": 1,
  "yatomi.aichi.jp": 1,
  "akita.akita.jp": 1,
  "daisen.akita.jp": 1,
  "fujisato.akita.jp": 1,
  "gojome.akita.jp": 1,
  "hachirogata.akita.jp": 1,
  "happou.akita.jp": 1,
  "higashinaruse.akita.jp": 1,
  "honjo.akita.jp": 1,
  "honjyo.akita.jp": 1,
  "ikawa.akita.jp": 1,
  "kamikoani.akita.jp": 1,
  "kamioka.akita.jp": 1,
  "katagami.akita.jp": 1,
  "kazuno.akita.jp": 1,
  "kitaakita.akita.jp": 1,
  "kosaka.akita.jp": 1,
  "kyowa.akita.jp": 1,
  "misato.akita.jp": 1,
  "mitane.akita.jp": 1,
  "moriyoshi.akita.jp": 1,
  "nikaho.akita.jp": 1,
  "noshiro.akita.jp": 1,
  "odate.akita.jp": 1,
  "oga.akita.jp": 1,
  "ogata.akita.jp": 1,
  "semboku.akita.jp": 1,
  "yokote.akita.jp": 1,
  "yurihonjo.akita.jp": 1,
  "aomori.aomori.jp": 1,
  "gonohe.aomori.jp": 1,
  "hachinohe.aomori.jp": 1,
  "hashikami.aomori.jp": 1,
  "hiranai.aomori.jp": 1,
  "hirosaki.aomori.jp": 1,
  "itayanagi.aomori.jp": 1,
  "kuroishi.aomori.jp": 1,
  "misawa.aomori.jp": 1,
  "mutsu.aomori.jp": 1,
  "nakadomari.aomori.jp": 1,
  "noheji.aomori.jp": 1,
  "oirase.aomori.jp": 1,
  "owani.aomori.jp": 1,
  "rokunohe.aomori.jp": 1,
  "sannohe.aomori.jp": 1,
  "shichinohe.aomori.jp": 1,
  "shingo.aomori.jp": 1,
  "takko.aomori.jp": 1,
  "towada.aomori.jp": 1,
  "tsugaru.aomori.jp": 1,
  "tsuruta.aomori.jp": 1,
  "abiko.chiba.jp": 1,
  "asahi.chiba.jp": 1,
  "chonan.chiba.jp": 1,
  "chosei.chiba.jp": 1,
  "choshi.chiba.jp": 1,
  "chuo.chiba.jp": 1,
  "funabashi.chiba.jp": 1,
  "futtsu.chiba.jp": 1,
  "hanamigawa.chiba.jp": 1,
  "ichihara.chiba.jp": 1,
  "ichikawa.chiba.jp": 1,
  "ichinomiya.chiba.jp": 1,
  "inzai.chiba.jp": 1,
  "isumi.chiba.jp": 1,
  "kamagaya.chiba.jp": 1,
  "kamogawa.chiba.jp": 1,
  "kashiwa.chiba.jp": 1,
  "katori.chiba.jp": 1,
  "katsuura.chiba.jp": 1,
  "kimitsu.chiba.jp": 1,
  "kisarazu.chiba.jp": 1,
  "kozaki.chiba.jp": 1,
  "kujukuri.chiba.jp": 1,
  "kyonan.chiba.jp": 1,
  "matsudo.chiba.jp": 1,
  "midori.chiba.jp": 1,
  "mihama.chiba.jp": 1,
  "minamiboso.chiba.jp": 1,
  "mobara.chiba.jp": 1,
  "mutsuzawa.chiba.jp": 1,
  "nagara.chiba.jp": 1,
  "nagareyama.chiba.jp": 1,
  "narashino.chiba.jp": 1,
  "narita.chiba.jp": 1,
  "noda.chiba.jp": 1,
  "oamishirasato.chiba.jp": 1,
  "omigawa.chiba.jp": 1,
  "onjuku.chiba.jp": 1,
  "otaki.chiba.jp": 1,
  "sakae.chiba.jp": 1,
  "sakura.chiba.jp": 1,
  "shimofusa.chiba.jp": 1,
  "shirako.chiba.jp": 1,
  "shiroi.chiba.jp": 1,
  "shisui.chiba.jp": 1,
  "sodegaura.chiba.jp": 1,
  "sosa.chiba.jp": 1,
  "tako.chiba.jp": 1,
  "tateyama.chiba.jp": 1,
  "togane.chiba.jp": 1,
  "tohnosho.chiba.jp": 1,
  "tomisato.chiba.jp": 1,
  "urayasu.chiba.jp": 1,
  "yachimata.chiba.jp": 1,
  "yachiyo.chiba.jp": 1,
  "yokaichiba.chiba.jp": 1,
  "yokoshibahikari.chiba.jp": 1,
  "yotsukaido.chiba.jp": 1,
  "ainan.ehime.jp": 1,
  "honai.ehime.jp": 1,
  "ikata.ehime.jp": 1,
  "imabari.ehime.jp": 1,
  "iyo.ehime.jp": 1,
  "kamijima.ehime.jp": 1,
  "kihoku.ehime.jp": 1,
  "kumakogen.ehime.jp": 1,
  "masaki.ehime.jp": 1,
  "matsuno.ehime.jp": 1,
  "matsuyama.ehime.jp": 1,
  "namikata.ehime.jp": 1,
  "niihama.ehime.jp": 1,
  "ozu.ehime.jp": 1,
  "saijo.ehime.jp": 1,
  "seiyo.ehime.jp": 1,
  "shikokuchuo.ehime.jp": 1,
  "tobe.ehime.jp": 1,
  "toon.ehime.jp": 1,
  "uchiko.ehime.jp": 1,
  "uwajima.ehime.jp": 1,
  "yawatahama.ehime.jp": 1,
  "echizen.fukui.jp": 1,
  "eiheiji.fukui.jp": 1,
  "fukui.fukui.jp": 1,
  "ikeda.fukui.jp": 1,
  "katsuyama.fukui.jp": 1,
  "mihama.fukui.jp": 1,
  "minamiechizen.fukui.jp": 1,
  "obama.fukui.jp": 1,
  "ohi.fukui.jp": 1,
  "ono.fukui.jp": 1,
  "sabae.fukui.jp": 1,
  "sakai.fukui.jp": 1,
  "takahama.fukui.jp": 1,
  "tsuruga.fukui.jp": 1,
  "wakasa.fukui.jp": 1,
  "ashiya.fukuoka.jp": 1,
  "buzen.fukuoka.jp": 1,
  "chikugo.fukuoka.jp": 1,
  "chikuho.fukuoka.jp": 1,
  "chikujo.fukuoka.jp": 1,
  "chikushino.fukuoka.jp": 1,
  "chikuzen.fukuoka.jp": 1,
  "chuo.fukuoka.jp": 1,
  "dazaifu.fukuoka.jp": 1,
  "fukuchi.fukuoka.jp": 1,
  "hakata.fukuoka.jp": 1,
  "higashi.fukuoka.jp": 1,
  "hirokawa.fukuoka.jp": 1,
  "hisayama.fukuoka.jp": 1,
  "iizuka.fukuoka.jp": 1,
  "inatsuki.fukuoka.jp": 1,
  "kaho.fukuoka.jp": 1,
  "kasuga.fukuoka.jp": 1,
  "kasuya.fukuoka.jp": 1,
  "kawara.fukuoka.jp": 1,
  "keisen.fukuoka.jp": 1,
  "koga.fukuoka.jp": 1,
  "kurate.fukuoka.jp": 1,
  "kurogi.fukuoka.jp": 1,
  "kurume.fukuoka.jp": 1,
  "minami.fukuoka.jp": 1,
  "miyako.fukuoka.jp": 1,
  "miyama.fukuoka.jp": 1,
  "miyawaka.fukuoka.jp": 1,
  "mizumaki.fukuoka.jp": 1,
  "munakata.fukuoka.jp": 1,
  "nakagawa.fukuoka.jp": 1,
  "nakama.fukuoka.jp": 1,
  "nishi.fukuoka.jp": 1,
  "nogata.fukuoka.jp": 1,
  "ogori.fukuoka.jp": 1,
  "okagaki.fukuoka.jp": 1,
  "okawa.fukuoka.jp": 1,
  "oki.fukuoka.jp": 1,
  "omuta.fukuoka.jp": 1,
  "onga.fukuoka.jp": 1,
  "onojo.fukuoka.jp": 1,
  "oto.fukuoka.jp": 1,
  "saigawa.fukuoka.jp": 1,
  "sasaguri.fukuoka.jp": 1,
  "shingu.fukuoka.jp": 1,
  "shinyoshitomi.fukuoka.jp": 1,
  "shonai.fukuoka.jp": 1,
  "soeda.fukuoka.jp": 1,
  "sue.fukuoka.jp": 1,
  "tachiarai.fukuoka.jp": 1,
  "tagawa.fukuoka.jp": 1,
  "takata.fukuoka.jp": 1,
  "toho.fukuoka.jp": 1,
  "toyotsu.fukuoka.jp": 1,
  "tsuiki.fukuoka.jp": 1,
  "ukiha.fukuoka.jp": 1,
  "umi.fukuoka.jp": 1,
  "usui.fukuoka.jp": 1,
  "yamada.fukuoka.jp": 1,
  "yame.fukuoka.jp": 1,
  "yanagawa.fukuoka.jp": 1,
  "yukuhashi.fukuoka.jp": 1,
  "aizubange.fukushima.jp": 1,
  "aizumisato.fukushima.jp": 1,
  "aizuwakamatsu.fukushima.jp": 1,
  "asakawa.fukushima.jp": 1,
  "bandai.fukushima.jp": 1,
  "date.fukushima.jp": 1,
  "fukushima.fukushima.jp": 1,
  "furudono.fukushima.jp": 1,
  "futaba.fukushima.jp": 1,
  "hanawa.fukushima.jp": 1,
  "higashi.fukushima.jp": 1,
  "hirata.fukushima.jp": 1,
  "hirono.fukushima.jp": 1,
  "iitate.fukushima.jp": 1,
  "inawashiro.fukushima.jp": 1,
  "ishikawa.fukushima.jp": 1,
  "iwaki.fukushima.jp": 1,
  "izumizaki.fukushima.jp": 1,
  "kagamiishi.fukushima.jp": 1,
  "kaneyama.fukushima.jp": 1,
  "kawamata.fukushima.jp": 1,
  "kitakata.fukushima.jp": 1,
  "kitashiobara.fukushima.jp": 1,
  "koori.fukushima.jp": 1,
  "koriyama.fukushima.jp": 1,
  "kunimi.fukushima.jp": 1,
  "miharu.fukushima.jp": 1,
  "mishima.fukushima.jp": 1,
  "namie.fukushima.jp": 1,
  "nango.fukushima.jp": 1,
  "nishiaizu.fukushima.jp": 1,
  "nishigo.fukushima.jp": 1,
  "okuma.fukushima.jp": 1,
  "omotego.fukushima.jp": 1,
  "ono.fukushima.jp": 1,
  "otama.fukushima.jp": 1,
  "samegawa.fukushima.jp": 1,
  "shimogo.fukushima.jp": 1,
  "shirakawa.fukushima.jp": 1,
  "showa.fukushima.jp": 1,
  "soma.fukushima.jp": 1,
  "sukagawa.fukushima.jp": 1,
  "taishin.fukushima.jp": 1,
  "tamakawa.fukushima.jp": 1,
  "tanagura.fukushima.jp": 1,
  "tenei.fukushima.jp": 1,
  "yabuki.fukushima.jp": 1,
  "yamato.fukushima.jp": 1,
  "yamatsuri.fukushima.jp": 1,
  "yanaizu.fukushima.jp": 1,
  "yugawa.fukushima.jp": 1,
  "anpachi.gifu.jp": 1,
  "ena.gifu.jp": 1,
  "gifu.gifu.jp": 1,
  "ginan.gifu.jp": 1,
  "godo.gifu.jp": 1,
  "gujo.gifu.jp": 1,
  "hashima.gifu.jp": 1,
  "hichiso.gifu.jp": 1,
  "hida.gifu.jp": 1,
  "higashishirakawa.gifu.jp": 1,
  "ibigawa.gifu.jp": 1,
  "ikeda.gifu.jp": 1,
  "kakamigahara.gifu.jp": 1,
  "kani.gifu.jp": 1,
  "kasahara.gifu.jp": 1,
  "kasamatsu.gifu.jp": 1,
  "kawaue.gifu.jp": 1,
  "kitagata.gifu.jp": 1,
  "mino.gifu.jp": 1,
  "minokamo.gifu.jp": 1,
  "mitake.gifu.jp": 1,
  "mizunami.gifu.jp": 1,
  "motosu.gifu.jp": 1,
  "nakatsugawa.gifu.jp": 1,
  "ogaki.gifu.jp": 1,
  "sakahogi.gifu.jp": 1,
  "seki.gifu.jp": 1,
  "sekigahara.gifu.jp": 1,
  "shirakawa.gifu.jp": 1,
  "tajimi.gifu.jp": 1,
  "takayama.gifu.jp": 1,
  "tarui.gifu.jp": 1,
  "toki.gifu.jp": 1,
  "tomika.gifu.jp": 1,
  "wanouchi.gifu.jp": 1,
  "yamagata.gifu.jp": 1,
  "yaotsu.gifu.jp": 1,
  "yoro.gifu.jp": 1,
  "annaka.gunma.jp": 1,
  "chiyoda.gunma.jp": 1,
  "fujioka.gunma.jp": 1,
  "higashiagatsuma.gunma.jp": 1,
  "isesaki.gunma.jp": 1,
  "itakura.gunma.jp": 1,
  "kanna.gunma.jp": 1,
  "kanra.gunma.jp": 1,
  "katashina.gunma.jp": 1,
  "kawaba.gunma.jp": 1,
  "kiryu.gunma.jp": 1,
  "kusatsu.gunma.jp": 1,
  "maebashi.gunma.jp": 1,
  "meiwa.gunma.jp": 1,
  "midori.gunma.jp": 1,
  "minakami.gunma.jp": 1,
  "naganohara.gunma.jp": 1,
  "nakanojo.gunma.jp": 1,
  "nanmoku.gunma.jp": 1,
  "numata.gunma.jp": 1,
  "oizumi.gunma.jp": 1,
  "ora.gunma.jp": 1,
  "ota.gunma.jp": 1,
  "shibukawa.gunma.jp": 1,
  "shimonita.gunma.jp": 1,
  "shinto.gunma.jp": 1,
  "showa.gunma.jp": 1,
  "takasaki.gunma.jp": 1,
  "takayama.gunma.jp": 1,
  "tamamura.gunma.jp": 1,
  "tatebayashi.gunma.jp": 1,
  "tomioka.gunma.jp": 1,
  "tsukiyono.gunma.jp": 1,
  "tsumagoi.gunma.jp": 1,
  "ueno.gunma.jp": 1,
  "yoshioka.gunma.jp": 1,
  "asaminami.hiroshima.jp": 1,
  "daiwa.hiroshima.jp": 1,
  "etajima.hiroshima.jp": 1,
  "fuchu.hiroshima.jp": 1,
  "fukuyama.hiroshima.jp": 1,
  "hatsukaichi.hiroshima.jp": 1,
  "higashihiroshima.hiroshima.jp": 1,
  "hongo.hiroshima.jp": 1,
  "jinsekikogen.hiroshima.jp": 1,
  "kaita.hiroshima.jp": 1,
  "kui.hiroshima.jp": 1,
  "kumano.hiroshima.jp": 1,
  "kure.hiroshima.jp": 1,
  "mihara.hiroshima.jp": 1,
  "miyoshi.hiroshima.jp": 1,
  "naka.hiroshima.jp": 1,
  "onomichi.hiroshima.jp": 1,
  "osakikamijima.hiroshima.jp": 1,
  "otake.hiroshima.jp": 1,
  "saka.hiroshima.jp": 1,
  "sera.hiroshima.jp": 1,
  "seranishi.hiroshima.jp": 1,
  "shinichi.hiroshima.jp": 1,
  "shobara.hiroshima.jp": 1,
  "takehara.hiroshima.jp": 1,
  "abashiri.hokkaido.jp": 1,
  "abira.hokkaido.jp": 1,
  "aibetsu.hokkaido.jp": 1,
  "akabira.hokkaido.jp": 1,
  "akkeshi.hokkaido.jp": 1,
  "asahikawa.hokkaido.jp": 1,
  "ashibetsu.hokkaido.jp": 1,
  "ashoro.hokkaido.jp": 1,
  "assabu.hokkaido.jp": 1,
  "atsuma.hokkaido.jp": 1,
  "bibai.hokkaido.jp": 1,
  "biei.hokkaido.jp": 1,
  "bifuka.hokkaido.jp": 1,
  "bihoro.hokkaido.jp": 1,
  "biratori.hokkaido.jp": 1,
  "chippubetsu.hokkaido.jp": 1,
  "chitose.hokkaido.jp": 1,
  "date.hokkaido.jp": 1,
  "ebetsu.hokkaido.jp": 1,
  "embetsu.hokkaido.jp": 1,
  "eniwa.hokkaido.jp": 1,
  "erimo.hokkaido.jp": 1,
  "esan.hokkaido.jp": 1,
  "esashi.hokkaido.jp": 1,
  "fukagawa.hokkaido.jp": 1,
  "fukushima.hokkaido.jp": 1,
  "furano.hokkaido.jp": 1,
  "furubira.hokkaido.jp": 1,
  "haboro.hokkaido.jp": 1,
  "hakodate.hokkaido.jp": 1,
  "hamatonbetsu.hokkaido.jp": 1,
  "hidaka.hokkaido.jp": 1,
  "higashikagura.hokkaido.jp": 1,
  "higashikawa.hokkaido.jp": 1,
  "hiroo.hokkaido.jp": 1,
  "hokuryu.hokkaido.jp": 1,
  "hokuto.hokkaido.jp": 1,
  "honbetsu.hokkaido.jp": 1,
  "horokanai.hokkaido.jp": 1,
  "horonobe.hokkaido.jp": 1,
  "ikeda.hokkaido.jp": 1,
  "imakane.hokkaido.jp": 1,
  "ishikari.hokkaido.jp": 1,
  "iwamizawa.hokkaido.jp": 1,
  "iwanai.hokkaido.jp": 1,
  "kamifurano.hokkaido.jp": 1,
  "kamikawa.hokkaido.jp": 1,
  "kamishihoro.hokkaido.jp": 1,
  "kamisunagawa.hokkaido.jp": 1,
  "kamoenai.hokkaido.jp": 1,
  "kayabe.hokkaido.jp": 1,
  "kembuchi.hokkaido.jp": 1,
  "kikonai.hokkaido.jp": 1,
  "kimobetsu.hokkaido.jp": 1,
  "kitahiroshima.hokkaido.jp": 1,
  "kitami.hokkaido.jp": 1,
  "kiyosato.hokkaido.jp": 1,
  "koshimizu.hokkaido.jp": 1,
  "kunneppu.hokkaido.jp": 1,
  "kuriyama.hokkaido.jp": 1,
  "kuromatsunai.hokkaido.jp": 1,
  "kushiro.hokkaido.jp": 1,
  "kutchan.hokkaido.jp": 1,
  "kyowa.hokkaido.jp": 1,
  "mashike.hokkaido.jp": 1,
  "matsumae.hokkaido.jp": 1,
  "mikasa.hokkaido.jp": 1,
  "minamifurano.hokkaido.jp": 1,
  "mombetsu.hokkaido.jp": 1,
  "moseushi.hokkaido.jp": 1,
  "mukawa.hokkaido.jp": 1,
  "muroran.hokkaido.jp": 1,
  "naie.hokkaido.jp": 1,
  "nakagawa.hokkaido.jp": 1,
  "nakasatsunai.hokkaido.jp": 1,
  "nakatombetsu.hokkaido.jp": 1,
  "nanae.hokkaido.jp": 1,
  "nanporo.hokkaido.jp": 1,
  "nayoro.hokkaido.jp": 1,
  "nemuro.hokkaido.jp": 1,
  "niikappu.hokkaido.jp": 1,
  "niki.hokkaido.jp": 1,
  "nishiokoppe.hokkaido.jp": 1,
  "noboribetsu.hokkaido.jp": 1,
  "numata.hokkaido.jp": 1,
  "obihiro.hokkaido.jp": 1,
  "obira.hokkaido.jp": 1,
  "oketo.hokkaido.jp": 1,
  "okoppe.hokkaido.jp": 1,
  "otaru.hokkaido.jp": 1,
  "otobe.hokkaido.jp": 1,
  "otofuke.hokkaido.jp": 1,
  "otoineppu.hokkaido.jp": 1,
  "oumu.hokkaido.jp": 1,
  "ozora.hokkaido.jp": 1,
  "pippu.hokkaido.jp": 1,
  "rankoshi.hokkaido.jp": 1,
  "rebun.hokkaido.jp": 1,
  "rikubetsu.hokkaido.jp": 1,
  "rishiri.hokkaido.jp": 1,
  "rishirifuji.hokkaido.jp": 1,
  "saroma.hokkaido.jp": 1,
  "sarufutsu.hokkaido.jp": 1,
  "shakotan.hokkaido.jp": 1,
  "shari.hokkaido.jp": 1,
  "shibecha.hokkaido.jp": 1,
  "shibetsu.hokkaido.jp": 1,
  "shikabe.hokkaido.jp": 1,
  "shikaoi.hokkaido.jp": 1,
  "shimamaki.hokkaido.jp": 1,
  "shimizu.hokkaido.jp": 1,
  "shimokawa.hokkaido.jp": 1,
  "shinshinotsu.hokkaido.jp": 1,
  "shintoku.hokkaido.jp": 1,
  "shiranuka.hokkaido.jp": 1,
  "shiraoi.hokkaido.jp": 1,
  "shiriuchi.hokkaido.jp": 1,
  "sobetsu.hokkaido.jp": 1,
  "sunagawa.hokkaido.jp": 1,
  "taiki.hokkaido.jp": 1,
  "takasu.hokkaido.jp": 1,
  "takikawa.hokkaido.jp": 1,
  "takinoue.hokkaido.jp": 1,
  "teshikaga.hokkaido.jp": 1,
  "tobetsu.hokkaido.jp": 1,
  "tohma.hokkaido.jp": 1,
  "tomakomai.hokkaido.jp": 1,
  "tomari.hokkaido.jp": 1,
  "toya.hokkaido.jp": 1,
  "toyako.hokkaido.jp": 1,
  "toyotomi.hokkaido.jp": 1,
  "toyoura.hokkaido.jp": 1,
  "tsubetsu.hokkaido.jp": 1,
  "tsukigata.hokkaido.jp": 1,
  "urakawa.hokkaido.jp": 1,
  "urausu.hokkaido.jp": 1,
  "uryu.hokkaido.jp": 1,
  "utashinai.hokkaido.jp": 1,
  "wakkanai.hokkaido.jp": 1,
  "wassamu.hokkaido.jp": 1,
  "yakumo.hokkaido.jp": 1,
  "yoichi.hokkaido.jp": 1,
  "aioi.hyogo.jp": 1,
  "akashi.hyogo.jp": 1,
  "ako.hyogo.jp": 1,
  "amagasaki.hyogo.jp": 1,
  "aogaki.hyogo.jp": 1,
  "asago.hyogo.jp": 1,
  "ashiya.hyogo.jp": 1,
  "awaji.hyogo.jp": 1,
  "fukusaki.hyogo.jp": 1,
  "goshiki.hyogo.jp": 1,
  "harima.hyogo.jp": 1,
  "himeji.hyogo.jp": 1,
  "ichikawa.hyogo.jp": 1,
  "inagawa.hyogo.jp": 1,
  "itami.hyogo.jp": 1,
  "kakogawa.hyogo.jp": 1,
  "kamigori.hyogo.jp": 1,
  "kamikawa.hyogo.jp": 1,
  "kasai.hyogo.jp": 1,
  "kasuga.hyogo.jp": 1,
  "kawanishi.hyogo.jp": 1,
  "miki.hyogo.jp": 1,
  "minamiawaji.hyogo.jp": 1,
  "nishinomiya.hyogo.jp": 1,
  "nishiwaki.hyogo.jp": 1,
  "ono.hyogo.jp": 1,
  "sanda.hyogo.jp": 1,
  "sannan.hyogo.jp": 1,
  "sasayama.hyogo.jp": 1,
  "sayo.hyogo.jp": 1,
  "shingu.hyogo.jp": 1,
  "shinonsen.hyogo.jp": 1,
  "shiso.hyogo.jp": 1,
  "sumoto.hyogo.jp": 1,
  "taishi.hyogo.jp": 1,
  "taka.hyogo.jp": 1,
  "takarazuka.hyogo.jp": 1,
  "takasago.hyogo.jp": 1,
  "takino.hyogo.jp": 1,
  "tamba.hyogo.jp": 1,
  "tatsuno.hyogo.jp": 1,
  "toyooka.hyogo.jp": 1,
  "yabu.hyogo.jp": 1,
  "yashiro.hyogo.jp": 1,
  "yoka.hyogo.jp": 1,
  "yokawa.hyogo.jp": 1,
  "ami.ibaraki.jp": 1,
  "asahi.ibaraki.jp": 1,
  "bando.ibaraki.jp": 1,
  "chikusei.ibaraki.jp": 1,
  "daigo.ibaraki.jp": 1,
  "fujishiro.ibaraki.jp": 1,
  "hitachi.ibaraki.jp": 1,
  "hitachinaka.ibaraki.jp": 1,
  "hitachiomiya.ibaraki.jp": 1,
  "hitachiota.ibaraki.jp": 1,
  "ibaraki.ibaraki.jp": 1,
  "ina.ibaraki.jp": 1,
  "inashiki.ibaraki.jp": 1,
  "itako.ibaraki.jp": 1,
  "iwama.ibaraki.jp": 1,
  "joso.ibaraki.jp": 1,
  "kamisu.ibaraki.jp": 1,
  "kasama.ibaraki.jp": 1,
  "kashima.ibaraki.jp": 1,
  "kasumigaura.ibaraki.jp": 1,
  "koga.ibaraki.jp": 1,
  "miho.ibaraki.jp": 1,
  "mito.ibaraki.jp": 1,
  "moriya.ibaraki.jp": 1,
  "naka.ibaraki.jp": 1,
  "namegata.ibaraki.jp": 1,
  "oarai.ibaraki.jp": 1,
  "ogawa.ibaraki.jp": 1,
  "omitama.ibaraki.jp": 1,
  "ryugasaki.ibaraki.jp": 1,
  "sakai.ibaraki.jp": 1,
  "sakuragawa.ibaraki.jp": 1,
  "shimodate.ibaraki.jp": 1,
  "shimotsuma.ibaraki.jp": 1,
  "shirosato.ibaraki.jp": 1,
  "sowa.ibaraki.jp": 1,
  "suifu.ibaraki.jp": 1,
  "takahagi.ibaraki.jp": 1,
  "tamatsukuri.ibaraki.jp": 1,
  "tokai.ibaraki.jp": 1,
  "tomobe.ibaraki.jp": 1,
  "tone.ibaraki.jp": 1,
  "toride.ibaraki.jp": 1,
  "tsuchiura.ibaraki.jp": 1,
  "tsukuba.ibaraki.jp": 1,
  "uchihara.ibaraki.jp": 1,
  "ushiku.ibaraki.jp": 1,
  "yachiyo.ibaraki.jp": 1,
  "yamagata.ibaraki.jp": 1,
  "yawara.ibaraki.jp": 1,
  "yuki.ibaraki.jp": 1,
  "anamizu.ishikawa.jp": 1,
  "hakui.ishikawa.jp": 1,
  "hakusan.ishikawa.jp": 1,
  "kaga.ishikawa.jp": 1,
  "kahoku.ishikawa.jp": 1,
  "kanazawa.ishikawa.jp": 1,
  "kawakita.ishikawa.jp": 1,
  "komatsu.ishikawa.jp": 1,
  "nakanoto.ishikawa.jp": 1,
  "nanao.ishikawa.jp": 1,
  "nomi.ishikawa.jp": 1,
  "nonoichi.ishikawa.jp": 1,
  "noto.ishikawa.jp": 1,
  "shika.ishikawa.jp": 1,
  "suzu.ishikawa.jp": 1,
  "tsubata.ishikawa.jp": 1,
  "tsurugi.ishikawa.jp": 1,
  "uchinada.ishikawa.jp": 1,
  "wajima.ishikawa.jp": 1,
  "fudai.iwate.jp": 1,
  "fujisawa.iwate.jp": 1,
  "hanamaki.iwate.jp": 1,
  "hiraizumi.iwate.jp": 1,
  "hirono.iwate.jp": 1,
  "ichinohe.iwate.jp": 1,
  "ichinoseki.iwate.jp": 1,
  "iwaizumi.iwate.jp": 1,
  "iwate.iwate.jp": 1,
  "joboji.iwate.jp": 1,
  "kamaishi.iwate.jp": 1,
  "kanegasaki.iwate.jp": 1,
  "karumai.iwate.jp": 1,
  "kawai.iwate.jp": 1,
  "kitakami.iwate.jp": 1,
  "kuji.iwate.jp": 1,
  "kunohe.iwate.jp": 1,
  "kuzumaki.iwate.jp": 1,
  "miyako.iwate.jp": 1,
  "mizusawa.iwate.jp": 1,
  "morioka.iwate.jp": 1,
  "ninohe.iwate.jp": 1,
  "noda.iwate.jp": 1,
  "ofunato.iwate.jp": 1,
  "oshu.iwate.jp": 1,
  "otsuchi.iwate.jp": 1,
  "rikuzentakata.iwate.jp": 1,
  "shiwa.iwate.jp": 1,
  "shizukuishi.iwate.jp": 1,
  "sumita.iwate.jp": 1,
  "tanohata.iwate.jp": 1,
  "tono.iwate.jp": 1,
  "yahaba.iwate.jp": 1,
  "yamada.iwate.jp": 1,
  "ayagawa.kagawa.jp": 1,
  "higashikagawa.kagawa.jp": 1,
  "kanonji.kagawa.jp": 1,
  "kotohira.kagawa.jp": 1,
  "manno.kagawa.jp": 1,
  "marugame.kagawa.jp": 1,
  "mitoyo.kagawa.jp": 1,
  "naoshima.kagawa.jp": 1,
  "sanuki.kagawa.jp": 1,
  "tadotsu.kagawa.jp": 1,
  "takamatsu.kagawa.jp": 1,
  "tonosho.kagawa.jp": 1,
  "uchinomi.kagawa.jp": 1,
  "utazu.kagawa.jp": 1,
  "zentsuji.kagawa.jp": 1,
  "akune.kagoshima.jp": 1,
  "amami.kagoshima.jp": 1,
  "hioki.kagoshima.jp": 1,
  "isa.kagoshima.jp": 1,
  "isen.kagoshima.jp": 1,
  "izumi.kagoshima.jp": 1,
  "kagoshima.kagoshima.jp": 1,
  "kanoya.kagoshima.jp": 1,
  "kawanabe.kagoshima.jp": 1,
  "kinko.kagoshima.jp": 1,
  "kouyama.kagoshima.jp": 1,
  "makurazaki.kagoshima.jp": 1,
  "matsumoto.kagoshima.jp": 1,
  "minamitane.kagoshima.jp": 1,
  "nakatane.kagoshima.jp": 1,
  "nishinoomote.kagoshima.jp": 1,
  "satsumasendai.kagoshima.jp": 1,
  "soo.kagoshima.jp": 1,
  "tarumizu.kagoshima.jp": 1,
  "yusui.kagoshima.jp": 1,
  "aikawa.kanagawa.jp": 1,
  "atsugi.kanagawa.jp": 1,
  "ayase.kanagawa.jp": 1,
  "chigasaki.kanagawa.jp": 1,
  "ebina.kanagawa.jp": 1,
  "fujisawa.kanagawa.jp": 1,
  "hadano.kanagawa.jp": 1,
  "hakone.kanagawa.jp": 1,
  "hiratsuka.kanagawa.jp": 1,
  "isehara.kanagawa.jp": 1,
  "kaisei.kanagawa.jp": 1,
  "kamakura.kanagawa.jp": 1,
  "kiyokawa.kanagawa.jp": 1,
  "matsuda.kanagawa.jp": 1,
  "minamiashigara.kanagawa.jp": 1,
  "miura.kanagawa.jp": 1,
  "nakai.kanagawa.jp": 1,
  "ninomiya.kanagawa.jp": 1,
  "odawara.kanagawa.jp": 1,
  "oi.kanagawa.jp": 1,
  "oiso.kanagawa.jp": 1,
  "sagamihara.kanagawa.jp": 1,
  "samukawa.kanagawa.jp": 1,
  "tsukui.kanagawa.jp": 1,
  "yamakita.kanagawa.jp": 1,
  "yamato.kanagawa.jp": 1,
  "yokosuka.kanagawa.jp": 1,
  "yugawara.kanagawa.jp": 1,
  "zama.kanagawa.jp": 1,
  "zushi.kanagawa.jp": 1,
  "aki.kochi.jp": 1,
  "geisei.kochi.jp": 1,
  "hidaka.kochi.jp": 1,
  "higashitsuno.kochi.jp": 1,
  "ino.kochi.jp": 1,
  "kagami.kochi.jp": 1,
  "kami.kochi.jp": 1,
  "kitagawa.kochi.jp": 1,
  "kochi.kochi.jp": 1,
  "mihara.kochi.jp": 1,
  "motoyama.kochi.jp": 1,
  "muroto.kochi.jp": 1,
  "nahari.kochi.jp": 1,
  "nakamura.kochi.jp": 1,
  "nankoku.kochi.jp": 1,
  "nishitosa.kochi.jp": 1,
  "niyodogawa.kochi.jp": 1,
  "ochi.kochi.jp": 1,
  "okawa.kochi.jp": 1,
  "otoyo.kochi.jp": 1,
  "otsuki.kochi.jp": 1,
  "sakawa.kochi.jp": 1,
  "sukumo.kochi.jp": 1,
  "susaki.kochi.jp": 1,
  "tosa.kochi.jp": 1,
  "tosashimizu.kochi.jp": 1,
  "toyo.kochi.jp": 1,
  "tsuno.kochi.jp": 1,
  "umaji.kochi.jp": 1,
  "yasuda.kochi.jp": 1,
  "yusuhara.kochi.jp": 1,
  "amakusa.kumamoto.jp": 1,
  "arao.kumamoto.jp": 1,
  "aso.kumamoto.jp": 1,
  "choyo.kumamoto.jp": 1,
  "gyokuto.kumamoto.jp": 1,
  "kamiamakusa.kumamoto.jp": 1,
  "kikuchi.kumamoto.jp": 1,
  "kumamoto.kumamoto.jp": 1,
  "mashiki.kumamoto.jp": 1,
  "mifune.kumamoto.jp": 1,
  "minamata.kumamoto.jp": 1,
  "minamioguni.kumamoto.jp": 1,
  "nagasu.kumamoto.jp": 1,
  "nishihara.kumamoto.jp": 1,
  "oguni.kumamoto.jp": 1,
  "ozu.kumamoto.jp": 1,
  "sumoto.kumamoto.jp": 1,
  "takamori.kumamoto.jp": 1,
  "uki.kumamoto.jp": 1,
  "uto.kumamoto.jp": 1,
  "yamaga.kumamoto.jp": 1,
  "yamato.kumamoto.jp": 1,
  "yatsushiro.kumamoto.jp": 1,
  "ayabe.kyoto.jp": 1,
  "fukuchiyama.kyoto.jp": 1,
  "higashiyama.kyoto.jp": 1,
  "ide.kyoto.jp": 1,
  "ine.kyoto.jp": 1,
  "joyo.kyoto.jp": 1,
  "kameoka.kyoto.jp": 1,
  "kamo.kyoto.jp": 1,
  "kita.kyoto.jp": 1,
  "kizu.kyoto.jp": 1,
  "kumiyama.kyoto.jp": 1,
  "kyotamba.kyoto.jp": 1,
  "kyotanabe.kyoto.jp": 1,
  "kyotango.kyoto.jp": 1,
  "maizuru.kyoto.jp": 1,
  "minami.kyoto.jp": 1,
  "minamiyamashiro.kyoto.jp": 1,
  "miyazu.kyoto.jp": 1,
  "muko.kyoto.jp": 1,
  "nagaokakyo.kyoto.jp": 1,
  "nakagyo.kyoto.jp": 1,
  "nantan.kyoto.jp": 1,
  "oyamazaki.kyoto.jp": 1,
  "sakyo.kyoto.jp": 1,
  "seika.kyoto.jp": 1,
  "tanabe.kyoto.jp": 1,
  "uji.kyoto.jp": 1,
  "ujitawara.kyoto.jp": 1,
  "wazuka.kyoto.jp": 1,
  "yamashina.kyoto.jp": 1,
  "yawata.kyoto.jp": 1,
  "asahi.mie.jp": 1,
  "inabe.mie.jp": 1,
  "ise.mie.jp": 1,
  "kameyama.mie.jp": 1,
  "kawagoe.mie.jp": 1,
  "kiho.mie.jp": 1,
  "kisosaki.mie.jp": 1,
  "kiwa.mie.jp": 1,
  "komono.mie.jp": 1,
  "kumano.mie.jp": 1,
  "kuwana.mie.jp": 1,
  "matsusaka.mie.jp": 1,
  "meiwa.mie.jp": 1,
  "mihama.mie.jp": 1,
  "minamiise.mie.jp": 1,
  "misugi.mie.jp": 1,
  "miyama.mie.jp": 1,
  "nabari.mie.jp": 1,
  "shima.mie.jp": 1,
  "suzuka.mie.jp": 1,
  "tado.mie.jp": 1,
  "taiki.mie.jp": 1,
  "taki.mie.jp": 1,
  "tamaki.mie.jp": 1,
  "toba.mie.jp": 1,
  "tsu.mie.jp": 1,
  "udono.mie.jp": 1,
  "ureshino.mie.jp": 1,
  "watarai.mie.jp": 1,
  "yokkaichi.mie.jp": 1,
  "furukawa.miyagi.jp": 1,
  "higashimatsushima.miyagi.jp": 1,
  "ishinomaki.miyagi.jp": 1,
  "iwanuma.miyagi.jp": 1,
  "kakuda.miyagi.jp": 1,
  "kami.miyagi.jp": 1,
  "kawasaki.miyagi.jp": 1,
  "marumori.miyagi.jp": 1,
  "matsushima.miyagi.jp": 1,
  "minamisanriku.miyagi.jp": 1,
  "misato.miyagi.jp": 1,
  "murata.miyagi.jp": 1,
  "natori.miyagi.jp": 1,
  "ogawara.miyagi.jp": 1,
  "ohira.miyagi.jp": 1,
  "onagawa.miyagi.jp": 1,
  "osaki.miyagi.jp": 1,
  "rifu.miyagi.jp": 1,
  "semine.miyagi.jp": 1,
  "shibata.miyagi.jp": 1,
  "shichikashuku.miyagi.jp": 1,
  "shikama.miyagi.jp": 1,
  "shiogama.miyagi.jp": 1,
  "shiroishi.miyagi.jp": 1,
  "tagajo.miyagi.jp": 1,
  "taiwa.miyagi.jp": 1,
  "tome.miyagi.jp": 1,
  "tomiya.miyagi.jp": 1,
  "wakuya.miyagi.jp": 1,
  "watari.miyagi.jp": 1,
  "yamamoto.miyagi.jp": 1,
  "zao.miyagi.jp": 1,
  "aya.miyazaki.jp": 1,
  "ebino.miyazaki.jp": 1,
  "gokase.miyazaki.jp": 1,
  "hyuga.miyazaki.jp": 1,
  "kadogawa.miyazaki.jp": 1,
  "kawaminami.miyazaki.jp": 1,
  "kijo.miyazaki.jp": 1,
  "kitagawa.miyazaki.jp": 1,
  "kitakata.miyazaki.jp": 1,
  "kitaura.miyazaki.jp": 1,
  "kobayashi.miyazaki.jp": 1,
  "kunitomi.miyazaki.jp": 1,
  "kushima.miyazaki.jp": 1,
  "mimata.miyazaki.jp": 1,
  "miyakonojo.miyazaki.jp": 1,
  "miyazaki.miyazaki.jp": 1,
  "morotsuka.miyazaki.jp": 1,
  "nichinan.miyazaki.jp": 1,
  "nishimera.miyazaki.jp": 1,
  "nobeoka.miyazaki.jp": 1,
  "saito.miyazaki.jp": 1,
  "shiiba.miyazaki.jp": 1,
  "shintomi.miyazaki.jp": 1,
  "takaharu.miyazaki.jp": 1,
  "takanabe.miyazaki.jp": 1,
  "takazaki.miyazaki.jp": 1,
  "tsuno.miyazaki.jp": 1,
  "achi.nagano.jp": 1,
  "agematsu.nagano.jp": 1,
  "anan.nagano.jp": 1,
  "aoki.nagano.jp": 1,
  "asahi.nagano.jp": 1,
  "azumino.nagano.jp": 1,
  "chikuhoku.nagano.jp": 1,
  "chikuma.nagano.jp": 1,
  "chino.nagano.jp": 1,
  "fujimi.nagano.jp": 1,
  "hakuba.nagano.jp": 1,
  "hara.nagano.jp": 1,
  "hiraya.nagano.jp": 1,
  "iida.nagano.jp": 1,
  "iijima.nagano.jp": 1,
  "iiyama.nagano.jp": 1,
  "iizuna.nagano.jp": 1,
  "ikeda.nagano.jp": 1,
  "ikusaka.nagano.jp": 1,
  "ina.nagano.jp": 1,
  "karuizawa.nagano.jp": 1,
  "kawakami.nagano.jp": 1,
  "kiso.nagano.jp": 1,
  "kisofukushima.nagano.jp": 1,
  "kitaaiki.nagano.jp": 1,
  "komagane.nagano.jp": 1,
  "komoro.nagano.jp": 1,
  "matsukawa.nagano.jp": 1,
  "matsumoto.nagano.jp": 1,
  "miasa.nagano.jp": 1,
  "minamiaiki.nagano.jp": 1,
  "minamimaki.nagano.jp": 1,
  "minamiminowa.nagano.jp": 1,
  "minowa.nagano.jp": 1,
  "miyada.nagano.jp": 1,
  "miyota.nagano.jp": 1,
  "mochizuki.nagano.jp": 1,
  "nagano.nagano.jp": 1,
  "nagawa.nagano.jp": 1,
  "nagiso.nagano.jp": 1,
  "nakagawa.nagano.jp": 1,
  "nakano.nagano.jp": 1,
  "nozawaonsen.nagano.jp": 1,
  "obuse.nagano.jp": 1,
  "ogawa.nagano.jp": 1,
  "okaya.nagano.jp": 1,
  "omachi.nagano.jp": 1,
  "omi.nagano.jp": 1,
  "ookuwa.nagano.jp": 1,
  "ooshika.nagano.jp": 1,
  "otaki.nagano.jp": 1,
  "otari.nagano.jp": 1,
  "sakae.nagano.jp": 1,
  "sakaki.nagano.jp": 1,
  "saku.nagano.jp": 1,
  "sakuho.nagano.jp": 1,
  "shimosuwa.nagano.jp": 1,
  "shinanomachi.nagano.jp": 1,
  "shiojiri.nagano.jp": 1,
  "suwa.nagano.jp": 1,
  "suzaka.nagano.jp": 1,
  "takagi.nagano.jp": 1,
  "takamori.nagano.jp": 1,
  "takayama.nagano.jp": 1,
  "tateshina.nagano.jp": 1,
  "tatsuno.nagano.jp": 1,
  "togakushi.nagano.jp": 1,
  "togura.nagano.jp": 1,
  "tomi.nagano.jp": 1,
  "ueda.nagano.jp": 1,
  "wada.nagano.jp": 1,
  "yamagata.nagano.jp": 1,
  "yamanouchi.nagano.jp": 1,
  "yasaka.nagano.jp": 1,
  "yasuoka.nagano.jp": 1,
  "chijiwa.nagasaki.jp": 1,
  "futsu.nagasaki.jp": 1,
  "goto.nagasaki.jp": 1,
  "hasami.nagasaki.jp": 1,
  "hirado.nagasaki.jp": 1,
  "iki.nagasaki.jp": 1,
  "isahaya.nagasaki.jp": 1,
  "kawatana.nagasaki.jp": 1,
  "kuchinotsu.nagasaki.jp": 1,
  "matsuura.nagasaki.jp": 1,
  "nagasaki.nagasaki.jp": 1,
  "obama.nagasaki.jp": 1,
  "omura.nagasaki.jp": 1,
  "oseto.nagasaki.jp": 1,
  "saikai.nagasaki.jp": 1,
  "sasebo.nagasaki.jp": 1,
  "seihi.nagasaki.jp": 1,
  "shimabara.nagasaki.jp": 1,
  "shinkamigoto.nagasaki.jp": 1,
  "togitsu.nagasaki.jp": 1,
  "tsushima.nagasaki.jp": 1,
  "unzen.nagasaki.jp": 1,
  "ando.nara.jp": 1,
  "gose.nara.jp": 1,
  "heguri.nara.jp": 1,
  "higashiyoshino.nara.jp": 1,
  "ikaruga.nara.jp": 1,
  "ikoma.nara.jp": 1,
  "kamikitayama.nara.jp": 1,
  "kanmaki.nara.jp": 1,
  "kashiba.nara.jp": 1,
  "kashihara.nara.jp": 1,
  "katsuragi.nara.jp": 1,
  "kawai.nara.jp": 1,
  "kawakami.nara.jp": 1,
  "kawanishi.nara.jp": 1,
  "koryo.nara.jp": 1,
  "kurotaki.nara.jp": 1,
  "mitsue.nara.jp": 1,
  "miyake.nara.jp": 1,
  "nara.nara.jp": 1,
  "nosegawa.nara.jp": 1,
  "oji.nara.jp": 1,
  "ouda.nara.jp": 1,
  "oyodo.nara.jp": 1,
  "sakurai.nara.jp": 1,
  "sango.nara.jp": 1,
  "shimoichi.nara.jp": 1,
  "shimokitayama.nara.jp": 1,
  "shinjo.nara.jp": 1,
  "soni.nara.jp": 1,
  "takatori.nara.jp": 1,
  "tawaramoto.nara.jp": 1,
  "tenkawa.nara.jp": 1,
  "tenri.nara.jp": 1,
  "uda.nara.jp": 1,
  "yamatokoriyama.nara.jp": 1,
  "yamatotakada.nara.jp": 1,
  "yamazoe.nara.jp": 1,
  "yoshino.nara.jp": 1,
  "aga.niigata.jp": 1,
  "agano.niigata.jp": 1,
  "gosen.niigata.jp": 1,
  "itoigawa.niigata.jp": 1,
  "izumozaki.niigata.jp": 1,
  "joetsu.niigata.jp": 1,
  "kamo.niigata.jp": 1,
  "kariwa.niigata.jp": 1,
  "kashiwazaki.niigata.jp": 1,
  "minamiuonuma.niigata.jp": 1,
  "mitsuke.niigata.jp": 1,
  "muika.niigata.jp": 1,
  "murakami.niigata.jp": 1,
  "myoko.niigata.jp": 1,
  "nagaoka.niigata.jp": 1,
  "niigata.niigata.jp": 1,
  "ojiya.niigata.jp": 1,
  "omi.niigata.jp": 1,
  "sado.niigata.jp": 1,
  "sanjo.niigata.jp": 1,
  "seiro.niigata.jp": 1,
  "seirou.niigata.jp": 1,
  "sekikawa.niigata.jp": 1,
  "shibata.niigata.jp": 1,
  "tagami.niigata.jp": 1,
  "tainai.niigata.jp": 1,
  "tochio.niigata.jp": 1,
  "tokamachi.niigata.jp": 1,
  "tsubame.niigata.jp": 1,
  "tsunan.niigata.jp": 1,
  "uonuma.niigata.jp": 1,
  "yahiko.niigata.jp": 1,
  "yoita.niigata.jp": 1,
  "yuzawa.niigata.jp": 1,
  "beppu.oita.jp": 1,
  "bungoono.oita.jp": 1,
  "bungotakada.oita.jp": 1,
  "hasama.oita.jp": 1,
  "hiji.oita.jp": 1,
  "himeshima.oita.jp": 1,
  "hita.oita.jp": 1,
  "kamitsue.oita.jp": 1,
  "kokonoe.oita.jp": 1,
  "kuju.oita.jp": 1,
  "kunisaki.oita.jp": 1,
  "kusu.oita.jp": 1,
  "oita.oita.jp": 1,
  "saiki.oita.jp": 1,
  "taketa.oita.jp": 1,
  "tsukumi.oita.jp": 1,
  "usa.oita.jp": 1,
  "usuki.oita.jp": 1,
  "yufu.oita.jp": 1,
  "akaiwa.okayama.jp": 1,
  "asakuchi.okayama.jp": 1,
  "bizen.okayama.jp": 1,
  "hayashima.okayama.jp": 1,
  "ibara.okayama.jp": 1,
  "kagamino.okayama.jp": 1,
  "kasaoka.okayama.jp": 1,
  "kibichuo.okayama.jp": 1,
  "kumenan.okayama.jp": 1,
  "kurashiki.okayama.jp": 1,
  "maniwa.okayama.jp": 1,
  "misaki.okayama.jp": 1,
  "nagi.okayama.jp": 1,
  "niimi.okayama.jp": 1,
  "nishiawakura.okayama.jp": 1,
  "okayama.okayama.jp": 1,
  "satosho.okayama.jp": 1,
  "setouchi.okayama.jp": 1,
  "shinjo.okayama.jp": 1,
  "shoo.okayama.jp": 1,
  "soja.okayama.jp": 1,
  "takahashi.okayama.jp": 1,
  "tamano.okayama.jp": 1,
  "tsuyama.okayama.jp": 1,
  "wake.okayama.jp": 1,
  "yakage.okayama.jp": 1,
  "aguni.okinawa.jp": 1,
  "ginowan.okinawa.jp": 1,
  "ginoza.okinawa.jp": 1,
  "gushikami.okinawa.jp": 1,
  "haebaru.okinawa.jp": 1,
  "higashi.okinawa.jp": 1,
  "hirara.okinawa.jp": 1,
  "iheya.okinawa.jp": 1,
  "ishigaki.okinawa.jp": 1,
  "ishikawa.okinawa.jp": 1,
  "itoman.okinawa.jp": 1,
  "izena.okinawa.jp": 1,
  "kadena.okinawa.jp": 1,
  "kin.okinawa.jp": 1,
  "kitadaito.okinawa.jp": 1,
  "kitanakagusuku.okinawa.jp": 1,
  "kumejima.okinawa.jp": 1,
  "kunigami.okinawa.jp": 1,
  "minamidaito.okinawa.jp": 1,
  "motobu.okinawa.jp": 1,
  "nago.okinawa.jp": 1,
  "naha.okinawa.jp": 1,
  "nakagusuku.okinawa.jp": 1,
  "nakijin.okinawa.jp": 1,
  "nanjo.okinawa.jp": 1,
  "nishihara.okinawa.jp": 1,
  "ogimi.okinawa.jp": 1,
  "okinawa.okinawa.jp": 1,
  "onna.okinawa.jp": 1,
  "shimoji.okinawa.jp": 1,
  "taketomi.okinawa.jp": 1,
  "tarama.okinawa.jp": 1,
  "tokashiki.okinawa.jp": 1,
  "tomigusuku.okinawa.jp": 1,
  "tonaki.okinawa.jp": 1,
  "urasoe.okinawa.jp": 1,
  "uruma.okinawa.jp": 1,
  "yaese.okinawa.jp": 1,
  "yomitan.okinawa.jp": 1,
  "yonabaru.okinawa.jp": 1,
  "yonaguni.okinawa.jp": 1,
  "zamami.okinawa.jp": 1,
  "abeno.osaka.jp": 1,
  "chihayaakasaka.osaka.jp": 1,
  "chuo.osaka.jp": 1,
  "daito.osaka.jp": 1,
  "fujiidera.osaka.jp": 1,
  "habikino.osaka.jp": 1,
  "hannan.osaka.jp": 1,
  "higashiosaka.osaka.jp": 1,
  "higashisumiyoshi.osaka.jp": 1,
  "higashiyodogawa.osaka.jp": 1,
  "hirakata.osaka.jp": 1,
  "ibaraki.osaka.jp": 1,
  "ikeda.osaka.jp": 1,
  "izumi.osaka.jp": 1,
  "izumiotsu.osaka.jp": 1,
  "izumisano.osaka.jp": 1,
  "kadoma.osaka.jp": 1,
  "kaizuka.osaka.jp": 1,
  "kanan.osaka.jp": 1,
  "kashiwara.osaka.jp": 1,
  "katano.osaka.jp": 1,
  "kawachinagano.osaka.jp": 1,
  "kishiwada.osaka.jp": 1,
  "kita.osaka.jp": 1,
  "kumatori.osaka.jp": 1,
  "matsubara.osaka.jp": 1,
  "minato.osaka.jp": 1,
  "minoh.osaka.jp": 1,
  "misaki.osaka.jp": 1,
  "moriguchi.osaka.jp": 1,
  "neyagawa.osaka.jp": 1,
  "nishi.osaka.jp": 1,
  "nose.osaka.jp": 1,
  "osakasayama.osaka.jp": 1,
  "sakai.osaka.jp": 1,
  "sayama.osaka.jp": 1,
  "sennan.osaka.jp": 1,
  "settsu.osaka.jp": 1,
  "shijonawate.osaka.jp": 1,
  "shimamoto.osaka.jp": 1,
  "suita.osaka.jp": 1,
  "tadaoka.osaka.jp": 1,
  "taishi.osaka.jp": 1,
  "tajiri.osaka.jp": 1,
  "takaishi.osaka.jp": 1,
  "takatsuki.osaka.jp": 1,
  "tondabayashi.osaka.jp": 1,
  "toyonaka.osaka.jp": 1,
  "toyono.osaka.jp": 1,
  "yao.osaka.jp": 1,
  "ariake.saga.jp": 1,
  "arita.saga.jp": 1,
  "fukudomi.saga.jp": 1,
  "genkai.saga.jp": 1,
  "hamatama.saga.jp": 1,
  "hizen.saga.jp": 1,
  "imari.saga.jp": 1,
  "kamimine.saga.jp": 1,
  "kanzaki.saga.jp": 1,
  "karatsu.saga.jp": 1,
  "kashima.saga.jp": 1,
  "kitagata.saga.jp": 1,
  "kitahata.saga.jp": 1,
  "kiyama.saga.jp": 1,
  "kouhoku.saga.jp": 1,
  "kyuragi.saga.jp": 1,
  "nishiarita.saga.jp": 1,
  "ogi.saga.jp": 1,
  "omachi.saga.jp": 1,
  "ouchi.saga.jp": 1,
  "saga.saga.jp": 1,
  "shiroishi.saga.jp": 1,
  "taku.saga.jp": 1,
  "tara.saga.jp": 1,
  "tosu.saga.jp": 1,
  "yoshinogari.saga.jp": 1,
  "arakawa.saitama.jp": 1,
  "asaka.saitama.jp": 1,
  "chichibu.saitama.jp": 1,
  "fujimi.saitama.jp": 1,
  "fujimino.saitama.jp": 1,
  "fukaya.saitama.jp": 1,
  "hanno.saitama.jp": 1,
  "hanyu.saitama.jp": 1,
  "hasuda.saitama.jp": 1,
  "hatogaya.saitama.jp": 1,
  "hatoyama.saitama.jp": 1,
  "hidaka.saitama.jp": 1,
  "higashichichibu.saitama.jp": 1,
  "higashimatsuyama.saitama.jp": 1,
  "honjo.saitama.jp": 1,
  "ina.saitama.jp": 1,
  "iruma.saitama.jp": 1,
  "iwatsuki.saitama.jp": 1,
  "kamiizumi.saitama.jp": 1,
  "kamikawa.saitama.jp": 1,
  "kamisato.saitama.jp": 1,
  "kasukabe.saitama.jp": 1,
  "kawagoe.saitama.jp": 1,
  "kawaguchi.saitama.jp": 1,
  "kawajima.saitama.jp": 1,
  "kazo.saitama.jp": 1,
  "kitamoto.saitama.jp": 1,
  "koshigaya.saitama.jp": 1,
  "kounosu.saitama.jp": 1,
  "kuki.saitama.jp": 1,
  "kumagaya.saitama.jp": 1,
  "matsubushi.saitama.jp": 1,
  "minano.saitama.jp": 1,
  "misato.saitama.jp": 1,
  "miyashiro.saitama.jp": 1,
  "miyoshi.saitama.jp": 1,
  "moroyama.saitama.jp": 1,
  "nagatoro.saitama.jp": 1,
  "namegawa.saitama.jp": 1,
  "niiza.saitama.jp": 1,
  "ogano.saitama.jp": 1,
  "ogawa.saitama.jp": 1,
  "ogose.saitama.jp": 1,
  "okegawa.saitama.jp": 1,
  "omiya.saitama.jp": 1,
  "otaki.saitama.jp": 1,
  "ranzan.saitama.jp": 1,
  "ryokami.saitama.jp": 1,
  "saitama.saitama.jp": 1,
  "sakado.saitama.jp": 1,
  "satte.saitama.jp": 1,
  "sayama.saitama.jp": 1,
  "shiki.saitama.jp": 1,
  "shiraoka.saitama.jp": 1,
  "soka.saitama.jp": 1,
  "sugito.saitama.jp": 1,
  "toda.saitama.jp": 1,
  "tokigawa.saitama.jp": 1,
  "tokorozawa.saitama.jp": 1,
  "tsurugashima.saitama.jp": 1,
  "urawa.saitama.jp": 1,
  "warabi.saitama.jp": 1,
  "yashio.saitama.jp": 1,
  "yokoze.saitama.jp": 1,
  "yono.saitama.jp": 1,
  "yorii.saitama.jp": 1,
  "yoshida.saitama.jp": 1,
  "yoshikawa.saitama.jp": 1,
  "yoshimi.saitama.jp": 1,
  "aisho.shiga.jp": 1,
  "gamo.shiga.jp": 1,
  "higashiomi.shiga.jp": 1,
  "hikone.shiga.jp": 1,
  "koka.shiga.jp": 1,
  "konan.shiga.jp": 1,
  "kosei.shiga.jp": 1,
  "koto.shiga.jp": 1,
  "kusatsu.shiga.jp": 1,
  "maibara.shiga.jp": 1,
  "moriyama.shiga.jp": 1,
  "nagahama.shiga.jp": 1,
  "nishiazai.shiga.jp": 1,
  "notogawa.shiga.jp": 1,
  "omihachiman.shiga.jp": 1,
  "otsu.shiga.jp": 1,
  "ritto.shiga.jp": 1,
  "ryuoh.shiga.jp": 1,
  "takashima.shiga.jp": 1,
  "takatsuki.shiga.jp": 1,
  "torahime.shiga.jp": 1,
  "toyosato.shiga.jp": 1,
  "yasu.shiga.jp": 1,
  "akagi.shimane.jp": 1,
  "ama.shimane.jp": 1,
  "gotsu.shimane.jp": 1,
  "hamada.shimane.jp": 1,
  "higashiizumo.shimane.jp": 1,
  "hikawa.shimane.jp": 1,
  "hikimi.shimane.jp": 1,
  "izumo.shimane.jp": 1,
  "kakinoki.shimane.jp": 1,
  "masuda.shimane.jp": 1,
  "matsue.shimane.jp": 1,
  "misato.shimane.jp": 1,
  "nishinoshima.shimane.jp": 1,
  "ohda.shimane.jp": 1,
  "okinoshima.shimane.jp": 1,
  "okuizumo.shimane.jp": 1,
  "shimane.shimane.jp": 1,
  "tamayu.shimane.jp": 1,
  "tsuwano.shimane.jp": 1,
  "unnan.shimane.jp": 1,
  "yakumo.shimane.jp": 1,
  "yasugi.shimane.jp": 1,
  "yatsuka.shimane.jp": 1,
  "arai.shizuoka.jp": 1,
  "atami.shizuoka.jp": 1,
  "fuji.shizuoka.jp": 1,
  "fujieda.shizuoka.jp": 1,
  "fujikawa.shizuoka.jp": 1,
  "fujinomiya.shizuoka.jp": 1,
  "fukuroi.shizuoka.jp": 1,
  "gotemba.shizuoka.jp": 1,
  "haibara.shizuoka.jp": 1,
  "hamamatsu.shizuoka.jp": 1,
  "higashiizu.shizuoka.jp": 1,
  "ito.shizuoka.jp": 1,
  "iwata.shizuoka.jp": 1,
  "izu.shizuoka.jp": 1,
  "izunokuni.shizuoka.jp": 1,
  "kakegawa.shizuoka.jp": 1,
  "kannami.shizuoka.jp": 1,
  "kawanehon.shizuoka.jp": 1,
  "kawazu.shizuoka.jp": 1,
  "kikugawa.shizuoka.jp": 1,
  "kosai.shizuoka.jp": 1,
  "makinohara.shizuoka.jp": 1,
  "matsuzaki.shizuoka.jp": 1,
  "minamiizu.shizuoka.jp": 1,
  "mishima.shizuoka.jp": 1,
  "morimachi.shizuoka.jp": 1,
  "nishiizu.shizuoka.jp": 1,
  "numazu.shizuoka.jp": 1,
  "omaezaki.shizuoka.jp": 1,
  "shimada.shizuoka.jp": 1,
  "shimizu.shizuoka.jp": 1,
  "shimoda.shizuoka.jp": 1,
  "shizuoka.shizuoka.jp": 1,
  "susono.shizuoka.jp": 1,
  "yaizu.shizuoka.jp": 1,
  "yoshida.shizuoka.jp": 1,
  "ashikaga.tochigi.jp": 1,
  "bato.tochigi.jp": 1,
  "haga.tochigi.jp": 1,
  "ichikai.tochigi.jp": 1,
  "iwafune.tochigi.jp": 1,
  "kaminokawa.tochigi.jp": 1,
  "kanuma.tochigi.jp": 1,
  "karasuyama.tochigi.jp": 1,
  "kuroiso.tochigi.jp": 1,
  "mashiko.tochigi.jp": 1,
  "mibu.tochigi.jp": 1,
  "moka.tochigi.jp": 1,
  "motegi.tochigi.jp": 1,
  "nasu.tochigi.jp": 1,
  "nasushiobara.tochigi.jp": 1,
  "nikko.tochigi.jp": 1,
  "nishikata.tochigi.jp": 1,
  "nogi.tochigi.jp": 1,
  "ohira.tochigi.jp": 1,
  "ohtawara.tochigi.jp": 1,
  "oyama.tochigi.jp": 1,
  "sakura.tochigi.jp": 1,
  "sano.tochigi.jp": 1,
  "shimotsuke.tochigi.jp": 1,
  "shioya.tochigi.jp": 1,
  "takanezawa.tochigi.jp": 1,
  "tochigi.tochigi.jp": 1,
  "tsuga.tochigi.jp": 1,
  "ujiie.tochigi.jp": 1,
  "utsunomiya.tochigi.jp": 1,
  "yaita.tochigi.jp": 1,
  "aizumi.tokushima.jp": 1,
  "anan.tokushima.jp": 1,
  "ichiba.tokushima.jp": 1,
  "itano.tokushima.jp": 1,
  "kainan.tokushima.jp": 1,
  "komatsushima.tokushima.jp": 1,
  "matsushige.tokushima.jp": 1,
  "mima.tokushima.jp": 1,
  "minami.tokushima.jp": 1,
  "miyoshi.tokushima.jp": 1,
  "mugi.tokushima.jp": 1,
  "nakagawa.tokushima.jp": 1,
  "naruto.tokushima.jp": 1,
  "sanagochi.tokushima.jp": 1,
  "shishikui.tokushima.jp": 1,
  "tokushima.tokushima.jp": 1,
  "wajiki.tokushima.jp": 1,
  "adachi.tokyo.jp": 1,
  "akiruno.tokyo.jp": 1,
  "akishima.tokyo.jp": 1,
  "aogashima.tokyo.jp": 1,
  "arakawa.tokyo.jp": 1,
  "bunkyo.tokyo.jp": 1,
  "chiyoda.tokyo.jp": 1,
  "chofu.tokyo.jp": 1,
  "chuo.tokyo.jp": 1,
  "edogawa.tokyo.jp": 1,
  "fuchu.tokyo.jp": 1,
  "fussa.tokyo.jp": 1,
  "hachijo.tokyo.jp": 1,
  "hachioji.tokyo.jp": 1,
  "hamura.tokyo.jp": 1,
  "higashikurume.tokyo.jp": 1,
  "higashimurayama.tokyo.jp": 1,
  "higashiyamato.tokyo.jp": 1,
  "hino.tokyo.jp": 1,
  "hinode.tokyo.jp": 1,
  "hinohara.tokyo.jp": 1,
  "inagi.tokyo.jp": 1,
  "itabashi.tokyo.jp": 1,
  "katsushika.tokyo.jp": 1,
  "kita.tokyo.jp": 1,
  "kiyose.tokyo.jp": 1,
  "kodaira.tokyo.jp": 1,
  "koganei.tokyo.jp": 1,
  "kokubunji.tokyo.jp": 1,
  "komae.tokyo.jp": 1,
  "koto.tokyo.jp": 1,
  "kouzushima.tokyo.jp": 1,
  "kunitachi.tokyo.jp": 1,
  "machida.tokyo.jp": 1,
  "meguro.tokyo.jp": 1,
  "minato.tokyo.jp": 1,
  "mitaka.tokyo.jp": 1,
  "mizuho.tokyo.jp": 1,
  "musashimurayama.tokyo.jp": 1,
  "musashino.tokyo.jp": 1,
  "nakano.tokyo.jp": 1,
  "nerima.tokyo.jp": 1,
  "ogasawara.tokyo.jp": 1,
  "okutama.tokyo.jp": 1,
  "ome.tokyo.jp": 1,
  "oshima.tokyo.jp": 1,
  "ota.tokyo.jp": 1,
  "setagaya.tokyo.jp": 1,
  "shibuya.tokyo.jp": 1,
  "shinagawa.tokyo.jp": 1,
  "shinjuku.tokyo.jp": 1,
  "suginami.tokyo.jp": 1,
  "sumida.tokyo.jp": 1,
  "tachikawa.tokyo.jp": 1,
  "taito.tokyo.jp": 1,
  "tama.tokyo.jp": 1,
  "toshima.tokyo.jp": 1,
  "chizu.tottori.jp": 1,
  "hino.tottori.jp": 1,
  "kawahara.tottori.jp": 1,
  "koge.tottori.jp": 1,
  "kotoura.tottori.jp": 1,
  "misasa.tottori.jp": 1,
  "nanbu.tottori.jp": 1,
  "nichinan.tottori.jp": 1,
  "sakaiminato.tottori.jp": 1,
  "tottori.tottori.jp": 1,
  "wakasa.tottori.jp": 1,
  "yazu.tottori.jp": 1,
  "yonago.tottori.jp": 1,
  "asahi.toyama.jp": 1,
  "fuchu.toyama.jp": 1,
  "fukumitsu.toyama.jp": 1,
  "funahashi.toyama.jp": 1,
  "himi.toyama.jp": 1,
  "imizu.toyama.jp": 1,
  "inami.toyama.jp": 1,
  "johana.toyama.jp": 1,
  "kamiichi.toyama.jp": 1,
  "kurobe.toyama.jp": 1,
  "nakaniikawa.toyama.jp": 1,
  "namerikawa.toyama.jp": 1,
  "nanto.toyama.jp": 1,
  "nyuzen.toyama.jp": 1,
  "oyabe.toyama.jp": 1,
  "taira.toyama.jp": 1,
  "takaoka.toyama.jp": 1,
  "tateyama.toyama.jp": 1,
  "toga.toyama.jp": 1,
  "tonami.toyama.jp": 1,
  "toyama.toyama.jp": 1,
  "unazuki.toyama.jp": 1,
  "uozu.toyama.jp": 1,
  "yamada.toyama.jp": 1,
  "arida.wakayama.jp": 1,
  "aridagawa.wakayama.jp": 1,
  "gobo.wakayama.jp": 1,
  "hashimoto.wakayama.jp": 1,
  "hidaka.wakayama.jp": 1,
  "hirogawa.wakayama.jp": 1,
  "inami.wakayama.jp": 1,
  "iwade.wakayama.jp": 1,
  "kainan.wakayama.jp": 1,
  "kamitonda.wakayama.jp": 1,
  "katsuragi.wakayama.jp": 1,
  "kimino.wakayama.jp": 1,
  "kinokawa.wakayama.jp": 1,
  "kitayama.wakayama.jp": 1,
  "koya.wakayama.jp": 1,
  "koza.wakayama.jp": 1,
  "kozagawa.wakayama.jp": 1,
  "kudoyama.wakayama.jp": 1,
  "kushimoto.wakayama.jp": 1,
  "mihama.wakayama.jp": 1,
  "misato.wakayama.jp": 1,
  "nachikatsuura.wakayama.jp": 1,
  "shingu.wakayama.jp": 1,
  "shirahama.wakayama.jp": 1,
  "taiji.wakayama.jp": 1,
  "tanabe.wakayama.jp": 1,
  "wakayama.wakayama.jp": 1,
  "yuasa.wakayama.jp": 1,
  "yura.wakayama.jp": 1,
  "asahi.yamagata.jp": 1,
  "funagata.yamagata.jp": 1,
  "higashine.yamagata.jp": 1,
  "iide.yamagata.jp": 1,
  "kahoku.yamagata.jp": 1,
  "kaminoyama.yamagata.jp": 1,
  "kaneyama.yamagata.jp": 1,
  "kawanishi.yamagata.jp": 1,
  "mamurogawa.yamagata.jp": 1,
  "mikawa.yamagata.jp": 1,
  "murayama.yamagata.jp": 1,
  "nagai.yamagata.jp": 1,
  "nakayama.yamagata.jp": 1,
  "nanyo.yamagata.jp": 1,
  "nishikawa.yamagata.jp": 1,
  "obanazawa.yamagata.jp": 1,
  "oe.yamagata.jp": 1,
  "oguni.yamagata.jp": 1,
  "ohkura.yamagata.jp": 1,
  "oishida.yamagata.jp": 1,
  "sagae.yamagata.jp": 1,
  "sakata.yamagata.jp": 1,
  "sakegawa.yamagata.jp": 1,
  "shinjo.yamagata.jp": 1,
  "shirataka.yamagata.jp": 1,
  "shonai.yamagata.jp": 1,
  "takahata.yamagata.jp": 1,
  "tendo.yamagata.jp": 1,
  "tozawa.yamagata.jp": 1,
  "tsuruoka.yamagata.jp": 1,
  "yamagata.yamagata.jp": 1,
  "yamanobe.yamagata.jp": 1,
  "yonezawa.yamagata.jp": 1,
  "yuza.yamagata.jp": 1,
  "abu.yamaguchi.jp": 1,
  "hagi.yamaguchi.jp": 1,
  "hikari.yamaguchi.jp": 1,
  "hofu.yamaguchi.jp": 1,
  "iwakuni.yamaguchi.jp": 1,
  "kudamatsu.yamaguchi.jp": 1,
  "mitou.yamaguchi.jp": 1,
  "nagato.yamaguchi.jp": 1,
  "oshima.yamaguchi.jp": 1,
  "shimonoseki.yamaguchi.jp": 1,
  "shunan.yamaguchi.jp": 1,
  "tabuse.yamaguchi.jp": 1,
  "tokuyama.yamaguchi.jp": 1,
  "toyota.yamaguchi.jp": 1,
  "ube.yamaguchi.jp": 1,
  "yuu.yamaguchi.jp": 1,
  "chuo.yamanashi.jp": 1,
  "doshi.yamanashi.jp": 1,
  "fuefuki.yamanashi.jp": 1,
  "fujikawa.yamanashi.jp": 1,
  "fujikawaguchiko.yamanashi.jp": 1,
  "fujiyoshida.yamanashi.jp": 1,
  "hayakawa.yamanashi.jp": 1,
  "hokuto.yamanashi.jp": 1,
  "ichikawamisato.yamanashi.jp": 1,
  "kai.yamanashi.jp": 1,
  "kofu.yamanashi.jp": 1,
  "koshu.yamanashi.jp": 1,
  "kosuge.yamanashi.jp": 1,
  "minami-alps.yamanashi.jp": 1,
  "minobu.yamanashi.jp": 1,
  "nakamichi.yamanashi.jp": 1,
  "nanbu.yamanashi.jp": 1,
  "narusawa.yamanashi.jp": 1,
  "nirasaki.yamanashi.jp": 1,
  "nishikatsura.yamanashi.jp": 1,
  "oshino.yamanashi.jp": 1,
  "otsuki.yamanashi.jp": 1,
  "showa.yamanashi.jp": 1,
  "tabayama.yamanashi.jp": 1,
  "tsuru.yamanashi.jp": 1,
  "uenohara.yamanashi.jp": 1,
  "yamanakako.yamanashi.jp": 1,
  "yamanashi.yamanashi.jp": 1,
  "ke": 1,
  "ac.ke": 1,
  "co.ke": 1,
  "go.ke": 1,
  "info.ke": 1,
  "me.ke": 1,
  "mobi.ke": 1,
  "ne.ke": 1,
  "or.ke": 1,
  "sc.ke": 1,
  "kg": 1,
  "org.kg": 1,
  "net.kg": 1,
  "com.kg": 1,
  "edu.kg": 1,
  "gov.kg": 1,
  "mil.kg": 1,
  "kh": 2,
  "ki": 1,
  "edu.ki": 1,
  "biz.ki": 1,
  "net.ki": 1,
  "org.ki": 1,
  "gov.ki": 1,
  "info.ki": 1,
  "com.ki": 1,
  "km": 1,
  "org.km": 1,
  "nom.km": 1,
  "gov.km": 1,
  "prd.km": 1,
  "tm.km": 1,
  "edu.km": 1,
  "mil.km": 1,
  "ass.km": 1,
  "com.km": 1,
  "coop.km": 1,
  "asso.km": 1,
  "presse.km": 1,
  "medecin.km": 1,
  "notaires.km": 1,
  "pharmaciens.km": 1,
  "veterinaire.km": 1,
  "gouv.km": 1,
  "kn": 1,
  "net.kn": 1,
  "org.kn": 1,
  "edu.kn": 1,
  "gov.kn": 1,
  "kp": 1,
  "com.kp": 1,
  "edu.kp": 1,
  "gov.kp": 1,
  "org.kp": 1,
  "rep.kp": 1,
  "tra.kp": 1,
  "kr": 1,
  "ac.kr": 1,
  "co.kr": 1,
  "es.kr": 1,
  "go.kr": 1,
  "hs.kr": 1,
  "kg.kr": 1,
  "mil.kr": 1,
  "ms.kr": 1,
  "ne.kr": 1,
  "or.kr": 1,
  "pe.kr": 1,
  "re.kr": 1,
  "sc.kr": 1,
  "busan.kr": 1,
  "chungbuk.kr": 1,
  "chungnam.kr": 1,
  "daegu.kr": 1,
  "daejeon.kr": 1,
  "gangwon.kr": 1,
  "gwangju.kr": 1,
  "gyeongbuk.kr": 1,
  "gyeonggi.kr": 1,
  "gyeongnam.kr": 1,
  "incheon.kr": 1,
  "jeju.kr": 1,
  "jeonbuk.kr": 1,
  "jeonnam.kr": 1,
  "seoul.kr": 1,
  "ulsan.kr": 1,
  "kw": 1,
  "com.kw": 1,
  "edu.kw": 1,
  "emb.kw": 1,
  "gov.kw": 1,
  "ind.kw": 1,
  "net.kw": 1,
  "org.kw": 1,
  "ky": 1,
  "com.ky": 1,
  "edu.ky": 1,
  "net.ky": 1,
  "org.ky": 1,
  "kz": 1,
  "org.kz": 1,
  "edu.kz": 1,
  "net.kz": 1,
  "gov.kz": 1,
  "mil.kz": 1,
  "com.kz": 1,
  "la": 1,
  "int.la": 1,
  "net.la": 1,
  "info.la": 1,
  "edu.la": 1,
  "gov.la": 1,
  "per.la": 1,
  "com.la": 1,
  "org.la": 1,
  "lb": 1,
  "com.lb": 1,
  "edu.lb": 1,
  "gov.lb": 1,
  "net.lb": 1,
  "org.lb": 1,
  "lc": 1,
  "com.lc": 1,
  "net.lc": 1,
  "co.lc": 1,
  "org.lc": 1,
  "edu.lc": 1,
  "gov.lc": 1,
  "li": 1,
  "lk": 1,
  "gov.lk": 1,
  "sch.lk": 1,
  "net.lk": 1,
  "int.lk": 1,
  "com.lk": 1,
  "org.lk": 1,
  "edu.lk": 1,
  "ngo.lk": 1,
  "soc.lk": 1,
  "web.lk": 1,
  "ltd.lk": 1,
  "assn.lk": 1,
  "grp.lk": 1,
  "hotel.lk": 1,
  "ac.lk": 1,
  "lr": 1,
  "com.lr": 1,
  "edu.lr": 1,
  "gov.lr": 1,
  "org.lr": 1,
  "net.lr": 1,
  "ls": 1,
  "ac.ls": 1,
  "biz.ls": 1,
  "co.ls": 1,
  "edu.ls": 1,
  "gov.ls": 1,
  "info.ls": 1,
  "net.ls": 1,
  "org.ls": 1,
  "sc.ls": 1,
  "lt": 1,
  "gov.lt": 1,
  "lu": 1,
  "lv": 1,
  "com.lv": 1,
  "edu.lv": 1,
  "gov.lv": 1,
  "org.lv": 1,
  "mil.lv": 1,
  "id.lv": 1,
  "net.lv": 1,
  "asn.lv": 1,
  "conf.lv": 1,
  "ly": 1,
  "com.ly": 1,
  "net.ly": 1,
  "gov.ly": 1,
  "plc.ly": 1,
  "edu.ly": 1,
  "sch.ly": 1,
  "med.ly": 1,
  "org.ly": 1,
  "id.ly": 1,
  "ma": 1,
  "co.ma": 1,
  "net.ma": 1,
  "gov.ma": 1,
  "org.ma": 1,
  "ac.ma": 1,
  "press.ma": 1,
  "mc": 1,
  "tm.mc": 1,
  "asso.mc": 1,
  "md": 1,
  "me": 1,
  "co.me": 1,
  "net.me": 1,
  "org.me": 1,
  "edu.me": 1,
  "ac.me": 1,
  "gov.me": 1,
  "its.me": 1,
  "priv.me": 1,
  "mg": 1,
  "org.mg": 1,
  "nom.mg": 1,
  "gov.mg": 1,
  "prd.mg": 1,
  "tm.mg": 1,
  "edu.mg": 1,
  "mil.mg": 1,
  "com.mg": 1,
  "co.mg": 1,
  "mh": 1,
  "mil": 1,
  "mk": 1,
  "com.mk": 1,
  "org.mk": 1,
  "net.mk": 1,
  "edu.mk": 1,
  "gov.mk": 1,
  "inf.mk": 1,
  "name.mk": 1,
  "ml": 1,
  "com.ml": 1,
  "edu.ml": 1,
  "gouv.ml": 1,
  "gov.ml": 1,
  "net.ml": 1,
  "org.ml": 1,
  "presse.ml": 1,
  "mm": 2,
  "mn": 1,
  "gov.mn": 1,
  "edu.mn": 1,
  "org.mn": 1,
  "mo": 1,
  "com.mo": 1,
  "net.mo": 1,
  "org.mo": 1,
  "edu.mo": 1,
  "gov.mo": 1,
  "mobi": 1,
  "mp": 1,
  "mq": 1,
  "mr": 1,
  "gov.mr": 1,
  "ms": 1,
  "com.ms": 1,
  "edu.ms": 1,
  "gov.ms": 1,
  "net.ms": 1,
  "org.ms": 1,
  "mt": 1,
  "com.mt": 1,
  "edu.mt": 1,
  "net.mt": 1,
  "org.mt": 1,
  "mu": 1,
  "com.mu": 1,
  "net.mu": 1,
  "org.mu": 1,
  "gov.mu": 1,
  "ac.mu": 1,
  "co.mu": 1,
  "or.mu": 1,
  "museum": 1,
  "mv": 1,
  "aero.mv": 1,
  "biz.mv": 1,
  "com.mv": 1,
  "coop.mv": 1,
  "edu.mv": 1,
  "gov.mv": 1,
  "info.mv": 1,
  "int.mv": 1,
  "mil.mv": 1,
  "museum.mv": 1,
  "name.mv": 1,
  "net.mv": 1,
  "org.mv": 1,
  "pro.mv": 1,
  "mw": 1,
  "ac.mw": 1,
  "biz.mw": 1,
  "co.mw": 1,
  "com.mw": 1,
  "coop.mw": 1,
  "edu.mw": 1,
  "gov.mw": 1,
  "int.mw": 1,
  "museum.mw": 1,
  "net.mw": 1,
  "org.mw": 1,
  "mx": 1,
  "com.mx": 1,
  "org.mx": 1,
  "gob.mx": 1,
  "edu.mx": 1,
  "net.mx": 1,
  "my": 1,
  "biz.my": 1,
  "com.my": 1,
  "edu.my": 1,
  "gov.my": 1,
  "mil.my": 1,
  "name.my": 1,
  "net.my": 1,
  "org.my": 1,
  "mz": 1,
  "ac.mz": 1,
  "adv.mz": 1,
  "co.mz": 1,
  "edu.mz": 1,
  "gov.mz": 1,
  "mil.mz": 1,
  "net.mz": 1,
  "org.mz": 1,
  "na": 1,
  "info.na": 1,
  "pro.na": 1,
  "name.na": 1,
  "school.na": 1,
  "or.na": 1,
  "dr.na": 1,
  "us.na": 1,
  "mx.na": 1,
  "ca.na": 1,
  "in.na": 1,
  "cc.na": 1,
  "tv.na": 1,
  "ws.na": 1,
  "mobi.na": 1,
  "co.na": 1,
  "com.na": 1,
  "org.na": 1,
  "name": 1,
  "nc": 1,
  "asso.nc": 1,
  "nom.nc": 1,
  "ne": 1,
  "net": 1,
  "nf": 1,
  "com.nf": 1,
  "net.nf": 1,
  "per.nf": 1,
  "rec.nf": 1,
  "web.nf": 1,
  "arts.nf": 1,
  "firm.nf": 1,
  "info.nf": 1,
  "other.nf": 1,
  "store.nf": 1,
  "ng": 1,
  "com.ng": 1,
  "edu.ng": 1,
  "gov.ng": 1,
  "i.ng": 1,
  "mil.ng": 1,
  "mobi.ng": 1,
  "name.ng": 1,
  "net.ng": 1,
  "org.ng": 1,
  "sch.ng": 1,
  "ni": 1,
  "ac.ni": 1,
  "biz.ni": 1,
  "co.ni": 1,
  "com.ni": 1,
  "edu.ni": 1,
  "gob.ni": 1,
  "in.ni": 1,
  "info.ni": 1,
  "int.ni": 1,
  "mil.ni": 1,
  "net.ni": 1,
  "nom.ni": 1,
  "org.ni": 1,
  "web.ni": 1,
  "nl": 1,
  "no": 1,
  "fhs.no": 1,
  "vgs.no": 1,
  "fylkesbibl.no": 1,
  "folkebibl.no": 1,
  "museum.no": 1,
  "idrett.no": 1,
  "priv.no": 1,
  "mil.no": 1,
  "stat.no": 1,
  "dep.no": 1,
  "kommune.no": 1,
  "herad.no": 1,
  "aa.no": 1,
  "ah.no": 1,
  "bu.no": 1,
  "fm.no": 1,
  "hl.no": 1,
  "hm.no": 1,
  "jan-mayen.no": 1,
  "mr.no": 1,
  "nl.no": 1,
  "nt.no": 1,
  "of.no": 1,
  "ol.no": 1,
  "oslo.no": 1,
  "rl.no": 1,
  "sf.no": 1,
  "st.no": 1,
  "svalbard.no": 1,
  "tm.no": 1,
  "tr.no": 1,
  "va.no": 1,
  "vf.no": 1,
  "gs.aa.no": 1,
  "gs.ah.no": 1,
  "gs.bu.no": 1,
  "gs.fm.no": 1,
  "gs.hl.no": 1,
  "gs.hm.no": 1,
  "gs.jan-mayen.no": 1,
  "gs.mr.no": 1,
  "gs.nl.no": 1,
  "gs.nt.no": 1,
  "gs.of.no": 1,
  "gs.ol.no": 1,
  "gs.oslo.no": 1,
  "gs.rl.no": 1,
  "gs.sf.no": 1,
  "gs.st.no": 1,
  "gs.svalbard.no": 1,
  "gs.tm.no": 1,
  "gs.tr.no": 1,
  "gs.va.no": 1,
  "gs.vf.no": 1,
  "akrehamn.no": 1,
  "xn--krehamn-dxa.no": 1,
  "algard.no": 1,
  "xn--lgrd-poac.no": 1,
  "arna.no": 1,
  "brumunddal.no": 1,
  "bryne.no": 1,
  "bronnoysund.no": 1,
  "xn--brnnysund-m8ac.no": 1,
  "drobak.no": 1,
  "xn--drbak-wua.no": 1,
  "egersund.no": 1,
  "fetsund.no": 1,
  "floro.no": 1,
  "xn--flor-jra.no": 1,
  "fredrikstad.no": 1,
  "hokksund.no": 1,
  "honefoss.no": 1,
  "xn--hnefoss-q1a.no": 1,
  "jessheim.no": 1,
  "jorpeland.no": 1,
  "xn--jrpeland-54a.no": 1,
  "kirkenes.no": 1,
  "kopervik.no": 1,
  "krokstadelva.no": 1,
  "langevag.no": 1,
  "xn--langevg-jxa.no": 1,
  "leirvik.no": 1,
  "mjondalen.no": 1,
  "xn--mjndalen-64a.no": 1,
  "mo-i-rana.no": 1,
  "mosjoen.no": 1,
  "xn--mosjen-eya.no": 1,
  "nesoddtangen.no": 1,
  "orkanger.no": 1,
  "osoyro.no": 1,
  "xn--osyro-wua.no": 1,
  "raholt.no": 1,
  "xn--rholt-mra.no": 1,
  "sandnessjoen.no": 1,
  "xn--sandnessjen-ogb.no": 1,
  "skedsmokorset.no": 1,
  "slattum.no": 1,
  "spjelkavik.no": 1,
  "stathelle.no": 1,
  "stavern.no": 1,
  "stjordalshalsen.no": 1,
  "xn--stjrdalshalsen-sqb.no": 1,
  "tananger.no": 1,
  "tranby.no": 1,
  "vossevangen.no": 1,
  "afjord.no": 1,
  "xn--fjord-lra.no": 1,
  "agdenes.no": 1,
  "al.no": 1,
  "xn--l-1fa.no": 1,
  "alesund.no": 1,
  "xn--lesund-hua.no": 1,
  "alstahaug.no": 1,
  "alta.no": 1,
  "xn--lt-liac.no": 1,
  "alaheadju.no": 1,
  "xn--laheadju-7ya.no": 1,
  "alvdal.no": 1,
  "amli.no": 1,
  "xn--mli-tla.no": 1,
  "amot.no": 1,
  "xn--mot-tla.no": 1,
  "andebu.no": 1,
  "andoy.no": 1,
  "xn--andy-ira.no": 1,
  "andasuolo.no": 1,
  "ardal.no": 1,
  "xn--rdal-poa.no": 1,
  "aremark.no": 1,
  "arendal.no": 1,
  "xn--s-1fa.no": 1,
  "aseral.no": 1,
  "xn--seral-lra.no": 1,
  "asker.no": 1,
  "askim.no": 1,
  "askvoll.no": 1,
  "askoy.no": 1,
  "xn--asky-ira.no": 1,
  "asnes.no": 1,
  "xn--snes-poa.no": 1,
  "audnedaln.no": 1,
  "aukra.no": 1,
  "aure.no": 1,
  "aurland.no": 1,
  "aurskog-holand.no": 1,
  "xn--aurskog-hland-jnb.no": 1,
  "austevoll.no": 1,
  "austrheim.no": 1,
  "averoy.no": 1,
  "xn--avery-yua.no": 1,
  "balestrand.no": 1,
  "ballangen.no": 1,
  "balat.no": 1,
  "xn--blt-elab.no": 1,
  "balsfjord.no": 1,
  "bahccavuotna.no": 1,
  "xn--bhccavuotna-k7a.no": 1,
  "bamble.no": 1,
  "bardu.no": 1,
  "beardu.no": 1,
  "beiarn.no": 1,
  "bajddar.no": 1,
  "xn--bjddar-pta.no": 1,
  "baidar.no": 1,
  "xn--bidr-5nac.no": 1,
  "berg.no": 1,
  "bergen.no": 1,
  "berlevag.no": 1,
  "xn--berlevg-jxa.no": 1,
  "bearalvahki.no": 1,
  "xn--bearalvhki-y4a.no": 1,
  "bindal.no": 1,
  "birkenes.no": 1,
  "bjarkoy.no": 1,
  "xn--bjarky-fya.no": 1,
  "bjerkreim.no": 1,
  "bjugn.no": 1,
  "bodo.no": 1,
  "xn--bod-2na.no": 1,
  "badaddja.no": 1,
  "xn--bdddj-mrabd.no": 1,
  "budejju.no": 1,
  "bokn.no": 1,
  "bremanger.no": 1,
  "bronnoy.no": 1,
  "xn--brnny-wuac.no": 1,
  "bygland.no": 1,
  "bykle.no": 1,
  "barum.no": 1,
  "xn--brum-voa.no": 1,
  "bo.telemark.no": 1,
  "xn--b-5ga.telemark.no": 1,
  "bo.nordland.no": 1,
  "xn--b-5ga.nordland.no": 1,
  "bievat.no": 1,
  "xn--bievt-0qa.no": 1,
  "bomlo.no": 1,
  "xn--bmlo-gra.no": 1,
  "batsfjord.no": 1,
  "xn--btsfjord-9za.no": 1,
  "bahcavuotna.no": 1,
  "xn--bhcavuotna-s4a.no": 1,
  "dovre.no": 1,
  "drammen.no": 1,
  "drangedal.no": 1,
  "dyroy.no": 1,
  "xn--dyry-ira.no": 1,
  "donna.no": 1,
  "xn--dnna-gra.no": 1,
  "eid.no": 1,
  "eidfjord.no": 1,
  "eidsberg.no": 1,
  "eidskog.no": 1,
  "eidsvoll.no": 1,
  "eigersund.no": 1,
  "elverum.no": 1,
  "enebakk.no": 1,
  "engerdal.no": 1,
  "etne.no": 1,
  "etnedal.no": 1,
  "evenes.no": 1,
  "evenassi.no": 1,
  "xn--eveni-0qa01ga.no": 1,
  "evje-og-hornnes.no": 1,
  "farsund.no": 1,
  "fauske.no": 1,
  "fuossko.no": 1,
  "fuoisku.no": 1,
  "fedje.no": 1,
  "fet.no": 1,
  "finnoy.no": 1,
  "xn--finny-yua.no": 1,
  "fitjar.no": 1,
  "fjaler.no": 1,
  "fjell.no": 1,
  "flakstad.no": 1,
  "flatanger.no": 1,
  "flekkefjord.no": 1,
  "flesberg.no": 1,
  "flora.no": 1,
  "fla.no": 1,
  "xn--fl-zia.no": 1,
  "folldal.no": 1,
  "forsand.no": 1,
  "fosnes.no": 1,
  "frei.no": 1,
  "frogn.no": 1,
  "froland.no": 1,
  "frosta.no": 1,
  "frana.no": 1,
  "xn--frna-woa.no": 1,
  "froya.no": 1,
  "xn--frya-hra.no": 1,
  "fusa.no": 1,
  "fyresdal.no": 1,
  "forde.no": 1,
  "xn--frde-gra.no": 1,
  "gamvik.no": 1,
  "gangaviika.no": 1,
  "xn--ggaviika-8ya47h.no": 1,
  "gaular.no": 1,
  "gausdal.no": 1,
  "gildeskal.no": 1,
  "xn--gildeskl-g0a.no": 1,
  "giske.no": 1,
  "gjemnes.no": 1,
  "gjerdrum.no": 1,
  "gjerstad.no": 1,
  "gjesdal.no": 1,
  "gjovik.no": 1,
  "xn--gjvik-wua.no": 1,
  "gloppen.no": 1,
  "gol.no": 1,
  "gran.no": 1,
  "grane.no": 1,
  "granvin.no": 1,
  "gratangen.no": 1,
  "grimstad.no": 1,
  "grong.no": 1,
  "kraanghke.no": 1,
  "xn--kranghke-b0a.no": 1,
  "grue.no": 1,
  "gulen.no": 1,
  "hadsel.no": 1,
  "halden.no": 1,
  "halsa.no": 1,
  "hamar.no": 1,
  "hamaroy.no": 1,
  "habmer.no": 1,
  "xn--hbmer-xqa.no": 1,
  "hapmir.no": 1,
  "xn--hpmir-xqa.no": 1,
  "hammerfest.no": 1,
  "hammarfeasta.no": 1,
  "xn--hmmrfeasta-s4ac.no": 1,
  "haram.no": 1,
  "hareid.no": 1,
  "harstad.no": 1,
  "hasvik.no": 1,
  "aknoluokta.no": 1,
  "xn--koluokta-7ya57h.no": 1,
  "hattfjelldal.no": 1,
  "aarborte.no": 1,
  "haugesund.no": 1,
  "hemne.no": 1,
  "hemnes.no": 1,
  "hemsedal.no": 1,
  "heroy.more-og-romsdal.no": 1,
  "xn--hery-ira.xn--mre-og-romsdal-qqb.no": 1,
  "heroy.nordland.no": 1,
  "xn--hery-ira.nordland.no": 1,
  "hitra.no": 1,
  "hjartdal.no": 1,
  "hjelmeland.no": 1,
  "hobol.no": 1,
  "xn--hobl-ira.no": 1,
  "hof.no": 1,
  "hol.no": 1,
  "hole.no": 1,
  "holmestrand.no": 1,
  "holtalen.no": 1,
  "xn--holtlen-hxa.no": 1,
  "hornindal.no": 1,
  "horten.no": 1,
  "hurdal.no": 1,
  "hurum.no": 1,
  "hvaler.no": 1,
  "hyllestad.no": 1,
  "hagebostad.no": 1,
  "xn--hgebostad-g3a.no": 1,
  "hoyanger.no": 1,
  "xn--hyanger-q1a.no": 1,
  "hoylandet.no": 1,
  "xn--hylandet-54a.no": 1,
  "ha.no": 1,
  "xn--h-2fa.no": 1,
  "ibestad.no": 1,
  "inderoy.no": 1,
  "xn--indery-fya.no": 1,
  "iveland.no": 1,
  "jevnaker.no": 1,
  "jondal.no": 1,
  "jolster.no": 1,
  "xn--jlster-bya.no": 1,
  "karasjok.no": 1,
  "karasjohka.no": 1,
  "xn--krjohka-hwab49j.no": 1,
  "karlsoy.no": 1,
  "galsa.no": 1,
  "xn--gls-elac.no": 1,
  "karmoy.no": 1,
  "xn--karmy-yua.no": 1,
  "kautokeino.no": 1,
  "guovdageaidnu.no": 1,
  "klepp.no": 1,
  "klabu.no": 1,
  "xn--klbu-woa.no": 1,
  "kongsberg.no": 1,
  "kongsvinger.no": 1,
  "kragero.no": 1,
  "xn--krager-gya.no": 1,
  "kristiansand.no": 1,
  "kristiansund.no": 1,
  "krodsherad.no": 1,
  "xn--krdsherad-m8a.no": 1,
  "kvalsund.no": 1,
  "rahkkeravju.no": 1,
  "xn--rhkkervju-01af.no": 1,
  "kvam.no": 1,
  "kvinesdal.no": 1,
  "kvinnherad.no": 1,
  "kviteseid.no": 1,
  "kvitsoy.no": 1,
  "xn--kvitsy-fya.no": 1,
  "kvafjord.no": 1,
  "xn--kvfjord-nxa.no": 1,
  "giehtavuoatna.no": 1,
  "kvanangen.no": 1,
  "xn--kvnangen-k0a.no": 1,
  "navuotna.no": 1,
  "xn--nvuotna-hwa.no": 1,
  "kafjord.no": 1,
  "xn--kfjord-iua.no": 1,
  "gaivuotna.no": 1,
  "xn--givuotna-8ya.no": 1,
  "larvik.no": 1,
  "lavangen.no": 1,
  "lavagis.no": 1,
  "loabat.no": 1,
  "xn--loabt-0qa.no": 1,
  "lebesby.no": 1,
  "davvesiida.no": 1,
  "leikanger.no": 1,
  "leirfjord.no": 1,
  "leka.no": 1,
  "leksvik.no": 1,
  "lenvik.no": 1,
  "leangaviika.no": 1,
  "xn--leagaviika-52b.no": 1,
  "lesja.no": 1,
  "levanger.no": 1,
  "lier.no": 1,
  "lierne.no": 1,
  "lillehammer.no": 1,
  "lillesand.no": 1,
  "lindesnes.no": 1,
  "lindas.no": 1,
  "xn--linds-pra.no": 1,
  "lom.no": 1,
  "loppa.no": 1,
  "lahppi.no": 1,
  "xn--lhppi-xqa.no": 1,
  "lund.no": 1,
  "lunner.no": 1,
  "luroy.no": 1,
  "xn--lury-ira.no": 1,
  "luster.no": 1,
  "lyngdal.no": 1,
  "lyngen.no": 1,
  "ivgu.no": 1,
  "lardal.no": 1,
  "lerdal.no": 1,
  "xn--lrdal-sra.no": 1,
  "lodingen.no": 1,
  "xn--ldingen-q1a.no": 1,
  "lorenskog.no": 1,
  "xn--lrenskog-54a.no": 1,
  "loten.no": 1,
  "xn--lten-gra.no": 1,
  "malvik.no": 1,
  "masoy.no": 1,
  "xn--msy-ula0h.no": 1,
  "muosat.no": 1,
  "xn--muost-0qa.no": 1,
  "mandal.no": 1,
  "marker.no": 1,
  "marnardal.no": 1,
  "masfjorden.no": 1,
  "meland.no": 1,
  "meldal.no": 1,
  "melhus.no": 1,
  "meloy.no": 1,
  "xn--mely-ira.no": 1,
  "meraker.no": 1,
  "xn--merker-kua.no": 1,
  "moareke.no": 1,
  "xn--moreke-jua.no": 1,
  "midsund.no": 1,
  "midtre-gauldal.no": 1,
  "modalen.no": 1,
  "modum.no": 1,
  "molde.no": 1,
  "moskenes.no": 1,
  "moss.no": 1,
  "mosvik.no": 1,
  "malselv.no": 1,
  "xn--mlselv-iua.no": 1,
  "malatvuopmi.no": 1,
  "xn--mlatvuopmi-s4a.no": 1,
  "namdalseid.no": 1,
  "aejrie.no": 1,
  "namsos.no": 1,
  "namsskogan.no": 1,
  "naamesjevuemie.no": 1,
  "xn--nmesjevuemie-tcba.no": 1,
  "laakesvuemie.no": 1,
  "nannestad.no": 1,
  "narvik.no": 1,
  "narviika.no": 1,
  "naustdal.no": 1,
  "nedre-eiker.no": 1,
  "nes.akershus.no": 1,
  "nes.buskerud.no": 1,
  "nesna.no": 1,
  "nesodden.no": 1,
  "nesseby.no": 1,
  "unjarga.no": 1,
  "xn--unjrga-rta.no": 1,
  "nesset.no": 1,
  "nissedal.no": 1,
  "nittedal.no": 1,
  "nord-aurdal.no": 1,
  "nord-fron.no": 1,
  "nord-odal.no": 1,
  "norddal.no": 1,
  "nordkapp.no": 1,
  "davvenjarga.no": 1,
  "xn--davvenjrga-y4a.no": 1,
  "nordre-land.no": 1,
  "nordreisa.no": 1,
  "raisa.no": 1,
  "xn--risa-5na.no": 1,
  "nore-og-uvdal.no": 1,
  "notodden.no": 1,
  "naroy.no": 1,
  "xn--nry-yla5g.no": 1,
  "notteroy.no": 1,
  "xn--nttery-byae.no": 1,
  "odda.no": 1,
  "oksnes.no": 1,
  "xn--ksnes-uua.no": 1,
  "oppdal.no": 1,
  "oppegard.no": 1,
  "xn--oppegrd-ixa.no": 1,
  "orkdal.no": 1,
  "orland.no": 1,
  "xn--rland-uua.no": 1,
  "orskog.no": 1,
  "xn--rskog-uua.no": 1,
  "orsta.no": 1,
  "xn--rsta-fra.no": 1,
  "os.hedmark.no": 1,
  "os.hordaland.no": 1,
  "osen.no": 1,
  "osteroy.no": 1,
  "xn--ostery-fya.no": 1,
  "ostre-toten.no": 1,
  "xn--stre-toten-zcb.no": 1,
  "overhalla.no": 1,
  "ovre-eiker.no": 1,
  "xn--vre-eiker-k8a.no": 1,
  "oyer.no": 1,
  "xn--yer-zna.no": 1,
  "oygarden.no": 1,
  "xn--ygarden-p1a.no": 1,
  "oystre-slidre.no": 1,
  "xn--ystre-slidre-ujb.no": 1,
  "porsanger.no": 1,
  "porsangu.no": 1,
  "xn--porsgu-sta26f.no": 1,
  "porsgrunn.no": 1,
  "radoy.no": 1,
  "xn--rady-ira.no": 1,
  "rakkestad.no": 1,
  "rana.no": 1,
  "ruovat.no": 1,
  "randaberg.no": 1,
  "rauma.no": 1,
  "rendalen.no": 1,
  "rennebu.no": 1,
  "rennesoy.no": 1,
  "xn--rennesy-v1a.no": 1,
  "rindal.no": 1,
  "ringebu.no": 1,
  "ringerike.no": 1,
  "ringsaker.no": 1,
  "rissa.no": 1,
  "risor.no": 1,
  "xn--risr-ira.no": 1,
  "roan.no": 1,
  "rollag.no": 1,
  "rygge.no": 1,
  "ralingen.no": 1,
  "xn--rlingen-mxa.no": 1,
  "rodoy.no": 1,
  "xn--rdy-0nab.no": 1,
  "romskog.no": 1,
  "xn--rmskog-bya.no": 1,
  "roros.no": 1,
  "xn--rros-gra.no": 1,
  "rost.no": 1,
  "xn--rst-0na.no": 1,
  "royken.no": 1,
  "xn--ryken-vua.no": 1,
  "royrvik.no": 1,
  "xn--ryrvik-bya.no": 1,
  "rade.no": 1,
  "xn--rde-ula.no": 1,
  "salangen.no": 1,
  "siellak.no": 1,
  "saltdal.no": 1,
  "salat.no": 1,
  "xn--slt-elab.no": 1,
  "xn--slat-5na.no": 1,
  "samnanger.no": 1,
  "sande.more-og-romsdal.no": 1,
  "sande.xn--mre-og-romsdal-qqb.no": 1,
  "sande.vestfold.no": 1,
  "sandefjord.no": 1,
  "sandnes.no": 1,
  "sandoy.no": 1,
  "xn--sandy-yua.no": 1,
  "sarpsborg.no": 1,
  "sauda.no": 1,
  "sauherad.no": 1,
  "sel.no": 1,
  "selbu.no": 1,
  "selje.no": 1,
  "seljord.no": 1,
  "sigdal.no": 1,
  "siljan.no": 1,
  "sirdal.no": 1,
  "skaun.no": 1,
  "skedsmo.no": 1,
  "ski.no": 1,
  "skien.no": 1,
  "skiptvet.no": 1,
  "skjervoy.no": 1,
  "xn--skjervy-v1a.no": 1,
  "skierva.no": 1,
  "xn--skierv-uta.no": 1,
  "skjak.no": 1,
  "xn--skjk-soa.no": 1,
  "skodje.no": 1,
  "skanland.no": 1,
  "xn--sknland-fxa.no": 1,
  "skanit.no": 1,
  "xn--sknit-yqa.no": 1,
  "smola.no": 1,
  "xn--smla-hra.no": 1,
  "snillfjord.no": 1,
  "snasa.no": 1,
  "xn--snsa-roa.no": 1,
  "snoasa.no": 1,
  "snaase.no": 1,
  "xn--snase-nra.no": 1,
  "sogndal.no": 1,
  "sokndal.no": 1,
  "sola.no": 1,
  "solund.no": 1,
  "songdalen.no": 1,
  "sortland.no": 1,
  "spydeberg.no": 1,
  "stange.no": 1,
  "stavanger.no": 1,
  "steigen.no": 1,
  "steinkjer.no": 1,
  "stjordal.no": 1,
  "xn--stjrdal-s1a.no": 1,
  "stokke.no": 1,
  "stor-elvdal.no": 1,
  "stord.no": 1,
  "stordal.no": 1,
  "storfjord.no": 1,
  "omasvuotna.no": 1,
  "strand.no": 1,
  "stranda.no": 1,
  "stryn.no": 1,
  "sula.no": 1,
  "suldal.no": 1,
  "sund.no": 1,
  "sunndal.no": 1,
  "surnadal.no": 1,
  "sveio.no": 1,
  "svelvik.no": 1,
  "sykkylven.no": 1,
  "sogne.no": 1,
  "xn--sgne-gra.no": 1,
  "somna.no": 1,
  "xn--smna-gra.no": 1,
  "sondre-land.no": 1,
  "xn--sndre-land-0cb.no": 1,
  "sor-aurdal.no": 1,
  "xn--sr-aurdal-l8a.no": 1,
  "sor-fron.no": 1,
  "xn--sr-fron-q1a.no": 1,
  "sor-odal.no": 1,
  "xn--sr-odal-q1a.no": 1,
  "sor-varanger.no": 1,
  "xn--sr-varanger-ggb.no": 1,
  "matta-varjjat.no": 1,
  "xn--mtta-vrjjat-k7af.no": 1,
  "sorfold.no": 1,
  "xn--srfold-bya.no": 1,
  "sorreisa.no": 1,
  "xn--srreisa-q1a.no": 1,
  "sorum.no": 1,
  "xn--srum-gra.no": 1,
  "tana.no": 1,
  "deatnu.no": 1,
  "time.no": 1,
  "tingvoll.no": 1,
  "tinn.no": 1,
  "tjeldsund.no": 1,
  "dielddanuorri.no": 1,
  "tjome.no": 1,
  "xn--tjme-hra.no": 1,
  "tokke.no": 1,
  "tolga.no": 1,
  "torsken.no": 1,
  "tranoy.no": 1,
  "xn--trany-yua.no": 1,
  "tromso.no": 1,
  "xn--troms-zua.no": 1,
  "tromsa.no": 1,
  "romsa.no": 1,
  "trondheim.no": 1,
  "troandin.no": 1,
  "trysil.no": 1,
  "trana.no": 1,
  "xn--trna-woa.no": 1,
  "trogstad.no": 1,
  "xn--trgstad-r1a.no": 1,
  "tvedestrand.no": 1,
  "tydal.no": 1,
  "tynset.no": 1,
  "tysfjord.no": 1,
  "divtasvuodna.no": 1,
  "divttasvuotna.no": 1,
  "tysnes.no": 1,
  "tysvar.no": 1,
  "xn--tysvr-vra.no": 1,
  "tonsberg.no": 1,
  "xn--tnsberg-q1a.no": 1,
  "ullensaker.no": 1,
  "ullensvang.no": 1,
  "ulvik.no": 1,
  "utsira.no": 1,
  "vadso.no": 1,
  "xn--vads-jra.no": 1,
  "cahcesuolo.no": 1,
  "xn--hcesuolo-7ya35b.no": 1,
  "vaksdal.no": 1,
  "valle.no": 1,
  "vang.no": 1,
  "vanylven.no": 1,
  "vardo.no": 1,
  "xn--vard-jra.no": 1,
  "varggat.no": 1,
  "xn--vrggt-xqad.no": 1,
  "vefsn.no": 1,
  "vaapste.no": 1,
  "vega.no": 1,
  "vegarshei.no": 1,
  "xn--vegrshei-c0a.no": 1,
  "vennesla.no": 1,
  "verdal.no": 1,
  "verran.no": 1,
  "vestby.no": 1,
  "vestnes.no": 1,
  "vestre-slidre.no": 1,
  "vestre-toten.no": 1,
  "vestvagoy.no": 1,
  "xn--vestvgy-ixa6o.no": 1,
  "vevelstad.no": 1,
  "vik.no": 1,
  "vikna.no": 1,
  "vindafjord.no": 1,
  "volda.no": 1,
  "voss.no": 1,
  "varoy.no": 1,
  "xn--vry-yla5g.no": 1,
  "vagan.no": 1,
  "xn--vgan-qoa.no": 1,
  "voagat.no": 1,
  "vagsoy.no": 1,
  "xn--vgsy-qoa0j.no": 1,
  "vaga.no": 1,
  "xn--vg-yiab.no": 1,
  "valer.ostfold.no": 1,
  "xn--vler-qoa.xn--stfold-9xa.no": 1,
  "valer.hedmark.no": 1,
  "xn--vler-qoa.hedmark.no": 1,
  "np": 2,
  "nr": 1,
  "biz.nr": 1,
  "info.nr": 1,
  "gov.nr": 1,
  "edu.nr": 1,
  "org.nr": 1,
  "net.nr": 1,
  "com.nr": 1,
  "nu": 1,
  "nz": 1,
  "ac.nz": 1,
  "co.nz": 1,
  "cri.nz": 1,
  "geek.nz": 1,
  "gen.nz": 1,
  "govt.nz": 1,
  "health.nz": 1,
  "iwi.nz": 1,
  "kiwi.nz": 1,
  "maori.nz": 1,
  "mil.nz": 1,
  "xn--mori-qsa.nz": 1,
  "net.nz": 1,
  "org.nz": 1,
  "parliament.nz": 1,
  "school.nz": 1,
  "om": 1,
  "co.om": 1,
  "com.om": 1,
  "edu.om": 1,
  "gov.om": 1,
  "med.om": 1,
  "museum.om": 1,
  "net.om": 1,
  "org.om": 1,
  "pro.om": 1,
  "onion": 1,
  "org": 1,
  "pa": 1,
  "ac.pa": 1,
  "gob.pa": 1,
  "com.pa": 1,
  "org.pa": 1,
  "sld.pa": 1,
  "edu.pa": 1,
  "net.pa": 1,
  "ing.pa": 1,
  "abo.pa": 1,
  "med.pa": 1,
  "nom.pa": 1,
  "pe": 1,
  "edu.pe": 1,
  "gob.pe": 1,
  "nom.pe": 1,
  "mil.pe": 1,
  "org.pe": 1,
  "com.pe": 1,
  "net.pe": 1,
  "pf": 1,
  "com.pf": 1,
  "org.pf": 1,
  "edu.pf": 1,
  "pg": 2,
  "ph": 1,
  "com.ph": 1,
  "net.ph": 1,
  "org.ph": 1,
  "gov.ph": 1,
  "edu.ph": 1,
  "ngo.ph": 1,
  "mil.ph": 1,
  "i.ph": 1,
  "pk": 1,
  "com.pk": 1,
  "net.pk": 1,
  "edu.pk": 1,
  "org.pk": 1,
  "fam.pk": 1,
  "biz.pk": 1,
  "web.pk": 1,
  "gov.pk": 1,
  "gob.pk": 1,
  "gok.pk": 1,
  "gon.pk": 1,
  "gop.pk": 1,
  "gos.pk": 1,
  "info.pk": 1,
  "pl": 1,
  "com.pl": 1,
  "net.pl": 1,
  "org.pl": 1,
  "aid.pl": 1,
  "agro.pl": 1,
  "atm.pl": 1,
  "auto.pl": 1,
  "biz.pl": 1,
  "edu.pl": 1,
  "gmina.pl": 1,
  "gsm.pl": 1,
  "info.pl": 1,
  "mail.pl": 1,
  "miasta.pl": 1,
  "media.pl": 1,
  "mil.pl": 1,
  "nieruchomosci.pl": 1,
  "nom.pl": 1,
  "pc.pl": 1,
  "powiat.pl": 1,
  "priv.pl": 1,
  "realestate.pl": 1,
  "rel.pl": 1,
  "sex.pl": 1,
  "shop.pl": 1,
  "sklep.pl": 1,
  "sos.pl": 1,
  "szkola.pl": 1,
  "targi.pl": 1,
  "tm.pl": 1,
  "tourism.pl": 1,
  "travel.pl": 1,
  "turystyka.pl": 1,
  "gov.pl": 1,
  "ap.gov.pl": 1,
  "griw.gov.pl": 1,
  "ic.gov.pl": 1,
  "is.gov.pl": 1,
  "kmpsp.gov.pl": 1,
  "konsulat.gov.pl": 1,
  "kppsp.gov.pl": 1,
  "kwp.gov.pl": 1,
  "kwpsp.gov.pl": 1,
  "mup.gov.pl": 1,
  "mw.gov.pl": 1,
  "oia.gov.pl": 1,
  "oirm.gov.pl": 1,
  "oke.gov.pl": 1,
  "oow.gov.pl": 1,
  "oschr.gov.pl": 1,
  "oum.gov.pl": 1,
  "pa.gov.pl": 1,
  "pinb.gov.pl": 1,
  "piw.gov.pl": 1,
  "po.gov.pl": 1,
  "pr.gov.pl": 1,
  "psp.gov.pl": 1,
  "psse.gov.pl": 1,
  "pup.gov.pl": 1,
  "rzgw.gov.pl": 1,
  "sa.gov.pl": 1,
  "sdn.gov.pl": 1,
  "sko.gov.pl": 1,
  "so.gov.pl": 1,
  "sr.gov.pl": 1,
  "starostwo.gov.pl": 1,
  "ug.gov.pl": 1,
  "ugim.gov.pl": 1,
  "um.gov.pl": 1,
  "umig.gov.pl": 1,
  "upow.gov.pl": 1,
  "uppo.gov.pl": 1,
  "us.gov.pl": 1,
  "uw.gov.pl": 1,
  "uzs.gov.pl": 1,
  "wif.gov.pl": 1,
  "wiih.gov.pl": 1,
  "winb.gov.pl": 1,
  "wios.gov.pl": 1,
  "witd.gov.pl": 1,
  "wiw.gov.pl": 1,
  "wkz.gov.pl": 1,
  "wsa.gov.pl": 1,
  "wskr.gov.pl": 1,
  "wsse.gov.pl": 1,
  "wuoz.gov.pl": 1,
  "wzmiuw.gov.pl": 1,
  "zp.gov.pl": 1,
  "zpisdn.gov.pl": 1,
  "augustow.pl": 1,
  "babia-gora.pl": 1,
  "bedzin.pl": 1,
  "beskidy.pl": 1,
  "bialowieza.pl": 1,
  "bialystok.pl": 1,
  "bielawa.pl": 1,
  "bieszczady.pl": 1,
  "boleslawiec.pl": 1,
  "bydgoszcz.pl": 1,
  "bytom.pl": 1,
  "cieszyn.pl": 1,
  "czeladz.pl": 1,
  "czest.pl": 1,
  "dlugoleka.pl": 1,
  "elblag.pl": 1,
  "elk.pl": 1,
  "glogow.pl": 1,
  "gniezno.pl": 1,
  "gorlice.pl": 1,
  "grajewo.pl": 1,
  "ilawa.pl": 1,
  "jaworzno.pl": 1,
  "jelenia-gora.pl": 1,
  "jgora.pl": 1,
  "kalisz.pl": 1,
  "kazimierz-dolny.pl": 1,
  "karpacz.pl": 1,
  "kartuzy.pl": 1,
  "kaszuby.pl": 1,
  "katowice.pl": 1,
  "kepno.pl": 1,
  "ketrzyn.pl": 1,
  "klodzko.pl": 1,
  "kobierzyce.pl": 1,
  "kolobrzeg.pl": 1,
  "konin.pl": 1,
  "konskowola.pl": 1,
  "kutno.pl": 1,
  "lapy.pl": 1,
  "lebork.pl": 1,
  "legnica.pl": 1,
  "lezajsk.pl": 1,
  "limanowa.pl": 1,
  "lomza.pl": 1,
  "lowicz.pl": 1,
  "lubin.pl": 1,
  "lukow.pl": 1,
  "malbork.pl": 1,
  "malopolska.pl": 1,
  "mazowsze.pl": 1,
  "mazury.pl": 1,
  "mielec.pl": 1,
  "mielno.pl": 1,
  "mragowo.pl": 1,
  "naklo.pl": 1,
  "nowaruda.pl": 1,
  "nysa.pl": 1,
  "olawa.pl": 1,
  "olecko.pl": 1,
  "olkusz.pl": 1,
  "olsztyn.pl": 1,
  "opoczno.pl": 1,
  "opole.pl": 1,
  "ostroda.pl": 1,
  "ostroleka.pl": 1,
  "ostrowiec.pl": 1,
  "ostrowwlkp.pl": 1,
  "pila.pl": 1,
  "pisz.pl": 1,
  "podhale.pl": 1,
  "podlasie.pl": 1,
  "polkowice.pl": 1,
  "pomorze.pl": 1,
  "pomorskie.pl": 1,
  "prochowice.pl": 1,
  "pruszkow.pl": 1,
  "przeworsk.pl": 1,
  "pulawy.pl": 1,
  "radom.pl": 1,
  "rawa-maz.pl": 1,
  "rybnik.pl": 1,
  "rzeszow.pl": 1,
  "sanok.pl": 1,
  "sejny.pl": 1,
  "slask.pl": 1,
  "slupsk.pl": 1,
  "sosnowiec.pl": 1,
  "stalowa-wola.pl": 1,
  "skoczow.pl": 1,
  "starachowice.pl": 1,
  "stargard.pl": 1,
  "suwalki.pl": 1,
  "swidnica.pl": 1,
  "swiebodzin.pl": 1,
  "swinoujscie.pl": 1,
  "szczecin.pl": 1,
  "szczytno.pl": 1,
  "tarnobrzeg.pl": 1,
  "tgory.pl": 1,
  "turek.pl": 1,
  "tychy.pl": 1,
  "ustka.pl": 1,
  "walbrzych.pl": 1,
  "warmia.pl": 1,
  "warszawa.pl": 1,
  "waw.pl": 1,
  "wegrow.pl": 1,
  "wielun.pl": 1,
  "wlocl.pl": 1,
  "wloclawek.pl": 1,
  "wodzislaw.pl": 1,
  "wolomin.pl": 1,
  "wroclaw.pl": 1,
  "zachpomor.pl": 1,
  "zagan.pl": 1,
  "zarow.pl": 1,
  "zgora.pl": 1,
  "zgorzelec.pl": 1,
  "pm": 1,
  "pn": 1,
  "gov.pn": 1,
  "co.pn": 1,
  "org.pn": 1,
  "edu.pn": 1,
  "net.pn": 1,
  "post": 1,
  "pr": 1,
  "com.pr": 1,
  "net.pr": 1,
  "org.pr": 1,
  "gov.pr": 1,
  "edu.pr": 1,
  "isla.pr": 1,
  "pro.pr": 1,
  "biz.pr": 1,
  "info.pr": 1,
  "name.pr": 1,
  "est.pr": 1,
  "prof.pr": 1,
  "ac.pr": 1,
  "pro": 1,
  "aaa.pro": 1,
  "aca.pro": 1,
  "acct.pro": 1,
  "avocat.pro": 1,
  "bar.pro": 1,
  "cpa.pro": 1,
  "eng.pro": 1,
  "jur.pro": 1,
  "law.pro": 1,
  "med.pro": 1,
  "recht.pro": 1,
  "ps": 1,
  "edu.ps": 1,
  "gov.ps": 1,
  "sec.ps": 1,
  "plo.ps": 1,
  "com.ps": 1,
  "org.ps": 1,
  "net.ps": 1,
  "pt": 1,
  "net.pt": 1,
  "gov.pt": 1,
  "org.pt": 1,
  "edu.pt": 1,
  "int.pt": 1,
  "publ.pt": 1,
  "com.pt": 1,
  "nome.pt": 1,
  "pw": 1,
  "co.pw": 1,
  "ne.pw": 1,
  "or.pw": 1,
  "ed.pw": 1,
  "go.pw": 1,
  "belau.pw": 1,
  "py": 1,
  "com.py": 1,
  "coop.py": 1,
  "edu.py": 1,
  "gov.py": 1,
  "mil.py": 1,
  "net.py": 1,
  "org.py": 1,
  "qa": 1,
  "com.qa": 1,
  "edu.qa": 1,
  "gov.qa": 1,
  "mil.qa": 1,
  "name.qa": 1,
  "net.qa": 1,
  "org.qa": 1,
  "sch.qa": 1,
  "re": 1,
  "asso.re": 1,
  "com.re": 1,
  "nom.re": 1,
  "ro": 1,
  "arts.ro": 1,
  "com.ro": 1,
  "firm.ro": 1,
  "info.ro": 1,
  "nom.ro": 1,
  "nt.ro": 1,
  "org.ro": 1,
  "rec.ro": 1,
  "store.ro": 1,
  "tm.ro": 1,
  "www.ro": 1,
  "rs": 1,
  "ac.rs": 1,
  "co.rs": 1,
  "edu.rs": 1,
  "gov.rs": 1,
  "in.rs": 1,
  "org.rs": 1,
  "ru": 1,
  "rw": 1,
  "ac.rw": 1,
  "co.rw": 1,
  "coop.rw": 1,
  "gov.rw": 1,
  "mil.rw": 1,
  "net.rw": 1,
  "org.rw": 1,
  "sa": 1,
  "com.sa": 1,
  "net.sa": 1,
  "org.sa": 1,
  "gov.sa": 1,
  "med.sa": 1,
  "pub.sa": 1,
  "edu.sa": 1,
  "sch.sa": 1,
  "sb": 1,
  "com.sb": 1,
  "edu.sb": 1,
  "gov.sb": 1,
  "net.sb": 1,
  "org.sb": 1,
  "sc": 1,
  "com.sc": 1,
  "gov.sc": 1,
  "net.sc": 1,
  "org.sc": 1,
  "edu.sc": 1,
  "sd": 1,
  "com.sd": 1,
  "net.sd": 1,
  "org.sd": 1,
  "edu.sd": 1,
  "med.sd": 1,
  "tv.sd": 1,
  "gov.sd": 1,
  "info.sd": 1,
  "se": 1,
  "a.se": 1,
  "ac.se": 1,
  "b.se": 1,
  "bd.se": 1,
  "brand.se": 1,
  "c.se": 1,
  "d.se": 1,
  "e.se": 1,
  "f.se": 1,
  "fh.se": 1,
  "fhsk.se": 1,
  "fhv.se": 1,
  "g.se": 1,
  "h.se": 1,
  "i.se": 1,
  "k.se": 1,
  "komforb.se": 1,
  "kommunalforbund.se": 1,
  "komvux.se": 1,
  "l.se": 1,
  "lanbib.se": 1,
  "m.se": 1,
  "n.se": 1,
  "naturbruksgymn.se": 1,
  "o.se": 1,
  "org.se": 1,
  "p.se": 1,
  "parti.se": 1,
  "pp.se": 1,
  "press.se": 1,
  "r.se": 1,
  "s.se": 1,
  "t.se": 1,
  "tm.se": 1,
  "u.se": 1,
  "w.se": 1,
  "x.se": 1,
  "y.se": 1,
  "z.se": 1,
  "sg": 1,
  "com.sg": 1,
  "net.sg": 1,
  "org.sg": 1,
  "gov.sg": 1,
  "edu.sg": 1,
  "per.sg": 1,
  "sh": 1,
  "com.sh": 1,
  "net.sh": 1,
  "gov.sh": 1,
  "org.sh": 1,
  "mil.sh": 1,
  "si": 1,
  "sj": 1,
  "sk": 1,
  "sl": 1,
  "com.sl": 1,
  "net.sl": 1,
  "edu.sl": 1,
  "gov.sl": 1,
  "org.sl": 1,
  "sm": 1,
  "sn": 1,
  "art.sn": 1,
  "com.sn": 1,
  "edu.sn": 1,
  "gouv.sn": 1,
  "org.sn": 1,
  "perso.sn": 1,
  "univ.sn": 1,
  "so": 1,
  "com.so": 1,
  "edu.so": 1,
  "gov.so": 1,
  "me.so": 1,
  "net.so": 1,
  "org.so": 1,
  "sr": 1,
  "ss": 1,
  "biz.ss": 1,
  "com.ss": 1,
  "edu.ss": 1,
  "gov.ss": 1,
  "me.ss": 1,
  "net.ss": 1,
  "org.ss": 1,
  "sch.ss": 1,
  "st": 1,
  "co.st": 1,
  "com.st": 1,
  "consulado.st": 1,
  "edu.st": 1,
  "embaixada.st": 1,
  "mil.st": 1,
  "net.st": 1,
  "org.st": 1,
  "principe.st": 1,
  "saotome.st": 1,
  "store.st": 1,
  "su": 1,
  "sv": 1,
  "com.sv": 1,
  "edu.sv": 1,
  "gob.sv": 1,
  "org.sv": 1,
  "red.sv": 1,
  "sx": 1,
  "gov.sx": 1,
  "sy": 1,
  "edu.sy": 1,
  "gov.sy": 1,
  "net.sy": 1,
  "mil.sy": 1,
  "com.sy": 1,
  "org.sy": 1,
  "sz": 1,
  "co.sz": 1,
  "ac.sz": 1,
  "org.sz": 1,
  "tc": 1,
  "td": 1,
  "tel": 1,
  "tf": 1,
  "tg": 1,
  "th": 1,
  "ac.th": 1,
  "co.th": 1,
  "go.th": 1,
  "in.th": 1,
  "mi.th": 1,
  "net.th": 1,
  "or.th": 1,
  "tj": 1,
  "ac.tj": 1,
  "biz.tj": 1,
  "co.tj": 1,
  "com.tj": 1,
  "edu.tj": 1,
  "go.tj": 1,
  "gov.tj": 1,
  "int.tj": 1,
  "mil.tj": 1,
  "name.tj": 1,
  "net.tj": 1,
  "nic.tj": 1,
  "org.tj": 1,
  "test.tj": 1,
  "web.tj": 1,
  "tk": 1,
  "tl": 1,
  "gov.tl": 1,
  "tm": 1,
  "com.tm": 1,
  "co.tm": 1,
  "org.tm": 1,
  "net.tm": 1,
  "nom.tm": 1,
  "gov.tm": 1,
  "mil.tm": 1,
  "edu.tm": 1,
  "tn": 1,
  "com.tn": 1,
  "ens.tn": 1,
  "fin.tn": 1,
  "gov.tn": 1,
  "ind.tn": 1,
  "info.tn": 1,
  "intl.tn": 1,
  "mincom.tn": 1,
  "nat.tn": 1,
  "net.tn": 1,
  "org.tn": 1,
  "perso.tn": 1,
  "tourism.tn": 1,
  "to": 1,
  "com.to": 1,
  "gov.to": 1,
  "net.to": 1,
  "org.to": 1,
  "edu.to": 1,
  "mil.to": 1,
  "tr": 1,
  "av.tr": 1,
  "bbs.tr": 1,
  "bel.tr": 1,
  "biz.tr": 1,
  "com.tr": 1,
  "dr.tr": 1,
  "edu.tr": 1,
  "gen.tr": 1,
  "gov.tr": 1,
  "info.tr": 1,
  "mil.tr": 1,
  "k12.tr": 1,
  "kep.tr": 1,
  "name.tr": 1,
  "net.tr": 1,
  "org.tr": 1,
  "pol.tr": 1,
  "tel.tr": 1,
  "tsk.tr": 1,
  "tv.tr": 1,
  "web.tr": 1,
  "nc.tr": 1,
  "gov.nc.tr": 1,
  "tt": 1,
  "co.tt": 1,
  "com.tt": 1,
  "org.tt": 1,
  "net.tt": 1,
  "biz.tt": 1,
  "info.tt": 1,
  "pro.tt": 1,
  "int.tt": 1,
  "coop.tt": 1,
  "jobs.tt": 1,
  "mobi.tt": 1,
  "travel.tt": 1,
  "museum.tt": 1,
  "aero.tt": 1,
  "name.tt": 1,
  "gov.tt": 1,
  "edu.tt": 1,
  "tv": 1,
  "tw": 1,
  "edu.tw": 1,
  "gov.tw": 1,
  "mil.tw": 1,
  "com.tw": 1,
  "net.tw": 1,
  "org.tw": 1,
  "idv.tw": 1,
  "game.tw": 1,
  "ebiz.tw": 1,
  "club.tw": 1,
  "xn--zf0ao64a.tw": 1,
  "xn--uc0atv.tw": 1,
  "xn--czrw28b.tw": 1,
  "tz": 1,
  "ac.tz": 1,
  "co.tz": 1,
  "go.tz": 1,
  "hotel.tz": 1,
  "info.tz": 1,
  "me.tz": 1,
  "mil.tz": 1,
  "mobi.tz": 1,
  "ne.tz": 1,
  "or.tz": 1,
  "sc.tz": 1,
  "tv.tz": 1,
  "ua": 1,
  "com.ua": 1,
  "edu.ua": 1,
  "gov.ua": 1,
  "in.ua": 1,
  "net.ua": 1,
  "org.ua": 1,
  "cherkassy.ua": 1,
  "cherkasy.ua": 1,
  "chernigov.ua": 1,
  "chernihiv.ua": 1,
  "chernivtsi.ua": 1,
  "chernovtsy.ua": 1,
  "ck.ua": 1,
  "cn.ua": 1,
  "cr.ua": 1,
  "crimea.ua": 1,
  "cv.ua": 1,
  "dn.ua": 1,
  "dnepropetrovsk.ua": 1,
  "dnipropetrovsk.ua": 1,
  "donetsk.ua": 1,
  "dp.ua": 1,
  "if.ua": 1,
  "ivano-frankivsk.ua": 1,
  "kh.ua": 1,
  "kharkiv.ua": 1,
  "kharkov.ua": 1,
  "kherson.ua": 1,
  "khmelnitskiy.ua": 1,
  "khmelnytskyi.ua": 1,
  "kiev.ua": 1,
  "kirovograd.ua": 1,
  "km.ua": 1,
  "kr.ua": 1,
  "kropyvnytskyi.ua": 1,
  "krym.ua": 1,
  "ks.ua": 1,
  "kv.ua": 1,
  "kyiv.ua": 1,
  "lg.ua": 1,
  "lt.ua": 1,
  "lugansk.ua": 1,
  "luhansk.ua": 1,
  "lutsk.ua": 1,
  "lv.ua": 1,
  "lviv.ua": 1,
  "mk.ua": 1,
  "mykolaiv.ua": 1,
  "nikolaev.ua": 1,
  "od.ua": 1,
  "odesa.ua": 1,
  "odessa.ua": 1,
  "pl.ua": 1,
  "poltava.ua": 1,
  "rivne.ua": 1,
  "rovno.ua": 1,
  "rv.ua": 1,
  "sb.ua": 1,
  "sebastopol.ua": 1,
  "sevastopol.ua": 1,
  "sm.ua": 1,
  "sumy.ua": 1,
  "te.ua": 1,
  "ternopil.ua": 1,
  "uz.ua": 1,
  "uzhgorod.ua": 1,
  "uzhhorod.ua": 1,
  "vinnica.ua": 1,
  "vinnytsia.ua": 1,
  "vn.ua": 1,
  "volyn.ua": 1,
  "yalta.ua": 1,
  "zakarpattia.ua": 1,
  "zaporizhzhe.ua": 1,
  "zaporizhzhia.ua": 1,
  "zhitomir.ua": 1,
  "zhytomyr.ua": 1,
  "zp.ua": 1,
  "zt.ua": 1,
  "ug": 1,
  "co.ug": 1,
  "or.ug": 1,
  "ac.ug": 1,
  "sc.ug": 1,
  "go.ug": 1,
  "ne.ug": 1,
  "com.ug": 1,
  "org.ug": 1,
  "uk": 1,
  "ac.uk": 1,
  "co.uk": 1,
  "gov.uk": 1,
  "ltd.uk": 1,
  "me.uk": 1,
  "net.uk": 1,
  "nhs.uk": 1,
  "org.uk": 1,
  "plc.uk": 1,
  "police.uk": 1,
  "sch.uk": 2,
  "us": 1,
  "dni.us": 1,
  "fed.us": 1,
  "isa.us": 1,
  "kids.us": 1,
  "nsn.us": 1,
  "ak.us": 1,
  "al.us": 1,
  "ar.us": 1,
  "as.us": 1,
  "az.us": 1,
  "ca.us": 1,
  "co.us": 1,
  "ct.us": 1,
  "dc.us": 1,
  "de.us": 1,
  "fl.us": 1,
  "ga.us": 1,
  "gu.us": 1,
  "hi.us": 1,
  "ia.us": 1,
  "id.us": 1,
  "il.us": 1,
  "in.us": 1,
  "ks.us": 1,
  "ky.us": 1,
  "la.us": 1,
  "ma.us": 1,
  "md.us": 1,
  "me.us": 1,
  "mi.us": 1,
  "mn.us": 1,
  "mo.us": 1,
  "ms.us": 1,
  "mt.us": 1,
  "nc.us": 1,
  "nd.us": 1,
  "ne.us": 1,
  "nh.us": 1,
  "nj.us": 1,
  "nm.us": 1,
  "nv.us": 1,
  "ny.us": 1,
  "oh.us": 1,
  "ok.us": 1,
  "or.us": 1,
  "pa.us": 1,
  "pr.us": 1,
  "ri.us": 1,
  "sc.us": 1,
  "sd.us": 1,
  "tn.us": 1,
  "tx.us": 1,
  "ut.us": 1,
  "vi.us": 1,
  "vt.us": 1,
  "va.us": 1,
  "wa.us": 1,
  "wi.us": 1,
  "wv.us": 1,
  "wy.us": 1,
  "k12.ak.us": 1,
  "k12.al.us": 1,
  "k12.ar.us": 1,
  "k12.as.us": 1,
  "k12.az.us": 1,
  "k12.ca.us": 1,
  "k12.co.us": 1,
  "k12.ct.us": 1,
  "k12.dc.us": 1,
  "k12.fl.us": 1,
  "k12.ga.us": 1,
  "k12.gu.us": 1,
  "k12.ia.us": 1,
  "k12.id.us": 1,
  "k12.il.us": 1,
  "k12.in.us": 1,
  "k12.ks.us": 1,
  "k12.ky.us": 1,
  "k12.la.us": 1,
  "k12.ma.us": 1,
  "k12.md.us": 1,
  "k12.me.us": 1,
  "k12.mi.us": 1,
  "k12.mn.us": 1,
  "k12.mo.us": 1,
  "k12.ms.us": 1,
  "k12.mt.us": 1,
  "k12.nc.us": 1,
  "k12.ne.us": 1,
  "k12.nh.us": 1,
  "k12.nj.us": 1,
  "k12.nm.us": 1,
  "k12.nv.us": 1,
  "k12.ny.us": 1,
  "k12.oh.us": 1,
  "k12.ok.us": 1,
  "k12.or.us": 1,
  "k12.pa.us": 1,
  "k12.pr.us": 1,
  "k12.sc.us": 1,
  "k12.tn.us": 1,
  "k12.tx.us": 1,
  "k12.ut.us": 1,
  "k12.vi.us": 1,
  "k12.vt.us": 1,
  "k12.va.us": 1,
  "k12.wa.us": 1,
  "k12.wi.us": 1,
  "k12.wy.us": 1,
  "cc.ak.us": 1,
  "cc.al.us": 1,
  "cc.ar.us": 1,
  "cc.as.us": 1,
  "cc.az.us": 1,
  "cc.ca.us": 1,
  "cc.co.us": 1,
  "cc.ct.us": 1,
  "cc.dc.us": 1,
  "cc.de.us": 1,
  "cc.fl.us": 1,
  "cc.ga.us": 1,
  "cc.gu.us": 1,
  "cc.hi.us": 1,
  "cc.ia.us": 1,
  "cc.id.us": 1,
  "cc.il.us": 1,
  "cc.in.us": 1,
  "cc.ks.us": 1,
  "cc.ky.us": 1,
  "cc.la.us": 1,
  "cc.ma.us": 1,
  "cc.md.us": 1,
  "cc.me.us": 1,
  "cc.mi.us": 1,
  "cc.mn.us": 1,
  "cc.mo.us": 1,
  "cc.ms.us": 1,
  "cc.mt.us": 1,
  "cc.nc.us": 1,
  "cc.nd.us": 1,
  "cc.ne.us": 1,
  "cc.nh.us": 1,
  "cc.nj.us": 1,
  "cc.nm.us": 1,
  "cc.nv.us": 1,
  "cc.ny.us": 1,
  "cc.oh.us": 1,
  "cc.ok.us": 1,
  "cc.or.us": 1,
  "cc.pa.us": 1,
  "cc.pr.us": 1,
  "cc.ri.us": 1,
  "cc.sc.us": 1,
  "cc.sd.us": 1,
  "cc.tn.us": 1,
  "cc.tx.us": 1,
  "cc.ut.us": 1,
  "cc.vi.us": 1,
  "cc.vt.us": 1,
  "cc.va.us": 1,
  "cc.wa.us": 1,
  "cc.wi.us": 1,
  "cc.wv.us": 1,
  "cc.wy.us": 1,
  "lib.ak.us": 1,
  "lib.al.us": 1,
  "lib.ar.us": 1,
  "lib.as.us": 1,
  "lib.az.us": 1,
  "lib.ca.us": 1,
  "lib.co.us": 1,
  "lib.ct.us": 1,
  "lib.dc.us": 1,
  "lib.fl.us": 1,
  "lib.ga.us": 1,
  "lib.gu.us": 1,
  "lib.hi.us": 1,
  "lib.ia.us": 1,
  "lib.id.us": 1,
  "lib.il.us": 1,
  "lib.in.us": 1,
  "lib.ks.us": 1,
  "lib.ky.us": 1,
  "lib.la.us": 1,
  "lib.ma.us": 1,
  "lib.md.us": 1,
  "lib.me.us": 1,
  "lib.mi.us": 1,
  "lib.mn.us": 1,
  "lib.mo.us": 1,
  "lib.ms.us": 1,
  "lib.mt.us": 1,
  "lib.nc.us": 1,
  "lib.nd.us": 1,
  "lib.ne.us": 1,
  "lib.nh.us": 1,
  "lib.nj.us": 1,
  "lib.nm.us": 1,
  "lib.nv.us": 1,
  "lib.ny.us": 1,
  "lib.oh.us": 1,
  "lib.ok.us": 1,
  "lib.or.us": 1,
  "lib.pa.us": 1,
  "lib.pr.us": 1,
  "lib.ri.us": 1,
  "lib.sc.us": 1,
  "lib.sd.us": 1,
  "lib.tn.us": 1,
  "lib.tx.us": 1,
  "lib.ut.us": 1,
  "lib.vi.us": 1,
  "lib.vt.us": 1,
  "lib.va.us": 1,
  "lib.wa.us": 1,
  "lib.wi.us": 1,
  "lib.wy.us": 1,
  "pvt.k12.ma.us": 1,
  "chtr.k12.ma.us": 1,
  "paroch.k12.ma.us": 1,
  "ann-arbor.mi.us": 1,
  "cog.mi.us": 1,
  "dst.mi.us": 1,
  "eaton.mi.us": 1,
  "gen.mi.us": 1,
  "mus.mi.us": 1,
  "tec.mi.us": 1,
  "washtenaw.mi.us": 1,
  "uy": 1,
  "com.uy": 1,
  "edu.uy": 1,
  "gub.uy": 1,
  "mil.uy": 1,
  "net.uy": 1,
  "org.uy": 1,
  "uz": 1,
  "co.uz": 1,
  "com.uz": 1,
  "net.uz": 1,
  "org.uz": 1,
  "va": 1,
  "vc": 1,
  "com.vc": 1,
  "net.vc": 1,
  "org.vc": 1,
  "gov.vc": 1,
  "mil.vc": 1,
  "edu.vc": 1,
  "ve": 1,
  "arts.ve": 1,
  "bib.ve": 1,
  "co.ve": 1,
  "com.ve": 1,
  "e12.ve": 1,
  "edu.ve": 1,
  "firm.ve": 1,
  "gob.ve": 1,
  "gov.ve": 1,
  "info.ve": 1,
  "int.ve": 1,
  "mil.ve": 1,
  "net.ve": 1,
  "nom.ve": 1,
  "org.ve": 1,
  "rar.ve": 1,
  "rec.ve": 1,
  "store.ve": 1,
  "tec.ve": 1,
  "web.ve": 1,
  "vg": 1,
  "vi": 1,
  "co.vi": 1,
  "com.vi": 1,
  "k12.vi": 1,
  "net.vi": 1,
  "org.vi": 1,
  "vn": 1,
  "ac.vn": 1,
  "ai.vn": 1,
  "biz.vn": 1,
  "com.vn": 1,
  "edu.vn": 1,
  "gov.vn": 1,
  "health.vn": 1,
  "id.vn": 1,
  "info.vn": 1,
  "int.vn": 1,
  "io.vn": 1,
  "name.vn": 1,
  "net.vn": 1,
  "org.vn": 1,
  "pro.vn": 1,
  "angiang.vn": 1,
  "bacgiang.vn": 1,
  "backan.vn": 1,
  "baclieu.vn": 1,
  "bacninh.vn": 1,
  "baria-vungtau.vn": 1,
  "bentre.vn": 1,
  "binhdinh.vn": 1,
  "binhduong.vn": 1,
  "binhphuoc.vn": 1,
  "binhthuan.vn": 1,
  "camau.vn": 1,
  "cantho.vn": 1,
  "caobang.vn": 1,
  "daklak.vn": 1,
  "daknong.vn": 1,
  "danang.vn": 1,
  "dienbien.vn": 1,
  "dongnai.vn": 1,
  "dongthap.vn": 1,
  "gialai.vn": 1,
  "hagiang.vn": 1,
  "haiduong.vn": 1,
  "haiphong.vn": 1,
  "hanam.vn": 1,
  "hanoi.vn": 1,
  "hatinh.vn": 1,
  "haugiang.vn": 1,
  "hoabinh.vn": 1,
  "hungyen.vn": 1,
  "khanhhoa.vn": 1,
  "kiengiang.vn": 1,
  "kontum.vn": 1,
  "laichau.vn": 1,
  "lamdong.vn": 1,
  "langson.vn": 1,
  "laocai.vn": 1,
  "longan.vn": 1,
  "namdinh.vn": 1,
  "nghean.vn": 1,
  "ninhbinh.vn": 1,
  "ninhthuan.vn": 1,
  "phutho.vn": 1,
  "phuyen.vn": 1,
  "quangbinh.vn": 1,
  "quangnam.vn": 1,
  "quangngai.vn": 1,
  "quangninh.vn": 1,
  "quangtri.vn": 1,
  "soctrang.vn": 1,
  "sonla.vn": 1,
  "tayninh.vn": 1,
  "thaibinh.vn": 1,
  "thainguyen.vn": 1,
  "thanhhoa.vn": 1,
  "thanhphohochiminh.vn": 1,
  "thuathienhue.vn": 1,
  "tiengiang.vn": 1,
  "travinh.vn": 1,
  "tuyenquang.vn": 1,
  "vinhlong.vn": 1,
  "vinhphuc.vn": 1,
  "yenbai.vn": 1,
  "vu": 1,
  "com.vu": 1,
  "edu.vu": 1,
  "net.vu": 1,
  "org.vu": 1,
  "wf": 1,
  "ws": 1,
  "com.ws": 1,
  "net.ws": 1,
  "org.ws": 1,
  "gov.ws": 1,
  "edu.ws": 1,
  "yt": 1,
  "xn--mgbaam7a8h": 1,
  "xn--y9a3aq": 1,
  "xn--54b7fta0cc": 1,
  "xn--90ae": 1,
  "xn--mgbcpq6gpa1a": 1,
  "xn--90ais": 1,
  "xn--fiqs8s": 1,
  "xn--fiqz9s": 1,
  "xn--lgbbat1ad8j": 1,
  "xn--wgbh1c": 1,
  "xn--e1a4c": 1,
  "xn--qxa6a": 1,
  "xn--mgbah1a3hjkrd": 1,
  "xn--node": 1,
  "xn--qxam": 1,
  "xn--j6w193g": 1,
  "xn--55qx5d.xn--j6w193g": 1,
  "xn--wcvs22d.xn--j6w193g": 1,
  "xn--mxtq1m.xn--j6w193g": 1,
  "xn--gmqw5a.xn--j6w193g": 1,
  "xn--od0alg.xn--j6w193g": 1,
  "xn--uc0atv.xn--j6w193g": 1,
  "xn--2scrj9c": 1,
  "xn--3hcrj9c": 1,
  "xn--45br5cyl": 1,
  "xn--h2breg3eve": 1,
  "xn--h2brj9c8c": 1,
  "xn--mgbgu82a": 1,
  "xn--rvc1e0am3e": 1,
  "xn--h2brj9c": 1,
  "xn--mgbbh1a": 1,
  "xn--mgbbh1a71e": 1,
  "xn--fpcrj9c3d": 1,
  "xn--gecrj9c": 1,
  "xn--s9brj9c": 1,
  "xn--45brj9c": 1,
  "xn--xkc2dl3a5ee0h": 1,
  "xn--mgba3a4f16a": 1,
  "xn--mgba3a4fra": 1,
  "xn--mgbtx2b": 1,
  "xn--mgbayh7gpa": 1,
  "xn--3e0b707e": 1,
  "xn--80ao21a": 1,
  "xn--q7ce6a": 1,
  "xn--fzc2c9e2c": 1,
  "xn--xkc2al3hye2a": 1,
  "xn--mgbc0a9azcg": 1,
  "xn--d1alf": 1,
  "xn--l1acc": 1,
  "xn--mix891f": 1,
  "xn--mix082f": 1,
  "xn--mgbx4cd0ab": 1,
  "xn--mgb9awbf": 1,
  "xn--mgbai9azgqp6j": 1,
  "xn--mgbai9a5eva00b": 1,
  "xn--ygbi2ammx": 1,
  "xn--90a3ac": 1,
  "xn--o1ac.xn--90a3ac": 1,
  "xn--c1avg.xn--90a3ac": 1,
  "xn--90azh.xn--90a3ac": 1,
  "xn--d1at.xn--90a3ac": 1,
  "xn--o1ach.xn--90a3ac": 1,
  "xn--80au.xn--90a3ac": 1,
  "xn--p1ai": 1,
  "xn--wgbl6a": 1,
  "xn--mgberp4a5d4ar": 1,
  "xn--mgberp4a5d4a87g": 1,
  "xn--mgbqly7c0a67fbc": 1,
  "xn--mgbqly7cvafr": 1,
  "xn--mgbpl2fh": 1,
  "xn--yfro4i67o": 1,
  "xn--clchc0ea0b2g2a9gcd": 1,
  "xn--ogbpf8fl": 1,
  "xn--mgbtf8fl": 1,
  "xn--o3cw4h": 1,
  "xn--12c1fe0br.xn--o3cw4h": 1,
  "xn--12co0c3b4eva.xn--o3cw4h": 1,
  "xn--h3cuzk1di.xn--o3cw4h": 1,
  "xn--o3cyx2a.xn--o3cw4h": 1,
  "xn--m3ch0j3a.xn--o3cw4h": 1,
  "xn--12cfi8ixb8l.xn--o3cw4h": 1,
  "xn--pgbs0dh": 1,
  "xn--kpry57d": 1,
  "xn--kprw13d": 1,
  "xn--nnx388a": 1,
  "xn--j1amh": 1,
  "xn--mgb2ddes": 1,
  "xxx": 1,
  "ye": 1,
  "com.ye": 1,
  "edu.ye": 1,
  "gov.ye": 1,
  "net.ye": 1,
  "mil.ye": 1,
  "org.ye": 1,
  "ac.za": 1,
  "agric.za": 1,
  "alt.za": 1,
  "co.za": 1,
  "edu.za": 1,
  "gov.za": 1,
  "grondar.za": 1,
  "law.za": 1,
  "mil.za": 1,
  "net.za": 1,
  "ngo.za": 1,
  "nic.za": 1,
  "nis.za": 1,
  "nom.za": 1,
  "org.za": 1,
  "school.za": 1,
  "tm.za": 1,
  "web.za": 1,
  "zm": 1,
  "ac.zm": 1,
  "biz.zm": 1,
  "co.zm": 1,
  "com.zm": 1,
  "edu.zm": 1,
  "gov.zm": 1,
  "info.zm": 1,
  "mil.zm": 1,
  "net.zm": 1,
  "org.zm": 1,
  "sch.zm": 1,
  "zw": 1,
  "ac.zw": 1,
  "co.zw": 1,
  "gov.zw": 1,
  "mil.zw": 1,
  "org.zw": 1,
  "aaa": 1,
  "aarp": 1,
  "abb": 1,
  "abbott": 1,
  "abbvie": 1,
  "abc": 1,
  "able": 1,
  "abogado": 1,
  "abudhabi": 1,
  "academy": 1,
  "accenture": 1,
  "accountant": 1,
  "accountants": 1,
  "aco": 1,
  "actor": 1,
  "ads": 1,
  "adult": 1,
  "aeg": 1,
  "aetna": 1,
  "afl": 1,
  "africa": 1,
  "agakhan": 1,
  "agency": 1,
  "aig": 1,
  "airbus": 1,
  "airforce": 1,
  "airtel": 1,
  "akdn": 1,
  "alibaba": 1,
  "alipay": 1,
  "allfinanz": 1,
  "allstate": 1,
  "ally": 1,
  "alsace": 1,
  "alstom": 1,
  "amazon": 1,
  "americanexpress": 1,
  "americanfamily": 1,
  "amex": 1,
  "amfam": 1,
  "amica": 1,
  "amsterdam": 1,
  "analytics": 1,
  "android": 1,
  "anquan": 1,
  "anz": 1,
  "aol": 1,
  "apartments": 1,
  "app": 1,
  "apple": 1,
  "aquarelle": 1,
  "arab": 1,
  "aramco": 1,
  "archi": 1,
  "army": 1,
  "art": 1,
  "arte": 1,
  "asda": 1,
  "associates": 1,
  "athleta": 1,
  "attorney": 1,
  "auction": 1,
  "audi": 1,
  "audible": 1,
  "audio": 1,
  "auspost": 1,
  "author": 1,
  "auto": 1,
  "autos": 1,
  "avianca": 1,
  "aws": 1,
  "axa": 1,
  "azure": 1,
  "baby": 1,
  "baidu": 1,
  "banamex": 1,
  "bananarepublic": 1,
  "band": 1,
  "bank": 1,
  "bar": 1,
  "barcelona": 1,
  "barclaycard": 1,
  "barclays": 1,
  "barefoot": 1,
  "bargains": 1,
  "baseball": 1,
  "basketball": 1,
  "bauhaus": 1,
  "bayern": 1,
  "bbc": 1,
  "bbt": 1,
  "bbva": 1,
  "bcg": 1,
  "bcn": 1,
  "beats": 1,
  "beauty": 1,
  "beer": 1,
  "bentley": 1,
  "berlin": 1,
  "best": 1,
  "bestbuy": 1,
  "bet": 1,
  "bharti": 1,
  "bible": 1,
  "bid": 1,
  "bike": 1,
  "bing": 1,
  "bingo": 1,
  "bio": 1,
  "black": 1,
  "blackfriday": 1,
  "blockbuster": 1,
  "blog": 1,
  "bloomberg": 1,
  "blue": 1,
  "bms": 1,
  "bmw": 1,
  "bnpparibas": 1,
  "boats": 1,
  "boehringer": 1,
  "bofa": 1,
  "bom": 1,
  "bond": 1,
  "boo": 1,
  "book": 1,
  "booking": 1,
  "bosch": 1,
  "bostik": 1,
  "boston": 1,
  "bot": 1,
  "boutique": 1,
  "box": 1,
  "bradesco": 1,
  "bridgestone": 1,
  "broadway": 1,
  "broker": 1,
  "brother": 1,
  "brussels": 1,
  "build": 1,
  "builders": 1,
  "business": 1,
  "buy": 1,
  "buzz": 1,
  "bzh": 1,
  "cab": 1,
  "cafe": 1,
  "cal": 1,
  "call": 1,
  "calvinklein": 1,
  "cam": 1,
  "camera": 1,
  "camp": 1,
  "canon": 1,
  "capetown": 1,
  "capital": 1,
  "capitalone": 1,
  "car": 1,
  "caravan": 1,
  "cards": 1,
  "care": 1,
  "career": 1,
  "careers": 1,
  "cars": 1,
  "casa": 1,
  "case": 1,
  "cash": 1,
  "casino": 1,
  "catering": 1,
  "catholic": 1,
  "cba": 1,
  "cbn": 1,
  "cbre": 1,
  "center": 1,
  "ceo": 1,
  "cern": 1,
  "cfa": 1,
  "cfd": 1,
  "chanel": 1,
  "channel": 1,
  "charity": 1,
  "chase": 1,
  "chat": 1,
  "cheap": 1,
  "chintai": 1,
  "christmas": 1,
  "chrome": 1,
  "church": 1,
  "cipriani": 1,
  "circle": 1,
  "cisco": 1,
  "citadel": 1,
  "citi": 1,
  "citic": 1,
  "city": 1,
  "claims": 1,
  "cleaning": 1,
  "click": 1,
  "clinic": 1,
  "clinique": 1,
  "clothing": 1,
  "cloud": 1,
  "club": 1,
  "clubmed": 1,
  "coach": 1,
  "codes": 1,
  "coffee": 1,
  "college": 1,
  "cologne": 1,
  "comcast": 1,
  "commbank": 1,
  "community": 1,
  "company": 1,
  "compare": 1,
  "computer": 1,
  "comsec": 1,
  "condos": 1,
  "construction": 1,
  "consulting": 1,
  "contact": 1,
  "contractors": 1,
  "cooking": 1,
  "cool": 1,
  "corsica": 1,
  "country": 1,
  "coupon": 1,
  "coupons": 1,
  "courses": 1,
  "cpa": 1,
  "credit": 1,
  "creditcard": 1,
  "creditunion": 1,
  "cricket": 1,
  "crown": 1,
  "crs": 1,
  "cruise": 1,
  "cruises": 1,
  "cuisinella": 1,
  "cymru": 1,
  "cyou": 1,
  "dabur": 1,
  "dad": 1,
  "dance": 1,
  "data": 1,
  "date": 1,
  "dating": 1,
  "datsun": 1,
  "day": 1,
  "dclk": 1,
  "dds": 1,
  "deal": 1,
  "dealer": 1,
  "deals": 1,
  "degree": 1,
  "delivery": 1,
  "dell": 1,
  "deloitte": 1,
  "delta": 1,
  "democrat": 1,
  "dental": 1,
  "dentist": 1,
  "desi": 1,
  "design": 1,
  "dev": 1,
  "dhl": 1,
  "diamonds": 1,
  "diet": 1,
  "digital": 1,
  "direct": 1,
  "directory": 1,
  "discount": 1,
  "discover": 1,
  "dish": 1,
  "diy": 1,
  "dnp": 1,
  "docs": 1,
  "doctor": 1,
  "dog": 1,
  "domains": 1,
  "dot": 1,
  "download": 1,
  "drive": 1,
  "dtv": 1,
  "dubai": 1,
  "dunlop": 1,
  "dupont": 1,
  "durban": 1,
  "dvag": 1,
  "dvr": 1,
  "earth": 1,
  "eat": 1,
  "eco": 1,
  "edeka": 1,
  "education": 1,
  "email": 1,
  "emerck": 1,
  "energy": 1,
  "engineer": 1,
  "engineering": 1,
  "enterprises": 1,
  "epson": 1,
  "equipment": 1,
  "ericsson": 1,
  "erni": 1,
  "esq": 1,
  "estate": 1,
  "eurovision": 1,
  "eus": 1,
  "events": 1,
  "exchange": 1,
  "expert": 1,
  "exposed": 1,
  "express": 1,
  "extraspace": 1,
  "fage": 1,
  "fail": 1,
  "fairwinds": 1,
  "faith": 1,
  "family": 1,
  "fan": 1,
  "fans": 1,
  "farm": 1,
  "farmers": 1,
  "fashion": 1,
  "fast": 1,
  "fedex": 1,
  "feedback": 1,
  "ferrari": 1,
  "ferrero": 1,
  "fidelity": 1,
  "fido": 1,
  "film": 1,
  "final": 1,
  "finance": 1,
  "financial": 1,
  "fire": 1,
  "firestone": 1,
  "firmdale": 1,
  "fish": 1,
  "fishing": 1,
  "fit": 1,
  "fitness": 1,
  "flickr": 1,
  "flights": 1,
  "flir": 1,
  "florist": 1,
  "flowers": 1,
  "fly": 1,
  "foo": 1,
  "food": 1,
  "football": 1,
  "ford": 1,
  "forex": 1,
  "forsale": 1,
  "forum": 1,
  "foundation": 1,
  "fox": 1,
  "free": 1,
  "fresenius": 1,
  "frl": 1,
  "frogans": 1,
  "frontier": 1,
  "ftr": 1,
  "fujitsu": 1,
  "fun": 1,
  "fund": 1,
  "furniture": 1,
  "futbol": 1,
  "fyi": 1,
  "gal": 1,
  "gallery": 1,
  "gallo": 1,
  "gallup": 1,
  "game": 1,
  "games": 1,
  "gap": 1,
  "garden": 1,
  "gay": 1,
  "gbiz": 1,
  "gdn": 1,
  "gea": 1,
  "gent": 1,
  "genting": 1,
  "george": 1,
  "ggee": 1,
  "gift": 1,
  "gifts": 1,
  "gives": 1,
  "giving": 1,
  "glass": 1,
  "gle": 1,
  "global": 1,
  "globo": 1,
  "gmail": 1,
  "gmbh": 1,
  "gmo": 1,
  "gmx": 1,
  "godaddy": 1,
  "gold": 1,
  "goldpoint": 1,
  "golf": 1,
  "goo": 1,
  "goodyear": 1,
  "goog": 1,
  "google": 1,
  "gop": 1,
  "got": 1,
  "grainger": 1,
  "graphics": 1,
  "gratis": 1,
  "green": 1,
  "gripe": 1,
  "grocery": 1,
  "group": 1,
  "guardian": 1,
  "gucci": 1,
  "guge": 1,
  "guide": 1,
  "guitars": 1,
  "guru": 1,
  "hair": 1,
  "hamburg": 1,
  "hangout": 1,
  "haus": 1,
  "hbo": 1,
  "hdfc": 1,
  "hdfcbank": 1,
  "health": 1,
  "healthcare": 1,
  "help": 1,
  "helsinki": 1,
  "here": 1,
  "hermes": 1,
  "hiphop": 1,
  "hisamitsu": 1,
  "hitachi": 1,
  "hiv": 1,
  "hkt": 1,
  "hockey": 1,
  "holdings": 1,
  "holiday": 1,
  "homedepot": 1,
  "homegoods": 1,
  "homes": 1,
  "homesense": 1,
  "honda": 1,
  "horse": 1,
  "hospital": 1,
  "host": 1,
  "hosting": 1,
  "hot": 1,
  "hotels": 1,
  "hotmail": 1,
  "house": 1,
  "how": 1,
  "hsbc": 1,
  "hughes": 1,
  "hyatt": 1,
  "hyundai": 1,
  "ibm": 1,
  "icbc": 1,
  "ice": 1,
  "icu": 1,
  "ieee": 1,
  "ifm": 1,
  "ikano": 1,
  "imamat": 1,
  "imdb": 1,
  "immo": 1,
  "immobilien": 1,
  "inc": 1,
  "industries": 1,
  "infiniti": 1,
  "ing": 1,
  "ink": 1,
  "institute": 1,
  "insurance": 1,
  "insure": 1,
  "international": 1,
  "intuit": 1,
  "investments": 1,
  "ipiranga": 1,
  "irish": 1,
  "ismaili": 1,
  "ist": 1,
  "istanbul": 1,
  "itau": 1,
  "itv": 1,
  "jaguar": 1,
  "java": 1,
  "jcb": 1,
  "jeep": 1,
  "jetzt": 1,
  "jewelry": 1,
  "jio": 1,
  "jll": 1,
  "jmp": 1,
  "jnj": 1,
  "joburg": 1,
  "jot": 1,
  "joy": 1,
  "jpmorgan": 1,
  "jprs": 1,
  "juegos": 1,
  "juniper": 1,
  "kaufen": 1,
  "kddi": 1,
  "kerryhotels": 1,
  "kerrylogistics": 1,
  "kerryproperties": 1,
  "kfh": 1,
  "kia": 1,
  "kids": 1,
  "kim": 1,
  "kindle": 1,
  "kitchen": 1,
  "kiwi": 1,
  "koeln": 1,
  "komatsu": 1,
  "kosher": 1,
  "kpmg": 1,
  "kpn": 1,
  "krd": 1,
  "kred": 1,
  "kuokgroup": 1,
  "kyoto": 1,
  "lacaixa": 1,
  "lamborghini": 1,
  "lamer": 1,
  "lancaster": 1,
  "land": 1,
  "landrover": 1,
  "lanxess": 1,
  "lasalle": 1,
  "lat": 1,
  "latino": 1,
  "latrobe": 1,
  "law": 1,
  "lawyer": 1,
  "lds": 1,
  "lease": 1,
  "leclerc": 1,
  "lefrak": 1,
  "legal": 1,
  "lego": 1,
  "lexus": 1,
  "lgbt": 1,
  "lidl": 1,
  "life": 1,
  "lifeinsurance": 1,
  "lifestyle": 1,
  "lighting": 1,
  "like": 1,
  "lilly": 1,
  "limited": 1,
  "limo": 1,
  "lincoln": 1,
  "link": 1,
  "lipsy": 1,
  "live": 1,
  "living": 1,
  "llc": 1,
  "llp": 1,
  "loan": 1,
  "loans": 1,
  "locker": 1,
  "locus": 1,
  "lol": 1,
  "london": 1,
  "lotte": 1,
  "lotto": 1,
  "love": 1,
  "lpl": 1,
  "lplfinancial": 1,
  "ltd": 1,
  "ltda": 1,
  "lundbeck": 1,
  "luxe": 1,
  "luxury": 1,
  "madrid": 1,
  "maif": 1,
  "maison": 1,
  "makeup": 1,
  "man": 1,
  "management": 1,
  "mango": 1,
  "map": 1,
  "market": 1,
  "marketing": 1,
  "markets": 1,
  "marriott": 1,
  "marshalls": 1,
  "mattel": 1,
  "mba": 1,
  "mckinsey": 1,
  "med": 1,
  "media": 1,
  "meet": 1,
  "melbourne": 1,
  "meme": 1,
  "memorial": 1,
  "men": 1,
  "menu": 1,
  "merckmsd": 1,
  "miami": 1,
  "microsoft": 1,
  "mini": 1,
  "mint": 1,
  "mit": 1,
  "mitsubishi": 1,
  "mlb": 1,
  "mls": 1,
  "mma": 1,
  "mobile": 1,
  "moda": 1,
  "moe": 1,
  "moi": 1,
  "mom": 1,
  "monash": 1,
  "money": 1,
  "monster": 1,
  "mormon": 1,
  "mortgage": 1,
  "moscow": 1,
  "moto": 1,
  "motorcycles": 1,
  "mov": 1,
  "movie": 1,
  "msd": 1,
  "mtn": 1,
  "mtr": 1,
  "music": 1,
  "nab": 1,
  "nagoya": 1,
  "natura": 1,
  "navy": 1,
  "nba": 1,
  "nec": 1,
  "netbank": 1,
  "netflix": 1,
  "network": 1,
  "neustar": 1,
  "new": 1,
  "news": 1,
  "next": 1,
  "nextdirect": 1,
  "nexus": 1,
  "nfl": 1,
  "ngo": 1,
  "nhk": 1,
  "nico": 1,
  "nike": 1,
  "nikon": 1,
  "ninja": 1,
  "nissan": 1,
  "nissay": 1,
  "nokia": 1,
  "norton": 1,
  "now": 1,
  "nowruz": 1,
  "nowtv": 1,
  "nra": 1,
  "nrw": 1,
  "ntt": 1,
  "nyc": 1,
  "obi": 1,
  "observer": 1,
  "office": 1,
  "okinawa": 1,
  "olayan": 1,
  "olayangroup": 1,
  "oldnavy": 1,
  "ollo": 1,
  "omega": 1,
  "one": 1,
  "ong": 1,
  "onl": 1,
  "online": 1,
  "ooo": 1,
  "open": 1,
  "oracle": 1,
  "orange": 1,
  "organic": 1,
  "origins": 1,
  "osaka": 1,
  "otsuka": 1,
  "ott": 1,
  "ovh": 1,
  "page": 1,
  "panasonic": 1,
  "paris": 1,
  "pars": 1,
  "partners": 1,
  "parts": 1,
  "party": 1,
  "pay": 1,
  "pccw": 1,
  "pet": 1,
  "pfizer": 1,
  "pharmacy": 1,
  "phd": 1,
  "philips": 1,
  "phone": 1,
  "photo": 1,
  "photography": 1,
  "photos": 1,
  "physio": 1,
  "pics": 1,
  "pictet": 1,
  "pictures": 1,
  "pid": 1,
  "pin": 1,
  "ping": 1,
  "pink": 1,
  "pioneer": 1,
  "pizza": 1,
  "place": 1,
  "play": 1,
  "playstation": 1,
  "plumbing": 1,
  "plus": 1,
  "pnc": 1,
  "pohl": 1,
  "poker": 1,
  "politie": 1,
  "porn": 1,
  "pramerica": 1,
  "praxi": 1,
  "press": 1,
  "prime": 1,
  "prod": 1,
  "productions": 1,
  "prof": 1,
  "progressive": 1,
  "promo": 1,
  "properties": 1,
  "property": 1,
  "protection": 1,
  "pru": 1,
  "prudential": 1,
  "pub": 1,
  "pwc": 1,
  "qpon": 1,
  "quebec": 1,
  "quest": 1,
  "racing": 1,
  "radio": 1,
  "read": 1,
  "realestate": 1,
  "realtor": 1,
  "realty": 1,
  "recipes": 1,
  "red": 1,
  "redstone": 1,
  "redumbrella": 1,
  "rehab": 1,
  "reise": 1,
  "reisen": 1,
  "reit": 1,
  "reliance": 1,
  "ren": 1,
  "rent": 1,
  "rentals": 1,
  "repair": 1,
  "report": 1,
  "republican": 1,
  "rest": 1,
  "restaurant": 1,
  "review": 1,
  "reviews": 1,
  "rexroth": 1,
  "rich": 1,
  "richardli": 1,
  "ricoh": 1,
  "ril": 1,
  "rio": 1,
  "rip": 1,
  "rocks": 1,
  "rodeo": 1,
  "rogers": 1,
  "room": 1,
  "rsvp": 1,
  "rugby": 1,
  "ruhr": 1,
  "run": 1,
  "rwe": 1,
  "ryukyu": 1,
  "saarland": 1,
  "safe": 1,
  "safety": 1,
  "sakura": 1,
  "sale": 1,
  "salon": 1,
  "samsclub": 1,
  "samsung": 1,
  "sandvik": 1,
  "sandvikcoromant": 1,
  "sanofi": 1,
  "sap": 1,
  "sarl": 1,
  "sas": 1,
  "save": 1,
  "saxo": 1,
  "sbi": 1,
  "sbs": 1,
  "sca": 1,
  "scb": 1,
  "schaeffler": 1,
  "schmidt": 1,
  "scholarships": 1,
  "school": 1,
  "schule": 1,
  "schwarz": 1,
  "science": 1,
  "scot": 1,
  "search": 1,
  "seat": 1,
  "secure": 1,
  "security": 1,
  "seek": 1,
  "select": 1,
  "sener": 1,
  "services": 1,
  "seven": 1,
  "sew": 1,
  "sex": 1,
  "sexy": 1,
  "sfr": 1,
  "shangrila": 1,
  "sharp": 1,
  "shaw": 1,
  "shell": 1,
  "shia": 1,
  "shiksha": 1,
  "shoes": 1,
  "shop": 1,
  "shopping": 1,
  "shouji": 1,
  "show": 1,
  "silk": 1,
  "sina": 1,
  "singles": 1,
  "site": 1,
  "ski": 1,
  "skin": 1,
  "sky": 1,
  "skype": 1,
  "sling": 1,
  "smart": 1,
  "smile": 1,
  "sncf": 1,
  "soccer": 1,
  "social": 1,
  "softbank": 1,
  "software": 1,
  "sohu": 1,
  "solar": 1,
  "solutions": 1,
  "song": 1,
  "sony": 1,
  "soy": 1,
  "spa": 1,
  "space": 1,
  "sport": 1,
  "spot": 1,
  "srl": 1,
  "stada": 1,
  "staples": 1,
  "star": 1,
  "statebank": 1,
  "statefarm": 1,
  "stc": 1,
  "stcgroup": 1,
  "stockholm": 1,
  "storage": 1,
  "store": 1,
  "stream": 1,
  "studio": 1,
  "study": 1,
  "style": 1,
  "sucks": 1,
  "supplies": 1,
  "supply": 1,
  "support": 1,
  "surf": 1,
  "surgery": 1,
  "suzuki": 1,
  "swatch": 1,
  "swiss": 1,
  "sydney": 1,
  "systems": 1,
  "tab": 1,
  "taipei": 1,
  "talk": 1,
  "taobao": 1,
  "target": 1,
  "tatamotors": 1,
  "tatar": 1,
  "tattoo": 1,
  "tax": 1,
  "taxi": 1,
  "tci": 1,
  "tdk": 1,
  "team": 1,
  "tech": 1,
  "technology": 1,
  "temasek": 1,
  "tennis": 1,
  "teva": 1,
  "thd": 1,
  "theater": 1,
  "theatre": 1,
  "tiaa": 1,
  "tickets": 1,
  "tienda": 1,
  "tips": 1,
  "tires": 1,
  "tirol": 1,
  "tjmaxx": 1,
  "tjx": 1,
  "tkmaxx": 1,
  "tmall": 1,
  "today": 1,
  "tokyo": 1,
  "tools": 1,
  "top": 1,
  "toray": 1,
  "toshiba": 1,
  "total": 1,
  "tours": 1,
  "town": 1,
  "toyota": 1,
  "toys": 1,
  "trade": 1,
  "trading": 1,
  "training": 1,
  "travel": 1,
  "travelers": 1,
  "travelersinsurance": 1,
  "trust": 1,
  "trv": 1,
  "tube": 1,
  "tui": 1,
  "tunes": 1,
  "tushu": 1,
  "tvs": 1,
  "ubank": 1,
  "ubs": 1,
  "unicom": 1,
  "university": 1,
  "uno": 1,
  "uol": 1,
  "ups": 1,
  "vacations": 1,
  "vana": 1,
  "vanguard": 1,
  "vegas": 1,
  "ventures": 1,
  "verisign": 1,
  "versicherung": 1,
  "vet": 1,
  "viajes": 1,
  "video": 1,
  "vig": 1,
  "viking": 1,
  "villas": 1,
  "vin": 1,
  "vip": 1,
  "virgin": 1,
  "visa": 1,
  "vision": 1,
  "viva": 1,
  "vivo": 1,
  "vlaanderen": 1,
  "vodka": 1,
  "volvo": 1,
  "vote": 1,
  "voting": 1,
  "voto": 1,
  "voyage": 1,
  "wales": 1,
  "walmart": 1,
  "walter": 1,
  "wang": 1,
  "wanggou": 1,
  "watch": 1,
  "watches": 1,
  "weather": 1,
  "weatherchannel": 1,
  "webcam": 1,
  "weber": 1,
  "website": 1,
  "wed": 1,
  "wedding": 1,
  "weibo": 1,
  "weir": 1,
  "whoswho": 1,
  "wien": 1,
  "wiki": 1,
  "williamhill": 1,
  "win": 1,
  "windows": 1,
  "wine": 1,
  "winners": 1,
  "wme": 1,
  "wolterskluwer": 1,
  "woodside": 1,
  "work": 1,
  "works": 1,
  "world": 1,
  "wow": 1,
  "wtc": 1,
  "wtf": 1,
  "xbox": 1,
  "xerox": 1,
  "xfinity": 1,
  "xihuan": 1,
  "xin": 1,
  "xn--11b4c3d": 1,
  "xn--1ck2e1b": 1,
  "xn--1qqw23a": 1,
  "xn--30rr7y": 1,
  "xn--3bst00m": 1,
  "xn--3ds443g": 1,
  "xn--3pxu8k": 1,
  "xn--42c2d9a": 1,
  "xn--45q11c": 1,
  "xn--4gbrim": 1,
  "xn--55qw42g": 1,
  "xn--55qx5d": 1,
  "xn--5su34j936bgsg": 1,
  "xn--5tzm5g": 1,
  "xn--6frz82g": 1,
  "xn--6qq986b3xl": 1,
  "xn--80adxhks": 1,
  "xn--80aqecdr1a": 1,
  "xn--80asehdb": 1,
  "xn--80aswg": 1,
  "xn--8y0a063a": 1,
  "xn--9dbq2a": 1,
  "xn--9et52u": 1,
  "xn--9krt00a": 1,
  "xn--b4w605ferd": 1,
  "xn--bck1b9a5dre4c": 1,
  "xn--c1avg": 1,
  "xn--c2br7g": 1,
  "xn--cck2b3b": 1,
  "xn--cckwcxetd": 1,
  "xn--cg4bki": 1,
  "xn--czr694b": 1,
  "xn--czrs0t": 1,
  "xn--czru2d": 1,
  "xn--d1acj3b": 1,
  "xn--eckvdtc9d": 1,
  "xn--efvy88h": 1,
  "xn--fct429k": 1,
  "xn--fhbei": 1,
  "xn--fiq228c5hs": 1,
  "xn--fiq64b": 1,
  "xn--fjq720a": 1,
  "xn--flw351e": 1,
  "xn--fzys8d69uvgm": 1,
  "xn--g2xx48c": 1,
  "xn--gckr3f0f": 1,
  "xn--gk3at1e": 1,
  "xn--hxt814e": 1,
  "xn--i1b6b1a6a2e": 1,
  "xn--imr513n": 1,
  "xn--io0a7i": 1,
  "xn--j1aef": 1,
  "xn--jlq480n2rg": 1,
  "xn--jvr189m": 1,
  "xn--kcrx77d1x4a": 1,
  "xn--kput3i": 1,
  "xn--mgba3a3ejt": 1,
  "xn--mgba7c0bbn0a": 1,
  "xn--mgbab2bd": 1,
  "xn--mgbca7dzdo": 1,
  "xn--mgbi4ecexp": 1,
  "xn--mgbt3dhd": 1,
  "xn--mk1bu44c": 1,
  "xn--mxtq1m": 1,
  "xn--ngbc5azd": 1,
  "xn--ngbe9e0a": 1,
  "xn--ngbrx": 1,
  "xn--nqv7f": 1,
  "xn--nqv7fs00ema": 1,
  "xn--nyqy26a": 1,
  "xn--otu796d": 1,
  "xn--p1acf": 1,
  "xn--pssy2u": 1,
  "xn--q9jyb4c": 1,
  "xn--qcka1pmc": 1,
  "xn--rhqv96g": 1,
  "xn--rovu88b": 1,
  "xn--ses554g": 1,
  "xn--t60b56a": 1,
  "xn--tckwe": 1,
  "xn--tiq49xqyj": 1,
  "xn--unup4y": 1,
  "xn--vermgensberater-ctb": 1,
  "xn--vermgensberatung-pwb": 1,
  "xn--vhquv": 1,
  "xn--vuq861b": 1,
  "xn--w4r85el8fhu5dnra": 1,
  "xn--w4rs40l": 1,
  "xn--xhq521b": 1,
  "xn--zfr164b": 1,
  "xyz": 1,
  "yachts": 1,
  "yahoo": 1,
  "yamaxun": 1,
  "yandex": 1,
  "yodobashi": 1,
  "yoga": 1,
  "yokohama": 1,
  "you": 1,
  "youtube": 1,
  "yun": 1,
  "zappos": 1,
  "zara": 1,
  "zero": 1,
  "zip": 1,
  "zone": 1,
  "zuerich": 1
}

/***/ }),

/***/ "./core/data/nonIcannPublicSuffixList.js":
/*!***********************************************!*\
  !*** ./core/data/nonIcannPublicSuffixList.js ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports) => {

exports.nonIcannPublicSuffixes = {
  "cc.ua": 1,
  "inf.ua": 1,
  "ltd.ua": 1,
  "611.to": 1,
  "graphox.us": 1,
  "devcdnaccesso.com": 2,
  "on-acorn.io": 2,
  "activetrail.biz": 1,
  "adobeaemcloud.com": 1,
  "dev.adobeaemcloud.com": 2,
  "hlx.live": 1,
  "adobeaemcloud.net": 1,
  "hlx.page": 1,
  "hlx3.page": 1,
  "adobeio-static.net": 1,
  "adobeioruntime.net": 1,
  "beep.pl": 1,
  "airkitapps.com": 1,
  "airkitapps-au.com": 1,
  "airkitapps.eu": 1,
  "aivencloud.com": 1,
  "akadns.net": 1,
  "akamai.net": 1,
  "akamai-staging.net": 1,
  "akamaiedge.net": 1,
  "akamaiedge-staging.net": 1,
  "akamaihd.net": 1,
  "akamaihd-staging.net": 1,
  "akamaiorigin.net": 1,
  "akamaiorigin-staging.net": 1,
  "akamaized.net": 1,
  "akamaized-staging.net": 1,
  "edgekey.net": 1,
  "edgekey-staging.net": 1,
  "edgesuite.net": 1,
  "edgesuite-staging.net": 1,
  "barsy.ca": 1,
  "compute.estate": 2,
  "alces.network": 2,
  "kasserver.com": 1,
  "altervista.org": 1,
  "alwaysdata.net": 1,
  "myamaze.net": 1,
  "execute-api.cn-north-1.amazonaws.com.cn": 1,
  "execute-api.cn-northwest-1.amazonaws.com.cn": 1,
  "execute-api.af-south-1.amazonaws.com": 1,
  "execute-api.ap-east-1.amazonaws.com": 1,
  "execute-api.ap-northeast-1.amazonaws.com": 1,
  "execute-api.ap-northeast-2.amazonaws.com": 1,
  "execute-api.ap-northeast-3.amazonaws.com": 1,
  "execute-api.ap-south-1.amazonaws.com": 1,
  "execute-api.ap-south-2.amazonaws.com": 1,
  "execute-api.ap-southeast-1.amazonaws.com": 1,
  "execute-api.ap-southeast-2.amazonaws.com": 1,
  "execute-api.ap-southeast-3.amazonaws.com": 1,
  "execute-api.ap-southeast-4.amazonaws.com": 1,
  "execute-api.ca-central-1.amazonaws.com": 1,
  "execute-api.eu-central-1.amazonaws.com": 1,
  "execute-api.eu-central-2.amazonaws.com": 1,
  "execute-api.eu-north-1.amazonaws.com": 1,
  "execute-api.eu-south-1.amazonaws.com": 1,
  "execute-api.eu-south-2.amazonaws.com": 1,
  "execute-api.eu-west-1.amazonaws.com": 1,
  "execute-api.eu-west-2.amazonaws.com": 1,
  "execute-api.eu-west-3.amazonaws.com": 1,
  "execute-api.il-central-1.amazonaws.com": 1,
  "execute-api.me-central-1.amazonaws.com": 1,
  "execute-api.me-south-1.amazonaws.com": 1,
  "execute-api.sa-east-1.amazonaws.com": 1,
  "execute-api.us-east-1.amazonaws.com": 1,
  "execute-api.us-east-2.amazonaws.com": 1,
  "execute-api.us-gov-east-1.amazonaws.com": 1,
  "execute-api.us-gov-west-1.amazonaws.com": 1,
  "execute-api.us-west-1.amazonaws.com": 1,
  "execute-api.us-west-2.amazonaws.com": 1,
  "cloudfront.net": 1,
  "auth.af-south-1.amazoncognito.com": 1,
  "auth.ap-northeast-1.amazoncognito.com": 1,
  "auth.ap-northeast-2.amazoncognito.com": 1,
  "auth.ap-northeast-3.amazoncognito.com": 1,
  "auth.ap-south-1.amazoncognito.com": 1,
  "auth.ap-southeast-1.amazoncognito.com": 1,
  "auth.ap-southeast-2.amazoncognito.com": 1,
  "auth.ap-southeast-3.amazoncognito.com": 1,
  "auth.ca-central-1.amazoncognito.com": 1,
  "auth.eu-central-1.amazoncognito.com": 1,
  "auth.eu-north-1.amazoncognito.com": 1,
  "auth.eu-south-1.amazoncognito.com": 1,
  "auth.eu-west-1.amazoncognito.com": 1,
  "auth.eu-west-2.amazoncognito.com": 1,
  "auth.eu-west-3.amazoncognito.com": 1,
  "auth.il-central-1.amazoncognito.com": 1,
  "auth.me-south-1.amazoncognito.com": 1,
  "auth.sa-east-1.amazoncognito.com": 1,
  "auth.us-east-1.amazoncognito.com": 1,
  "auth-fips.us-east-1.amazoncognito.com": 1,
  "auth.us-east-2.amazoncognito.com": 1,
  "auth-fips.us-east-2.amazoncognito.com": 1,
  "auth-fips.us-gov-west-1.amazoncognito.com": 1,
  "auth.us-west-1.amazoncognito.com": 1,
  "auth-fips.us-west-1.amazoncognito.com": 1,
  "auth.us-west-2.amazoncognito.com": 1,
  "auth-fips.us-west-2.amazoncognito.com": 1,
  "compute.amazonaws.com": 2,
  "compute-1.amazonaws.com": 2,
  "compute.amazonaws.com.cn": 2,
  "us-east-1.amazonaws.com": 1,
  "emrappui-prod.cn-north-1.amazonaws.com.cn": 1,
  "emrnotebooks-prod.cn-north-1.amazonaws.com.cn": 1,
  "emrstudio-prod.cn-north-1.amazonaws.com.cn": 1,
  "emrappui-prod.cn-northwest-1.amazonaws.com.cn": 1,
  "emrnotebooks-prod.cn-northwest-1.amazonaws.com.cn": 1,
  "emrstudio-prod.cn-northwest-1.amazonaws.com.cn": 1,
  "emrappui-prod.af-south-1.amazonaws.com": 1,
  "emrnotebooks-prod.af-south-1.amazonaws.com": 1,
  "emrstudio-prod.af-south-1.amazonaws.com": 1,
  "emrappui-prod.ap-east-1.amazonaws.com": 1,
  "emrnotebooks-prod.ap-east-1.amazonaws.com": 1,
  "emrstudio-prod.ap-east-1.amazonaws.com": 1,
  "emrappui-prod.ap-northeast-1.amazonaws.com": 1,
  "emrnotebooks-prod.ap-northeast-1.amazonaws.com": 1,
  "emrstudio-prod.ap-northeast-1.amazonaws.com": 1,
  "emrappui-prod.ap-northeast-2.amazonaws.com": 1,
  "emrnotebooks-prod.ap-northeast-2.amazonaws.com": 1,
  "emrstudio-prod.ap-northeast-2.amazonaws.com": 1,
  "emrappui-prod.ap-northeast-3.amazonaws.com": 1,
  "emrnotebooks-prod.ap-northeast-3.amazonaws.com": 1,
  "emrstudio-prod.ap-northeast-3.amazonaws.com": 1,
  "emrappui-prod.ap-south-1.amazonaws.com": 1,
  "emrnotebooks-prod.ap-south-1.amazonaws.com": 1,
  "emrstudio-prod.ap-south-1.amazonaws.com": 1,
  "emrappui-prod.ap-southeast-1.amazonaws.com": 1,
  "emrnotebooks-prod.ap-southeast-1.amazonaws.com": 1,
  "emrstudio-prod.ap-southeast-1.amazonaws.com": 1,
  "emrappui-prod.ap-southeast-2.amazonaws.com": 1,
  "emrnotebooks-prod.ap-southeast-2.amazonaws.com": 1,
  "emrstudio-prod.ap-southeast-2.amazonaws.com": 1,
  "emrappui-prod.ap-southeast-3.amazonaws.com": 1,
  "emrnotebooks-prod.ap-southeast-3.amazonaws.com": 1,
  "emrstudio-prod.ap-southeast-3.amazonaws.com": 1,
  "emrappui-prod.ca-central-1.amazonaws.com": 1,
  "emrnotebooks-prod.ca-central-1.amazonaws.com": 1,
  "emrstudio-prod.ca-central-1.amazonaws.com": 1,
  "emrappui-prod.eu-central-1.amazonaws.com": 1,
  "emrnotebooks-prod.eu-central-1.amazonaws.com": 1,
  "emrstudio-prod.eu-central-1.amazonaws.com": 1,
  "emrappui-prod.eu-north-1.amazonaws.com": 1,
  "emrnotebooks-prod.eu-north-1.amazonaws.com": 1,
  "emrstudio-prod.eu-north-1.amazonaws.com": 1,
  "emrappui-prod.eu-south-1.amazonaws.com": 1,
  "emrnotebooks-prod.eu-south-1.amazonaws.com": 1,
  "emrstudio-prod.eu-south-1.amazonaws.com": 1,
  "emrappui-prod.eu-west-1.amazonaws.com": 1,
  "emrnotebooks-prod.eu-west-1.amazonaws.com": 1,
  "emrstudio-prod.eu-west-1.amazonaws.com": 1,
  "emrappui-prod.eu-west-2.amazonaws.com": 1,
  "emrnotebooks-prod.eu-west-2.amazonaws.com": 1,
  "emrstudio-prod.eu-west-2.amazonaws.com": 1,
  "emrappui-prod.eu-west-3.amazonaws.com": 1,
  "emrnotebooks-prod.eu-west-3.amazonaws.com": 1,
  "emrstudio-prod.eu-west-3.amazonaws.com": 1,
  "emrappui-prod.me-central-1.amazonaws.com": 1,
  "emrnotebooks-prod.me-central-1.amazonaws.com": 1,
  "emrstudio-prod.me-central-1.amazonaws.com": 1,
  "emrappui-prod.me-south-1.amazonaws.com": 1,
  "emrnotebooks-prod.me-south-1.amazonaws.com": 1,
  "emrstudio-prod.me-south-1.amazonaws.com": 1,
  "emrappui-prod.sa-east-1.amazonaws.com": 1,
  "emrnotebooks-prod.sa-east-1.amazonaws.com": 1,
  "emrstudio-prod.sa-east-1.amazonaws.com": 1,
  "emrappui-prod.us-east-1.amazonaws.com": 1,
  "emrnotebooks-prod.us-east-1.amazonaws.com": 1,
  "emrstudio-prod.us-east-1.amazonaws.com": 1,
  "emrappui-prod.us-east-2.amazonaws.com": 1,
  "emrnotebooks-prod.us-east-2.amazonaws.com": 1,
  "emrstudio-prod.us-east-2.amazonaws.com": 1,
  "emrappui-prod.us-gov-east-1.amazonaws.com": 1,
  "emrnotebooks-prod.us-gov-east-1.amazonaws.com": 1,
  "emrstudio-prod.us-gov-east-1.amazonaws.com": 1,
  "emrappui-prod.us-gov-west-1.amazonaws.com": 1,
  "emrnotebooks-prod.us-gov-west-1.amazonaws.com": 1,
  "emrstudio-prod.us-gov-west-1.amazonaws.com": 1,
  "emrappui-prod.us-west-1.amazonaws.com": 1,
  "emrnotebooks-prod.us-west-1.amazonaws.com": 1,
  "emrstudio-prod.us-west-1.amazonaws.com": 1,
  "emrappui-prod.us-west-2.amazonaws.com": 1,
  "emrnotebooks-prod.us-west-2.amazonaws.com": 1,
  "emrstudio-prod.us-west-2.amazonaws.com": 1,
  "cn-north-1.airflow.amazonaws.com.cn": 2,
  "cn-northwest-1.airflow.amazonaws.com.cn": 2,
  "ap-northeast-1.airflow.amazonaws.com": 2,
  "ap-northeast-2.airflow.amazonaws.com": 2,
  "ap-south-1.airflow.amazonaws.com": 2,
  "ap-southeast-1.airflow.amazonaws.com": 2,
  "ap-southeast-2.airflow.amazonaws.com": 2,
  "ca-central-1.airflow.amazonaws.com": 2,
  "eu-central-1.airflow.amazonaws.com": 2,
  "eu-north-1.airflow.amazonaws.com": 2,
  "eu-west-1.airflow.amazonaws.com": 2,
  "eu-west-2.airflow.amazonaws.com": 2,
  "eu-west-3.airflow.amazonaws.com": 2,
  "sa-east-1.airflow.amazonaws.com": 2,
  "us-east-1.airflow.amazonaws.com": 2,
  "us-east-2.airflow.amazonaws.com": 2,
  "us-west-2.airflow.amazonaws.com": 2,
  "s3.dualstack.cn-north-1.amazonaws.com.cn": 1,
  "s3-accesspoint.dualstack.cn-north-1.amazonaws.com.cn": 1,
  "s3-website.dualstack.cn-north-1.amazonaws.com.cn": 1,
  "s3.cn-north-1.amazonaws.com.cn": 1,
  "s3-accesspoint.cn-north-1.amazonaws.com.cn": 1,
  "s3-deprecated.cn-north-1.amazonaws.com.cn": 1,
  "s3-object-lambda.cn-north-1.amazonaws.com.cn": 1,
  "s3-website.cn-north-1.amazonaws.com.cn": 1,
  "s3.dualstack.cn-northwest-1.amazonaws.com.cn": 1,
  "s3-accesspoint.dualstack.cn-northwest-1.amazonaws.com.cn": 1,
  "s3.cn-northwest-1.amazonaws.com.cn": 1,
  "s3-accesspoint.cn-northwest-1.amazonaws.com.cn": 1,
  "s3-object-lambda.cn-northwest-1.amazonaws.com.cn": 1,
  "s3-website.cn-northwest-1.amazonaws.com.cn": 1,
  "s3.dualstack.af-south-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.af-south-1.amazonaws.com": 1,
  "s3-website.dualstack.af-south-1.amazonaws.com": 1,
  "s3.af-south-1.amazonaws.com": 1,
  "s3-accesspoint.af-south-1.amazonaws.com": 1,
  "s3-object-lambda.af-south-1.amazonaws.com": 1,
  "s3-website.af-south-1.amazonaws.com": 1,
  "s3.dualstack.ap-east-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-east-1.amazonaws.com": 1,
  "s3.ap-east-1.amazonaws.com": 1,
  "s3-accesspoint.ap-east-1.amazonaws.com": 1,
  "s3-object-lambda.ap-east-1.amazonaws.com": 1,
  "s3-website.ap-east-1.amazonaws.com": 1,
  "s3.dualstack.ap-northeast-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-northeast-1.amazonaws.com": 1,
  "s3-website.dualstack.ap-northeast-1.amazonaws.com": 1,
  "s3.ap-northeast-1.amazonaws.com": 1,
  "s3-accesspoint.ap-northeast-1.amazonaws.com": 1,
  "s3-object-lambda.ap-northeast-1.amazonaws.com": 1,
  "s3-website.ap-northeast-1.amazonaws.com": 1,
  "s3.dualstack.ap-northeast-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-northeast-2.amazonaws.com": 1,
  "s3-website.dualstack.ap-northeast-2.amazonaws.com": 1,
  "s3.ap-northeast-2.amazonaws.com": 1,
  "s3-accesspoint.ap-northeast-2.amazonaws.com": 1,
  "s3-object-lambda.ap-northeast-2.amazonaws.com": 1,
  "s3-website.ap-northeast-2.amazonaws.com": 1,
  "s3.dualstack.ap-northeast-3.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-northeast-3.amazonaws.com": 1,
  "s3-website.dualstack.ap-northeast-3.amazonaws.com": 1,
  "s3.ap-northeast-3.amazonaws.com": 1,
  "s3-accesspoint.ap-northeast-3.amazonaws.com": 1,
  "s3-object-lambda.ap-northeast-3.amazonaws.com": 1,
  "s3-website.ap-northeast-3.amazonaws.com": 1,
  "s3.dualstack.ap-south-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-south-1.amazonaws.com": 1,
  "s3-website.dualstack.ap-south-1.amazonaws.com": 1,
  "s3.ap-south-1.amazonaws.com": 1,
  "s3-accesspoint.ap-south-1.amazonaws.com": 1,
  "s3-object-lambda.ap-south-1.amazonaws.com": 1,
  "s3-website.ap-south-1.amazonaws.com": 1,
  "s3.dualstack.ap-south-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-south-2.amazonaws.com": 1,
  "s3.ap-south-2.amazonaws.com": 1,
  "s3-accesspoint.ap-south-2.amazonaws.com": 1,
  "s3-object-lambda.ap-south-2.amazonaws.com": 1,
  "s3-website.ap-south-2.amazonaws.com": 1,
  "s3.dualstack.ap-southeast-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-southeast-1.amazonaws.com": 1,
  "s3-website.dualstack.ap-southeast-1.amazonaws.com": 1,
  "s3.ap-southeast-1.amazonaws.com": 1,
  "s3-accesspoint.ap-southeast-1.amazonaws.com": 1,
  "s3-object-lambda.ap-southeast-1.amazonaws.com": 1,
  "s3-website.ap-southeast-1.amazonaws.com": 1,
  "s3.dualstack.ap-southeast-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-southeast-2.amazonaws.com": 1,
  "s3-website.dualstack.ap-southeast-2.amazonaws.com": 1,
  "s3.ap-southeast-2.amazonaws.com": 1,
  "s3-accesspoint.ap-southeast-2.amazonaws.com": 1,
  "s3-object-lambda.ap-southeast-2.amazonaws.com": 1,
  "s3-website.ap-southeast-2.amazonaws.com": 1,
  "s3.dualstack.ap-southeast-3.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-southeast-3.amazonaws.com": 1,
  "s3.ap-southeast-3.amazonaws.com": 1,
  "s3-accesspoint.ap-southeast-3.amazonaws.com": 1,
  "s3-object-lambda.ap-southeast-3.amazonaws.com": 1,
  "s3-website.ap-southeast-3.amazonaws.com": 1,
  "s3.dualstack.ap-southeast-4.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ap-southeast-4.amazonaws.com": 1,
  "s3.ap-southeast-4.amazonaws.com": 1,
  "s3-accesspoint.ap-southeast-4.amazonaws.com": 1,
  "s3-object-lambda.ap-southeast-4.amazonaws.com": 1,
  "s3-website.ap-southeast-4.amazonaws.com": 1,
  "s3.dualstack.ca-central-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.ca-central-1.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.ca-central-1.amazonaws.com": 1,
  "s3-fips.dualstack.ca-central-1.amazonaws.com": 1,
  "s3-website.dualstack.ca-central-1.amazonaws.com": 1,
  "s3.ca-central-1.amazonaws.com": 1,
  "s3-accesspoint.ca-central-1.amazonaws.com": 1,
  "s3-accesspoint-fips.ca-central-1.amazonaws.com": 1,
  "s3-fips.ca-central-1.amazonaws.com": 1,
  "s3-object-lambda.ca-central-1.amazonaws.com": 1,
  "s3-website.ca-central-1.amazonaws.com": 1,
  "s3.dualstack.eu-central-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-central-1.amazonaws.com": 1,
  "s3-website.dualstack.eu-central-1.amazonaws.com": 1,
  "s3.eu-central-1.amazonaws.com": 1,
  "s3-accesspoint.eu-central-1.amazonaws.com": 1,
  "s3-object-lambda.eu-central-1.amazonaws.com": 1,
  "s3-website.eu-central-1.amazonaws.com": 1,
  "s3.dualstack.eu-central-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-central-2.amazonaws.com": 1,
  "s3.eu-central-2.amazonaws.com": 1,
  "s3-accesspoint.eu-central-2.amazonaws.com": 1,
  "s3-object-lambda.eu-central-2.amazonaws.com": 1,
  "s3-website.eu-central-2.amazonaws.com": 1,
  "s3.dualstack.eu-north-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-north-1.amazonaws.com": 1,
  "s3.eu-north-1.amazonaws.com": 1,
  "s3-accesspoint.eu-north-1.amazonaws.com": 1,
  "s3-object-lambda.eu-north-1.amazonaws.com": 1,
  "s3-website.eu-north-1.amazonaws.com": 1,
  "s3.dualstack.eu-south-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-south-1.amazonaws.com": 1,
  "s3-website.dualstack.eu-south-1.amazonaws.com": 1,
  "s3.eu-south-1.amazonaws.com": 1,
  "s3-accesspoint.eu-south-1.amazonaws.com": 1,
  "s3-object-lambda.eu-south-1.amazonaws.com": 1,
  "s3-website.eu-south-1.amazonaws.com": 1,
  "s3.dualstack.eu-south-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-south-2.amazonaws.com": 1,
  "s3.eu-south-2.amazonaws.com": 1,
  "s3-accesspoint.eu-south-2.amazonaws.com": 1,
  "s3-object-lambda.eu-south-2.amazonaws.com": 1,
  "s3-website.eu-south-2.amazonaws.com": 1,
  "s3.dualstack.eu-west-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-west-1.amazonaws.com": 1,
  "s3-website.dualstack.eu-west-1.amazonaws.com": 1,
  "s3.eu-west-1.amazonaws.com": 1,
  "s3-accesspoint.eu-west-1.amazonaws.com": 1,
  "s3-deprecated.eu-west-1.amazonaws.com": 1,
  "s3-object-lambda.eu-west-1.amazonaws.com": 1,
  "s3-website.eu-west-1.amazonaws.com": 1,
  "s3.dualstack.eu-west-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-west-2.amazonaws.com": 1,
  "s3.eu-west-2.amazonaws.com": 1,
  "s3-accesspoint.eu-west-2.amazonaws.com": 1,
  "s3-object-lambda.eu-west-2.amazonaws.com": 1,
  "s3-website.eu-west-2.amazonaws.com": 1,
  "s3.dualstack.eu-west-3.amazonaws.com": 1,
  "s3-accesspoint.dualstack.eu-west-3.amazonaws.com": 1,
  "s3-website.dualstack.eu-west-3.amazonaws.com": 1,
  "s3.eu-west-3.amazonaws.com": 1,
  "s3-accesspoint.eu-west-3.amazonaws.com": 1,
  "s3-object-lambda.eu-west-3.amazonaws.com": 1,
  "s3-website.eu-west-3.amazonaws.com": 1,
  "s3.dualstack.il-central-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.il-central-1.amazonaws.com": 1,
  "s3.il-central-1.amazonaws.com": 1,
  "s3-accesspoint.il-central-1.amazonaws.com": 1,
  "s3-object-lambda.il-central-1.amazonaws.com": 1,
  "s3-website.il-central-1.amazonaws.com": 1,
  "s3.dualstack.me-central-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.me-central-1.amazonaws.com": 1,
  "s3.me-central-1.amazonaws.com": 1,
  "s3-accesspoint.me-central-1.amazonaws.com": 1,
  "s3-object-lambda.me-central-1.amazonaws.com": 1,
  "s3-website.me-central-1.amazonaws.com": 1,
  "s3.dualstack.me-south-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.me-south-1.amazonaws.com": 1,
  "s3.me-south-1.amazonaws.com": 1,
  "s3-accesspoint.me-south-1.amazonaws.com": 1,
  "s3-object-lambda.me-south-1.amazonaws.com": 1,
  "s3-website.me-south-1.amazonaws.com": 1,
  "s3.amazonaws.com": 1,
  "s3-1.amazonaws.com": 1,
  "s3-ap-east-1.amazonaws.com": 1,
  "s3-ap-northeast-1.amazonaws.com": 1,
  "s3-ap-northeast-2.amazonaws.com": 1,
  "s3-ap-northeast-3.amazonaws.com": 1,
  "s3-ap-south-1.amazonaws.com": 1,
  "s3-ap-southeast-1.amazonaws.com": 1,
  "s3-ap-southeast-2.amazonaws.com": 1,
  "s3-ca-central-1.amazonaws.com": 1,
  "s3-eu-central-1.amazonaws.com": 1,
  "s3-eu-north-1.amazonaws.com": 1,
  "s3-eu-west-1.amazonaws.com": 1,
  "s3-eu-west-2.amazonaws.com": 1,
  "s3-eu-west-3.amazonaws.com": 1,
  "s3-external-1.amazonaws.com": 1,
  "s3-fips-us-gov-east-1.amazonaws.com": 1,
  "s3-fips-us-gov-west-1.amazonaws.com": 1,
  "mrap.accesspoint.s3-global.amazonaws.com": 1,
  "s3-me-south-1.amazonaws.com": 1,
  "s3-sa-east-1.amazonaws.com": 1,
  "s3-us-east-2.amazonaws.com": 1,
  "s3-us-gov-east-1.amazonaws.com": 1,
  "s3-us-gov-west-1.amazonaws.com": 1,
  "s3-us-west-1.amazonaws.com": 1,
  "s3-us-west-2.amazonaws.com": 1,
  "s3-website-ap-northeast-1.amazonaws.com": 1,
  "s3-website-ap-southeast-1.amazonaws.com": 1,
  "s3-website-ap-southeast-2.amazonaws.com": 1,
  "s3-website-eu-west-1.amazonaws.com": 1,
  "s3-website-sa-east-1.amazonaws.com": 1,
  "s3-website-us-east-1.amazonaws.com": 1,
  "s3-website-us-gov-west-1.amazonaws.com": 1,
  "s3-website-us-west-1.amazonaws.com": 1,
  "s3-website-us-west-2.amazonaws.com": 1,
  "s3.dualstack.sa-east-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.sa-east-1.amazonaws.com": 1,
  "s3-website.dualstack.sa-east-1.amazonaws.com": 1,
  "s3.sa-east-1.amazonaws.com": 1,
  "s3-accesspoint.sa-east-1.amazonaws.com": 1,
  "s3-object-lambda.sa-east-1.amazonaws.com": 1,
  "s3-website.sa-east-1.amazonaws.com": 1,
  "s3.dualstack.us-east-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-east-1.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-east-1.amazonaws.com": 1,
  "s3-fips.dualstack.us-east-1.amazonaws.com": 1,
  "s3-website.dualstack.us-east-1.amazonaws.com": 1,
  "s3.us-east-1.amazonaws.com": 1,
  "s3-accesspoint.us-east-1.amazonaws.com": 1,
  "s3-accesspoint-fips.us-east-1.amazonaws.com": 1,
  "s3-deprecated.us-east-1.amazonaws.com": 1,
  "s3-fips.us-east-1.amazonaws.com": 1,
  "s3-object-lambda.us-east-1.amazonaws.com": 1,
  "s3-website.us-east-1.amazonaws.com": 1,
  "s3.dualstack.us-east-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-east-2.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-east-2.amazonaws.com": 1,
  "s3-fips.dualstack.us-east-2.amazonaws.com": 1,
  "s3.us-east-2.amazonaws.com": 1,
  "s3-accesspoint.us-east-2.amazonaws.com": 1,
  "s3-accesspoint-fips.us-east-2.amazonaws.com": 1,
  "s3-deprecated.us-east-2.amazonaws.com": 1,
  "s3-fips.us-east-2.amazonaws.com": 1,
  "s3-object-lambda.us-east-2.amazonaws.com": 1,
  "s3-website.us-east-2.amazonaws.com": 1,
  "s3.dualstack.us-gov-east-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-gov-east-1.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-gov-east-1.amazonaws.com": 1,
  "s3-fips.dualstack.us-gov-east-1.amazonaws.com": 1,
  "s3.us-gov-east-1.amazonaws.com": 1,
  "s3-accesspoint.us-gov-east-1.amazonaws.com": 1,
  "s3-accesspoint-fips.us-gov-east-1.amazonaws.com": 1,
  "s3-fips.us-gov-east-1.amazonaws.com": 1,
  "s3-object-lambda.us-gov-east-1.amazonaws.com": 1,
  "s3-website.us-gov-east-1.amazonaws.com": 1,
  "s3.dualstack.us-gov-west-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-gov-west-1.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-gov-west-1.amazonaws.com": 1,
  "s3-fips.dualstack.us-gov-west-1.amazonaws.com": 1,
  "s3.us-gov-west-1.amazonaws.com": 1,
  "s3-accesspoint.us-gov-west-1.amazonaws.com": 1,
  "s3-accesspoint-fips.us-gov-west-1.amazonaws.com": 1,
  "s3-fips.us-gov-west-1.amazonaws.com": 1,
  "s3-object-lambda.us-gov-west-1.amazonaws.com": 1,
  "s3-website.us-gov-west-1.amazonaws.com": 1,
  "s3.dualstack.us-west-1.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-west-1.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-west-1.amazonaws.com": 1,
  "s3-fips.dualstack.us-west-1.amazonaws.com": 1,
  "s3-website.dualstack.us-west-1.amazonaws.com": 1,
  "s3.us-west-1.amazonaws.com": 1,
  "s3-accesspoint.us-west-1.amazonaws.com": 1,
  "s3-accesspoint-fips.us-west-1.amazonaws.com": 1,
  "s3-fips.us-west-1.amazonaws.com": 1,
  "s3-object-lambda.us-west-1.amazonaws.com": 1,
  "s3-website.us-west-1.amazonaws.com": 1,
  "s3.dualstack.us-west-2.amazonaws.com": 1,
  "s3-accesspoint.dualstack.us-west-2.amazonaws.com": 1,
  "s3-accesspoint-fips.dualstack.us-west-2.amazonaws.com": 1,
  "s3-fips.dualstack.us-west-2.amazonaws.com": 1,
  "s3-website.dualstack.us-west-2.amazonaws.com": 1,
  "s3.us-west-2.amazonaws.com": 1,
  "s3-accesspoint.us-west-2.amazonaws.com": 1,
  "s3-accesspoint-fips.us-west-2.amazonaws.com": 1,
  "s3-deprecated.us-west-2.amazonaws.com": 1,
  "s3-fips.us-west-2.amazonaws.com": 1,
  "s3-object-lambda.us-west-2.amazonaws.com": 1,
  "s3-website.us-west-2.amazonaws.com": 1,
  "notebook.af-south-1.sagemaker.aws": 1,
  "notebook.ap-east-1.sagemaker.aws": 1,
  "notebook.ap-northeast-1.sagemaker.aws": 1,
  "notebook.ap-northeast-2.sagemaker.aws": 1,
  "notebook.ap-northeast-3.sagemaker.aws": 1,
  "notebook.ap-south-1.sagemaker.aws": 1,
  "notebook.ap-south-2.sagemaker.aws": 1,
  "notebook.ap-southeast-1.sagemaker.aws": 1,
  "notebook.ap-southeast-2.sagemaker.aws": 1,
  "notebook.ap-southeast-3.sagemaker.aws": 1,
  "notebook.ap-southeast-4.sagemaker.aws": 1,
  "notebook.ca-central-1.sagemaker.aws": 1,
  "notebook.eu-central-1.sagemaker.aws": 1,
  "notebook.eu-central-2.sagemaker.aws": 1,
  "notebook.eu-north-1.sagemaker.aws": 1,
  "notebook.eu-south-1.sagemaker.aws": 1,
  "notebook.eu-south-2.sagemaker.aws": 1,
  "notebook.eu-west-1.sagemaker.aws": 1,
  "notebook.eu-west-2.sagemaker.aws": 1,
  "notebook.eu-west-3.sagemaker.aws": 1,
  "notebook.il-central-1.sagemaker.aws": 1,
  "notebook.me-central-1.sagemaker.aws": 1,
  "notebook.me-south-1.sagemaker.aws": 1,
  "notebook.sa-east-1.sagemaker.aws": 1,
  "notebook.us-east-1.sagemaker.aws": 1,
  "notebook-fips.us-east-1.sagemaker.aws": 1,
  "notebook.us-east-2.sagemaker.aws": 1,
  "notebook-fips.us-east-2.sagemaker.aws": 1,
  "notebook.us-gov-east-1.sagemaker.aws": 1,
  "notebook-fips.us-gov-east-1.sagemaker.aws": 1,
  "notebook.us-gov-west-1.sagemaker.aws": 1,
  "notebook-fips.us-gov-west-1.sagemaker.aws": 1,
  "notebook.us-west-1.sagemaker.aws": 1,
  "notebook.us-west-2.sagemaker.aws": 1,
  "notebook-fips.us-west-2.sagemaker.aws": 1,
  "notebook.cn-north-1.sagemaker.com.cn": 1,
  "notebook.cn-northwest-1.sagemaker.com.cn": 1,
  "studio.af-south-1.sagemaker.aws": 1,
  "studio.ap-east-1.sagemaker.aws": 1,
  "studio.ap-northeast-1.sagemaker.aws": 1,
  "studio.ap-northeast-2.sagemaker.aws": 1,
  "studio.ap-northeast-3.sagemaker.aws": 1,
  "studio.ap-south-1.sagemaker.aws": 1,
  "studio.ap-southeast-1.sagemaker.aws": 1,
  "studio.ap-southeast-2.sagemaker.aws": 1,
  "studio.ap-southeast-3.sagemaker.aws": 1,
  "studio.ca-central-1.sagemaker.aws": 1,
  "studio.eu-central-1.sagemaker.aws": 1,
  "studio.eu-north-1.sagemaker.aws": 1,
  "studio.eu-south-1.sagemaker.aws": 1,
  "studio.eu-west-1.sagemaker.aws": 1,
  "studio.eu-west-2.sagemaker.aws": 1,
  "studio.eu-west-3.sagemaker.aws": 1,
  "studio.il-central-1.sagemaker.aws": 1,
  "studio.me-central-1.sagemaker.aws": 1,
  "studio.me-south-1.sagemaker.aws": 1,
  "studio.sa-east-1.sagemaker.aws": 1,
  "studio.us-east-1.sagemaker.aws": 1,
  "studio.us-east-2.sagemaker.aws": 1,
  "studio.us-gov-east-1.sagemaker.aws": 1,
  "studio-fips.us-gov-east-1.sagemaker.aws": 1,
  "studio.us-gov-west-1.sagemaker.aws": 1,
  "studio-fips.us-gov-west-1.sagemaker.aws": 1,
  "studio.us-west-1.sagemaker.aws": 1,
  "studio.us-west-2.sagemaker.aws": 1,
  "studio.cn-north-1.sagemaker.com.cn": 1,
  "studio.cn-northwest-1.sagemaker.com.cn": 1,
  "analytics-gateway.ap-northeast-1.amazonaws.com": 1,
  "analytics-gateway.ap-northeast-2.amazonaws.com": 1,
  "analytics-gateway.ap-south-1.amazonaws.com": 1,
  "analytics-gateway.ap-southeast-1.amazonaws.com": 1,
  "analytics-gateway.ap-southeast-2.amazonaws.com": 1,
  "analytics-gateway.eu-central-1.amazonaws.com": 1,
  "analytics-gateway.eu-west-1.amazonaws.com": 1,
  "analytics-gateway.us-east-1.amazonaws.com": 1,
  "analytics-gateway.us-east-2.amazonaws.com": 1,
  "analytics-gateway.us-west-2.amazonaws.com": 1,
  "amplifyapp.com": 2,
  "awsapprunner.com": 2,
  "webview-assets.aws-cloud9.af-south-1.amazonaws.com": 1,
  "vfs.cloud9.af-south-1.amazonaws.com": 1,
  "webview-assets.cloud9.af-south-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-east-1.amazonaws.com": 1,
  "vfs.cloud9.ap-east-1.amazonaws.com": 1,
  "webview-assets.cloud9.ap-east-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-northeast-1.amazonaws.com": 1,
  "vfs.cloud9.ap-northeast-1.amazonaws.com": 1,
  "webview-assets.cloud9.ap-northeast-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-northeast-2.amazonaws.com": 1,
  "vfs.cloud9.ap-northeast-2.amazonaws.com": 1,
  "webview-assets.cloud9.ap-northeast-2.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-northeast-3.amazonaws.com": 1,
  "vfs.cloud9.ap-northeast-3.amazonaws.com": 1,
  "webview-assets.cloud9.ap-northeast-3.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-south-1.amazonaws.com": 1,
  "vfs.cloud9.ap-south-1.amazonaws.com": 1,
  "webview-assets.cloud9.ap-south-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-southeast-1.amazonaws.com": 1,
  "vfs.cloud9.ap-southeast-1.amazonaws.com": 1,
  "webview-assets.cloud9.ap-southeast-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ap-southeast-2.amazonaws.com": 1,
  "vfs.cloud9.ap-southeast-2.amazonaws.com": 1,
  "webview-assets.cloud9.ap-southeast-2.amazonaws.com": 1,
  "webview-assets.aws-cloud9.ca-central-1.amazonaws.com": 1,
  "vfs.cloud9.ca-central-1.amazonaws.com": 1,
  "webview-assets.cloud9.ca-central-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-central-1.amazonaws.com": 1,
  "vfs.cloud9.eu-central-1.amazonaws.com": 1,
  "webview-assets.cloud9.eu-central-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-north-1.amazonaws.com": 1,
  "vfs.cloud9.eu-north-1.amazonaws.com": 1,
  "webview-assets.cloud9.eu-north-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-south-1.amazonaws.com": 1,
  "vfs.cloud9.eu-south-1.amazonaws.com": 1,
  "webview-assets.cloud9.eu-south-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-west-1.amazonaws.com": 1,
  "vfs.cloud9.eu-west-1.amazonaws.com": 1,
  "webview-assets.cloud9.eu-west-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-west-2.amazonaws.com": 1,
  "vfs.cloud9.eu-west-2.amazonaws.com": 1,
  "webview-assets.cloud9.eu-west-2.amazonaws.com": 1,
  "webview-assets.aws-cloud9.eu-west-3.amazonaws.com": 1,
  "vfs.cloud9.eu-west-3.amazonaws.com": 1,
  "webview-assets.cloud9.eu-west-3.amazonaws.com": 1,
  "webview-assets.aws-cloud9.me-south-1.amazonaws.com": 1,
  "vfs.cloud9.me-south-1.amazonaws.com": 1,
  "webview-assets.cloud9.me-south-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.sa-east-1.amazonaws.com": 1,
  "vfs.cloud9.sa-east-1.amazonaws.com": 1,
  "webview-assets.cloud9.sa-east-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.us-east-1.amazonaws.com": 1,
  "vfs.cloud9.us-east-1.amazonaws.com": 1,
  "webview-assets.cloud9.us-east-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.us-east-2.amazonaws.com": 1,
  "vfs.cloud9.us-east-2.amazonaws.com": 1,
  "webview-assets.cloud9.us-east-2.amazonaws.com": 1,
  "webview-assets.aws-cloud9.us-west-1.amazonaws.com": 1,
  "vfs.cloud9.us-west-1.amazonaws.com": 1,
  "webview-assets.cloud9.us-west-1.amazonaws.com": 1,
  "webview-assets.aws-cloud9.us-west-2.amazonaws.com": 1,
  "vfs.cloud9.us-west-2.amazonaws.com": 1,
  "webview-assets.cloud9.us-west-2.amazonaws.com": 1,
  "cn-north-1.eb.amazonaws.com.cn": 1,
  "cn-northwest-1.eb.amazonaws.com.cn": 1,
  "elasticbeanstalk.com": 1,
  "af-south-1.elasticbeanstalk.com": 1,
  "ap-east-1.elasticbeanstalk.com": 1,
  "ap-northeast-1.elasticbeanstalk.com": 1,
  "ap-northeast-2.elasticbeanstalk.com": 1,
  "ap-northeast-3.elasticbeanstalk.com": 1,
  "ap-south-1.elasticbeanstalk.com": 1,
  "ap-southeast-1.elasticbeanstalk.com": 1,
  "ap-southeast-2.elasticbeanstalk.com": 1,
  "ap-southeast-3.elasticbeanstalk.com": 1,
  "ca-central-1.elasticbeanstalk.com": 1,
  "eu-central-1.elasticbeanstalk.com": 1,
  "eu-north-1.elasticbeanstalk.com": 1,
  "eu-south-1.elasticbeanstalk.com": 1,
  "eu-west-1.elasticbeanstalk.com": 1,
  "eu-west-2.elasticbeanstalk.com": 1,
  "eu-west-3.elasticbeanstalk.com": 1,
  "il-central-1.elasticbeanstalk.com": 1,
  "me-south-1.elasticbeanstalk.com": 1,
  "sa-east-1.elasticbeanstalk.com": 1,
  "us-east-1.elasticbeanstalk.com": 1,
  "us-east-2.elasticbeanstalk.com": 1,
  "us-gov-east-1.elasticbeanstalk.com": 1,
  "us-gov-west-1.elasticbeanstalk.com": 1,
  "us-west-1.elasticbeanstalk.com": 1,
  "us-west-2.elasticbeanstalk.com": 1,
  "elb.amazonaws.com.cn": 2,
  "elb.amazonaws.com": 2,
  "awsglobalaccelerator.com": 1,
  "eero.online": 1,
  "eero-stage.online": 1,
  "t3l3p0rt.net": 1,
  "tele.amune.org": 1,
  "apigee.io": 1,
  "siiites.com": 1,
  "appspacehosted.com": 1,
  "appspaceusercontent.com": 1,
  "appudo.net": 1,
  "on-aptible.com": 1,
  "user.aseinet.ne.jp": 1,
  "gv.vc": 1,
  "d.gv.vc": 1,
  "user.party.eus": 1,
  "pimienta.org": 1,
  "poivron.org": 1,
  "potager.org": 1,
  "sweetpepper.org": 1,
  "myasustor.com": 1,
  "cdn.prod.atlassian-dev.net": 1,
  "translated.page": 1,
  "autocode.dev": 1,
  "myfritz.net": 1,
  "onavstack.net": 1,
  "awdev.ca": 2,
  "advisor.ws": 2,
  "ecommerce-shop.pl": 1,
  "b-data.io": 1,
  "backplaneapp.io": 1,
  "balena-devices.com": 1,
  "rs.ba": 1,
  "banzai.cloud": 2,
  "app.banzaicloud.io": 1,
  "backyards.banzaicloud.io": 2,
  "base.ec": 1,
  "official.ec": 1,
  "buyshop.jp": 1,
  "fashionstore.jp": 1,
  "handcrafted.jp": 1,
  "kawaiishop.jp": 1,
  "supersale.jp": 1,
  "theshop.jp": 1,
  "shopselect.net": 1,
  "base.shop": 1,
  "beagleboard.io": 1,
  "beget.app": 2,
  "betainabox.com": 1,
  "bnr.la": 1,
  "bitbucket.io": 1,
  "blackbaudcdn.net": 1,
  "of.je": 1,
  "bluebite.io": 1,
  "boomla.net": 1,
  "boutir.com": 1,
  "boxfuse.io": 1,
  "square7.ch": 1,
  "bplaced.com": 1,
  "bplaced.de": 1,
  "square7.de": 1,
  "bplaced.net": 1,
  "square7.net": 1,
  "shop.brendly.rs": 1,
  "browsersafetymark.io": 1,
  "uk0.bigv.io": 1,
  "dh.bytemark.co.uk": 1,
  "vm.bytemark.co.uk": 1,
  "cafjs.com": 1,
  "mycd.eu": 1,
  "canva-apps.cn": 1,
  "canva-apps.com": 1,
  "drr.ac": 1,
  "uwu.ai": 1,
  "carrd.co": 1,
  "crd.co": 1,
  "ju.mp": 1,
  "ae.org": 1,
  "br.com": 1,
  "cn.com": 1,
  "com.de": 1,
  "com.se": 1,
  "de.com": 1,
  "eu.com": 1,
  "gb.net": 1,
  "hu.net": 1,
  "jp.net": 1,
  "jpn.com": 1,
  "mex.com": 1,
  "ru.com": 1,
  "sa.com": 1,
  "se.net": 1,
  "uk.com": 1,
  "uk.net": 1,
  "us.com": 1,
  "za.bz": 1,
  "za.com": 1,
  "ar.com": 1,
  "hu.com": 1,
  "kr.com": 1,
  "no.com": 1,
  "qc.com": 1,
  "uy.com": 1,
  "africa.com": 1,
  "gr.com": 1,
  "in.net": 1,
  "web.in": 1,
  "us.org": 1,
  "co.com": 1,
  "aus.basketball": 1,
  "nz.basketball": 1,
  "radio.am": 1,
  "radio.fm": 1,
  "c.la": 1,
  "certmgr.org": 1,
  "cx.ua": 1,
  "discourse.group": 1,
  "discourse.team": 1,
  "cleverapps.io": 1,
  "clerk.app": 1,
  "clerkstage.app": 1,
  "lcl.dev": 2,
  "lclstage.dev": 2,
  "stg.dev": 2,
  "stgstage.dev": 2,
  "clickrising.net": 1,
  "c66.me": 1,
  "cloud66.ws": 1,
  "cloud66.zone": 1,
  "jdevcloud.com": 1,
  "wpdevcloud.com": 1,
  "cloudaccess.host": 1,
  "freesite.host": 1,
  "cloudaccess.net": 1,
  "cloudcontrolled.com": 1,
  "cloudcontrolapp.com": 1,
  "cloudera.site": 2,
  "cf-ipfs.com": 1,
  "cloudflare-ipfs.com": 1,
  "trycloudflare.com": 1,
  "pages.dev": 1,
  "r2.dev": 1,
  "workers.dev": 1,
  "wnext.app": 1,
  "co.ca": 1,
  "otap.co": 2,
  "co.cz": 1,
  "c.cdn77.org": 1,
  "cdn77-ssl.net": 1,
  "r.cdn77.net": 1,
  "rsc.cdn77.org": 1,
  "ssl.origin.cdn77-secure.org": 1,
  "cloudns.asia": 1,
  "cloudns.biz": 1,
  "cloudns.club": 1,
  "cloudns.cc": 1,
  "cloudns.eu": 1,
  "cloudns.in": 1,
  "cloudns.info": 1,
  "cloudns.org": 1,
  "cloudns.pro": 1,
  "cloudns.pw": 1,
  "cloudns.us": 1,
  "cnpy.gdn": 1,
  "codeberg.page": 1,
  "co.nl": 1,
  "co.no": 1,
  "webhosting.be": 1,
  "hosting-cluster.nl": 1,
  "ac.ru": 1,
  "edu.ru": 1,
  "gov.ru": 1,
  "int.ru": 1,
  "mil.ru": 1,
  "test.ru": 1,
  "dyn.cosidns.de": 1,
  "dynamisches-dns.de": 1,
  "dnsupdater.de": 1,
  "internet-dns.de": 1,
  "l-o-g-i-n.de": 1,
  "dynamic-dns.info": 1,
  "feste-ip.net": 1,
  "knx-server.net": 1,
  "static-access.net": 1,
  "realm.cz": 1,
  "cryptonomic.net": 2,
  "cupcake.is": 1,
  "curv.dev": 1,
  "customer-oci.com": 2,
  "oci.customer-oci.com": 2,
  "ocp.customer-oci.com": 2,
  "ocs.customer-oci.com": 2,
  "cyon.link": 1,
  "cyon.site": 1,
  "fnwk.site": 1,
  "folionetwork.site": 1,
  "platform0.app": 1,
  "daplie.me": 1,
  "localhost.daplie.me": 1,
  "dattolocal.com": 1,
  "dattorelay.com": 1,
  "dattoweb.com": 1,
  "mydatto.com": 1,
  "dattolocal.net": 1,
  "mydatto.net": 1,
  "biz.dk": 1,
  "co.dk": 1,
  "firm.dk": 1,
  "reg.dk": 1,
  "store.dk": 1,
  "dyndns.dappnode.io": 1,
  "dapps.earth": 2,
  "bzz.dapps.earth": 2,
  "builtwithdark.com": 1,
  "demo.datadetect.com": 1,
  "instance.datadetect.com": 1,
  "edgestack.me": 1,
  "ddns5.com": 1,
  "debian.net": 1,
  "deno.dev": 1,
  "deno-staging.dev": 1,
  "dedyn.io": 1,
  "deta.app": 1,
  "deta.dev": 1,
  "rss.my.id": 2,
  "diher.solutions": 2,
  "discordsays.com": 1,
  "discordsez.com": 1,
  "jozi.biz": 1,
  "dnshome.de": 1,
  "online.th": 1,
  "shop.th": 1,
  "drayddns.com": 1,
  "shoparena.pl": 1,
  "dreamhosters.com": 1,
  "mydrobo.com": 1,
  "drud.io": 1,
  "drud.us": 1,
  "duckdns.org": 1,
  "bip.sh": 1,
  "bitbridge.net": 1,
  "dy.fi": 1,
  "tunk.org": 1,
  "dyndns-at-home.com": 1,
  "dyndns-at-work.com": 1,
  "dyndns-blog.com": 1,
  "dyndns-free.com": 1,
  "dyndns-home.com": 1,
  "dyndns-ip.com": 1,
  "dyndns-mail.com": 1,
  "dyndns-office.com": 1,
  "dyndns-pics.com": 1,
  "dyndns-remote.com": 1,
  "dyndns-server.com": 1,
  "dyndns-web.com": 1,
  "dyndns-wiki.com": 1,
  "dyndns-work.com": 1,
  "dyndns.biz": 1,
  "dyndns.info": 1,
  "dyndns.org": 1,
  "dyndns.tv": 1,
  "at-band-camp.net": 1,
  "ath.cx": 1,
  "barrel-of-knowledge.info": 1,
  "barrell-of-knowledge.info": 1,
  "better-than.tv": 1,
  "blogdns.com": 1,
  "blogdns.net": 1,
  "blogdns.org": 1,
  "blogsite.org": 1,
  "boldlygoingnowhere.org": 1,
  "broke-it.net": 1,
  "buyshouses.net": 1,
  "cechire.com": 1,
  "dnsalias.com": 1,
  "dnsalias.net": 1,
  "dnsalias.org": 1,
  "dnsdojo.com": 1,
  "dnsdojo.net": 1,
  "dnsdojo.org": 1,
  "does-it.net": 1,
  "doesntexist.com": 1,
  "doesntexist.org": 1,
  "dontexist.com": 1,
  "dontexist.net": 1,
  "dontexist.org": 1,
  "doomdns.com": 1,
  "doomdns.org": 1,
  "dvrdns.org": 1,
  "dyn-o-saur.com": 1,
  "dynalias.com": 1,
  "dynalias.net": 1,
  "dynalias.org": 1,
  "dynathome.net": 1,
  "dyndns.ws": 1,
  "endofinternet.net": 1,
  "endofinternet.org": 1,
  "endoftheinternet.org": 1,
  "est-a-la-maison.com": 1,
  "est-a-la-masion.com": 1,
  "est-le-patron.com": 1,
  "est-mon-blogueur.com": 1,
  "for-better.biz": 1,
  "for-more.biz": 1,
  "for-our.info": 1,
  "for-some.biz": 1,
  "for-the.biz": 1,
  "forgot.her.name": 1,
  "forgot.his.name": 1,
  "from-ak.com": 1,
  "from-al.com": 1,
  "from-ar.com": 1,
  "from-az.net": 1,
  "from-ca.com": 1,
  "from-co.net": 1,
  "from-ct.com": 1,
  "from-dc.com": 1,
  "from-de.com": 1,
  "from-fl.com": 1,
  "from-ga.com": 1,
  "from-hi.com": 1,
  "from-ia.com": 1,
  "from-id.com": 1,
  "from-il.com": 1,
  "from-in.com": 1,
  "from-ks.com": 1,
  "from-ky.com": 1,
  "from-la.net": 1,
  "from-ma.com": 1,
  "from-md.com": 1,
  "from-me.org": 1,
  "from-mi.com": 1,
  "from-mn.com": 1,
  "from-mo.com": 1,
  "from-ms.com": 1,
  "from-mt.com": 1,
  "from-nc.com": 1,
  "from-nd.com": 1,
  "from-ne.com": 1,
  "from-nh.com": 1,
  "from-nj.com": 1,
  "from-nm.com": 1,
  "from-nv.com": 1,
  "from-ny.net": 1,
  "from-oh.com": 1,
  "from-ok.com": 1,
  "from-or.com": 1,
  "from-pa.com": 1,
  "from-pr.com": 1,
  "from-ri.com": 1,
  "from-sc.com": 1,
  "from-sd.com": 1,
  "from-tn.com": 1,
  "from-tx.com": 1,
  "from-ut.com": 1,
  "from-va.com": 1,
  "from-vt.com": 1,
  "from-wa.com": 1,
  "from-wi.com": 1,
  "from-wv.com": 1,
  "from-wy.com": 1,
  "ftpaccess.cc": 1,
  "fuettertdasnetz.de": 1,
  "game-host.org": 1,
  "game-server.cc": 1,
  "getmyip.com": 1,
  "gets-it.net": 1,
  "go.dyndns.org": 1,
  "gotdns.com": 1,
  "gotdns.org": 1,
  "groks-the.info": 1,
  "groks-this.info": 1,
  "ham-radio-op.net": 1,
  "here-for-more.info": 1,
  "hobby-site.com": 1,
  "hobby-site.org": 1,
  "home.dyndns.org": 1,
  "homedns.org": 1,
  "homeftp.net": 1,
  "homeftp.org": 1,
  "homeip.net": 1,
  "homelinux.com": 1,
  "homelinux.net": 1,
  "homelinux.org": 1,
  "homeunix.com": 1,
  "homeunix.net": 1,
  "homeunix.org": 1,
  "iamallama.com": 1,
  "in-the-band.net": 1,
  "is-a-anarchist.com": 1,
  "is-a-blogger.com": 1,
  "is-a-bookkeeper.com": 1,
  "is-a-bruinsfan.org": 1,
  "is-a-bulls-fan.com": 1,
  "is-a-candidate.org": 1,
  "is-a-caterer.com": 1,
  "is-a-celticsfan.org": 1,
  "is-a-chef.com": 1,
  "is-a-chef.net": 1,
  "is-a-chef.org": 1,
  "is-a-conservative.com": 1,
  "is-a-cpa.com": 1,
  "is-a-cubicle-slave.com": 1,
  "is-a-democrat.com": 1,
  "is-a-designer.com": 1,
  "is-a-doctor.com": 1,
  "is-a-financialadvisor.com": 1,
  "is-a-geek.com": 1,
  "is-a-geek.net": 1,
  "is-a-geek.org": 1,
  "is-a-green.com": 1,
  "is-a-guru.com": 1,
  "is-a-hard-worker.com": 1,
  "is-a-hunter.com": 1,
  "is-a-knight.org": 1,
  "is-a-landscaper.com": 1,
  "is-a-lawyer.com": 1,
  "is-a-liberal.com": 1,
  "is-a-libertarian.com": 1,
  "is-a-linux-user.org": 1,
  "is-a-llama.com": 1,
  "is-a-musician.com": 1,
  "is-a-nascarfan.com": 1,
  "is-a-nurse.com": 1,
  "is-a-painter.com": 1,
  "is-a-patsfan.org": 1,
  "is-a-personaltrainer.com": 1,
  "is-a-photographer.com": 1,
  "is-a-player.com": 1,
  "is-a-republican.com": 1,
  "is-a-rockstar.com": 1,
  "is-a-socialist.com": 1,
  "is-a-soxfan.org": 1,
  "is-a-student.com": 1,
  "is-a-teacher.com": 1,
  "is-a-techie.com": 1,
  "is-a-therapist.com": 1,
  "is-an-accountant.com": 1,
  "is-an-actor.com": 1,
  "is-an-actress.com": 1,
  "is-an-anarchist.com": 1,
  "is-an-artist.com": 1,
  "is-an-engineer.com": 1,
  "is-an-entertainer.com": 1,
  "is-by.us": 1,
  "is-certified.com": 1,
  "is-found.org": 1,
  "is-gone.com": 1,
  "is-into-anime.com": 1,
  "is-into-cars.com": 1,
  "is-into-cartoons.com": 1,
  "is-into-games.com": 1,
  "is-leet.com": 1,
  "is-lost.org": 1,
  "is-not-certified.com": 1,
  "is-saved.org": 1,
  "is-slick.com": 1,
  "is-uberleet.com": 1,
  "is-very-bad.org": 1,
  "is-very-evil.org": 1,
  "is-very-good.org": 1,
  "is-very-nice.org": 1,
  "is-very-sweet.org": 1,
  "is-with-theband.com": 1,
  "isa-geek.com": 1,
  "isa-geek.net": 1,
  "isa-geek.org": 1,
  "isa-hockeynut.com": 1,
  "issmarterthanyou.com": 1,
  "isteingeek.de": 1,
  "istmein.de": 1,
  "kicks-ass.net": 1,
  "kicks-ass.org": 1,
  "knowsitall.info": 1,
  "land-4-sale.us": 1,
  "lebtimnetz.de": 1,
  "leitungsen.de": 1,
  "likes-pie.com": 1,
  "likescandy.com": 1,
  "merseine.nu": 1,
  "mine.nu": 1,
  "misconfused.org": 1,
  "mypets.ws": 1,
  "myphotos.cc": 1,
  "neat-url.com": 1,
  "office-on-the.net": 1,
  "on-the-web.tv": 1,
  "podzone.net": 1,
  "podzone.org": 1,
  "readmyblog.org": 1,
  "saves-the-whales.com": 1,
  "scrapper-site.net": 1,
  "scrapping.cc": 1,
  "selfip.biz": 1,
  "selfip.com": 1,
  "selfip.info": 1,
  "selfip.net": 1,
  "selfip.org": 1,
  "sells-for-less.com": 1,
  "sells-for-u.com": 1,
  "sells-it.net": 1,
  "sellsyourhome.org": 1,
  "servebbs.com": 1,
  "servebbs.net": 1,
  "servebbs.org": 1,
  "serveftp.net": 1,
  "serveftp.org": 1,
  "servegame.org": 1,
  "shacknet.nu": 1,
  "simple-url.com": 1,
  "space-to-rent.com": 1,
  "stuff-4-sale.org": 1,
  "stuff-4-sale.us": 1,
  "teaches-yoga.com": 1,
  "thruhere.net": 1,
  "traeumtgerade.de": 1,
  "webhop.biz": 1,
  "webhop.info": 1,
  "webhop.net": 1,
  "webhop.org": 1,
  "worse-than.tv": 1,
  "writesthisblog.com": 1,
  "ddnss.de": 1,
  "dyn.ddnss.de": 1,
  "dyndns.ddnss.de": 1,
  "dyndns1.de": 1,
  "dyn-ip24.de": 1,
  "home-webserver.de": 1,
  "dyn.home-webserver.de": 1,
  "myhome-server.de": 1,
  "ddnss.org": 1,
  "definima.net": 1,
  "definima.io": 1,
  "ondigitalocean.app": 1,
  "digitaloceanspaces.com": 2,
  "bci.dnstrace.pro": 1,
  "ddnsfree.com": 1,
  "ddnsgeek.com": 1,
  "giize.com": 1,
  "gleeze.com": 1,
  "kozow.com": 1,
  "loseyourip.com": 1,
  "ooguy.com": 1,
  "theworkpc.com": 1,
  "casacam.net": 1,
  "dynu.net": 1,
  "accesscam.org": 1,
  "camdvr.org": 1,
  "freeddns.org": 1,
  "mywire.org": 1,
  "webredirect.org": 1,
  "myddns.rocks": 1,
  "blogsite.xyz": 1,
  "dynv6.net": 1,
  "e4.cz": 1,
  "easypanel.app": 1,
  "easypanel.host": 1,
  "elementor.cloud": 1,
  "elementor.cool": 1,
  "en-root.fr": 1,
  "mytuleap.com": 1,
  "tuleap-partners.com": 1,
  "encr.app": 1,
  "encoreapi.com": 1,
  "onred.one": 1,
  "staging.onred.one": 1,
  "eu.encoway.cloud": 1,
  "eu.org": 1,
  "al.eu.org": 1,
  "asso.eu.org": 1,
  "at.eu.org": 1,
  "au.eu.org": 1,
  "be.eu.org": 1,
  "bg.eu.org": 1,
  "ca.eu.org": 1,
  "cd.eu.org": 1,
  "ch.eu.org": 1,
  "cn.eu.org": 1,
  "cy.eu.org": 1,
  "cz.eu.org": 1,
  "de.eu.org": 1,
  "dk.eu.org": 1,
  "edu.eu.org": 1,
  "ee.eu.org": 1,
  "es.eu.org": 1,
  "fi.eu.org": 1,
  "fr.eu.org": 1,
  "gr.eu.org": 1,
  "hr.eu.org": 1,
  "hu.eu.org": 1,
  "ie.eu.org": 1,
  "il.eu.org": 1,
  "in.eu.org": 1,
  "int.eu.org": 1,
  "is.eu.org": 1,
  "it.eu.org": 1,
  "jp.eu.org": 1,
  "kr.eu.org": 1,
  "lt.eu.org": 1,
  "lu.eu.org": 1,
  "lv.eu.org": 1,
  "mc.eu.org": 1,
  "me.eu.org": 1,
  "mk.eu.org": 1,
  "mt.eu.org": 1,
  "my.eu.org": 1,
  "net.eu.org": 1,
  "ng.eu.org": 1,
  "nl.eu.org": 1,
  "no.eu.org": 1,
  "nz.eu.org": 1,
  "paris.eu.org": 1,
  "pl.eu.org": 1,
  "pt.eu.org": 1,
  "q-a.eu.org": 1,
  "ro.eu.org": 1,
  "ru.eu.org": 1,
  "se.eu.org": 1,
  "si.eu.org": 1,
  "sk.eu.org": 1,
  "tr.eu.org": 1,
  "uk.eu.org": 1,
  "us.eu.org": 1,
  "eurodir.ru": 1,
  "eu-1.evennode.com": 1,
  "eu-2.evennode.com": 1,
  "eu-3.evennode.com": 1,
  "eu-4.evennode.com": 1,
  "us-1.evennode.com": 1,
  "us-2.evennode.com": 1,
  "us-3.evennode.com": 1,
  "us-4.evennode.com": 1,
  "twmail.cc": 1,
  "twmail.net": 1,
  "twmail.org": 1,
  "mymailer.com.tw": 1,
  "url.tw": 1,
  "onfabrica.com": 1,
  "apps.fbsbx.com": 1,
  "ru.net": 1,
  "adygeya.ru": 1,
  "bashkiria.ru": 1,
  "bir.ru": 1,
  "cbg.ru": 1,
  "com.ru": 1,
  "dagestan.ru": 1,
  "grozny.ru": 1,
  "kalmykia.ru": 1,
  "kustanai.ru": 1,
  "marine.ru": 1,
  "mordovia.ru": 1,
  "msk.ru": 1,
  "mytis.ru": 1,
  "nalchik.ru": 1,
  "nov.ru": 1,
  "pyatigorsk.ru": 1,
  "spb.ru": 1,
  "vladikavkaz.ru": 1,
  "vladimir.ru": 1,
  "abkhazia.su": 1,
  "adygeya.su": 1,
  "aktyubinsk.su": 1,
  "arkhangelsk.su": 1,
  "armenia.su": 1,
  "ashgabad.su": 1,
  "azerbaijan.su": 1,
  "balashov.su": 1,
  "bashkiria.su": 1,
  "bryansk.su": 1,
  "bukhara.su": 1,
  "chimkent.su": 1,
  "dagestan.su": 1,
  "east-kazakhstan.su": 1,
  "exnet.su": 1,
  "georgia.su": 1,
  "grozny.su": 1,
  "ivanovo.su": 1,
  "jambyl.su": 1,
  "kalmykia.su": 1,
  "kaluga.su": 1,
  "karacol.su": 1,
  "karaganda.su": 1,
  "karelia.su": 1,
  "khakassia.su": 1,
  "krasnodar.su": 1,
  "kurgan.su": 1,
  "kustanai.su": 1,
  "lenug.su": 1,
  "mangyshlak.su": 1,
  "mordovia.su": 1,
  "msk.su": 1,
  "murmansk.su": 1,
  "nalchik.su": 1,
  "navoi.su": 1,
  "north-kazakhstan.su": 1,
  "nov.su": 1,
  "obninsk.su": 1,
  "penza.su": 1,
  "pokrovsk.su": 1,
  "sochi.su": 1,
  "spb.su": 1,
  "tashkent.su": 1,
  "termez.su": 1,
  "togliatti.su": 1,
  "troitsk.su": 1,
  "tselinograd.su": 1,
  "tula.su": 1,
  "tuva.su": 1,
  "vladikavkaz.su": 1,
  "vladimir.su": 1,
  "vologda.su": 1,
  "channelsdvr.net": 1,
  "u.channelsdvr.net": 1,
  "edgecompute.app": 1,
  "fastly-edge.com": 1,
  "fastly-terrarium.com": 1,
  "fastlylb.net": 1,
  "map.fastlylb.net": 1,
  "freetls.fastly.net": 1,
  "map.fastly.net": 1,
  "a.prod.fastly.net": 1,
  "global.prod.fastly.net": 1,
  "a.ssl.fastly.net": 1,
  "b.ssl.fastly.net": 1,
  "global.ssl.fastly.net": 1,
  "user.fm": 2,
  "fastvps-server.com": 1,
  "fastvps.host": 1,
  "myfast.host": 1,
  "fastvps.site": 1,
  "myfast.space": 1,
  "fedorainfracloud.org": 1,
  "fedorapeople.org": 1,
  "cloud.fedoraproject.org": 1,
  "app.os.fedoraproject.org": 1,
  "app.os.stg.fedoraproject.org": 1,
  "conn.uk": 1,
  "copro.uk": 1,
  "hosp.uk": 1,
  "mydobiss.com": 1,
  "fh-muenster.io": 1,
  "filegear.me": 1,
  "filegear-au.me": 1,
  "filegear-de.me": 1,
  "filegear-gb.me": 1,
  "filegear-ie.me": 1,
  "filegear-jp.me": 1,
  "filegear-sg.me": 1,
  "firebaseapp.com": 1,
  "fireweb.app": 1,
  "flap.id": 1,
  "onflashdrive.app": 1,
  "fldrv.com": 1,
  "fly.dev": 1,
  "edgeapp.net": 1,
  "shw.io": 1,
  "flynnhosting.net": 1,
  "forgeblocks.com": 1,
  "id.forgerock.io": 1,
  "framer.app": 1,
  "framercanvas.com": 1,
  "framer.media": 1,
  "framer.photos": 1,
  "framer.website": 1,
  "framer.wiki": 1,
  "frusky.de": 2,
  "ravpage.co.il": 1,
  "0e.vc": 1,
  "freebox-os.com": 1,
  "freeboxos.com": 1,
  "fbx-os.fr": 1,
  "fbxos.fr": 1,
  "freebox-os.fr": 1,
  "freeboxos.fr": 1,
  "freedesktop.org": 1,
  "freemyip.com": 1,
  "wien.funkfeuer.at": 1,
  "futurecms.at": 2,
  "ex.futurecms.at": 2,
  "in.futurecms.at": 2,
  "futurehosting.at": 1,
  "futuremailing.at": 1,
  "ex.ortsinfo.at": 2,
  "kunden.ortsinfo.at": 2,
  "statics.cloud": 2,
  "independent-commission.uk": 1,
  "independent-inquest.uk": 1,
  "independent-inquiry.uk": 1,
  "independent-panel.uk": 1,
  "independent-review.uk": 1,
  "public-inquiry.uk": 1,
  "royal-commission.uk": 1,
  "campaign.gov.uk": 1,
  "service.gov.uk": 1,
  "api.gov.uk": 1,
  "gehirn.ne.jp": 1,
  "usercontent.jp": 1,
  "gentapps.com": 1,
  "gentlentapis.com": 1,
  "lab.ms": 1,
  "cdn-edges.net": 1,
  "ghost.io": 1,
  "gsj.bz": 1,
  "githubusercontent.com": 1,
  "githubpreview.dev": 1,
  "github.io": 1,
  "gitlab.io": 1,
  "gitapp.si": 1,
  "gitpage.si": 1,
  "glitch.me": 1,
  "nog.community": 1,
  "co.ro": 1,
  "shop.ro": 1,
  "lolipop.io": 1,
  "angry.jp": 1,
  "babyblue.jp": 1,
  "babymilk.jp": 1,
  "backdrop.jp": 1,
  "bambina.jp": 1,
  "bitter.jp": 1,
  "blush.jp": 1,
  "boo.jp": 1,
  "boy.jp": 1,
  "boyfriend.jp": 1,
  "but.jp": 1,
  "candypop.jp": 1,
  "capoo.jp": 1,
  "catfood.jp": 1,
  "cheap.jp": 1,
  "chicappa.jp": 1,
  "chillout.jp": 1,
  "chips.jp": 1,
  "chowder.jp": 1,
  "chu.jp": 1,
  "ciao.jp": 1,
  "cocotte.jp": 1,
  "coolblog.jp": 1,
  "cranky.jp": 1,
  "cutegirl.jp": 1,
  "daa.jp": 1,
  "deca.jp": 1,
  "deci.jp": 1,
  "digick.jp": 1,
  "egoism.jp": 1,
  "fakefur.jp": 1,
  "fem.jp": 1,
  "flier.jp": 1,
  "floppy.jp": 1,
  "fool.jp": 1,
  "frenchkiss.jp": 1,
  "girlfriend.jp": 1,
  "girly.jp": 1,
  "gloomy.jp": 1,
  "gonna.jp": 1,
  "greater.jp": 1,
  "hacca.jp": 1,
  "heavy.jp": 1,
  "her.jp": 1,
  "hiho.jp": 1,
  "hippy.jp": 1,
  "holy.jp": 1,
  "hungry.jp": 1,
  "icurus.jp": 1,
  "itigo.jp": 1,
  "jellybean.jp": 1,
  "kikirara.jp": 1,
  "kill.jp": 1,
  "kilo.jp": 1,
  "kuron.jp": 1,
  "littlestar.jp": 1,
  "lolipopmc.jp": 1,
  "lolitapunk.jp": 1,
  "lomo.jp": 1,
  "lovepop.jp": 1,
  "lovesick.jp": 1,
  "main.jp": 1,
  "mods.jp": 1,
  "mond.jp": 1,
  "mongolian.jp": 1,
  "moo.jp": 1,
  "namaste.jp": 1,
  "nikita.jp": 1,
  "nobushi.jp": 1,
  "noor.jp": 1,
  "oops.jp": 1,
  "parallel.jp": 1,
  "parasite.jp": 1,
  "pecori.jp": 1,
  "peewee.jp": 1,
  "penne.jp": 1,
  "pepper.jp": 1,
  "perma.jp": 1,
  "pigboat.jp": 1,
  "pinoko.jp": 1,
  "punyu.jp": 1,
  "pupu.jp": 1,
  "pussycat.jp": 1,
  "pya.jp": 1,
  "raindrop.jp": 1,
  "readymade.jp": 1,
  "sadist.jp": 1,
  "schoolbus.jp": 1,
  "secret.jp": 1,
  "staba.jp": 1,
  "stripper.jp": 1,
  "sub.jp": 1,
  "sunnyday.jp": 1,
  "thick.jp": 1,
  "tonkotsu.jp": 1,
  "under.jp": 1,
  "upper.jp": 1,
  "velvet.jp": 1,
  "verse.jp": 1,
  "versus.jp": 1,
  "vivian.jp": 1,
  "watson.jp": 1,
  "weblike.jp": 1,
  "whitesnow.jp": 1,
  "zombie.jp": 1,
  "heteml.net": 1,
  "cloudapps.digital": 1,
  "london.cloudapps.digital": 1,
  "pymnt.uk": 1,
  "homeoffice.gov.uk": 1,
  "ro.im": 1,
  "goip.de": 1,
  "run.app": 1,
  "a.run.app": 1,
  "web.app": 1,
  "0emm.com": 2,
  "appspot.com": 1,
  "r.appspot.com": 2,
  "codespot.com": 1,
  "googleapis.com": 1,
  "googlecode.com": 1,
  "pagespeedmobilizer.com": 1,
  "publishproxy.com": 1,
  "withgoogle.com": 1,
  "withyoutube.com": 1,
  "gateway.dev": 2,
  "cloud.goog": 1,
  "translate.goog": 1,
  "usercontent.goog": 2,
  "cloudfunctions.net": 1,
  "blogspot.ae": 1,
  "blogspot.al": 1,
  "blogspot.am": 1,
  "blogspot.ba": 1,
  "blogspot.be": 1,
  "blogspot.bg": 1,
  "blogspot.bj": 1,
  "blogspot.ca": 1,
  "blogspot.cf": 1,
  "blogspot.ch": 1,
  "blogspot.cl": 1,
  "blogspot.co.at": 1,
  "blogspot.co.id": 1,
  "blogspot.co.il": 1,
  "blogspot.co.ke": 1,
  "blogspot.co.nz": 1,
  "blogspot.co.uk": 1,
  "blogspot.co.za": 1,
  "blogspot.com": 1,
  "blogspot.com.ar": 1,
  "blogspot.com.au": 1,
  "blogspot.com.br": 1,
  "blogspot.com.by": 1,
  "blogspot.com.co": 1,
  "blogspot.com.cy": 1,
  "blogspot.com.ee": 1,
  "blogspot.com.eg": 1,
  "blogspot.com.es": 1,
  "blogspot.com.mt": 1,
  "blogspot.com.ng": 1,
  "blogspot.com.tr": 1,
  "blogspot.com.uy": 1,
  "blogspot.cv": 1,
  "blogspot.cz": 1,
  "blogspot.de": 1,
  "blogspot.dk": 1,
  "blogspot.fi": 1,
  "blogspot.fr": 1,
  "blogspot.gr": 1,
  "blogspot.hk": 1,
  "blogspot.hr": 1,
  "blogspot.hu": 1,
  "blogspot.ie": 1,
  "blogspot.in": 1,
  "blogspot.is": 1,
  "blogspot.it": 1,
  "blogspot.jp": 1,
  "blogspot.kr": 1,
  "blogspot.li": 1,
  "blogspot.lt": 1,
  "blogspot.lu": 1,
  "blogspot.md": 1,
  "blogspot.mk": 1,
  "blogspot.mr": 1,
  "blogspot.mx": 1,
  "blogspot.my": 1,
  "blogspot.nl": 1,
  "blogspot.no": 1,
  "blogspot.pe": 1,
  "blogspot.pt": 1,
  "blogspot.qa": 1,
  "blogspot.re": 1,
  "blogspot.ro": 1,
  "blogspot.rs": 1,
  "blogspot.ru": 1,
  "blogspot.se": 1,
  "blogspot.sg": 1,
  "blogspot.si": 1,
  "blogspot.sk": 1,
  "blogspot.sn": 1,
  "blogspot.td": 1,
  "blogspot.tw": 1,
  "blogspot.ug": 1,
  "blogspot.vn": 1,
  "goupile.fr": 1,
  "gov.nl": 1,
  "awsmppl.com": 1,
  "xn--gnstigbestellen-zvb.de": 1,
  "xn--gnstigliefern-wob.de": 1,
  "fin.ci": 1,
  "free.hr": 1,
  "caa.li": 1,
  "ua.rs": 1,
  "conf.se": 1,
  "hs.zone": 1,
  "hs.run": 1,
  "hashbang.sh": 1,
  "hasura.app": 1,
  "hasura-app.io": 1,
  "pages.it.hs-heilbronn.de": 1,
  "hepforge.org": 1,
  "herokuapp.com": 1,
  "herokussl.com": 1,
  "ravendb.cloud": 1,
  "ravendb.community": 1,
  "ravendb.me": 1,
  "development.run": 1,
  "ravendb.run": 1,
  "homesklep.pl": 1,
  "secaas.hk": 1,
  "hoplix.shop": 1,
  "orx.biz": 1,
  "biz.gl": 1,
  "col.ng": 1,
  "firm.ng": 1,
  "gen.ng": 1,
  "ltd.ng": 1,
  "ngo.ng": 1,
  "edu.scot": 1,
  "sch.so": 1,
  "ie.ua": 1,
  "hostyhosting.io": 1,
  "xn--hkkinen-5wa.fi": 1,
  "moonscale.io": 2,
  "moonscale.net": 1,
  "iki.fi": 1,
  "ibxos.it": 1,
  "iliadboxos.it": 1,
  "impertrixcdn.com": 1,
  "impertrix.com": 1,
  "smushcdn.com": 1,
  "wphostedmail.com": 1,
  "wpmucdn.com": 1,
  "tempurl.host": 1,
  "wpmudev.host": 1,
  "dyn-berlin.de": 1,
  "in-berlin.de": 1,
  "in-brb.de": 1,
  "in-butter.de": 1,
  "in-dsl.de": 1,
  "in-dsl.net": 1,
  "in-dsl.org": 1,
  "in-vpn.de": 1,
  "in-vpn.net": 1,
  "in-vpn.org": 1,
  "biz.at": 1,
  "info.at": 1,
  "info.cx": 1,
  "ac.leg.br": 1,
  "al.leg.br": 1,
  "am.leg.br": 1,
  "ap.leg.br": 1,
  "ba.leg.br": 1,
  "ce.leg.br": 1,
  "df.leg.br": 1,
  "es.leg.br": 1,
  "go.leg.br": 1,
  "ma.leg.br": 1,
  "mg.leg.br": 1,
  "ms.leg.br": 1,
  "mt.leg.br": 1,
  "pa.leg.br": 1,
  "pb.leg.br": 1,
  "pe.leg.br": 1,
  "pi.leg.br": 1,
  "pr.leg.br": 1,
  "rj.leg.br": 1,
  "rn.leg.br": 1,
  "ro.leg.br": 1,
  "rr.leg.br": 1,
  "rs.leg.br": 1,
  "sc.leg.br": 1,
  "se.leg.br": 1,
  "sp.leg.br": 1,
  "to.leg.br": 1,
  "pixolino.com": 1,
  "na4u.ru": 1,
  "iopsys.se": 1,
  "ipifony.net": 1,
  "iservschule.de": 1,
  "mein-iserv.de": 1,
  "schulplattform.de": 1,
  "schulserver.de": 1,
  "test-iserv.de": 1,
  "iserv.dev": 1,
  "iobb.net": 1,
  "mel.cloudlets.com.au": 1,
  "cloud.interhostsolutions.be": 1,
  "mycloud.by": 1,
  "alp1.ae.flow.ch": 1,
  "appengine.flow.ch": 1,
  "es-1.axarnet.cloud": 1,
  "diadem.cloud": 1,
  "vip.jelastic.cloud": 1,
  "jele.cloud": 1,
  "it1.eur.aruba.jenv-aruba.cloud": 1,
  "it1.jenv-aruba.cloud": 1,
  "keliweb.cloud": 1,
  "cs.keliweb.cloud": 1,
  "oxa.cloud": 1,
  "tn.oxa.cloud": 1,
  "uk.oxa.cloud": 1,
  "primetel.cloud": 1,
  "uk.primetel.cloud": 1,
  "ca.reclaim.cloud": 1,
  "uk.reclaim.cloud": 1,
  "us.reclaim.cloud": 1,
  "ch.trendhosting.cloud": 1,
  "de.trendhosting.cloud": 1,
  "jele.club": 1,
  "amscompute.com": 1,
  "dopaas.com": 1,
  "paas.hosted-by-previder.com": 1,
  "rag-cloud.hosteur.com": 1,
  "rag-cloud-ch.hosteur.com": 1,
  "jcloud.ik-server.com": 1,
  "jcloud-ver-jpc.ik-server.com": 1,
  "demo.jelastic.com": 1,
  "kilatiron.com": 1,
  "paas.massivegrid.com": 1,
  "jed.wafaicloud.com": 1,
  "lon.wafaicloud.com": 1,
  "ryd.wafaicloud.com": 1,
  "j.scaleforce.com.cy": 1,
  "jelastic.dogado.eu": 1,
  "fi.cloudplatform.fi": 1,
  "demo.datacenter.fi": 1,
  "paas.datacenter.fi": 1,
  "jele.host": 1,
  "mircloud.host": 1,
  "paas.beebyte.io": 1,
  "sekd1.beebyteapp.io": 1,
  "jele.io": 1,
  "cloud-fr1.unispace.io": 1,
  "jc.neen.it": 1,
  "cloud.jelastic.open.tim.it": 1,
  "jcloud.kz": 1,
  "upaas.kazteleport.kz": 1,
  "cloudjiffy.net": 1,
  "fra1-de.cloudjiffy.net": 1,
  "west1-us.cloudjiffy.net": 1,
  "jls-sto1.elastx.net": 1,
  "jls-sto2.elastx.net": 1,
  "jls-sto3.elastx.net": 1,
  "faststacks.net": 1,
  "fr-1.paas.massivegrid.net": 1,
  "lon-1.paas.massivegrid.net": 1,
  "lon-2.paas.massivegrid.net": 1,
  "ny-1.paas.massivegrid.net": 1,
  "ny-2.paas.massivegrid.net": 1,
  "sg-1.paas.massivegrid.net": 1,
  "jelastic.saveincloud.net": 1,
  "nordeste-idc.saveincloud.net": 1,
  "j.scaleforce.net": 1,
  "jelastic.tsukaeru.net": 1,
  "sdscloud.pl": 1,
  "unicloud.pl": 1,
  "mircloud.ru": 1,
  "jelastic.regruhosting.ru": 1,
  "enscaled.sg": 1,
  "jele.site": 1,
  "jelastic.team": 1,
  "orangecloud.tn": 1,
  "j.layershift.co.uk": 1,
  "phx.enscaled.us": 1,
  "mircloud.us": 1,
  "myjino.ru": 1,
  "hosting.myjino.ru": 2,
  "landing.myjino.ru": 2,
  "spectrum.myjino.ru": 2,
  "vps.myjino.ru": 2,
  "jotelulu.cloud": 1,
  "triton.zone": 2,
  "cns.joyent.com": 2,
  "js.org": 1,
  "kaas.gg": 1,
  "khplay.nl": 1,
  "ktistory.com": 1,
  "kapsi.fi": 1,
  "keymachine.de": 1,
  "kinghost.net": 1,
  "uni5.net": 1,
  "knightpoint.systems": 1,
  "koobin.events": 1,
  "oya.to": 1,
  "kuleuven.cloud": 1,
  "ezproxy.kuleuven.be": 1,
  "co.krd": 1,
  "edu.krd": 1,
  "krellian.net": 1,
  "webthings.io": 1,
  "git-repos.de": 1,
  "lcube-server.de": 1,
  "svn-repos.de": 1,
  "leadpages.co": 1,
  "lpages.co": 1,
  "lpusercontent.com": 1,
  "lelux.site": 1,
  "co.business": 1,
  "co.education": 1,
  "co.events": 1,
  "co.financial": 1,
  "co.network": 1,
  "co.place": 1,
  "co.technology": 1,
  "app.lmpm.com": 1,
  "linkyard.cloud": 1,
  "linkyard-cloud.ch": 1,
  "members.linode.com": 1,
  "nodebalancer.linode.com": 2,
  "linodeobjects.com": 2,
  "ip.linodeusercontent.com": 1,
  "we.bs": 1,
  "user.localcert.dev": 2,
  "localzone.xyz": 1,
  "loginline.app": 1,
  "loginline.dev": 1,
  "loginline.io": 1,
  "loginline.services": 1,
  "loginline.site": 1,
  "servers.run": 1,
  "lohmus.me": 1,
  "krasnik.pl": 1,
  "leczna.pl": 1,
  "lubartow.pl": 1,
  "lublin.pl": 1,
  "poniatowa.pl": 1,
  "swidnik.pl": 1,
  "glug.org.uk": 1,
  "lug.org.uk": 1,
  "lugs.org.uk": 1,
  "barsy.bg": 1,
  "barsy.co.uk": 1,
  "barsyonline.co.uk": 1,
  "barsycenter.com": 1,
  "barsyonline.com": 1,
  "barsy.club": 1,
  "barsy.de": 1,
  "barsy.eu": 1,
  "barsy.in": 1,
  "barsy.info": 1,
  "barsy.io": 1,
  "barsy.me": 1,
  "barsy.menu": 1,
  "barsy.mobi": 1,
  "barsy.net": 1,
  "barsy.online": 1,
  "barsy.org": 1,
  "barsy.pro": 1,
  "barsy.pub": 1,
  "barsy.ro": 1,
  "barsy.shop": 1,
  "barsy.site": 1,
  "barsy.support": 1,
  "barsy.uk": 1,
  "magentosite.cloud": 2,
  "mayfirst.info": 1,
  "mayfirst.org": 1,
  "hb.cldmail.ru": 1,
  "cn.vu": 1,
  "mazeplay.com": 1,
  "mcpe.me": 1,
  "mcdir.me": 1,
  "mcdir.ru": 1,
  "mcpre.ru": 1,
  "vps.mcdir.ru": 1,
  "mediatech.by": 1,
  "mediatech.dev": 1,
  "hra.health": 1,
  "miniserver.com": 1,
  "memset.net": 1,
  "messerli.app": 1,
  "cloud.metacentrum.cz": 2,
  "custom.metacentrum.cz": 1,
  "flt.cloud.muni.cz": 1,
  "usr.cloud.muni.cz": 1,
  "meteorapp.com": 1,
  "eu.meteorapp.com": 1,
  "co.pl": 1,
  "azurecontainer.io": 2,
  "azurewebsites.net": 1,
  "azure-mobile.net": 1,
  "cloudapp.net": 1,
  "azurestaticapps.net": 1,
  "1.azurestaticapps.net": 1,
  "2.azurestaticapps.net": 1,
  "3.azurestaticapps.net": 1,
  "4.azurestaticapps.net": 1,
  "5.azurestaticapps.net": 1,
  "6.azurestaticapps.net": 1,
  "7.azurestaticapps.net": 1,
  "centralus.azurestaticapps.net": 1,
  "eastasia.azurestaticapps.net": 1,
  "eastus2.azurestaticapps.net": 1,
  "westeurope.azurestaticapps.net": 1,
  "westus2.azurestaticapps.net": 1,
  "csx.cc": 1,
  "mintere.site": 1,
  "forte.id": 1,
  "mozilla-iot.org": 1,
  "bmoattachments.org": 1,
  "net.ru": 1,
  "org.ru": 1,
  "pp.ru": 1,
  "hostedpi.com": 1,
  "customer.mythic-beasts.com": 1,
  "caracal.mythic-beasts.com": 1,
  "fentiger.mythic-beasts.com": 1,
  "lynx.mythic-beasts.com": 1,
  "ocelot.mythic-beasts.com": 1,
  "oncilla.mythic-beasts.com": 1,
  "onza.mythic-beasts.com": 1,
  "sphinx.mythic-beasts.com": 1,
  "vs.mythic-beasts.com": 1,
  "x.mythic-beasts.com": 1,
  "yali.mythic-beasts.com": 1,
  "cust.retrosnub.co.uk": 1,
  "ui.nabu.casa": 1,
  "cloud.nospamproxy.com": 1,
  "netlify.app": 1,
  "4u.com": 1,
  "ngrok.app": 1,
  "ngrok-free.app": 1,
  "ngrok.dev": 1,
  "ngrok-free.dev": 1,
  "ngrok.io": 1,
  "ap.ngrok.io": 1,
  "au.ngrok.io": 1,
  "eu.ngrok.io": 1,
  "in.ngrok.io": 1,
  "jp.ngrok.io": 1,
  "sa.ngrok.io": 1,
  "us.ngrok.io": 1,
  "ngrok.pizza": 1,
  "torun.pl": 1,
  "nh-serv.co.uk": 1,
  "nfshost.com": 1,
  "developer.app": 2,
  "noop.app": 1,
  "northflank.app": 2,
  "build.run": 2,
  "code.run": 2,
  "database.run": 2,
  "migration.run": 2,
  "noticeable.news": 1,
  "dnsking.ch": 1,
  "mypi.co": 1,
  "n4t.co": 1,
  "001www.com": 1,
  "ddnslive.com": 1,
  "myiphost.com": 1,
  "forumz.info": 1,
  "16-b.it": 1,
  "32-b.it": 1,
  "64-b.it": 1,
  "soundcast.me": 1,
  "tcp4.me": 1,
  "dnsup.net": 1,
  "hicam.net": 1,
  "now-dns.net": 1,
  "ownip.net": 1,
  "vpndns.net": 1,
  "dynserv.org": 1,
  "now-dns.org": 1,
  "x443.pw": 1,
  "now-dns.top": 1,
  "ntdll.top": 1,
  "freeddns.us": 1,
  "crafting.xyz": 1,
  "zapto.xyz": 1,
  "nsupdate.info": 1,
  "nerdpol.ovh": 1,
  "blogsyte.com": 1,
  "brasilia.me": 1,
  "cable-modem.org": 1,
  "ciscofreak.com": 1,
  "collegefan.org": 1,
  "couchpotatofries.org": 1,
  "damnserver.com": 1,
  "ddns.me": 1,
  "ditchyourip.com": 1,
  "dnsfor.me": 1,
  "dnsiskinky.com": 1,
  "dvrcam.info": 1,
  "dynns.com": 1,
  "eating-organic.net": 1,
  "fantasyleague.cc": 1,
  "geekgalaxy.com": 1,
  "golffan.us": 1,
  "health-carereform.com": 1,
  "homesecuritymac.com": 1,
  "homesecuritypc.com": 1,
  "hopto.me": 1,
  "ilovecollege.info": 1,
  "loginto.me": 1,
  "mlbfan.org": 1,
  "mmafan.biz": 1,
  "myactivedirectory.com": 1,
  "mydissent.net": 1,
  "myeffect.net": 1,
  "mymediapc.net": 1,
  "mypsx.net": 1,
  "mysecuritycamera.com": 1,
  "mysecuritycamera.net": 1,
  "mysecuritycamera.org": 1,
  "net-freaks.com": 1,
  "nflfan.org": 1,
  "nhlfan.net": 1,
  "no-ip.ca": 1,
  "no-ip.co.uk": 1,
  "no-ip.net": 1,
  "noip.us": 1,
  "onthewifi.com": 1,
  "pgafan.net": 1,
  "point2this.com": 1,
  "pointto.us": 1,
  "privatizehealthinsurance.net": 1,
  "quicksytes.com": 1,
  "read-books.org": 1,
  "securitytactics.com": 1,
  "serveexchange.com": 1,
  "servehumour.com": 1,
  "servep2p.com": 1,
  "servesarcasm.com": 1,
  "stufftoread.com": 1,
  "ufcfan.org": 1,
  "unusualperson.com": 1,
  "workisboring.com": 1,
  "3utilities.com": 1,
  "bounceme.net": 1,
  "ddns.net": 1,
  "ddnsking.com": 1,
  "gotdns.ch": 1,
  "hopto.org": 1,
  "myftp.biz": 1,
  "myftp.org": 1,
  "myvnc.com": 1,
  "no-ip.biz": 1,
  "no-ip.info": 1,
  "no-ip.org": 1,
  "noip.me": 1,
  "redirectme.net": 1,
  "servebeer.com": 1,
  "serveblog.net": 1,
  "servecounterstrike.com": 1,
  "serveftp.com": 1,
  "servegame.com": 1,
  "servehalflife.com": 1,
  "servehttp.com": 1,
  "serveirc.com": 1,
  "serveminecraft.net": 1,
  "servemp3.com": 1,
  "servepics.com": 1,
  "servequake.com": 1,
  "sytes.net": 1,
  "webhop.me": 1,
  "zapto.org": 1,
  "stage.nodeart.io": 1,
  "pcloud.host": 1,
  "nyc.mn": 1,
  "static.observableusercontent.com": 1,
  "cya.gg": 1,
  "omg.lol": 1,
  "cloudycluster.net": 1,
  "omniwe.site": 1,
  "123hjemmeside.dk": 1,
  "123hjemmeside.no": 1,
  "123homepage.it": 1,
  "123kotisivu.fi": 1,
  "123minsida.se": 1,
  "123miweb.es": 1,
  "123paginaweb.pt": 1,
  "123sait.ru": 1,
  "123siteweb.fr": 1,
  "123webseite.at": 1,
  "123webseite.de": 1,
  "123website.be": 1,
  "123website.ch": 1,
  "123website.lu": 1,
  "123website.nl": 1,
  "service.one": 1,
  "simplesite.com": 1,
  "simplesite.com.br": 1,
  "simplesite.gr": 1,
  "simplesite.pl": 1,
  "nid.io": 1,
  "opensocial.site": 1,
  "opencraft.hosting": 1,
  "orsites.com": 1,
  "operaunite.com": 1,
  "tech.orange": 1,
  "authgear-staging.com": 1,
  "authgearapps.com": 1,
  "skygearapp.com": 1,
  "outsystemscloud.com": 1,
  "webpaas.ovh.net": 2,
  "hosting.ovh.net": 2,
  "ownprovider.com": 1,
  "own.pm": 1,
  "owo.codes": 2,
  "ox.rs": 1,
  "oy.lc": 1,
  "pgfog.com": 1,
  "pagefrontapp.com": 1,
  "pagexl.com": 1,
  "paywhirl.com": 2,
  "bar0.net": 1,
  "bar1.net": 1,
  "bar2.net": 1,
  "rdv.to": 1,
  "art.pl": 1,
  "gliwice.pl": 1,
  "krakow.pl": 1,
  "poznan.pl": 1,
  "wroc.pl": 1,
  "zakopane.pl": 1,
  "pantheonsite.io": 1,
  "gotpantheon.com": 1,
  "mypep.link": 1,
  "perspecta.cloud": 1,
  "lk3.ru": 1,
  "on-web.fr": 1,
  "bc.platform.sh": 1,
  "ent.platform.sh": 1,
  "eu.platform.sh": 1,
  "us.platform.sh": 1,
  "platformsh.site": 2,
  "tst.site": 2,
  "platter-app.com": 1,
  "platter-app.dev": 1,
  "platterp.us": 1,
  "pdns.page": 1,
  "plesk.page": 1,
  "pleskns.com": 1,
  "dyn53.io": 1,
  "onporter.run": 1,
  "co.bn": 1,
  "postman-echo.com": 1,
  "pstmn.io": 1,
  "mock.pstmn.io": 1,
  "httpbin.org": 1,
  "prequalifyme.today": 1,
  "xen.prgmr.com": 1,
  "priv.at": 1,
  "prvcy.page": 1,
  "dweb.link": 2,
  "protonet.io": 1,
  "chirurgiens-dentistes-en-france.fr": 1,
  "byen.site": 1,
  "pubtls.org": 1,
  "pythonanywhere.com": 1,
  "eu.pythonanywhere.com": 1,
  "qoto.io": 1,
  "qualifioapp.com": 1,
  "ladesk.com": 1,
  "qbuser.com": 1,
  "cloudsite.builders": 1,
  "instances.spawn.cc": 1,
  "instantcloud.cn": 1,
  "ras.ru": 1,
  "qa2.com": 1,
  "qcx.io": 1,
  "sys.qcx.io": 2,
  "dev-myqnapcloud.com": 1,
  "alpha-myqnapcloud.com": 1,
  "myqnapcloud.com": 1,
  "quipelements.com": 2,
  "vapor.cloud": 1,
  "vaporcloud.io": 1,
  "rackmaze.com": 1,
  "rackmaze.net": 1,
  "g.vbrplsbx.io": 1,
  "on-k3s.io": 2,
  "on-rancher.cloud": 2,
  "on-rio.io": 2,
  "readthedocs.io": 1,
  "rhcloud.com": 1,
  "app.render.com": 1,
  "onrender.com": 1,
  "firewalledreplit.co": 1,
  "id.firewalledreplit.co": 1,
  "repl.co": 1,
  "id.repl.co": 1,
  "repl.run": 1,
  "resindevice.io": 1,
  "devices.resinstaging.io": 1,
  "hzc.io": 1,
  "wellbeingzone.eu": 1,
  "wellbeingzone.co.uk": 1,
  "adimo.co.uk": 1,
  "itcouldbewor.se": 1,
  "git-pages.rit.edu": 1,
  "rocky.page": 1,
  "xn--90amc.xn--p1acf": 1,
  "xn--j1aef.xn--p1acf": 1,
  "xn--j1ael8b.xn--p1acf": 1,
  "xn--h1ahn.xn--p1acf": 1,
  "xn--j1adp.xn--p1acf": 1,
  "xn--c1avg.xn--p1acf": 1,
  "xn--80aaa0cvac.xn--p1acf": 1,
  "xn--h1aliz.xn--p1acf": 1,
  "xn--90a1af.xn--p1acf": 1,
  "xn--41a.xn--p1acf": 1,
  "180r.com": 1,
  "dojin.com": 1,
  "sakuratan.com": 1,
  "sakuraweb.com": 1,
  "x0.com": 1,
  "2-d.jp": 1,
  "bona.jp": 1,
  "crap.jp": 1,
  "daynight.jp": 1,
  "eek.jp": 1,
  "flop.jp": 1,
  "halfmoon.jp": 1,
  "jeez.jp": 1,
  "matrix.jp": 1,
  "mimoza.jp": 1,
  "ivory.ne.jp": 1,
  "mail-box.ne.jp": 1,
  "mints.ne.jp": 1,
  "mokuren.ne.jp": 1,
  "opal.ne.jp": 1,
  "sakura.ne.jp": 1,
  "sumomo.ne.jp": 1,
  "topaz.ne.jp": 1,
  "netgamers.jp": 1,
  "nyanta.jp": 1,
  "o0o0.jp": 1,
  "rdy.jp": 1,
  "rgr.jp": 1,
  "rulez.jp": 1,
  "s3.isk01.sakurastorage.jp": 1,
  "s3.isk02.sakurastorage.jp": 1,
  "saloon.jp": 1,
  "sblo.jp": 1,
  "skr.jp": 1,
  "tank.jp": 1,
  "uh-oh.jp": 1,
  "undo.jp": 1,
  "rs.webaccel.jp": 1,
  "user.webaccel.jp": 1,
  "websozai.jp": 1,
  "xii.jp": 1,
  "squares.net": 1,
  "jpn.org": 1,
  "kirara.st": 1,
  "x0.to": 1,
  "from.tv": 1,
  "sakura.tv": 1,
  "builder.code.com": 2,
  "dev-builder.code.com": 2,
  "stg-builder.code.com": 2,
  "sandcats.io": 1,
  "logoip.de": 1,
  "logoip.com": 1,
  "fr-par-1.baremetal.scw.cloud": 1,
  "fr-par-2.baremetal.scw.cloud": 1,
  "nl-ams-1.baremetal.scw.cloud": 1,
  "fnc.fr-par.scw.cloud": 1,
  "functions.fnc.fr-par.scw.cloud": 1,
  "k8s.fr-par.scw.cloud": 1,
  "nodes.k8s.fr-par.scw.cloud": 1,
  "s3.fr-par.scw.cloud": 1,
  "s3-website.fr-par.scw.cloud": 1,
  "whm.fr-par.scw.cloud": 1,
  "priv.instances.scw.cloud": 1,
  "pub.instances.scw.cloud": 1,
  "k8s.scw.cloud": 1,
  "k8s.nl-ams.scw.cloud": 1,
  "nodes.k8s.nl-ams.scw.cloud": 1,
  "s3.nl-ams.scw.cloud": 1,
  "s3-website.nl-ams.scw.cloud": 1,
  "whm.nl-ams.scw.cloud": 1,
  "k8s.pl-waw.scw.cloud": 1,
  "nodes.k8s.pl-waw.scw.cloud": 1,
  "s3.pl-waw.scw.cloud": 1,
  "s3-website.pl-waw.scw.cloud": 1,
  "scalebook.scw.cloud": 1,
  "smartlabeling.scw.cloud": 1,
  "dedibox.fr": 1,
  "schokokeks.net": 1,
  "gov.scot": 1,
  "service.gov.scot": 1,
  "scrysec.com": 1,
  "firewall-gateway.com": 1,
  "firewall-gateway.de": 1,
  "my-gateway.de": 1,
  "my-router.de": 1,
  "spdns.de": 1,
  "spdns.eu": 1,
  "firewall-gateway.net": 1,
  "my-firewall.org": 1,
  "myfirewall.org": 1,
  "spdns.org": 1,
  "seidat.net": 1,
  "sellfy.store": 1,
  "senseering.net": 1,
  "minisite.ms": 1,
  "magnet.page": 1,
  "biz.ua": 1,
  "co.ua": 1,
  "pp.ua": 1,
  "shiftcrypto.dev": 1,
  "shiftcrypto.io": 1,
  "shiftedit.io": 1,
  "myshopblocks.com": 1,
  "myshopify.com": 1,
  "shopitsite.com": 1,
  "shopware.store": 1,
  "mo-siemens.io": 1,
  "1kapp.com": 1,
  "appchizi.com": 1,
  "applinzi.com": 1,
  "sinaapp.com": 1,
  "vipsinaapp.com": 1,
  "siteleaf.net": 1,
  "bounty-full.com": 1,
  "alpha.bounty-full.com": 1,
  "beta.bounty-full.com": 1,
  "aeroport.fr": 1,
  "avocat.fr": 1,
  "chambagri.fr": 1,
  "chirurgiens-dentistes.fr": 1,
  "experts-comptables.fr": 1,
  "medecin.fr": 1,
  "notaires.fr": 1,
  "pharmacien.fr": 1,
  "port.fr": 1,
  "veterinaire.fr": 1,
  "small-web.org": 1,
  "vp4.me": 1,
  "snowflake.app": 1,
  "privatelink.snowflake.app": 1,
  "streamlit.app": 1,
  "streamlitapp.com": 1,
  "try-snowplow.com": 1,
  "srht.site": 1,
  "stackhero-network.com": 1,
  "musician.io": 1,
  "novecore.site": 1,
  "static.land": 1,
  "dev.static.land": 1,
  "sites.static.land": 1,
  "storebase.store": 1,
  "vps-host.net": 1,
  "atl.jelastic.vps-host.net": 1,
  "njs.jelastic.vps-host.net": 1,
  "ric.jelastic.vps-host.net": 1,
  "playstation-cloud.com": 1,
  "apps.lair.io": 1,
  "stolos.io": 2,
  "spacekit.io": 1,
  "customer.speedpartner.de": 1,
  "myspreadshop.at": 1,
  "myspreadshop.com.au": 1,
  "myspreadshop.be": 1,
  "myspreadshop.ca": 1,
  "myspreadshop.ch": 1,
  "myspreadshop.com": 1,
  "myspreadshop.de": 1,
  "myspreadshop.dk": 1,
  "myspreadshop.es": 1,
  "myspreadshop.fi": 1,
  "myspreadshop.fr": 1,
  "myspreadshop.ie": 1,
  "myspreadshop.it": 1,
  "myspreadshop.net": 1,
  "myspreadshop.nl": 1,
  "myspreadshop.no": 1,
  "myspreadshop.pl": 1,
  "myspreadshop.se": 1,
  "myspreadshop.co.uk": 1,
  "api.stdlib.com": 1,
  "storipress.app": 1,
  "storj.farm": 1,
  "utwente.io": 1,
  "soc.srcf.net": 1,
  "user.srcf.net": 1,
  "temp-dns.com": 1,
  "supabase.co": 1,
  "supabase.in": 1,
  "supabase.net": 1,
  "su.paba.se": 1,
  "s5y.io": 2,
  "sensiosite.cloud": 2,
  "syncloud.it": 1,
  "dscloud.biz": 1,
  "direct.quickconnect.cn": 1,
  "dsmynas.com": 1,
  "familyds.com": 1,
  "diskstation.me": 1,
  "dscloud.me": 1,
  "i234.me": 1,
  "myds.me": 1,
  "synology.me": 1,
  "dscloud.mobi": 1,
  "dsmynas.net": 1,
  "familyds.net": 1,
  "dsmynas.org": 1,
  "familyds.org": 1,
  "vpnplus.to": 1,
  "direct.quickconnect.to": 1,
  "tabitorder.co.il": 1,
  "mytabit.co.il": 1,
  "mytabit.com": 1,
  "taifun-dns.de": 1,
  "beta.tailscale.net": 1,
  "ts.net": 1,
  "gda.pl": 1,
  "gdansk.pl": 1,
  "gdynia.pl": 1,
  "med.pl": 1,
  "sopot.pl": 1,
  "site.tb-hosting.com": 1,
  "edugit.io": 1,
  "s3.teckids.org": 1,
  "telebit.app": 1,
  "telebit.io": 1,
  "telebit.xyz": 2,
  "firenet.ch": 2,
  "svc.firenet.ch": 2,
  "reservd.com": 1,
  "thingdustdata.com": 1,
  "cust.dev.thingdust.io": 1,
  "cust.disrec.thingdust.io": 1,
  "cust.prod.thingdust.io": 1,
  "cust.testing.thingdust.io": 1,
  "reservd.dev.thingdust.io": 1,
  "reservd.disrec.thingdust.io": 1,
  "reservd.testing.thingdust.io": 1,
  "tickets.io": 1,
  "arvo.network": 1,
  "azimuth.network": 1,
  "tlon.network": 1,
  "torproject.net": 1,
  "pages.torproject.net": 1,
  "bloxcms.com": 1,
  "townnews-staging.com": 1,
  "12hp.at": 1,
  "2ix.at": 1,
  "4lima.at": 1,
  "lima-city.at": 1,
  "12hp.ch": 1,
  "2ix.ch": 1,
  "4lima.ch": 1,
  "lima-city.ch": 1,
  "trafficplex.cloud": 1,
  "de.cool": 1,
  "12hp.de": 1,
  "2ix.de": 1,
  "4lima.de": 1,
  "lima-city.de": 1,
  "1337.pictures": 1,
  "clan.rip": 1,
  "lima-city.rocks": 1,
  "webspace.rocks": 1,
  "lima.zone": 1,
  "transurl.be": 2,
  "transurl.eu": 2,
  "transurl.nl": 2,
  "site.transip.me": 1,
  "tuxfamily.org": 1,
  "dd-dns.de": 1,
  "diskstation.eu": 1,
  "diskstation.org": 1,
  "dray-dns.de": 1,
  "draydns.de": 1,
  "dyn-vpn.de": 1,
  "dynvpn.de": 1,
  "mein-vigor.de": 1,
  "my-vigor.de": 1,
  "my-wan.de": 1,
  "syno-ds.de": 1,
  "synology-diskstation.de": 1,
  "synology-ds.de": 1,
  "typedream.app": 1,
  "pro.typeform.com": 1,
  "uber.space": 1,
  "uberspace.de": 2,
  "hk.com": 1,
  "hk.org": 1,
  "ltd.hk": 1,
  "inc.hk": 1,
  "it.com": 1,
  "name.pm": 1,
  "sch.tf": 1,
  "biz.wf": 1,
  "sch.wf": 1,
  "org.yt": 1,
  "virtualuser.de": 1,
  "virtual-user.de": 1,
  "upli.io": 1,
  "urown.cloud": 1,
  "dnsupdate.info": 1,
  "lib.de.us": 1,
  "2038.io": 1,
  "vercel.app": 1,
  "vercel.dev": 1,
  "now.sh": 1,
  "router.management": 1,
  "v-info.info": 1,
  "voorloper.cloud": 1,
  "neko.am": 1,
  "nyaa.am": 1,
  "be.ax": 1,
  "cat.ax": 1,
  "es.ax": 1,
  "eu.ax": 1,
  "gg.ax": 1,
  "mc.ax": 1,
  "us.ax": 1,
  "xy.ax": 1,
  "nl.ci": 1,
  "xx.gl": 1,
  "app.gp": 1,
  "blog.gt": 1,
  "de.gt": 1,
  "to.gt": 1,
  "be.gy": 1,
  "cc.hn": 1,
  "blog.kg": 1,
  "io.kg": 1,
  "jp.kg": 1,
  "tv.kg": 1,
  "uk.kg": 1,
  "us.kg": 1,
  "de.ls": 1,
  "at.md": 1,
  "de.md": 1,
  "jp.md": 1,
  "to.md": 1,
  "indie.porn": 1,
  "vxl.sh": 1,
  "ch.tc": 1,
  "me.tc": 1,
  "we.tc": 1,
  "nyan.to": 1,
  "at.vg": 1,
  "blog.vu": 1,
  "dev.vu": 1,
  "me.vu": 1,
  "v.ua": 1,
  "vultrobjects.com": 2,
  "wafflecell.com": 1,
  "webhare.dev": 2,
  "reserve-online.net": 1,
  "reserve-online.com": 1,
  "bookonline.app": 1,
  "hotelwithflight.com": 1,
  "wedeploy.io": 1,
  "wedeploy.me": 1,
  "wedeploy.sh": 1,
  "remotewd.com": 1,
  "pages.wiardweb.com": 1,
  "wmflabs.org": 1,
  "toolforge.org": 1,
  "wmcloud.org": 1,
  "panel.gg": 1,
  "daemon.panel.gg": 1,
  "messwithdns.com": 1,
  "woltlab-demo.com": 1,
  "myforum.community": 1,
  "community-pro.de": 1,
  "diskussionsbereich.de": 1,
  "community-pro.net": 1,
  "meinforum.net": 1,
  "affinitylottery.org.uk": 1,
  "raffleentry.org.uk": 1,
  "weeklylottery.org.uk": 1,
  "wpenginepowered.com": 1,
  "js.wpenginepowered.com": 1,
  "wixsite.com": 1,
  "editorx.io": 1,
  "wixstudio.io": 1,
  "wix.run": 1,
  "half.host": 1,
  "xnbay.com": 1,
  "u2.xnbay.com": 1,
  "u2-local.xnbay.com": 1,
  "cistron.nl": 1,
  "demon.nl": 1,
  "xs4all.space": 1,
  "yandexcloud.net": 1,
  "storage.yandexcloud.net": 1,
  "website.yandexcloud.net": 1,
  "official.academy": 1,
  "yolasite.com": 1,
  "ybo.faith": 1,
  "yombo.me": 1,
  "homelink.one": 1,
  "ybo.party": 1,
  "ybo.review": 1,
  "ybo.science": 1,
  "ybo.trade": 1,
  "ynh.fr": 1,
  "nohost.me": 1,
  "noho.st": 1,
  "za.net": 1,
  "za.org": 1,
  "bss.design": 1,
  "basicserver.io": 1,
  "virtualserver.io": 1,
  "enterprisecloud.nu": 1
}

/***/ }),

/***/ "./core/data/resources.js":
/*!********************************!*\
  !*** ./core/data/resources.js ***!
  \********************************/
/***/ ((__unused_webpack_module, exports) => {

exports.resources = {
  "blank-text": "data:text/plain,",
  "blank-css": "data:text/css,",
  "blank-js": "data:application/javascript,",
  "blank-html": "data:text/html,<!DOCTYPE html><html><head></head><body></body></html>",
  "blank-mp3": "data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjIwLjEwMAAAAAAAAAAAAAAA//tUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAAGAAADAABgYGBgYGBgYGBgYGBgYGBggICAgICAgICAgICAgICAgICgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4P////////////////////8AAAAATGF2YzU4LjM1AAAAAAAAAAAAAAAAJAYAAAAAAAAAAwDVxttG//sUZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUZB4P8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUZDwP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUZFoP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUZHgP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUZJYP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",
  "blank-mp4": "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAuJtZGF0AAACrwYF//+r3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE2MCByMzAxMU0gY2RlOWE5MyAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMjAgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0xIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDM6MHgxMTMgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MCB0cmVsbGlzPTEgOHg4ZGN0PTEgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0yIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAACNliIQAK//+9dvzLK5umjbe9jc2CT9EPcfnoOYC2tjtP+go4QAAAwRtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAAKAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACLnRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAZAAAADgAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAACgAAAAAAAEAAAAAAaZtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAADIAAAACAFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAFRbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABEXN0YmwAAACtc3RzZAAAAAAAAAABAAAAnWF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAZAA4AEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAA3YXZjQwFkAAr/4QAaZ2QACvNlHJ42JwEQAAADABAAAAMDIPEiWWABAAZo6+PLIsD8+PgAAAAAEHBhc3AAAAABAAAAAQAAABhzdHRzAAAAAAAAAAEAAAABAAACAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAALaAAAAAQAAABRzdGNvAAAAAAAAAAEAAAAwAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1OC40NS4xMDA=",
  "1x1-transparent-gif": "data:image/gif;base64,R0lGODlhAQABAIABAAAAAP///yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",
  "2x2-transparent-png": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAC0lEQVQI12NgQAcAABIAAe+JVKQAAAAASUVORK5CYII=",
  "3x2-transparent-png": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAC0lEQVQI12NgwAUAABoAASRETuUAAAAASUVORK5CYII=",
  "32x32-transparent-png": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGklEQVRYw+3BAQEAAACCIP+vbkhAAQAAAO8GECAAAZf3V9cAAAAASUVORK5CYII="
}

/***/ }),

/***/ "./core/lib/analytics.js":
/*!*******************************!*\
  !*** ./core/lib/analytics.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_210938__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



const {Prefs} = __nested_webpack_require_210938__(/*! prefs */ "./sdk/api/prefs.js");

const {MILLIS_IN_DAY} = __nested_webpack_require_210938__(/*! ./time */ "./core/lib/time.js");

/**
 * Converts a version string into a `Date` object with minute-level precision.
 *
 * @param {string} version The version string in `YYYYMMDD[HH[MM]]` format or
 *   just the value `"0"`.
 *
 * @returns {Date} A `Date` object. If the value of `version` is `"0"`, the
 *   returned value represents the Unix epoch.
 */
function versionToDate(version) {
  if (version == "0") {
    return new Date(0);
  }

  let year = version.substring(0, 4);
  let month = version.substring(4, 6);
  let date = version.substring(6, 8);

  let hours = version.substring(8, 10) || "00";
  let minutes = version.substring(10, 12) || "00";

  // The input is nearly a valid ISO 8601 timestamp, except for the hyphens,
  // the colon, and the special characters T and Z. We can use the timestamp
  // string version of the Date constructor directly. Alternatively, we could
  // use Date.UTC(), but that would require some adjustment to the values
  // (e.g. the month must be 0-based).
  return new Date(`${year}-${month}-${date}T${hours}:${minutes}Z`);
}

/**
 * Strips the value of the `firstVersion` parameter down to either `YYYYMMDD`,
 * `YYYYMM`, or `YYYY` depending on its distance from the value of the
 * `currentVersion` parameter.
 *
 * @param {string} firstVersion A version string in `YYYYMMDD[HH[MM]]` format
 *   with an optional `"-E"` suffix or just `"0"` or `"0-E"`.
 * @param {string} currentVersion A version string in `YYYYMMDD[HH[MM]]` format
 *   or just `"0"`.
 *
 * @returns {?string}
 */
function stripFirstVersion(firstVersion, currentVersion) {
  let eFlag = firstVersion.endsWith("-E");
  if (eFlag) {
    firstVersion = firstVersion.slice(0, -2);
  }

  try {
    let firstDate = versionToDate(firstVersion);
    let currentDate = versionToDate(currentVersion);

    if (currentDate - firstDate > 365 * MILLIS_IN_DAY) {
      firstVersion = firstVersion.substring(0, 4);
    }
    else if (currentDate - firstDate > 30 * MILLIS_IN_DAY) {
      firstVersion = firstVersion.substring(0, 6);
    }
    else {
      firstVersion = firstVersion.substring(0, 8);
    }
  }
  catch (error) {
    return null;
  }

  if (eFlag) {
    firstVersion += "-E";
  }

  return firstVersion;
}

/**
 * Checks whether this is a fresh installation.
 * @returns {boolean}
 */
function isFreshInstall() {
  return !("data" in Prefs.notificationdata);
}

/**
 * `{@link module:analytics.analytics analytics}` implementation.
 */
class Analytics {
  /**
   * @hideconstructor
   */
  constructor() {
  }

  /**
   * Checks whether the given URL is trusted for analytics purposes based on
   * the value of the `analytics.trustedHosts` preference.
   *
   * @param {string} url The URL.
   *
   * @returns {boolean} Whether the URL is trusted.
   */
  isTrusted(url) {
    let {trustedHosts} = Prefs.analytics || {};
    if (Array.isArray(trustedHosts)) {
      try {
        return trustedHosts.includes(new URL(url).host);
      }
      catch (error) {
      }
    }

    return false;
  }

  /**
   * Returns a string indicating the version of the first ever downloaded
   * resource (as recorded by
   * `{@link module:analytics~Analytics#recordVersion recordVersion()}`), for
   * the purpose of cohort analysis.
   *
   * For privacy reasons, the original value is stripped down to either
   * `YYYYMMDD`, `YYYYMM`, or `YYYY` depending on its age. An `-E` suffix is
   * appended to the original value if it was recorded on an existing
   * installation.
   *
   * @returns {?string} A string indicating the version of the first ever
   *   downloaded resource, or `"0"` or `"0-E"` if there is no data, or `null`
   *   in case of a parsing error.
   */
  getFirstVersion() {
    let {analytics} = Prefs;
    if (analytics) {
      let {firstVersion = "0", currentVersion = "0"} = analytics.data || {};
      let strippedFirstVersion = stripFirstVersion(firstVersion,
                                                   currentVersion);
      if (strippedFirstVersion) {
        if (strippedFirstVersion == "0" && !isFreshInstall()) {
          strippedFirstVersion = "0-E";
        }

        return strippedFirstVersion;
      }
    }

    return null;
  }

  /**
   * Records the version of a downloaded resource for the purpose of cohort
   * analysis.
   *
   * The value of the `analytics` preference must be set at least to an
   * empty object, otherwise nothing is ever recorded and
   * `{@link module:analytics~Analytics#getFirstVersion getFirstVersion()}`
   * always returns `null`.
   *
   * @param {string} version The version, in `YYYYMMDD[HH[MM]]` format.
   */
  recordVersion(version) {
    if (!/^(\d{8}|\d{10}|\d{12})$/.test(version)) {
      return;
    }

    let {analytics} = Prefs;
    if (analytics) {
      if (!analytics.data) {
        analytics.data = {};
      }

      let {data} = analytics;

      data.currentVersion = version;

      if (typeof data.firstVersion == "undefined") {
        // If this is not a new installation, set the -E flag.
        if (!isFreshInstall()) {
          version += "-E";
        }

        data.firstVersion = version;
      }

      // JSON values aren't saved unless they are assigned a different object.
      Prefs.analytics = JSON.parse(JSON.stringify(analytics));
    }
  }
}

/**
 * Implements data analytics functions.
 * @type {module:analytics~Analytics}
 */
exports.analytics = new Analytics();


/***/ }),

/***/ "./core/lib/caching.js":
/*!*****************************!*\
  !*** ./core/lib/caching.js ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * A `Cache` object represents a cache of arbitrary data.
 * @package
 */
exports.Cache = class Cache extends Map {
  /**
   * Creates a cache.
   * @param {number} capacity The maximum number of entries that can exist in
   *   the cache.
   */
  constructor(capacity) {
    // Note: This check works for non-number values.
    if (!(capacity >= 1)) {
      throw new Error("capacity must be a positive number.");
    }

    super();
    this._capacity = capacity;
  }

  /**
   * Writes an entry to the cache.
   *
   * If the cache has reached the specified maximum number of entries, all the
   * old entries are cleared first.
   *
   * @param {?*} key The key for the entry.
   * @param {?*} value The value of the entry.
   */
  set(key, value) {
    // To prevent logical errors, neither key nor value is allowed to be
    // undefined.
    if (typeof key == "undefined") {
      throw new Error("key must not be undefined.");
    }

    if (typeof value == "undefined") {
      throw new Error("value must not be undefined.");
    }

    if (this.size == this._capacity && !this.has(key)) {
      this.clear();
    }

    super.set(key, value);
  }
};


/***/ }),

/***/ "./core/lib/contentTypes.js":
/*!**********************************!*\
  !*** ./core/lib/contentTypes.js ***!
  \**********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



let contentTypes =
/**
 * Content types for request blocking and allowing (allowlisting).
 *
 * There are two kinds of content types: resource types, and special
 * (non-resource) types.
 *
 * Resource types include web resources like scripts, images, and so on.
 *
 * Special types include filter options for popup blocking and CSP header
 * injection as well as flags for allowing documents.
 *
 * By default a filter matches any resource type, but if a filter has an
 * explicit resource type, special option, or allowing flag, like
 * `$script`, `$popup`, or `$elemhide`, then it matches only the given type,
 * option, or flag.
 *
 * @type {Object}
 *
 * @public
 */
exports.contentTypes = {
  // Types of web resources.
  OTHER: 1,
  SCRIPT: 2,
  IMAGE: 4,
  STYLESHEET: 8,
  OBJECT: 16,
  SUBDOCUMENT: 32,
  WEBSOCKET: 128,
  WEBRTC: 256,
  WEBBUNDLE: 512,
  PING: 1024,
  XMLHTTPREQUEST: 2048, // 1 << 11

  MEDIA: 16384,
  FONT: 32768, // 1 << 15

  // Special filter options.
  POPUP: 1 << 24,
  CSP: 1 << 25,
  HEADER: 1 << 26,

  // Allowing flags.
  DOCUMENT: 1 << 27,
  GENERICBLOCK: 1 << 28,
  ELEMHIDE: 1 << 29,
  GENERICHIDE: 1 << 30
};

// Backwards compatibility.
contentTypes.BACKGROUND = contentTypes.IMAGE;
contentTypes.XBL = contentTypes.OTHER;
contentTypes.DTD = contentTypes.OTHER;

const RESOURCE_TYPES =
/**
 * Bitmask for resource types like `$script`, `$image`, `$stylesheet`, and so
 * on.
 *
 * If a filter has no explicit content type, it applies to all resource types
 * (but not to any {@link module:contentTypes.SPECIAL_TYPES special types}).
 *
 * @const {number}
 *
 * @package
 */
// The first 24 bits are reserved for resource types like "script", "image",
// and so on.
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/ResourceType
exports.RESOURCE_TYPES = (1 << 24) - 1;

const SPECIAL_TYPES = ~RESOURCE_TYPES & (1 << 31) - 1;
/**
 * Bitmask for special "types" (options and flags) like `$csp`, `$elemhide`,
 * and so on.
 *
 * @const {number}
 *
 * @package
 */
exports.SPECIAL_TYPES = SPECIAL_TYPES;

/**
 * Bitmask for "types" that match against request context more than
 * actual content type. When matching against context types, you
 * should also include the request's resource type.
 *
 * @const {number}
 *
 * @package
 */
const CONTEXT_TYPES = contentTypes.HEADER | contentTypes.CSP;
exports.CONTEXT_TYPES = CONTEXT_TYPES;

/**
 * Bitmask for "types" (flags) that are for exception rules only, like
 * `$document`, `$elemhide`, and so on.
 *
 * @const {number}
 *
 * @package
 */
exports.ALLOWING_TYPES = contentTypes.DOCUMENT |
                         contentTypes.GENERICBLOCK |
                         contentTypes.ELEMHIDE |
                         contentTypes.GENERICHIDE;

/**
 * Yields individual types from a filter's type mask.
 *
 * @param {number} contentType A filter's type mask.
 * @param {number} [selection] Which types to yield.
 *
 * @generator
 * @yields {number}
 *
 * @package
 */
exports.enumerateTypes = function* enumerateTypes(contentType, selection = ~0) {
  for (let mask = contentType & selection, bitIndex = 0;
    mask != 0; mask >>>= 1, bitIndex++) {
    if ((mask & 1) != 0) {
      // Note: The zero-fill right shift by zero is necessary for dropping the
      // sign.
      yield 1 << bitIndex >>> 0;
    }
  }
};


/***/ }),

/***/ "./core/lib/dnr/index.js":
/*!*******************************!*\
  !*** ./core/lib/dnr/index.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_223798__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/** @module */

const {Pattern} = __nested_webpack_require_223798__(/*! ../patterns */ "./core/lib/patterns.js");
const {parseDomains} = __nested_webpack_require_223798__(/*! ../url */ "./core/lib/url.js");
const {contentTypes, RESOURCE_TYPES} = __nested_webpack_require_223798__(/*! ../contentTypes */ "./core/lib/contentTypes.js");
const {
  generateCSPRules,
  generateAllowingRules,
  generateRedirectRules,
  generateBlockingRules,
  validateRule
} = __nested_webpack_require_223798__(/*! ./rules */ "./core/lib/dnr/rules.js");
const {parse, FilterParsingError} = __nested_webpack_require_223798__(/*! ../filters */ "./core/lib/filters/index.js");

/**
 * @typedef {Object} ConverterOptions
 * @property {function} isRegexSupported a sync/async method to check if a
 *  generic regular expression is compatible with the engine.
 * @property {function} modifyRule a sync method to modify a DNR rule if needed.
 */

/**
 * Returns a callback bound to the given options.
 * @param {ConverterOptions} options in Mv3 Web extensions this would be
 *  `chrome.declarativeNetRequest.isRegexSupported`, so that it's possible to
 *  pass `chrome.declarativeNetRequest` directly as option.
 * @returns {function}
 */
exports.createConverter = options => convert.bind({
  ...options,
  // ensure a callback to verify RegExp when needed
  // By default regex are not supported.
  isRegexSupported: options.isRegexSupported || (() => false),
  // ensure a callback to modify a DNR rule when needed
  modifyRule: options.modifyRule || ((rule, context) => rule)
});

/**
 * @typedef {Object} Rule see https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-Rule
 * @property {object} action see https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleAction
 * @property {object} condition see https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleCondition
 * @property {number} id a unique identifier for this rule
 * @property {number?} priority optional priority of the filter
 */

/**
 * Returns an array with DNR Rules if the text is network related, or an Error
 * if no suitable rule can be created.
 * @param {string} text the filter text to convert or the generated error.
 * @returns {Rule[]|FilterParsingError}
 */
function convert(text) {
  const result = parse(text);

  if (result instanceof FilterParsingError) {
    return result;
  }

  return asDNR.call(this, result);
}

/** Convert a parsed filter to a DeclarativeNetRequest
 *
 * To work properly this function must be bound to an object that
 * has a method `isRegexSupported` that will return whether the RegExp
 * passed as argument is valid or not for DNR. This is necessary as
 * they have to be RE2 expection and this syntax isn't supported by native
 * JavaScript. There is a (native) node module or the Chrome WebExtension
 * API. `createConverter` will provide a default function that always
 * return true.
 *
 * @param {module:filters/index~ParsedFilter} parsedFilter The parsed filter
 *   object.
 * @return {Rule[]|Error}
 */
function asDNR(parsedFilter) {
  let {
    blocking,
    text,
    regexpSource,
    contentType,
    matchCase,
    domains,
    thirdParty,
    sitekeys,
    header,
    rewrite,
    csp
  } = parsedFilter;

  // Sitekey aren't currently handled with DeclarativeNetRequest
  if (sitekeys || header) {
    return new FilterParsingError("filter_unknown_option",
                                  {
                                    option: sitekeys ? "sitekey" : "header",
                                    text
                                  });
  }

  try {
    const urlPattern = new Pattern(regexpSource, matchCase);
    let {pattern: urlFilter} = urlPattern;
    let checkValidRegExp = true;
    let hostname;

    matchCase = urlPattern.matchCase;

    if (urlFilter) {
      // We need to split out the hostname part (if any) of the filter, then
      // decide if it can be matched as lowercase or not.
      let match = /^(\|\||[a-zA-Z]*:\/\/)([^*^?/|]*)(.*)$/.exec(urlFilter);
      if (match) {
        hostname = match[2].toLowerCase();
        urlFilter = match[1] + hostname + match[3];
      }

      // The declarativeNetRequest API does not like the urlFilter to have a
      // redundant ||* prefix, so let's strip that now.
      if (urlFilter.startsWith("||*")) {
        // A pattern beginning with `||*` isn't allowed, and `*`
        // should be used instead. So let's remove the `||`
        // See https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#type-RuleCondition
        urlFilter = urlFilter.substr(2);
      }
    }
    else if (urlPattern.regexp) {
      checkValidRegExp = this.isRegexSupported({
        regex: urlPattern.regexp.source,
        isCaseSensitive: matchCase
      });
    }

    if (!checkValidRegExp) {
      return new FilterParsingError("filter_invalid_regexp",
                                    {
                                      regexp: urlPattern.regexp.source,
                                      text
                                    });
    }

    const filter = {
      blocking,
      regexp: urlPattern.regexp,
      contentType: contentType || RESOURCE_TYPES,
      thirdParty,
      rewrite,
      csp,
      domains: domains === null ? null : parseDomains(
        domains.toLowerCase(), "|")
    };

    let result;
    if (contentType & contentTypes.CSP) {
      result = generateCSPRules(filter, urlFilter, matchCase);
    }
    else if (!blocking) {
      result = generateAllowingRules(filter, urlFilter, matchCase);
    }
    else if (rewrite) {
      result = generateRedirectRules(filter, urlFilter, matchCase);
    }
    else {
      result = generateBlockingRules(filter, urlFilter, matchCase);
    }

    let context = {
      text: parsedFilter.text
    };
    return result
      .map(rule => this.modifyRule(rule, context))
      .map(validateRule);
  }
  catch (error) {
    return new FilterParsingError("filter_invalid_regexp",
                                  {regexp: regexpSource, text});
  }
}

exports.asDNR = asDNR;


/***/ }),

/***/ "./core/lib/dnr/mapper.js":
/*!********************************!*\
  !*** ./core/lib/dnr/mapper.js ***!
  \********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/** @module */

/**
 * DNR Mapper. Will lazy load the data as needed.
 */
exports.DnrMapper = class DnrMapper {
  /**
   * @param {Function} loader The loader for the mapping data. The
   *     loader function will return the JSON parse output of the map
   *     files. In a Web Extension it will likely use `fetch` to load
   *     it from the extension files. The loader will be called when
   *     the map needs to be used the first time. The function can be
   *     async.
   *
   * @constructor
   */
  constructor(loader) {
    this.loader = loader;
    // A null map is a map that needs to be loaded.
    this.map = null;
  }

  /**
   * Call the loader.
   * @private
   */
  async _loadMapper() {
    this.map = new Map(await this.loader());
  }

  /**
   * Load the map. Because it is async it can't be done on a get.
   * Ideally you'd delay calling it to when neeeded. It is safe to
   * call more than once.
   * @async
   */
  async load() {
    if (this.map === null) {
      await this._loadMapper();
    }
  }

  /**
   * Get the rule ids for the text. Make sure `load()` has been called
   * once previously.
   *
   * @param {string} text The filter text to get the mapping from.
   *
   * @returns {?Array.<number>} The array of rule IDs if found.
   */
  get(text) {
    if (this.map === null) {
      throw new Error("Mapper not loaded.");
    }

    return this.map.get(text);
  }
};


/***/ }),

/***/ "./core/lib/dnr/rules.js":
/*!*******************************!*\
  !*** ./core/lib/dnr/rules.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_233140__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/** @module */

const {contentTypes} = __nested_webpack_require_233140__(/*! ../contentTypes */ "./core/lib/contentTypes.js");
const {resources} = __nested_webpack_require_233140__(/*! ../../data/resources.js */ "./core/data/resources.js");

// We differentiate generic rules from specific ones in order to support the
// conversion of $genericblock exception filters. Since with the
// declarativeNetRequest API "allow" rules take priority over "allowAllRequest"
// rules, we also need to take care to give "allowAllRequest" rules a slighlty
// higher priority.
const GENERIC_PRIORITY = 1000;
exports.GENERIC_PRIORITY = GENERIC_PRIORITY;
const GENERIC_ALLOW_ALL_PRIORITY = 1001;
exports.GENERIC_ALLOW_ALL_PRIORITY = GENERIC_ALLOW_ALL_PRIORITY;
const SPECIFIC_PRIORITY = 2000;
exports.SPECIFIC_PRIORITY = SPECIFIC_PRIORITY;
const SPECIFIC_ALLOW_ALL_PRIORITY = 2001;
exports.SPECIFIC_ALLOW_ALL_PRIORITY = SPECIFIC_ALLOW_ALL_PRIORITY;


const requestTypes = new Map([
  [contentTypes.OTHER, ["other", "csp_report"]],
  [contentTypes.SCRIPT, ["script"]],
  [contentTypes.IMAGE, ["image"]],
  [contentTypes.STYLESHEET, ["stylesheet"]],
  [contentTypes.OBJECT, ["object"]],
  [contentTypes.SUBDOCUMENT, ["sub_frame"]],
  [contentTypes.WEBSOCKET, ["websocket"]],
  [contentTypes.WEBBUNDLE, ["webbundle"]],
  [contentTypes.PING, ["ping"]],
  [contentTypes.XMLHTTPREQUEST, ["xmlhttprequest"]],
  [contentTypes.MEDIA, ["media"]],
  [contentTypes.FONT, ["font"]]
]);
exports.requestTypes = requestTypes;

const supportedRequestTypes = Array.from(requestTypes.keys())
                                   .reduce(((srt, t) => srt | t));
exports.supportedRequestTypes = supportedRequestTypes;

function getResourceTypes(filterContentType) {
  // The default is to match everything except "main_frame", which is fine.
  if ((filterContentType & supportedRequestTypes) == supportedRequestTypes) {
    return;
  }

  let result = [];

  for (let [mask, types] of requestTypes) {
    if (filterContentType & mask) {
      result = result.concat(types);
    }
  }

  return result;
}

function getDomains(filterDomains) {
  let domains = [];
  let excludedDomains = [];
  let isGenericFilter = true;

  if (filterDomains) {
    for (let [domain, enabled] of filterDomains) {
      if (domain == "") {
        isGenericFilter = enabled;
      }
      else {
        (enabled ? domains : excludedDomains).push(domain);
      }
    }
  }

  return {domains, excludedDomains, isGenericFilter};
}

function getCondition(filter, urlFilter, resourceTypes, matchCase) {
  let condition = {};

  if (urlFilter) {
    condition.urlFilter = urlFilter;
  }
  else if (filter.regexp) {
    condition.regexFilter = filter.regexp.source;
  }

  if (resourceTypes) {
    condition.resourceTypes = resourceTypes;
  }

  // Before Chromium 118, the default for isUrlFilterCaseSensitive is true. From
  // Chromium 118, the default is false. If we at some point make our minimum
  // supported Chromium 118, then we can leave this undefined if !matchCase.
  condition.isUrlFilterCaseSensitive = matchCase;

  if (filter.thirdParty != null) {
    condition.domainType = filter.thirdParty ? "thirdParty" : "firstParty";
  }

  let {domains, excludedDomains, isGenericFilter} = getDomains(filter.domains);

  if (domains.length) {
    condition.domains = domains;
  }
  if (excludedDomains.length) {
    condition.excludedDomains = excludedDomains;
  }

  return [condition, isGenericFilter];
}

exports.generateRedirectRules = function(filter, urlFilter, matchCase) {
  let url = resources[filter.rewrite];

  // We can't generate rules for unknown abp-resources...
  if (!url) {
    return [];
  }

  let resourceTypes = getResourceTypes(filter.contentType);

  // We can't generate rules for filters which don't include any supported
  // resource types.
  if (resourceTypes && resourceTypes.length == 0) {
    return [];
  }

  let [condition, isGenericFilter] = getCondition(
    filter, urlFilter, resourceTypes, matchCase
  );

  return [{
    priority: isGenericFilter ? GENERIC_PRIORITY : SPECIFIC_PRIORITY,
    condition,
    action: {
      type: "redirect",
      redirect: {url}
    }
  }];
};

exports.generateCSPRules = function(filter, urlFilter, matchCase) {
  let [condition, isGenericFilter] = getCondition(
    filter, urlFilter, ["main_frame", "sub_frame"], matchCase
  );

  let rule;

  if (!filter.blocking) {
    // The DNR makes no distinction between CSP rules and main_frame/sub_frame
    // rules. Ideally, we would give CSP rules a different priority therefore,
    // to ensure that a $csp exception filter would not accidentally allowlist
    // the whole website. Unfortunately, I don't think that's possible if we are
    // to also support the distinction between specific and generic rules.
    //   Luckily, we are adding an "allow" rule (not "allowAllRequest") here and
    // there is no such thing as a blocking filter which applies to the
    // $document (main_frame), so we don't have to worry about that. There is
    // such a thing as a $subdocument blocking filter though, which a $csp
    // exception filter should not usually affect.
    //   As a compromise in order to support both $csp and $genericblock, we
    // accept that $csp exception filters might wrongly prevent frame-blocking
    // filters from matching. If this compromise proves problematic, we might
    // need to reconsider this in the future.
    rule = {
      action: {
        type: "allow"
      },
      condition,
      priority: filter.contentType & contentTypes.GENERICBLOCK ?
                  GENERIC_PRIORITY : SPECIFIC_PRIORITY
    };
  }
  else {
    rule = {
      action: {
        type: "modifyHeaders",
        responseHeaders: [{
          header: "Content-Security-Policy",
          operation: "append",
          value: filter.csp
        }]
      },
      condition,
      priority: isGenericFilter ? GENERIC_PRIORITY : SPECIFIC_PRIORITY
    };
  }

  // Chromium doesn't consider main_frame requests to have initiated from their
  // URL, so the domains/excludedDomains rule conditions won't work as expected
  // for main_frame requests. This is a problem for $csp filters which also use
  // the $domain option. As a partial workaround, we generate a separate
  // urlFilter rule for each domain. But note, we can't support excludedDomains
  // ($csp=...$~domain=...) or urlFilter conditions (||...$csp=...,domain=...).
  // See https://bugs.chromium.org/p/chromium/issues/detail?id=1207326
  //
  // Note: Hopefully, this workaround won't be necessary for long, but if we
  // need it long-term, then perhaps we should generate one rule with a longer
  // regexFilter condition instead. But if we do that, we will need to be
  // careful not to hit the memory limit for regular expression rule conditions
  // and also to match subdomains correctly.
  if (rule.condition.excludedDomains) {
    return [];
  }
  if (rule.condition.domains) {
    if (condition.urlFilter) {
      return [];
    }

    let {domains} = condition;
    delete condition.domains;

    let rules = [];
    for (let domain of domains) {
      let domainRule = JSON.parse(JSON.stringify(rule));
      domainRule.condition.urlFilter = "||" + domain + "^";
      rules.push(domainRule);
    }

    return rules;
  }

  return [rule];
};

exports.generateBlockingRules = function(filter, urlFilter, matchCase) {
  let resourceTypes = getResourceTypes(filter.contentType);

  // We can't generate rules for filters which don't include any supported
  // resource types.
  if (resourceTypes && resourceTypes.length == 0) {
    return [];
  }

  let [condition, isGenericFilter] = getCondition(
    filter, urlFilter, resourceTypes, matchCase
  );

  return [{
    priority: isGenericFilter ? GENERIC_PRIORITY : SPECIFIC_PRIORITY,
    condition,
    action: {
      type: "block"
    }
  }];
};

exports.generateAllowingRules = function(filter, urlFilter, matchCase) {
  let rules = [];
  let {contentType} = filter;

  let genericBlock = contentType & contentTypes.GENERICBLOCK;

  if (contentType & contentTypes.DOCUMENT || genericBlock) {
    contentType &= ~contentTypes.SUBDOCUMENT;

    rules.push({
      priority: genericBlock ?
                  GENERIC_ALLOW_ALL_PRIORITY : SPECIFIC_ALLOW_ALL_PRIORITY,
      condition: getCondition(
        filter, urlFilter, ["main_frame", "sub_frame"], matchCase)[0],
      action: {
        type: "allowAllRequests"
      }
    });
  }

  let resourceTypes = getResourceTypes(contentType);
  if (!resourceTypes || resourceTypes.length) {
    rules.push({
      priority: genericBlock ? GENERIC_PRIORITY : SPECIFIC_PRIORITY,
      condition: getCondition(filter, urlFilter, resourceTypes, matchCase)[0],
      action: {
        type: "allow"
      }
    });
  }

  return rules;
};

function validateIsAsciiOnly(str) {
  // [0-127] range is considered to be allowed ASCII characters
  if (!/^[\x00-\x7F]*$/.test(str)) {
    throw new Error(`Invalid ASCII characters found in: "${str}"`);
  }
}
exports.validateIsAsciiOnly = validateIsAsciiOnly;

function validateDomains(domains) {
  if (domains) {
    for (let domain of domains) {
      validateIsAsciiOnly(domain);
    }
  }
}

function validateCondition(condition) {
  if (condition.urlFilter) {
    validateIsAsciiOnly(condition.urlFilter);
  }
  if (condition.regexFilter) {
    validateIsAsciiOnly(condition.regexFilter);
  }

  validateDomains(condition.initiatorDomains);
  validateDomains(condition.requestDomains);

  // deprecated starting Chrome 101
  validateDomains(condition.domains);
  validateDomains(condition.excludedDomains);

  // starting Chrome 101
  validateDomains(condition.excludedInitiatorDomains);
  validateDomains(condition.excludedRequestDomains);
}

exports.validateRule = function(rule) {
  try {
    validateCondition(rule.condition);
    return rule;
  }
  catch (e) {
    return e;
  }
};


/***/ }),

/***/ "./core/lib/downloader.js":
/*!********************************!*\
  !*** ./core/lib/downloader.js ***!
  \********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_243952__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Downloads a set of URLs in regular time intervals.
 */

const {MILLIS_IN_DAY} = __nested_webpack_require_243952__(/*! ./time */ "./core/lib/time.js");
const {isLocalhost} = __nested_webpack_require_243952__(/*! ./url */ "./core/lib/url.js");

/**
 * A type of function that yields `{@link module:downloader.Downloadable}`
 * objects to a `{@link module:downloader.Downloader}`.
 *
 * **Note**: The implementation must yield a new
 * `{@link module:downloader.Downloadable}` instance on each call with
 * up-to-date values for properties like
 * `{@link module:downloader.Downloadable#lastCheck}`,
 * `{@link module:downloader.Downloadable#lastVersion}`,
 * `{@link module:downloader.Downloadable#downloadCount}`, and others. If a
 * value is outdated, it may result in unexpected behavior.
 *
 * @callback DataSource
 *
 * @yields {module:downloader.Downloadable}
 * @generator
 *
 * @see module:downloader.Downloader
 * @see module:downloader.Downloader#dataSource
 */

/**
 * Use a `Downloader` object to download a set of URLs at regular time
 * intervals.
 *
 * This class is used by `{@link module:synchronizer.synchronizer}` and
 * `{@link module:notifications.notifications}`.
 *
 * @example
 *
 * function* dataSource()
 * {
 *   yield new Downloadable("https://example.com/filters.txt");
 * }
 *
 * let initialDelay = 1000;
 * let checkInterval = 60000;
 *
 * let downloader = new Downloader(dataSource);
 * downloader.scheduleChecks(checkInterval, initialDelay);
 *
 * downloader.onDownloadStarted = function(downloadable)
 * {
 *   console.log(`Downloading ${downloadable.url} ...`);
 * }
 *
 * @package
 */
exports.Downloader = class Downloader {
  /**
   * Creates a new downloader instance.
   * @param {module:downloader~DataSource} dataSource
   *   A function that yields `{@link module:downloader.Downloadable}` objects
   *   on each {@link module:downloader.Downloader#scheduleChecks check}.
   */
  constructor(dataSource) {
    /**
     * Maximal time interval that the checks can be left out until the soft
     * expiration interval increases.
     * @type {number}
     */
    this.maxAbsenceInterval = 1 * MILLIS_IN_DAY;

    /**
     * Minimal time interval before retrying a download after an error.
     * @type {number}
     */
    this.minRetryInterval = 1 * MILLIS_IN_DAY;

    /**
     * Maximal allowed expiration interval; larger expiration
     * intervals will be corrected.
     * @type {number}
     */
    this.maxExpirationInterval = 14 * MILLIS_IN_DAY;

    /**
     * Maximal number of redirects before the download is considered as failed.
     * @type {number}
     */
    this.maxRedirects = 5;

    /**
     * Called whenever expiration intervals for an object need to be adapted.
     * @type {function?}
     */
    this.onExpirationChange = null;

    /**
     * Callback to be triggered whenever a download starts.
     * @type {function?}
     */
    this.onDownloadStarted = null;

    /**
     * Callback to be triggered whenever a download finishes successfully.
     *
     * The callback can return an error code to indicate that the data is
     * wrong.
     *
     * @type {function?}
     */
    this.onDownloadSuccess = null;

    /**
     * Callback to be triggered whenever a download fails.
     * @type {function?}
     */
    this.onDownloadError = null;

    /**
     * A function that yields `{@link module:downloader.Downloadable}` objects
     * on each {@link module:downloader.Downloader#scheduleChecks check}.
     * @type {module:downloader~DataSource}
     */
    this.dataSource = dataSource;

    /**
     * Set containing the URLs of objects currently being downloaded.
     * (for DiffUpdatable subscriptions it's subscription URL, not diff URL)
     * @type {Set.<string>}
     */
    this._downloading = new Set();

    /**
     * Store the timeout ID for scheduled checks.
     * @type {number}
     */
    this._timeout = 0;
  }

  /**
   * Schedules checks at regular time intervals.
   *
   * @param {number} interval The interval between checks in milliseconds.
   * @param {number} delay The delay before the initial check in milliseconds.
   */
  scheduleChecks(interval, delay) {
    // clear previous timeouts if called too many times
    this.unscheduleChecks();

    let check = () => {
      try {
        this._doCheck();
      }
      finally {
        // Schedule the next check only after the callback has finished with
        // the current check.
        this._timeout =
          setTimeout(check, interval); // eslint-disable-line no-undef
      }
    };

    // Note: test/_common.js overrides setTimeout() for the tests; if this
    // global function is used anywhere else, it may give incorrect results.
    // This is why we disable ESLint's no-undef rule locally.
    // https://gitlab.com/eyeo/adblockplus/abc/adblockpluscore/issues/43
    this._timeout = setTimeout(check, delay); // eslint-disable-line no-undef
  }

  /**
   * Clear previously scheduled checks, if any.
   */
  unscheduleChecks() {
    if (this._timeout) {
      clearTimeout(this._timeout); // eslint-disable-line no-undef
      this._timeout = 0;
    }
  }

  /**
   * Checks whether anything needs downloading.
   */
  _doCheck() {
    let now = Date.now();
    for (let downloadable of this.dataSource()) {
      if (downloadable.lastCheck &&
          now - downloadable.lastCheck > this.maxAbsenceInterval) {
        // No checks for a long time interval - user must have been offline,
        // e.g.  during a weekend. Increase soft expiration to prevent load
        // peaks on the server.
        downloadable.softExpiration += now - downloadable.lastCheck;
      }
      downloadable.lastCheck = now;

      // Sanity check: do expiration times make sense? Make sure people changing
      // system clock don't get stuck with outdated subscriptions.
      if (downloadable.hardExpiration - now > this.maxExpirationInterval) {
        downloadable.hardExpiration = now + this.maxExpirationInterval;
      }
      if (downloadable.softExpiration - now > this.maxExpirationInterval) {
        downloadable.softExpiration = now + this.maxExpirationInterval;
      }

      // Notify the caller about changes to expiration parameters
      if (this.onExpirationChange) {
        this.onExpirationChange(downloadable);
      }

      // Does that object need downloading?
      if (downloadable.softExpiration > now &&
          downloadable.hardExpiration > now) {
        continue;
      }

      // Do not retry downloads too often
      if (downloadable.lastError &&
          now - downloadable.lastError < this.minRetryInterval) {
        continue;
      }

      this._download(downloadable, 0);
    }
  }

  /**
   * Checks whether an address is currently being downloaded.
   * @param {string} url
   * @returns {boolean}
   */
  isDownloading(url) {
    return this._downloading.has(url);
  }

  /**
   * Starts downloading for an object.
   * @param {Downloadable} downloadable
   */
  download(downloadable) {
    this._download(downloadable, 0);
  }

  /**
   * Generates the real download URL for an object by appending various
   * parameters.
   * @param {Downloadable} downloadable
   * @returns {string}
   */
  getDownloadUrl(downloadable) {
    const {addonName, addonVersion, application, applicationVersion,
           platform, platformVersion, manifestVersion} = __nested_webpack_require_243952__(/*! info */ "./sdk/api/info.js");

    let url = downloadable.redirectURL || downloadable.url;
    if (url.includes("?")) {
      url += "&";
    }
    else {
      url += "?";
    }

    // We limit the download count to 4+ to keep the request anonymized.
    let {downloadCount, disabled} = downloadable;
    if (downloadCount > 4) {
      downloadCount = "4+";
    }
    if (typeof disabled == "undefined") {
      disabled = false;
    }

    url += "addonName=" + encodeURIComponent(addonName) +
           "&addonVersion=" + encodeURIComponent(addonVersion) +
           "&application=" + encodeURIComponent(application) +
           "&applicationVersion=" + encodeURIComponent(applicationVersion) +
           "&platform=" + encodeURIComponent(platform) +
           "&platformVersion=" + encodeURIComponent(platformVersion) +
           "&lastVersion=" + encodeURIComponent(downloadable.lastVersion) +
           "&downloadCount=" + encodeURIComponent(downloadCount) +
           "&disabled=" + String(disabled) +
           "&manifestVersion=" + encodeURIComponent(manifestVersion);

    if (downloadable.firstVersion && !downloadable.redirectURL) {
      url += "&firstVersion=" + encodeURIComponent(downloadable.firstVersion);
    }

    return url;
  }

  _download(downloadable, redirects) {
    if (this.isDownloading(downloadable.originalUrl || downloadable.url)) {
      return;
    }

    let downloadUrl = this.getDownloadUrl(downloadable);
    let responseStatus = 0;

    let errorCallback = error => {
      console.warn("Adblock Plus: Downloading URL " + downloadable.url +
                   " failed (" + error + ")\n" +
                   "Download address: " + downloadUrl + "\n" +
                   "Server response: " + responseStatus);

      if (this.onDownloadError) {
        // Allow one extra redirect if the error handler gives us a redirect URL
        let redirectCallback = null;
        if (redirects <= this.maxRedirects) {
          redirectCallback = url => {
            downloadable.redirectURL = url;
            this._download(downloadable, redirects + 1);
          };
        }

        this.onDownloadError(
          downloadable, downloadUrl, error, responseStatus, redirectCallback
        );
      }
    };

    if (!Downloader.isValidURL(downloadUrl)) {
      errorCallback("synchronize_invalid_url");
      return;
    }

    let requestURL = new URL(downloadUrl);

    let initObj = {
      cache: "no-store",
      credentials: "omit",
      referrer: "no-referrer",
      method: downloadable.method
    };

    let handleError = () => {
      this._downloading.delete(downloadable.originalUrl || downloadable.url);
      errorCallback("synchronize_connection_error");
    };

    let handleResponse = response => {
      this._downloading.delete(downloadable.originalUrl || downloadable.url);

      // If the Response.url property is available [1], disallow redirection
      // from HTTPS to any other protocol.
      // [1]: https://developer.mozilla.org/en-US/docs/Web/API/Response/url#Browser_compatibility
      if (typeof response.url == "string" && requestURL.protocol == "https:" &&
          new URL(response.url).protocol != requestURL.protocol) {
        errorCallback("synchronize_connection_error");
        return;
      }

      responseStatus = response.status;

      if (responseStatus != 200) {
        errorCallback("synchronize_connection_error");
        return;
      }

      // We need to keep updated the subscription version even via HEAD.
      if (downloadable.method === "HEAD" || downloadable.originalUrl) {
        // However, as we don't know if the server would respond with such
        // detail, we need to be sure there is such `Date` or `date` field.
        let date = response.headers.get("Date") || response.headers.get("date");
        if (date) {
          // if that's the case, we want it to be formatted as YYYYMMDDHHMM.
          downloadable.lastVersion =
            new Date(date).toISOString().replace(/\D/g, "").slice(0, 12);
        }
      }

      if (!downloadable.disabled) {
        downloadable.downloadCount++;
      }

      response.text().then(
        responseText => {
          this.onDownloadSuccess(
            downloadable, responseText, errorCallback, url => {
              if (redirects >= this.maxRedirects) {
                errorCallback("synchronize_connection_error");
                return;
              }

              downloadable.redirectURL = url;
              this._download(downloadable, redirects + 1);
            }
          );
        },
        () => {
          errorCallback("synchronize_connection_error");
        }
      );
    };

    fetch(requestURL.href, initObj).then(handleResponse, handleError);

    this._downloading.add(downloadable.originalUrl || downloadable.url);

    if (this.onDownloadStarted) {
      this.onDownloadStarted(downloadable);
    }
  }

  /**
   * Produces a soft and a hard expiration time for a given supplied
   * expiration interval.
   *
   * Downloadable things, like Subscription, have a certain time after
   * which they expire and you need to download a new, updated version.
   *
   * To spread the load on our download servers, we'd rather that all
   * users not download updates at exactly the same time, so on
   * download we calculate a soft expiration time, which is randomly
   * chosen between 80% and 120% of the original time. When we pass
   * the soft expiration, we start trying to download updates.
   *
   * However, there are other events that could cause downloads to all
   * happen at the same time. If many people leave their computer off
   * over the weekend and sign in at the beginning of business hours
   * on Monday, we could still see a spike in downloads at the same
   * time. To combat this, the soft expiration time may be delayed to
   * accomodate these periods of inactivity.
   *
   * There are limits to how far we want to delay our download due to
   * inactivity. This is why we also calculate a hard expiration time,
   * which is 200% of the original time. When we pass the hard
   * expiration, we should try to download an update whether there was
   * inactivity or not.
   *
   * This function must be called to calculate the new expiration
   * times as soon as a new version is downloaded.
   *
   * @param {number} interval how often in milliseconds the
   * downloadable should be updated
   * @returns {Array.<number>} soft and hard expiration times in
   * milliseconds since the Unix epoch
   */
  processExpirationInterval(interval) {
    interval = Math.min(Math.max(interval, 0), this.maxExpirationInterval);
    let soft = Math.round(interval * (Math.random() * 0.4 + 0.8));
    let hard = interval * 2;
    let now = Date.now();
    return [now + soft, now + hard];
  }
};

/**
 * Checks whether a URL is a valid download URL.
 *
 * For a URL to be a valid download URL, its scheme must be `https` or `data`.
 * If the host component of the URL is `localhost`, `127.0.0.1`, or `[::1]`,
 * however, but its scheme is not `https` or `data`, the URL is still
 * considered to be a valid download URL.
 *
 * `https://example.com/`, `data:,Hello%2C%20World!`, and
 * `http://127.0.0.1/example.txt` are all examples of valid download URLs.
 *
 * @param {string} url The URL.
 *
 * @returns {boolean} Whether the URL is a valid download URL.
 *
 * @package
 */
exports.Downloader.isValidURL = function isValidURL(url) {
  try {
    url = new URL(url);
  }
  catch (error) {
    return false;
  }

  if (!["https:", "data:"].includes(url.protocol) &&
      !isLocalhost(url.hostname)) {
    return false;
  }

  return true;
};

/**
 * A `Downloadable` object represents a downloadable resource.
 * @package
 */
exports.Downloadable = class Downloadable {
  /**
   * Creates an object that can be downloaded by the downloader.
   * @param {string} url  URL that has to be requested for the object
   */
  constructor(url) {
    /**
     * URL that the download was redirected to if any.
     * @type {string?}
     */
    this.redirectURL = null;

    /**
     * Time of last download error or 0 if the last download was successful.
     * @type {number}
     */
    this.lastError = 0;

    /**
     * Time of last check whether the object needs downloading.
     * @type {number}
     */
    this.lastCheck = 0;

    /**
     * Object version corresponding to the last successful download.
     * @type {number}
     */
    this.lastVersion = 0;

    /**
     * A string indicating the version of the first ever downloaded resource,
     * in `YYYY[MM[DD]][-E]` format or just `"0"` or `"0-E"`.
     *
     * Note that unlike `{@link module:downloader.Downloadable#lastVersion}`
     * this property is related to analytics and its value is common across all
     * downloadable resources.
     *
     * If `{@link module:downloader.Downloadable#url}` is not a trusted URL,
     * the value of this property should be set to `null`.
     *
     * @see module:analytics~Analytics#getFirstVersion
     * @see module:analytics~Analytics#isTrusted
     *
     * @type {?string}
     *
     * @package
     */
    this.firstVersion = null;

    /**
     * Soft expiration time in milliseconds since the Unix epoch. This
     * will increase if no checks are performed for a while.
     *
     * Updates should be downloaded if `softExpiration` or
     * `{@link module:downloader.Downloadable#hardExpiration}` are in the past.
     * @type {number}
     */
    this.softExpiration = 0;

    /**
     * Hard expiration time in milliseconds since the Unix epoch. This
     * is fixed.
     *
     * Updates should be downloaded if
     * `{@link module:downloader.Downloadable#softExpiration}` or
     * `hardExpiration` are in the past.
     * @type {number}
     */
    this.hardExpiration = 0;

    /**
     * Number indicating how often the object was downloaded.
     * @type {number}
     */
    this.downloadCount = 0;

    /**
     * Request method to use, which is either "GET" or "HEAD".
     * @type {string}
     */
    this.method = "GET";

    /**
     * URL that has to be requested for the object.
     * @type {string}
     */
    this.url = url;

    /**
     * URL that stores the subscription URL when downloading occurs for
     * the m3 diff mechanism.
     * @type {string}
     */
    this.originalUrl = null;
  }
};


/***/ }),

/***/ "./core/lib/elemHide.js":
/*!******************************!*\
  !*** ./core/lib/elemHide.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_262668__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Element hiding implementation.
 */

const {domainSuffixes} = __nested_webpack_require_262668__(/*! ./url */ "./core/lib/url.js");
const {FiltersByDomain, FilterMap} = __nested_webpack_require_262668__(/*! ./filtersByDomain */ "./core/lib/filtersByDomain.js");
const {Cache} = __nested_webpack_require_262668__(/*! ./caching */ "./core/lib/caching.js");
const {ElemHideExceptions} = __nested_webpack_require_262668__(/*! ./elemHideExceptions */ "./core/lib/elemHideExceptions.js");

class ElemHide {
  /**
   * @param {ElemHideExceptions} elemHideExceptions The associated element
   *   hiding exceptions.
   */
  constructor(elemHideExceptions) {
    if (!(elemHideExceptions instanceof ElemHideExceptions)) {
      throw new Error("elemHideExceptions must be an ElemHideExceptions");
    }

    /** @type {ElemHideExceptions} */
    this.elemHideExceptions = elemHideExceptions;

    /**
     * Lookup table, active flag, by filter by domain.
     *
     * (Only contains filters that aren't unconditionally matched for all
     * domains.)
     *
     * @type {FiltersByDomain}
     *
     * @private
     */
    this._filtersByDomain = new FiltersByDomain();

    /**
     * Lookup table, filter by selector.
     *
     * (Only used for selectors that are unconditionally matched for all
     * domains.)
     *
     * @type {Map.<string, Filter>}
     *
     * @private
     */
    this._filterBySelector = new Map();

    /**
     * This array caches the keys of
     * `{@link module:elemHide~ElemHide#_filterBySelector _filterBySelector}`
     * (selectors which unconditionally apply on all domains).
     *
     * It will be `null` if the cache needs to be rebuilt.
     *
     * @type {?Array.<string>}
     *
     * @private
     */
    this._unconditionalSelectors = null;

    /**
     * The default style sheet that applies on all domains.
     *
     * This is based on the value of
     * `{@link module:elemHide~ElemHide#_unconditionalSelectors
     *         _unconditionalSelectors}`.
     *
     * @type {?string}
     *
     * @private
     */
    this._defaultStyleSheet = null;

    /**
     * The common style sheet that applies on all unknown domains.
     *
     * This is a concatenation of the default style sheet and an additional
     * style sheet based on selectors from all generic filters that are not in
     * the `{@link module:elemHide~ElemHide#_unconditionalSelectors
     *             _unconditionalSelectors}` list.
     *
     * @type {?string}
     *
     * @private
     */
    this._commonStyleSheet = null;

    /**
     * Cache of generated domain-specific style sheets.
     *
     * This contains entries for only known domains. If a domain is unknown, it
     * gets `{@link module:elemHide~ElemHide#_commonStyleSheet
     *              _commonStyleSheet}`.
     *
     * @type {Cache.<string, string>}
     *
     * @private
     */
    this._styleSheetCache = new Cache(100);

    /**
     * Set containing known element hiding filters
     * @type {Set.<module:filterClasses.ElemHideFilter>}
     * @private
     */
    this._filters = new Set();

    /**
     * All domains known to occur in exceptions
     * @type {Set.<string>}
     * @private
     */
    this._exceptionDomains = new Set();

    this.elemHideExceptions.on("added", this._onExceptionAdded.bind(this));
  }

  /**
   * Removes all known element hiding filters.
   */
  clear() {
    this._commonStyleSheet = null;

    for (let collection of [this._styleSheetCache, this._filtersByDomain,
                            this._filterBySelector, this._filters,
                            this._exceptionDomains]) {
      collection.clear();
    }

    this._unconditionalSelectors = null;
    this._defaultStyleSheet = null;
  }

  /**
   * Add a new element hiding filter.
   * @param {module:filterClasses.ElemHideFilter} filter
   */
  add(filter) {
    if (this._filters.has(filter)) {
      return;
    }

    this._styleSheetCache.clear();
    this._commonStyleSheet = null;

    let {domains, selector} = filter;

    if (!(domains || this.elemHideExceptions.hasExceptions(selector))) {
      // The new filter's selector is unconditionally applied to all domains
      this._filterBySelector.set(selector, filter);
      this._unconditionalSelectors = null;
      this._defaultStyleSheet = null;
    }
    else {
      // The new filter's selector only applies to some domains
      this._filtersByDomain.add(filter, domains);
    }

    this._filters.add(filter);
  }

  /**
   * Removes an existing element hiding filter.
   * @param {module:filterClasses.ElemHideFilter} filter
   */
  remove(filter) {
    if (!this._filters.has(filter)) {
      return;
    }

    this._styleSheetCache.clear();
    this._commonStyleSheet = null;

    let {selector} = filter;

    // Unconditially applied element hiding filters
    if (this._filterBySelector.get(selector) == filter) {
      this._filterBySelector.delete(selector);
      this._unconditionalSelectors = null;
      this._defaultStyleSheet = null;
    }
    // Conditionally applied element hiding filters
    else {
      this._filtersByDomain.remove(filter);
    }

    this._filters.delete(filter);
  }

  /**
   * Checks whether an element hiding filter exists.
   * @param {module:filterClasses.ElemHideFilter} filter
   * @returns {boolean}
   */
  has(filter) {
    return this._filters.has(filter);
  }

  /**
   * @typedef {Object} ElemHideStyleSheet
   * @property {string} code CSS code.
   * @property {?Array.<string>} selectors List of selectors.
   * @property {?Array.<string>} exceptions List of exceptions.
   */

  /**
   * Returns a style sheet for a given domain based on the current set of
   * filters.
   *
   * @param {string} domain The domain.
   * @param {boolean} [specificOnly=false] Whether selectors from generic
   *   filters should be included.
   * @param {boolean} [includeExceptions=false] Whether the return value should
   *   include a separate list of exceptions.
   *
   * @returns {module:elemHide~ElemHideStyleSheet} An object containing the CSS
   *   code and the list of selectors.
   */
  getStyleSheet(domain, specificOnly = false,
                includeExceptions = false) {
    let code = null;
    let selectors = null;
    let exceptions = null;

    if (specificOnly) {
      if (includeExceptions) {
        let selectorsAndExceptions =
          this._getConditionalSelectorsWithExceptions(domain, true);

        selectors = selectorsAndExceptions.selectors;
        exceptions = selectorsAndExceptions.exceptions;
      }
      else {
        selectors = this._getConditionalSelectors(domain, true);
      }

      code = createStyleSheet(selectors);
    }
    else {
      let knownSuffix = this._getKnownSuffix(domain);

      let selectorsAndExceptions =
        this._getConditionalSelectorsWithExceptions(knownSuffix, false);

      selectors = selectorsAndExceptions.selectors;
      exceptions = selectorsAndExceptions.exceptions;
      code = knownSuffix == "" ? this._getCommonStyleSheet() :
        this._getDefaultStyleSheet() + createStyleSheet(selectors);

      selectors = this._getUnconditionalSelectors().concat(selectors);
    }

    return {
      code,
      selectors,
      exceptions: includeExceptions ? exceptions : null
    };
  }

  /**
   * Returns the suffix of the given domain that is known.
   *
   * If no suffix is known, an empty string is returned.
   *
   * @param {?string} domain
   *
   * @returns {string}
   *
   * @private
   */
  _getKnownSuffix(domain) {
    for (let suffix of domainSuffixes(domain)) {
      if (this._filtersByDomain.has(suffix) ||
          this._exceptionDomains.has(suffix)) {
        return suffix;
      }
    }

    return "";
  }

  /**
   * Returns a list of selectors that apply on each website unconditionally.
   * @returns {string[]}
   * @private
   */
  _getUnconditionalSelectors() {
    if (!this._unconditionalSelectors) {
      this._unconditionalSelectors = [...this._filterBySelector.keys()];
    }

    return this._unconditionalSelectors;
  }

  /**
   * Returns the list of selectors that apply on a given domain from the subset
   * of filters that do not apply unconditionally on all domains.
   *
   * @param {string} domain The domain.
   * @param {boolean} specificOnly Whether selectors from generic filters should
   *   be included.
   *
   * @returns {Array.<string>} The list of selectors.
   *
   * @private
   */
  _getConditionalSelectors(domain, specificOnly) {
    let selectors = [];

    let excluded = new Set();

    for (let currentDomain of domainSuffixes(domain, !specificOnly)) {
      let map = this._filtersByDomain.get(currentDomain);
      if (map) {
        for (let [filter, include] of (map instanceof FilterMap ?
          map.entries() : [[map, true]])) {
          if (!include) {
            excluded.add(filter);
          }
          else {
            let {selector} = filter;
            if ((excluded.size == 0 || !excluded.has(filter)) &&
                !this.elemHideExceptions.getException(selector, domain)) {
              selectors.push(selector);
            }
          }
        }
      }
    }

    return selectors;
  }

  /**
   * Returns the list of selectors and the list of exceptions that apply on a
   * given domain from the subset of filters that do not apply unconditionally
   * on all domains.
   *
   * @param {string} domain The domain.
   * @param {boolean} specificOnly Whether selectors from generic filters should
   *   be included.
   *
   * @returns {{selectors: Array.<string>,
   *            exceptions: Array.<module:filterClasses.ElemHideException>}}
   *   An object containing the lists of selectors and exceptions.
   *
   * @private
   */
  _getConditionalSelectorsWithExceptions(domain, specificOnly) {
    let selectors = [];
    let exceptions = [];

    let excluded = new Set();

    for (let currentDomain of domainSuffixes(domain, !specificOnly)) {
      let map = this._filtersByDomain.get(currentDomain);
      if (map) {
        for (let [filter, include] of (map instanceof FilterMap ?
          map.entries() : [[map, true]])) {
          if (!include) {
            excluded.add(filter);
          }
          else if (excluded.size == 0 || !excluded.has(filter)) {
            let {selector} = filter;
            let exception =
                this.elemHideExceptions.getException(selector, domain);

            if (exception) {
              exceptions.push(exception);
            }
            else {
              selectors.push(selector);
            }
          }
        }
      }
    }

    return {selectors, exceptions};
  }

  /**
   * Returns the default style sheet that applies on all domains.
   * @returns {string}
   * @private
   */
  _getDefaultStyleSheet() {
    if (!this._defaultStyleSheet) {
      this._defaultStyleSheet =
        createStyleSheet(this._getUnconditionalSelectors());
    }

    return this._defaultStyleSheet;
  }

  /**
   * Returns the common style sheet that applies on all unknown domains.
   * @returns {string}
   * @private
   */
  _getCommonStyleSheet() {
    if (!this._commonStyleSheet) {
      this._commonStyleSheet =
        this._getDefaultStyleSheet() +
        createStyleSheet(this._getConditionalSelectors("", false));
    }

    return this._commonStyleSheet;
  }

  /**
   * Returns the domain-specific style sheet that applies on a given domain.
   * @param {string} domain
   * @returns {string}
   * @private
   */
  _getDomainSpecificStyleSheet(domain) {
    let styleSheet = this._styleSheetCache.get(domain);

    if (typeof styleSheet == "undefined") {
      styleSheet =
        createStyleSheet(this._getConditionalSelectors(domain, false));
      this._styleSheetCache.set(domain, styleSheet);
    }

    return styleSheet;
  }

  _onExceptionAdded(exception) {
    let {domains, selector} = exception;

    this._styleSheetCache.clear();
    this._commonStyleSheet = null;

    if (domains) {
      for (let domain of domains.keys()) {
        // Note: Once an exception domain is known it never becomes unknown,
        // even when all the exceptions containing that domain are removed.
        // This is a best-case optimization.
        if (domain != "") {
          this._exceptionDomains.add(domain);
        }
      }
    }

    // If this is the first exception for a previously unconditionally applied
    // element hiding selector we need to take care to update the lookups.
    let unconditionalFilterForSelector = this._filterBySelector.get(selector);
    if (unconditionalFilterForSelector) {
      this._filtersByDomain.add(unconditionalFilterForSelector);
      this._filterBySelector.delete(selector);
      this._unconditionalSelectors = null;
      this._defaultStyleSheet = null;
    }
  }
}

/**
 * Container for element hiding filters.
 */
exports.ElemHide = ElemHide;

/**
 * Yields rules from a style sheet returned by
 * `{@link module:elemHide.createStyleSheet createStyleSheet()}`.
 *
 * @param {string} styleSheet A style sheet returned by
 *   `{@link module:elemHide.createStyleSheet createStyleSheet()}`. If the
 *   given style sheet is *not* a value previously returned by a call to
 *   `{@link module:elemHide.createStyleSheet createStyleSheet()}`, the
 *   behavior is undefined.
 *
 * @generator
 * @yields {string} A rule from the given style sheet.
 */
exports.rulesFromStyleSheet = function* rulesFromStyleSheet(styleSheet) {
  let startIndex = 0;
  while (startIndex < styleSheet.length) {
    let ruleTerminatorIndex = styleSheet.indexOf("\n", startIndex);
    yield styleSheet.substring(startIndex, ruleTerminatorIndex);
    startIndex = ruleTerminatorIndex + 1;
  }
};

/**
 * Escapes curly braces to prevent CSS rule injection.
 *
 * @param {string} selector
 *
 * @returns {string}
 */
function escapeSelector(selector) {
  return selector.replace(/[{}]/g, c => `\\${c.charCodeAt().toString(16)} `);
}

/**
 * Creates an element hiding CSS rule for a given list of selectors.
 *
 * @param {string} selector The CSS selector for the rule.
 * @param {string} [declarationBlock] Optional CSS code to use as the
 *   declaration block. By default, the code `{display: none !important;}` is
 *   used. If specified, the value is injected as-is into the rule.
 *
 * @returns {string} A CSS rule.
 */
function createRule(
  selector,
  declarationBlock = "{display: none !important;}"
) {
  return `${escapeSelector(selector)} ${declarationBlock}\n`;
}

let createStyleSheet =
/**
 * Creates an element hiding CSS style sheet from a given list of selectors.
 *
 * @param {Array.<string>} selectors The list of selectors.
 * @param {string} [declarationBlock] Optional CSS code to use as the
 *   declaration block. By default, the code `{display: none !important;}` is
 *   used. If specified, the value is injected as-is into the style sheet.
 *
 * @returns {string} A CSS style sheet.
 */
exports.createStyleSheet = function createStyleSheet(selectors,
                                                     declarationBlock) {
  let styleSheet = "";

  for (let selector of selectors) {
    styleSheet += createRule(selector, declarationBlock);
  }

  return styleSheet;
};


/***/ }),

/***/ "./core/lib/elemHideEmulation.js":
/*!***************************************!*\
  !*** ./core/lib/elemHideEmulation.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_278829__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



const {ElemHideExceptions} = __nested_webpack_require_278829__(/*! ./elemHideExceptions */ "./core/lib/elemHideExceptions.js");

/**
 * @file Element hiding emulation implementation.
 */

class ElemHideEmulation extends Set {
  /**
   * Construct an ElemHideEmulation object
   * @param {ElemHideExceptions} elemHideExceptions The associated element
   *  hiding exceptions.
   */
  constructor(elemHideExceptions) {
    super();
    if (!(elemHideExceptions instanceof ElemHideExceptions)) {
      throw new Error("elemHideExceptions must be an ElemHideExceptions");
    }

    /** @type {ElemHideExceptions} */
    this.elemHideExceptions = elemHideExceptions;
  }

  /**
   * Removes an existing element hiding emulation filter.
   * @param {module:filterClasses.ElemHideEmulationFilter} filter
   *
   * @deprecated Use
   *   <code>ElemHideEmulation#delete</code>
   *   instead.
   */
  remove(filter) {
    this.delete(filter);
  }

  /**
   * Returns a list of all element hiding emulation filters active on the given
   * domain.
   * @param {string} domain The domain.
   * @returns {Array.<module:filterClasses.ElemHideEmulationFilter>} A list of
   *   element hiding emulation filters.
   */
  getFilters(domain) {
    let result = [];

    for (let filter of this) {
      if (filter.isActiveOnDomain(domain) &&
          !this.elemHideExceptions.getException(filter.selector, domain)) {
        result.push(filter);
      }
    }

    return result;
  }

  /**
   * Returns a list of all element hiding emulation filters active on the given
   * domain.
   * @param {string} domain The domain.
   * @returns {Array.<module:filterClasses.ElemHideEmulationFilter>} A list of
   *   element hiding emulation filters.
   *
   * @deprecated Use
   *   <code>{@link
   *          module:elemHideEmulation~ElemHideEmulation#getFilters}</code>
   *   instead.
   * @see module:elemHideEmulation~ElemHideEmulation#getFilters
   */
  getRulesForDomain(domain) {
    return this.getFilters(domain);
  }
}

/**
 * Container for element hiding emulation filters.
 */
exports.ElemHideEmulation = ElemHideEmulation;


/***/ }),

/***/ "./core/lib/elemHideExceptions.js":
/*!****************************************!*\
  !*** ./core/lib/elemHideExceptions.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_281921__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Element hiding exceptions implementation.
 */

const {EventEmitter} = __nested_webpack_require_281921__(/*! ./events */ "./core/lib/events.js");

class ElemHideExceptions extends EventEmitter {
  /**
   * @hideconstructor
   */
  constructor() {
    super();

    /**
     * Lookup table, lists of element hiding exceptions by selector
     * @type {Map.<string, Set.<module:filterClasses.ElemHideException>>}
     * @private
     */
    this._exceptionsBySelector = new Map();

    /**
     * Set containing known element hiding exceptions
     * @type {Set.<module:filterClasses.ElemHideException>}
     * @private
     */
    this._exceptions = new Set();
  }

  /**
   * Removes all known element hiding exceptions.
   */
  clear() {
    this._exceptionsBySelector.clear();
    this._exceptions.clear();
  }

  /**
   * Adds a new element hiding exception.
   * @param {module:filterClasses.ElemHideException} exception
   */
  add(exception) {
    if (this._exceptions.has(exception)) {
      return;
    }

    let {selector} = exception;
    let set = this._exceptionsBySelector.get(selector);
    if (set) {
      set.add(exception);
    }
    else {
      this._exceptionsBySelector.set(selector, new Set([exception]));
    }

    this._exceptions.add(exception);

    this.emit("added", exception);
  }

  /**
   * Removes an existing element hiding exception.
   * @param {module:filterClasses.ElemHideException} exception
   */
  remove(exception) {
    if (!this._exceptions.has(exception)) {
      return;
    }

    let {selector} = exception;
    let set = this._exceptionsBySelector.get(selector);
    set.delete(exception);
    if (set.size == 0) {
      this._exceptionsBySelector.delete(selector);
    }

    this._exceptions.delete(exception);

    this.emit("removed", exception);
  }

  /**
   * Checks whether an element hiding exception exists.
   * @param {module:filterClasses.ElemHideException} exception
   * @returns {boolean}
   */
  has(exception) {
    return this._exceptions.has(exception);
  }

  /**
   * Checks whether any exception rules are registered for a selector.
   * @param {string} selector
   * @returns {boolean}
   */
  hasExceptions(selector) {
    return this._exceptionsBySelector.has(selector);
  }

  /**
   * Checks whether an exception rule is registered for a selector on a
   * particular domain.
   * @param {string} selector
   * @param {?string} [domain]
   * @returns {?module:filterClasses.ElemHideException}
   */
  getException(selector, domain) {
    let exceptions = this._exceptionsBySelector.get(selector);
    if (exceptions) {
      for (let exception of exceptions) {
        if (exception.isActiveOnDomain(domain)) {
          return exception;
        }
      }
    }

    return null;
  }
}

/**
 * Container for element hiding exceptions.
 */
exports.ElemHideExceptions = ElemHideExceptions;


/***/ }),

/***/ "./core/lib/events.js":
/*!****************************!*\
  !*** ./core/lib/events.js ***!
  \****************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * Registers and emits named events.
 */
exports.EventEmitter = class EventEmitter {
  constructor() {
    this._listeners = new Map();
  }

  /**
   * Adds a listener for the specified event name.
   *
   * @param {string}   name
   * @param {function} listener
   */
  on(name, listener) {
    let listeners = this._listeners.get(name);
    if (listeners) {
      listeners.push(listener);
    }
    else {
      this._listeners.set(name, [listener]);
    }
  }

  /**
   * Removes a listener for the specified event name.
   *
   * @param {string}   name
   * @param {function} listener
   */
  off(name, listener) {
    let listeners = this._listeners.get(name);
    if (listeners) {
      if (listeners.length > 1) {
        let idx = listeners.indexOf(listener);
        if (idx != -1) {
          listeners.splice(idx, 1);
        }
      }
      else if (listeners[0] === listener) {
        // We must use strict equality above for compatibility with
        // Array.prototype.indexOf
        this._listeners.delete(name);
      }
    }
  }

  /**
   * Returns a copy of the array of listeners for the specified event.
   *
   * @param {string} name
   *
   * @returns {Array.<function>}
   */
  listeners(name) {
    let listeners = this._listeners.size > 0 ? this._listeners.get(name) : null;
    return listeners ? listeners.slice() : [];
  }

  /**
   * Checks whether there are any listeners for the specified event.
   *
   * @param {string} [name] The name of the event. If omitted, checks whether
   *   there are any listeners for any event.
   *
   * @returns {boolean}
   */
  hasListeners(name) {
    return this._listeners.size > 0 &&
           (typeof name == "undefined" || this._listeners.has(name));
  }

  /**
   * Calls all previously added listeners for the given event name.
   *
   * @param {string} name
   * @param {...*}   [args]
   */
  emit(name, ...args) {
    let listeners = this._listeners.size > 0 ? this._listeners.get(name) : null;
    if (listeners) {
      for (let listener of listeners.slice()) {
        listener(...args);
      }
    }
  }
};


/***/ }),

/***/ "./core/lib/features.js":
/*!******************************!*\
  !*** ./core/lib/features.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * Feature flags for the filterEngine.
 *
 * @type {Object}
 *
 * @public
 */
exports.Features = {
  // Default features: Manifest v2.
  DEFAULT: 0,
  // We have DeclarativeNetRequest
  DNR: 1
};



/***/ }),

/***/ "./core/lib/filterClasses.js":
/*!***********************************!*\
  !*** ./core/lib/filterClasses.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_289908__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Definition of Filter class and its subclasses.
 */

const {
  contentTypes, RESOURCE_TYPES, CONTEXT_TYPES
} = __nested_webpack_require_289908__(/*! ./contentTypes */ "./core/lib/contentTypes.js");
const {CONTENT_FILTER} = __nested_webpack_require_289908__(/*! ./filters */ "./core/lib/filters/index.js");
const {Pattern} = __nested_webpack_require_289908__(/*! ./patterns */ "./core/lib/patterns.js");
const {parseDomains, domainSuffixes, isValidDomainWildcard,
       hasWildcard, matchesWildcards} = __nested_webpack_require_289908__(/*! ./url */ "./core/lib/url.js");
const {parse, FilterParsingError} = __nested_webpack_require_289908__(/*! ./filters */ "./core/lib/filters/index.js");

const {resources} = __nested_webpack_require_289908__(/*! ../data/resources.js */ "./core/data/resources.js");

const MIN_GENERIC_CONTENT_FILTER_BODY_LENGTH = 3;

/** The filter state
 * @type {module:filterState.FilterState}
 */
let filterState = null;

/**
 * @typedef {Object} HttpHeader
 * @property {string} name
 * @property {?string} value
 */

/**
 * Map of internal resources for URL rewriting.
 * @type {Map.<string,string>}
 */
let resourceMap = new Map(
  Object.keys(resources).map(key => [key, resources[key]])
);

let isActiveFilter =
/**
 * Checks whether the given filter is an active filter.
 *
 * Filters of type `blocking`, `allowing`, `elemhide`, `elemhideexception`,
 * `elemhideemulation`, and `snippet` are considered active; filters of type
 * `invalid` and `comment` are not considered active.
 *
 * @param {?Filter} filter The filter.
 *
 * @returns {boolean} Whether the filter is active.
 */
exports.isActiveFilter = function isActiveFilter(filter) {
  return filter instanceof ActiveFilter;
};

let Filter =
/**
 * Abstract base class for filters
 */
exports.Filter = class Filter {
  /**
   * @param {string} text   string representation of the filter
   */
  constructor(text) {
    this.text = text;
  }

  static useFilterState(reference) {
    filterState = reference;
  }

  /**
   * Filter type as a string, e.g. "blocking".
   *
   * Can be `blocking`, `allowing`, `elemhide`, `elemhideexception`,
   * `elemhideemulation`, `snippet`, `comment` or `invalid`.
   *
   * @type {string}
   */
  get type() {
    throw new Error("Please define filter type in the subclass");
  }

  /**
   * True if filter should only be loaded if it comes from a
   * privileged subscription (circumvention subscriptions or special
   * subscriptions).
   * @type {bool}
   */
  get requiresPrivilegedSubscription() {
    return false;
  }

  /**
   * Serializes the filter for writing out on disk.
   * @yields {string}
   */
  *serialize() {
    let {text} = this;

    yield "[Filter]";
    yield "text=" + text;
  }

  toString() {
    return this.text;
  }
};

/**
 * Cache for known filters, maps string representation to filter objects.
 * @type {Map.<string, module:filterClasses.Filter>}
 */
let knownFilters = new Map();

/**
 * Creates a filter of correct type from its text representation - does the
 * basic parsing and calls the right constructor then.
 *
 * @param {string} text   as in Filter()\
 * @return {module:filterClasses.Filter}
 */
exports.Filter.fromText = function(text) {
  let filter = knownFilters.get(text);
  if (filter) {
    return filter;
  }

  if (text.length === 0) {
    filter = new InvalidFilter(text, "filter_empty");
  }
  else if (text[0] == "!") {
    filter = new CommentFilter(text);
  }
  else {
    let match = text.includes("#") ? CONTENT_FILTER.exec(text) : null;
    if (match) {
      filter = ContentFilter.fromText(text, match[1], match[2], match[3]);
    }
    else {
      filter = URLFilter.fromText(text);
    }
  }

  if (filter.domains) {
    for (let domainWithWildcard of filter.domains.keys()) {
      if (domainWithWildcard == "") {
        continue;
      }

      if (!isValidDomainWildcard(domainWithWildcard)) {
        filter = new InvalidFilter(text, "filter_invalid_wildcard");
      }
    }
  }

  if (filter.type !== "invalid") {
    knownFilters.set(filter.text, filter);
  }

  return filter;
};

/**
 * Deserializes a filter
 *
 * @param {Object}  obj map of serialized properties and their values
 * @return {module:filterClasses.Filter} filter or null if the filter couldn't
 *   be created
 */
exports.Filter.fromObject = function(obj) {
  let filter = Filter.fromText(obj.text);
  if (isActiveFilter(filter) && filterState) {
    filterState.fromObject(filter.text, obj);
  }
  return filter;
};

let {normalize} = __nested_webpack_require_289908__(/*! ./filters/index.js */ "./core/lib/filters/index.js");
exports.Filter.normalize = normalize;

let InvalidFilter =
/**
 * Class for invalid filters
 * @extends module:filterClasses.Filter
 */
exports.InvalidFilter = class InvalidFilter extends Filter {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} reason Reason why this filter is invalid
   * @param {string?} option The optional option passed to the filter
   * @private
   */
  constructor(text, reason, option = null) {
    super(text);

    this.reason = reason;
    this.option = option;
  }

  get type() {
    return "invalid";
  }

  *serialize() {}
};

let CommentFilter =
/**
 * Class for comments
 * @extends module:filterClasses.Filter
 */
exports.CommentFilter = class CommentFilter extends Filter {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @private
   */
  constructor(text) {
    super(text);
  }

  get type() {
    return "comment";
  }

  *serialize() {}
};

let ActiveFilter =
/**
 * Abstract base class for filters that can get hits
 * @extends module:filterClasses.Filter
 */
exports.ActiveFilter = class ActiveFilter extends Filter {
  /**
   * @param {string} text
   *   see {@link module:filterClasses.Filter Filter()}
   * @param {string} [domains]
   *   Domains that the filter is restricted to separated by domainSeparator
   *   e.g. "foo.com|bar.com|~baz.com"
   * @private
   */
  constructor(text, domains) {
    super(text);

    /**
     * String that the domains property should be generated from
     * @type {?string}
     */
    this.domainSource = domains || null;

    this._domains = domains ? void 0 : null;
  }

  /**
   * Number of filters contained, will always be 1 (required to
   * optimize {@link module:matcher.Matcher Matcher}).
   * @type {number}
   */
  get size() {
    return 1;
  }

  /**
   * See Filter.serialize()
   * @inheritdoc
   */
  *serialize() {
    if (filterState) {
      yield* filterState.serialize(this.text);
    }
  }

  /**
   * Defines whether the filter is disabled globally.
   * @type {boolean}
   * @deprecated use
   * {@link module:filterClasses.ActiveFilter#isDisabledForSubscription} and
   * {@link module:filterClasses.ActiveFilter#setDisabledForSubscription} for
   * disabling and enabling filters for specific subscriptions.
   */
  get disabled() {
    return filterState && !filterState.isEnabled(this.text);
  }
  set disabled(value) {
    if (filterState) {
      filterState.setEnabled(this.text, !value);
    }
  }

  /**
   * Defines which subscriptions the filter is disabled for.
   * See {@link module:filterClasses.ActiveFilter#isDisabledForSubscription} and
   * {@link module:filterClasses.ActiveFilter#setDisabledForSubscription} for
   * disabling and enabling filters.
   * @type {Set<string>}
   */
  get disabledSubscriptions() {
    if (!filterState) {
      return new Set();
    }
    return filterState.disabledSubscriptions(this.text);
  }

  /**
   * Checks whether this filter is disabled.
   * @param {string} subscriptionUrl The subscription to check for
   * enabled / disabled state.
   * @return {boolean} true if the filter is disabled
   */
  isDisabledForSubscription(subscriptionUrl) {
    return filterState &&
      filterState.isDisabledForSubscription(this.text, subscriptionUrl);
  }
  /**
   * Disables or enables the filter.
   * @param {string} [subscriptionUrl] The subscription on which to
   * disable / enable the filter.
   * @param {boolean} [value] new disabled value, true for disabled
   * and false for enabled
   */
  setDisabledForSubscription(subscriptionUrl, value) {
    if (filterState) {
      filterState.setDisabledForSubscription(this.text, subscriptionUrl, value);
    }
  }

  /**
   * Separator character used in domainSource property
   * @type {string}
   */
  get domainSeparator() {
    return ",";
  }

  /**
   * Number of hits on the filter since the last reset
   * @type {number}
   */
  get hitCount() {
    return filterState ? filterState.getHitCount(this.text) : 0;
  }
  set hitCount(value) {
    if (filterState) {
      filterState.setHitCount(this.text, value);
    }
  }

  /**
   * Last time the filter had a hit (in milliseconds since the beginning of the
   * epoch)
   * @type {number}
   */
  get lastHit() {
    return filterState ? filterState.getLastHit(this.text) : 0;
  }
  set lastHit(value) {
    if (filterState) {
      filterState.setLastHit(this.text, value);
    }
  }

  /**
   * Map containing domains that this filter should match on/not match
   * on or null if the filter should match on all domains
   * @type {?Map.<string,boolean>}
   */
  get domains() {
    if (typeof this._domains == "undefined") {
      let {domainSource: source, domainSeparator: sep} = this;
      this._domains = parseDomains(source.toLowerCase(), sep);
    }
    return this._domains;
  }

  /**
   * Array containing public keys of websites that this filter should apply to
   * @type {?Array.<string>}
   */
  get sitekeys() {
    return null;
  }

  /**
   * String that the sitekey property should be generated from
   * @type {?string}
   */
  get sitekeySource() {
    return null;
  }

  /**
   * Checks whether this filter is active on a domain.
   * @param {?string} [docDomain] domain name of the document that loads the URL
   * @param {string} [sitekey] public key provided by the document
   * @return {boolean} true in case of the filter being active
   */
  isActiveOnDomain(docDomain, sitekey) {
    // Sitekeys are case-sensitive so we shouldn't convert them to
    // upper-case to avoid false positives here. Instead we need to
    // change the way filter options are parsed.
    if (this.sitekeys &&
        (!sitekey || !this.sitekeys.includes(sitekey))) {
      return false;
    }

    let {domains} = this;

    // If no domains are set the rule matches everywhere
    if (!domains) {
      return true;
    }

    if (docDomain == null) {
      docDomain = "";
    }
    else if (docDomain[docDomain.length - 1] == ".") {
      docDomain = docDomain.substring(0, docDomain.length - 1);
    }

    // If the document has no host name, match only if the filter
    // isn't restricted to specific domains
    if (!docDomain) {
      return domains.get("");
    }

    for (docDomain of domainSuffixes(docDomain)) {
      // exact domain match
      let isDomainIncluded = domains.get(docDomain);
      if (typeof isDomainIncluded != "undefined") {
        return isDomainIncluded;
      }

      // domains with wildcards match
      for (let [domain, isActiveOnDomain] of domains.entries()) {
        if (hasWildcard(domain)) {
          if (matchesWildcards(docDomain, domain)) {
            return isActiveOnDomain;
          }
        }
      }
    }

    return domains.get("");
  }

  /**
   * Checks whether this filter is active only on a domain and its subdomains.
   * @param {?string} [docDomain]
   * @return {boolean}
   */
  isActiveOnlyOnDomain(docDomain) {
    let {domains} = this;

    if (!domains || domains.get("")) {
      return false;
    }

    if (docDomain == null) {
      docDomain = "";
    }
    else if (docDomain[docDomain.length - 1] == ".") {
      docDomain = docDomain.substring(0, docDomain.length - 1);
    }

    if (!docDomain) {
      return false;
    }

    for (let [domain, isIncluded] of domains) {
      if (isIncluded && domain != docDomain) {
        if (domain.length <= docDomain.length) {
          return false;
        }

        if (!domain.endsWith("." + docDomain)) {
          return false;
        }
      }
    }

    return true;
  }

  /**
   * Checks whether this filter is generic or specific
   * @return {boolean}
   */
  isGeneric() {
    let {sitekeys, domains} = this;

    return !(sitekeys && sitekeys.length) && (!domains || domains.get(""));
  }

  /**
   * Yields the filter itself (required to optimize
   *   {@link module:matcher.Matcher Matcher}).
   * @yields {module:filterClasses.ActiveFilter}
   * @package
   */
  *[Symbol.iterator]() {
    yield this;
  }
};

let URLFilter =
/**
 * Abstract base class for URL filters
 * @extends module:filterClasses.ActiveFilter
 */
exports.URLFilter = class URLFilter extends ActiveFilter {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} regexpSource
   *   filter part that the regular expression should be build from
   * @param {number} [contentType]
   *   Content types the filter applies to, combination of values from
   *   `{@link module:contentTypes.contentTypes}`
   * @param {boolean} [matchCase]
   *   Defines whether the filter should distinguish between lower and upper
   *   case letters
   * @param {string} [domains]
   *   Domains that the filter is restricted to, e.g. "foo.com|bar.com|~baz.com"
   * @param {boolean} [thirdParty]
   *   Defines whether the filter should apply to third-party or first-party
   *   content only
   * @param {string} [sitekeys]
   *   Public keys of websites that this filter should apply to
   * @param {?HttpHeader} [header]
   *   Header-based filtering.
   * @param {?string} [rewrite]
   *   The name of the internal resource to which to rewrite the
   *   URL. e.g. if the value of the `$rewrite` option is
   *   `abp-resource:blank-html`, this should be `blank-html`.
   *
   * @private
   */
  constructor(text, regexpSource, contentType, matchCase, domains, thirdParty,
              sitekeys, header, rewrite) {
    super(text, domains);

    this._sitekeySource = sitekeys == null ? null : sitekeys;
    this._sitekeys = sitekeys == null ? null : void 0;

    /**
     * Content types the filter applies to, combination of values from
     * `{@link module:contentTypes.contentTypes}`
     * @type {number}
     */
    this.contentType = contentType != null ? contentType : RESOURCE_TYPES;

    /**
     * Defines whether the filter should apply to third-party or
     * first-party content only. Can be null (apply to all content).
     * @type {?boolean}
     */
    this.thirdParty = thirdParty != null ? thirdParty : null;

    /**
     * Header-based filtering expression. Refer to the filter
     * documentation reference for the syntax, or
     * `{@link BlockingFilter.filterHeaders}` for the reference
     * implementation.
     * @type {?HttpHeader}
     */
    this.header = header != null ? header : null;

    /**
     * The name of the internal resource to which to rewrite the
     * URL. e.g. if the value of the `$rewrite` option is
     * `abp-resource:blank-html`, this should be `blank-html`.
     * @type {?string}
     */
    this.rewrite = rewrite != null ? rewrite : null;

    /**
     * Pattern for matching request URLs
     * @type {Pattern}
     */
    this.urlPattern = new Pattern(regexpSource, matchCase);
  }

  /**
   * Expression from which a regular expression should be generated -
   * for delayed creation of the regexp property.
   *
   * Undefined if the filter uses a regex literal pattern.
   * @type {?string}
   * @deprecated Use <code>filter.urlPattern.pattern</code>, or other
   * functions available on <code>{@link module:patterns.Pattern}</code>.
   */
  get pattern() {
    return this.urlPattern.pattern;
  }

  /**
   * Regular expression to be used when testing against this pattern
   * @type {RegExp}
   * @deprecated Use <code>filter.urlPattern.regexp</code>, or other
   * functions available on <code>{@link module:patterns.Pattern}</code>.
   */
  get regexp() {
    return this.urlPattern.regexp;
  }

  /**
   * Defines whether the filter should distinguish between lower and
   * upper case letters
   * @type {boolean}
   */
  get matchCase() {
    return this.urlPattern.matchCase;
  }

  /**
   * @see ActiveFilter.domainSeparator
   */
  get domainSeparator() {
    return "|";
  }

  /**
   * @see ActiveFilter.sitekeys
   */
  get sitekeys() {
    if (typeof this._sitekeys == "undefined") {
      this._sitekeys = this._sitekeySource.split("|");
    }

    return this._sitekeys;
  }

  /**
   * @see ActiveFilter.sitekeySource
   */
  get sitekeySource() {
    return this._sitekeySource;
  }

  /**
   * Tests whether the URL request matches this filter
   * @param {module:url.URLRequest} request URL request to be tested
   * @param {number} typeMask bitmask of content / request types to match
   * @param {?string} [sitekey] public key provided by the document
   * @return {boolean} true in case of a match
   */
  matches(request, typeMask, sitekey) {
    let contextMask = typeMask & CONTEXT_TYPES;
    let resourceMask = typeMask & ~CONTEXT_TYPES;
    return (this.contentType & resourceMask) != 0 &&
      (contextMask == 0 ?
       (this.contentType & CONTEXT_TYPES) == 0 :
       (this.contentType & contextMask) != 0
      ) &&
      (this.thirdParty == null || this.thirdParty == request.thirdParty) &&
      (this.urlPattern.regexp ?
       this.isActiveOnDomain(request.documentHostname, sitekey) &&
       this.urlPattern.matchesLocation(request) :
       this.urlPattern.matchesLocation(request) &&
       this.isActiveOnDomain(request.documentHostname, sitekey));
  }
};

/**
 * Creates a URL filter from its text representation
 *
 * @param {string} filterText   same as in Filter()
 * @return {module:filterClasses.Filter}
 */
exports.URLFilter.fromText = function(filterText) {
  let result = parse(filterText);

  if (result instanceof FilterParsingError) {
    let option = null;
    if (result.message == "filter_unknown_option" && result.detail) {
      option = result.detail.option;
    }
    return new InvalidFilter(filterText, result.message, option);
  }

  let {
    blocking,
    text,
    regexpSource,
    contentType,
    matchCase,
    domains,
    thirdParty,
    sitekeys,
    header,
    rewrite,
    csp
  } = result;

  try {
    if (blocking) {
      return new BlockingFilter(
        text,
        regexpSource,
        contentType,
        matchCase,
        domains,
        thirdParty,
        sitekeys,
        header,
        rewrite,
        csp
      );
    }
    return new AllowingFilter(
      text,
      regexpSource,
      contentType,
      matchCase,
      domains,
      thirdParty,
      sitekeys,
      header
    );
  }
  catch (e) {
    return new InvalidFilter(filterText, "filter_invalid_regexp");
  }
};

/**
 * @deprecated Use <code>{@link contentTypes}</code> instead.
 * @see contentTypes
 */
// For backwards compatibility.
URLFilter.typeMap = contentTypes;

let BlockingFilter =
/**
 * Class for blocking filters
 * @extends module:filterClasses.URLFilter
 */
exports.BlockingFilter = class BlockingFilter extends URLFilter {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} regexpSource see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {number} [contentType] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {boolean} [matchCase] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {string} [domains] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {boolean} [thirdParty] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {string} [sitekeys] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {?HttpHeader} [header] see
   *   {@link module:filterClasses.URLFilter URLFilter()}
   * @param {?string} [rewrite]
   *   The name of the internal resource to which to rewrite the
   *   URL. e.g. if the value of the `$rewrite` option is
   *   `abp-resource:blank-html`, this should be `blank-html`.
   * @param {?string} [csp]
   *   Content Security Policy to inject when the filter matches
   *
   * @private
   */
  constructor(text, regexpSource, contentType, matchCase, domains, thirdParty,
              sitekeys, header, rewrite, csp) {
    super(
      text,
      regexpSource,
      contentType,
      matchCase,
      domains,
      thirdParty,
      sitekeys,
      header,
      rewrite
    );

    /**
     * Content Security Policy to inject for matching requests.
     * @type {?string}
     */
    this.csp = csp != null ? csp : null;
  }

  get type() {
    return "blocking";
  }

  get requiresPrivilegedSubscription() {
    return (this.contentType & contentTypes.HEADER) != 0;
  }

  /**
   * Rewrites an URL.
   * @param {string} url the URL to rewrite
   * @return {string} the rewritten URL, or the original in case of failure
   */
  rewriteUrl(url) {
    return resourceMap.get(this.rewrite) || url;
  }

  /**
   * Filter headers.
   *
   * This function would be called by the request blocker code after
   * matching the request.
   *
   * @param {webRequest.HttpHeaders} headers the HTTP response headers
   *   to match, as they are returned by the request blocker. They
   *   follow the {@link webRequest API
   *   https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/HttpHeaders}.
   * @return {boolean} Whether the headers match. Will return true if
   *   there is nothing to match against, or if the header is present
   *   but no value.
   */
  filterHeaders(headers) {
    if (!this.header) {
      return true;
    }

    for (let header of headers) {
      if (header.name.toLowerCase() == this.header.name) {
        if (this.header.value) {
          if (header.value.includes(this.header.value)) {
            return true;
          }
        }
        else {
          return true;
        }
      }
    }

    return false;
  }
};

let AllowingFilter =
/**
 * Class for allowing (allowlisting) filters
 * @extends module:filterClasses.URLFilter
 */
exports.AllowingFilter = class AllowingFilter extends URLFilter {
  get type() {
    return "allowing";
  }
};

let ContentFilter =
/**
 * Base class for content filters
 * @extends module:filterClasses.ActiveFilter
 */
exports.ContentFilter = class ContentFilter extends ActiveFilter {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} [domains] Host names or domains the filter should be
   *                           restricted to
   * @param {string} body      The body of the filter or the script that should
   *                           be executed or the CSS selector for the HTML
   *                           elements that should be hidden
   *
   * @private
   */
  constructor(text, domains, body) {
    super(text, domains || null);

    this.body = body;
  }
};

/**
 * Creates a content filter from a pre-parsed text representation
 *
 * @param {string} text         same as in Filter()
 * @param {string} [domains]
 *   domains part of the text representation
 * @param {string} [type]
 *   rule type, either:
 *     * "" for an element hiding filter
 *     * "@" for an element hiding exception filter
 *     * "?" for an element hiding emulation filter
 *     * "$" for a snippet filter
 * @param {string} body
 *   body part of the text representation, either a CSS selector or a snippet
 *   script
 * @return {module:filterClasses.ElemHideFilter|
 *          module:filterClasses.ElemHideException|
 *          module:filterClasses.ElemHideEmulationFilter|
 *          module:filterClasses.SnippetFilter|
 *          module:filterClasses.InvalidFilter}
 */
exports.ContentFilter.fromText = function(text, domains, type, body) {
  // We don't allow content filters which have any empty domains.
  // Note: The ContentFilter.prototype.domainSeparator is duplicated here, if
  // that changes this must be changed too.
  if (domains && /(^|,)~?(,|$)/.test(domains)) {
    return new InvalidFilter(text, "filter_invalid_domain");
  }

  let restrictedByDomain = /,[^~][^,.]*\.[^,]/.test("," + domains) ||
      ("," + domains + ",").includes(",localhost,");

  if (type == "?" || type == "$") {
    // Element hiding emulation and snippet filters are inefficient so we need
    // to make sure that they're only applied if they specify active domains.
    // The only exception is "hide-if-classifies" snippet (EE-138).

    if (type == "?") {
      if (!restrictedByDomain) {
        return new InvalidFilter(text, "filter_elemhideemulation_nodomain");
      }

      return new ElemHideEmulationFilter(text, domains, body);
    }

    let snippetFilter = new SnippetFilter(text, domains, body);
    if (!restrictedByDomain && !snippetFilter.script.startsWith("hide-if-classifies")) {
      return new InvalidFilter(text, "filter_snippet_nodomain");
    }
    return snippetFilter;
  }

  if (!restrictedByDomain &&
      body.length < MIN_GENERIC_CONTENT_FILTER_BODY_LENGTH) {
    return new InvalidFilter(text, "filter_elemhide_not_specific_enough");
  }

  if (type == "@") {
    return new ElemHideException(text, domains, body);
  }

  return new ElemHideFilter(text, domains, body);
};

let ElemHideBase =
/**
 * Base class for element hiding filters
 * @extends module:filterClasses.ContentFilter
 */
exports.ElemHideBase = class ElemHideBase extends ContentFilter {
  /**
   * CSS selector for the HTML elements that should be hidden
   * @type {string}
   */
  get selector() {
    return this.body;
  }
};

let ElemHideFilter =
/**
 * Class for element hiding filters
 * @extends module:filterClasses.ElemHideBase
 */
exports.ElemHideFilter = class ElemHideFilter extends ElemHideBase {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} [domains]  see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   * @param {string} selector see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   *
   * @private
   */
  constructor(text, domains, selector) {
    super(text, domains, selector);
  }

  get type() {
    return "elemhide";
  }
};

let ElemHideException =
/**
 * Class for element hiding exceptions
 * @extends module:filterClasses.ElemHideBase
 */
exports.ElemHideException = class ElemHideException extends ElemHideBase {
  /**
   * @param {string} text see {@link module:filterClasses.Filter Filter()}
   * @param {string} [domains]  see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   * @param {string} selector see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   *
   * @private
   */
  constructor(text, domains, selector) {
    super(text, domains, selector);
  }

  get type() {
    return "elemhideexception";
  }
};

let ElemHideEmulationFilter =
/**
 * Class for element hiding emulation filters
 */
exports.ElemHideEmulationFilter =
class ElemHideEmulationFilter extends ElemHideBase {
  /**
   * @param {string} text    see {@link module:filterClasses.Filter Filter()}
   * @param {string} domains see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   * @param {string} selector see
   *   {@link module:filterClasses.ElemHideBase ElemHideBase()}
   * @constructor
   * @extends module:filterClasses.ElemHideBase
   *
   * @private
   */
  constructor(text, domains, selector) {
    super(text, domains, selector);
  }

  get type() {
    return "elemhideemulation";
  }
};

let SnippetFilter =
/**
 * Class for snippet filters
 * @extends module:filterClasses.ContentFilter
 */
exports.SnippetFilter = class SnippetFilter extends ContentFilter {
  get type() {
    return "snippet";
  }
  get requiresPrivilegedSubscription() {
    return true;
  }

  /**
   * Script that should be executed
   * @type {string}
   */
  get script() {
    return this.body;
  }
};


/***/ }),

/***/ "./core/lib/filterEngine.js":
/*!**********************************!*\
  !*** ./core/lib/filterEngine.js ***!
  \**********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_318804__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



__nested_webpack_require_318804__(/*! ./polyfill */ "./core/lib/polyfill.js");
const {parseURL} = __nested_webpack_require_318804__(/*! ./url */ "./core/lib/url.js");
const {Filter} = __nested_webpack_require_318804__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {newDefaultMatcher} = __nested_webpack_require_318804__(/*! ./matcher */ "./core/lib/matcher.js");
const {ElemHide} = __nested_webpack_require_318804__(/*! ./elemHide */ "./core/lib/elemHide.js");
const {ElemHideEmulation} = __nested_webpack_require_318804__(/*! ./elemHideEmulation */ "./core/lib/elemHideEmulation.js");
const {ElemHideExceptions} = __nested_webpack_require_318804__(/*! ./elemHideExceptions */ "./core/lib/elemHideExceptions.js");
const {setRecommendations} = __nested_webpack_require_318804__(/*! ./recommendations */ "./core/lib/recommendations.js");
const {Snippets} = __nested_webpack_require_318804__(/*! ./snippets */ "./core/lib/snippets.js");
const {profiler} = __nested_webpack_require_318804__(/*! ./profiler */ "./core/lib/profiler.js");
const {Features} = __nested_webpack_require_318804__(/*! ./features */ "./core/lib/features.js");

/**
 * Filter engine.
 */
class FilterEngine {
  /**
   * @typedef FilterEngineOptions
   * @type {object}
   * @property {?Array.<object>} recommendations The index of known downloadable
   *   subscriptions.
   * @property {?module:features.Features} features Enable specific features
   */
  /**
   * Creates a `{@link module:filterEngine.FilterEngine FilterEngine}`
   * object.
   *
   * @param {?FilterEngineOptions} options The options to create the engine.
   */
  constructor(options) {
    this.p = profiler("FilterEngine");

    this.p.start();

    /** Activated features
     * @type {Features}
     */
    this.features = options ? options.features : Features.DEFAULT;

    if (options && options.recommendations) {
      setRecommendations(options.recommendations);
    }

    /** The `{@link module:elemHideExceptions.ElemHideExceptions}` for
     *    the engine.
     * @type {module:elemHideExceptions.ElemHideExceptions}
     */
    this.elemHideExceptions = new ElemHideExceptions();
    /** The `{@link module:elemHide.ElemHide}` for the engine.
     * @type {module:elemHide.ElemHide}
     */
    this.elemHide = new ElemHide(this.elemHideExceptions);
    /** The `{@link module:elemHideEmulation.ElemHideEmulation}` for
     *    the engine.
     * @type {module:elemHideEmulation.ElemHideEmulation}
     */
    this.elemHideEmulation = new ElemHideEmulation(this.elemHideExceptions);
    /** The `{@link module:snippets.Snippets}` for the engine.
     * @type {module:snippets.Snippets}
     */
    this.snippets = new Snippets();
    /** The `{@link module:matcher.CombinedMatcher}` to use with the engine.
     * @type {module:matcher.CombinedMatcher}
     */
    this.defaultMatcher = newDefaultMatcher();

    /** The `{@link module:filterListener.FilterListener}` to use.
     * @type {?module:filterListener.FilterListener}
     */
    this._filterListener = null;
    /** The `{@link module:filterStorage.FilterStorage}` to use.
     * @type {?module:filterStorage.FilterStorage}
     */
    this._filterStorage = null;

    /**
     * The promise returned by
     * `{@link module:filterEngine.FilterEngine#initialize}`.
     * @type {?Promise}
     * @private
     */
    this._initializationPromise = null;
  }

  /**
   * Initializes a `{@link module:filterEngine.FilterEngine FilterEngine}`
   * object with the given filters or filters loaded from disk.
   *
   * @param {Iterable.<string>} [filterSource] An iterable object that yields
   *   the text of the filters with which to initialize the
   *   `{@link module:filterEngine.FilterEngine FilterEngine}` object. If
   *   omitted, filters are loaded from disk.
   *
   * @returns {Promise} A promise that is fulfilled when the initialization is
   *   complete.
   *
   * @public
   */
  initialize(filterSource) {
    this.p.mark("initialize");
    if (!this._initializationPromise) {
      if (typeof filterSource == "undefined") {
        // Note: filterListener.js and filterStorage.js must be loaded
        // conditionally here in local scope in order for the engine
        // to be able to work in standalone mode with no disk and
        // network I/O.
        const {FilterStorage} = __nested_webpack_require_318804__(/*! ./filterStorage */ "./core/lib/filterStorage.js");
        const {FilterListener} = __nested_webpack_require_318804__(/*! ./filterListener */ "./core/lib/filterListener.js");
        this._filterStorage = new FilterStorage({features: this.features});
        this._filterListener = new FilterListener();
        this._initializationPromise = this._filterListener.initialize(
          this, this._filterStorage
        );
      }
      else {
        this._initializationPromise = Promise.resolve().then(() => {
          for (let text of filterSource) {
            text = Filter.normalize(text, true);
            if (text) {
              let filter = Filter.fromText(text);
              if (filter.type !== "invalid") {
                this.add(filter);
              }
            }
          }
        }).finally(() => {
          this.p.mark("download_done");
        });
      }
    }

    return this._initializationPromise;
  }

  get filterStorage() {
    return this._filterStorage;
  }

  /**
   * Selects the appropriate module for the given filter type.
   *
   * @param {string} type The type of a filter. This must be one of
   *   `"blocking"`, `"allowing"`, `"elemhide"`, `"elemhideemulation"`,
   *   `"elemhideexception"`, and `"snippet"`; otherwise the function returns
   *   `null`.
   *
   * @returns {?object} The appropriate module for the given filter type.
   */
  selectModule(type) {
    switch (type) {
      case "blocking":
      case "allowing":
        return this.defaultMatcher;
      case "elemhide":
        return this.elemHide;
      case "elemhideemulation":
        return this.elemHideEmulation;
      case "elemhideexception":
        return this.elemHideExceptions;
      case "snippet":
        return this.snippets;
    }

    return null;
  }

  /**
   * Adds a new filter.
   * @param {module:filterClasses.ActiveFilter} filter
   * @package
   */
  add(filter) {
    let module = this.selectModule(filter.type);
    if (module) {
      module.add(filter);
    }
  }

  /**
   * Removes an existing filter.
   * @param {module:filterClasses.ActiveFilter} filter
   * @package
   */
  remove(filter) {
    let module = this.selectModule(filter.type);
    if (module) {
      module.remove(filter);
    }
  }

  /**
   * Checks whether a filter exists.
   * @param {module:filterClasses.ActiveFilter} filter
   * @returns {boolean}
   * @package
   */
  has(filter) {
    let module = this.selectModule(filter.type);
    if (module) {
      return module.has(filter);
    }
    return false;
  }

  /**
   * Clears all filters.
   * @package
   */
  clear() {
    this.defaultMatcher.clear();
    this.elemHide.clear();
    this.elemHideEmulation.clear();
    this.elemHideExceptions.clear();
    this.snippets.clear();
  }

  /**
   * Matches existing URL filters against a web resource
   * (HTML document, CSS style sheet, PNG image, etc.) and returns the matching
   * filter if there's a match.
   *
   * @param {string|URL|module:url~URLInfo} url The URL of the resource.
   * @param {number} typeMask The
   *   {@link module:contentTypes.contentTypes content types} associated with
   *   the resource.
   * @param {string} documentHostname The hostname of the document of the
   *   resource.
   * @param {?string} [sitekey] An optional public key associated with the
   *   document of the resource.
   * @param {boolean} [specificOnly] Whether to ignore any generic filters.
   *
   * @returns {?string} A URL filter if there's a match; otherwise `null`.
   *
   * @public
   */
  match(url, typeMask, documentHostname, sitekey = null, specificOnly = false) {
    if (typeof url == "string") {
      url = parseURL(url);
    }

    let filter = this.defaultMatcher.match(
      url, typeMask, documentHostname, sitekey, specificOnly
    );
    return filter ? filter.text : null;
  }
}

/**
 * The `FilterEngine` class maintains filters for request blocking, element
 * hiding, and snippets.
 *
 * @public
 *
 * @example
 *
 * let {contentTypes, FilterEngine} = require("adblockpluscore");
 *
 * let filterEnginer = new FilterEngine();
 * await filterEngine.initialize(
 *   [
 *     "/annoying-ad^$image",
 *     "||example.com/social-widget.html^"
 *   ]
 * );
 *
 * let resource = {
 *   url: "https://ad-server.example.net/annoying-ad.png",
 *   documentURL: "https://news.example.com/world.html"
 * };
 *
 * let filter = filterEngine.match(resource.url, contentTypes.IMAGE,
 *                                 new URL(resource.documentURL).hostname);
 * console.log(filter); // prints "/annoying-ad^$image"
 */
exports.FilterEngine = FilterEngine;


/***/ }),

/***/ "./core/lib/filterListener.js":
/*!************************************!*\
  !*** ./core/lib/filterListener.js ***!
  \************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_328583__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Synchronization between filter storage and the filter engine.
 */

const {filterNotifier} = __nested_webpack_require_328583__(/*! ./filterNotifier */ "./core/lib/filterNotifier.js");
const {isActiveFilter, Filter} = __nested_webpack_require_328583__(/*! ./filterClasses */ "./core/lib/filterClasses.js");

/**
 * Checks whether filters from a given subscription should be deployed to the
 * filter engine.
 *
 * If the subscription is both valid and enabled, the function returns `true`;
 * otherwise, it returns `false`.
 *
 * @param {module:subscriptionClasses.Subscription} subscription
 *   The subscription.
 *
 * @returns {boolean} Whether filters from the subscription should be deployed
 *   to the filter engine.
 */
function shouldDeployFilters(subscription) {
  return subscription.valid && !subscription.disabled;
}

/**
 * Deploys a filter to the filter engine.
 *
 * The filter is deployed only if it belongs to at least one subscription that
 * is both valid and enabled.
 *
 * If the filter is a snippet filter, or a block filter with the `$header`
 * options, it is deployed only if it belongs to at
 * least one subscription that is valid, enabled, and of
 * {@link module:subscriptionClasses.Subscription#type type}
 * `circumvention` or a
 * {@link module:subscriptionClasses.SpecialSubscription special subscription}
 * that keeps user-defined filters.
 *
 * @param {module:filterEngine.FilterEngine} engine A reference to the
 *   filter engine.
 * @param {module:filterStorage.FilterStorage} storage A reference to
 *   the filter storage.
 * @param {Filter} filter The filter.
 * @param {?Array.<module:subscriptionClasses.Subscription>} [subscriptions]
 *   A list of subscriptions to which the filter belongs. If omitted or `null`,
 *   the information is looked up from
 *   {@link module:filterStorage.filterStorage filter storage}.
 */
function deployFilter(engine, storage, filter, subscriptions = null) {
  if (!isActiveFilter(filter)) {
    return;
  }

  let deploy = false;
  let allowPrivileged = false;
  let requiresPrivilegedSubscription = filter.requiresPrivilegedSubscription;

  for (let subscription of subscriptions ||
                           storage.subscriptions(filter.text)) {
    if (shouldDeployFilters(subscription) &&
        !filter.isDisabledForSubscription(subscription.url)) {
      deploy = true;
      if (!requiresPrivilegedSubscription) {
        break;
      }

      // Allow snippets to be executed only by the circumvention lists or the
      // user's own filters.
      if (subscription.privileged) {
        allowPrivileged = true;
        break;
      }
    }
  }

  if (!deploy) {
    return;
  }

  if (requiresPrivilegedSubscription && !allowPrivileged) {
    return;
  }

  engine.add(filter);
}

/**
 * Undeploys a filter from the filter engine.
 *
 * The filter is undeployed only if it does not belong to at least one
 * subscription that is both valid and enabled.
 *
 * @param {module:filterEngine.FilterEngine} engine A reference to the
 *   filter engine.
 * @param {module:filterStorage.FilterStorage} storage A reference to the
 *   filter storage.
 * @param {module:filterClasses.Filter} filter The filter.
 */
function undeployFilter(engine, storage, filter) {
  if (!isActiveFilter(filter)) {
    return;
  }

  let requiresPrivilegedSubscription = filter.requiresPrivilegedSubscription;

  for (let subscription of storage.subscriptions(filter.text)) {
    if (shouldDeployFilters(subscription) &&
        !filter.isDisabledForSubscription(subscription.url)) {
      if (!requiresPrivilegedSubscription ||
          (requiresPrivilegedSubscription && subscription.privileged)) {
        return;
      }
    }
  }

  engine.remove(filter);
}

/**
 * `{@link module:filterListener.filterListener filterListener}`
 * implementation.
 */
class FilterListener {
  /**
   * Initializes filter listener on startup, registers the necessary hooks.
   *
   * Initialization is asynchronous; once complete,
   * `{@link module:filterNotifier.filterNotifier filterNotifier}` emits the
   * `ready` event.
   *
   * @hideconstructor
   */
  constructor() {
    /**
     * A reference to the filter engine.
     * @type {?module:filterEngine.FilterEngine}
     * @private
     */
    this._engine = null;

    /**
     * A reference to the filter storage
     * @type {?module:filterStorage.FilterStorage}
     * @private
     */
    this._storage = null;

    /**
     * Increases on filter changes, filters will be saved if it exceeds 1.
     * @type {number}
     * @private
     */
    this._isDirty = 0;
  }

  /**
   * Initializes filter listener.
   * @param {module:filterEngine.FilterEngine} engine A reference to the
   *   filter engine.
   * @param {module:filterStorage.FilterStorage} storage A reference to the
   *   filter storage.
   * @returns {Promise} A promise that is fulfilled when the initialization is
   *   complete.
   * @package
   */
  async initialize(engine, storage) {
    if (engine == null || typeof engine != "object") {
      throw new Error("engine must be a non-null object.");
    }
    if (storage == null || typeof storage != "object") {
      throw new Error("filterStorage must be a non-null object.");
    }

    if (this._engine != null || this._storage != null) {
      throw new Error("Filter listener already initialized.");
    }

    this._engine = engine;
    this._storage = storage;

    await storage.loadFromDisk();

    let promise = Promise.resolve();

    // Initialize filters from each subscription asynchronously on startup by
    // setting up a chain of promises.
    for (let subscription of storage.subscriptions()) {
      if (shouldDeployFilters(subscription)) {
        await promise.then(() => {
          for (let text of subscription.filterText()) {
            deployFilter(
              this._engine, storage, Filter.fromText(text), [subscription]
            );
          }
        });
      }
    }

    filterNotifier.on("filter.added", this._onFilterAdded.bind(this));
    filterNotifier.on("filter.removed", this._onFilterRemoved.bind(this));
    filterNotifier.on("filter.moved", this._onGenericChange.bind(this));

    filterNotifier.on("filterState.enabled",
                      this._onFilterStateEnabled.bind(this));
    filterNotifier.on("filterState.disabledSubscriptions",
                      this._onFilterStateEnabled.bind(this));
    filterNotifier.on("filterState.hitCount",
                      this._onFilterStateHitCount.bind(this));
    filterNotifier.on("filterState.lastHit",
                      this._onFilterStateLastHit.bind(this));

    filterNotifier.on("subscription.added",
                      this._onSubscriptionAdded.bind(this));
    filterNotifier.on("subscription.removed",
                      this._onSubscriptionRemoved.bind(this));
    filterNotifier.on("subscription.disabled",
                      this._onSubscriptionDisabled.bind(this));
    filterNotifier.on("subscription.updated",
                      this._onSubscriptionUpdated.bind(this));
    filterNotifier.on("subscription.title", this._onGenericChange.bind(this));
    filterNotifier.on("subscription.fixedTitle",
                      this._onGenericChange.bind(this));
    filterNotifier.on("subscription.homepage",
                      this._onGenericChange.bind(this));
    filterNotifier.on("subscription.downloadStatus",
                      this._onGenericChange.bind(this));
    filterNotifier.on("subscription.lastCheck",
                      this._onGenericChange.bind(this));
    filterNotifier.on("subscription.errors",
                      this._onGenericChange.bind(this));
    filterNotifier.on("subscription.privileged",
                      this._onGenericChange.bind(this));

    filterNotifier.on("load", this._onLoad.bind(this));
    filterNotifier.on("save", this._onSave.bind(this));

    // Indicate that all filters are ready for use.
    filterNotifier.emit("ready");
  }

  /**
   * Increases "dirty factor" of the filters and calls
   * filterStorage.saveToDisk() if it becomes 1 or more.
   *
   * Save is executed delayed to prevent multiple subsequent calls. If the
   * parameter is 0 it forces saving filters if any changes were recorded after
   * the previous save.
   *
   * @param {number} factor
   *
   * @private
   */
  _setDirty(factor) {
    if (factor == 0 && this._isDirty > 0) {
      this._isDirty = 1;
    }
    else {
      this._isDirty += factor;
    }
    if (this._isDirty >= 1) {
      this._isDirty = 0;
      this._storage.saveToDisk();
    }
  }

  _onSubscriptionAdded(subscription) {
    this._setDirty(1);

    if (shouldDeployFilters(subscription)) {
      for (let text of subscription.filterText()) {
        deployFilter(
          this._engine, this._storage, Filter.fromText(text), [subscription]
        );
      }
    }
  }

  _onSubscriptionRemoved(subscription) {
    this._setDirty(1);

    if (shouldDeployFilters(subscription)) {
      for (let text of subscription.filterText()) {
        undeployFilter(this._engine, this._storage, Filter.fromText(text));
      }
    }
  }

  _onSubscriptionDisabled(subscription, newValue) {
    this._setDirty(1);

    if (this._storage.hasSubscription(subscription)) {
      if (newValue == false) {
        for (let text of subscription.filterText()) {
          deployFilter(
            this._engine, this._storage, Filter.fromText(text), [subscription]
          );
        }
      }
      else {
        for (let text of subscription.filterText()) {
          undeployFilter(this._engine, this._storage, Filter.fromText(text));
        }
      }
    }
  }

  _onSubscriptionUpdated(subscription, textDelta) {
    this._setDirty(1);

    if (textDelta && shouldDeployFilters(subscription) &&
        this._storage.hasSubscription(subscription)) {
      for (let text of textDelta.removed) {
        undeployFilter(
          this._engine, this._storage, Filter.fromText(text)
        );
      }

      for (let text of textDelta.added) {
        deployFilter(
          this._engine, this._storage, Filter.fromText(text), [subscription]
        );
      }
    }
  }

  _onFilterAdded(filter) {
    this._setDirty(1);
    deployFilter(this._engine, this._storage, filter);
  }

  _onFilterRemoved(filter) {
    this._setDirty(1);
    undeployFilter(this._engine, this._storage, filter);
  }

  _onFilterStateEnabled(text, newValue) {
    this._setDirty(1);

    // it's difficult to tell from newValue alone if we need to add or
    // remove the filter. Luckily, deployFilter and undeployFilter do
    // full checks that the filter should be added / removed.
    let filter = Filter.fromText(text);
    if (this._engine.has(filter)) {
      undeployFilter(this._engine, this._storage, filter);
    }
    else {
      deployFilter(this._engine, this._storage, filter);
    }
  }

  _onFilterStateHitCount(text, newValue) {
    if (newValue == 0) {
      this._setDirty(0);
    }
    else {
      this._setDirty(0.002);
    }
  }

  _onFilterStateLastHit() {
    this._setDirty(0.002);
  }

  _onGenericChange() {
    this._setDirty(1);
  }

  _onLoad() {
    this._isDirty = 0;

    this._engine.clear();

    for (let subscription of this._storage.subscriptions()) {
      if (shouldDeployFilters(subscription)) {
        for (let text of subscription.filterText()) {
          deployFilter(
            this._engine, this._storage, Filter.fromText(text), [subscription]
          );
        }
      }
    }
  }

  _onSave() {
    this._isDirty = 0;
  }
}

/**
 * Component synchronizing filter storage with the filter engine.
 * @package
 */
exports.FilterListener = FilterListener;


/***/ }),

/***/ "./core/lib/filterNotifier.js":
/*!************************************!*\
  !*** ./core/lib/filterNotifier.js ***!
  \************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_341210__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file This component manages listeners and calls them to distribute
 * messages about filter changes.
 */

const {EventEmitter} = __nested_webpack_require_341210__(/*! ./events */ "./core/lib/events.js");

/**
 * This object allows registering and triggering listeners for filter events.
 * @type {module:events.EventEmitter}
 */
exports.filterNotifier = new EventEmitter();


/***/ }),

/***/ "./core/lib/filterState.js":
/*!*********************************!*\
  !*** ./core/lib/filterState.js ***!
  \*********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_342540__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



const {filterNotifier} = __nested_webpack_require_342540__(/*! ./filterNotifier */ "./core/lib/filterNotifier.js");
const {Filter} = __nested_webpack_require_342540__(/*! ./filterClasses */ "./core/lib/filterClasses.js");

class FilterState {
  /**
   * Construct a new FilterState.
   * As a side effect this will set the global FilterState used
   * by Filter. Avoid constructing it more than once.
   */
  constructor() {
    /**
     * Internal map containing filter state.
     * @type {Map.<string, FilterStateEntry>}
     */
    this.map = new Map();

    // For now we'll assume that this is the filter state
    Filter.useFilterState(this);
  }

  /**
   * Gets which subscriptions this filters has been disabled for.
   * @param {string} filterText The text of the filter.
   * @returns {Set<string>} Set of subscription urls that this filter
   * has been disabled for.
   */
  disabledSubscriptions(filterText) {
    let state = this.map.get(filterText);
    if (!state || typeof state.disabledSubscriptions !== "object") {
      return new Set();
    }
    return state.disabledSubscriptions;
  }

  /**
   * Reset the disabled status of this filter to the default of
   * enabled for all subscriptions.
   * @param {string} filterText The text of the filter.
   */
  resetEnabled(filterText) {
    this._updateStateObject(filterText, state => {
      state.resetEnabled();
    });
  }

  /**
   * Checks whether a filter is disabled for a subscription.
   * @param {string} filterText The text of the filter.
   * @param {string} subscriptionUrl The subscription to check for
   * enabled / disabled state.
   * @returns {boolean} Whether the filter is disabled.
   */
  isDisabledForSubscription(filterText, subscriptionUrl) {
    let state = this.map.get(filterText);
    if (state) {
      return state.isDisabledForSubscription(subscriptionUrl);
    }
    return false;
  }

  /**
   * Sets the disabled state of a filter for a subscription.
   * @param {string} filterText The text of the filter.
   * @param {string} subscriptionUrl The subscription to enable /
   * disable the filter in.
   * @param {boolean} disabled The new disabled state of the filter.
   */
  setDisabledForSubscription(filterText, subscriptionUrl, disabled) {
    this._updateStateObject(filterText, state => {
      state.setDisabledForSubscription(subscriptionUrl, disabled);
    });
  }

  /**
   * Checks whether a filter is enabled.
   * @param {string} filterText The text of the filter.
   * @returns {boolean} Whether the filter is enabled.
   * @deprecated Use
   * {@link module:filterState.FilterState#isDisabledForSubscription} instead
   */
  isEnabled(filterText) {
    let state = this.map.get(filterText);
    if (state) {
      return state.enabled;
    }
    return true;
  }

  /**
   * Sets the enabled state of a filter.
   * @param {string} filterText The text of the filter.
   * @param {boolean} enabled The new enabled state of the filter.
   * @deprecated Use
   * {@link module:filterState.FilterState#setDisabledForSubscription} instead
   */
  setEnabled(filterText, enabled) {
    this._updateStateObject(filterText, state => {
      state.enabled = enabled;
    });
  }

  /**
   * Toggles the enabled state of a filter.
   * @param {string} filterText The text of the filter.
   * @deprecated Use
   * {@link module:filterState.FilterState#setDisabledForSubscription} instead
   */
  toggleEnabled(filterText) {
    let newValue = !this.isEnabled(filterText);
    this.setEnabled(filterText, newValue);
  }

  /**
   * Returns the hit count of a filter.
   * @param {string} filterText The text of the filter.
   * @returns {number} The hit count of the filter.
   */
  getHitCount(filterText) {
    let state = this.map.get(filterText);
    if (state) {
      return state.hitCount;
    }

    return 0;
  }

  /**
   * Sets the hit count of a filter.
   * @param {string} filterText The text of the filter.
   * @param {number} hitCount The new hit count of the filter.
   */
  setHitCount(filterText, hitCount) {
    this._updateStateObject(filterText, state => {
      state.hitCount = hitCount;
    });
  }

  /**
   * Resets the hit count of a filter.
   * @param {string} filterText The text of the filter.
   */
  resetHitCount(filterText) {
    this.setHitCount(filterText, 0);
  }

  /**
   * Returns the last hit time of a filter.
   * @param {string} filterText The text of the filter.
   * @returns {number} The last hit time of the filter in milliseconds since
   *   the Unix epoch.
   */
  getLastHit(filterText) {
    let state = this.map.get(filterText);
    if (state) {
      return state.lastHit;
    }

    return 0;
  }

  /**
   * Sets the last hit time of a filter.
   * @param {string} filterText The text of the filter.
   * @param {number} lastHit The new last hit time of the filter in
   *   milliseconds since the Unix epoch.
   */
  setLastHit(filterText, lastHit) {
    this._updateStateObject(filterText, state => {
      state.lastHit = lastHit;
    });
  }

  /**
   * Resets the last hit time of a filter.
   * @param {string} filterText The text of the filter.
   */
  resetLastHit(filterText) {
    this.setLastHit(filterText, 0);
  }

  /**
   * Registers a filter hit by incrementing the hit count of the filter and
   * setting the last hit time of the filter to the current time.
   * @param {string} filterText The text of the filter.
   */
  registerHit(filterText) {
    let now = Date.now();
    this._updateStateObject(filterText, state => {
      state.hitCount++;
      state.lastHit = now;
    });
  }

  /**
   * Resets the hit count and last hit time of a filter.
   * @param {string} filterText The text of the filter.
   */
  resetHits(filterText) {
    this._updateStateObject(filterText, state => {
      state.hitCount = 0;
      state.lastHit = 0;
    });
  }

  /**
   * Resets the enabled state, hit count, and last hit time of a filter.
   * @param {string} filterText The text of the filter.
   */
  reset(filterText) {
    let state = this.map.get(filterText);
    if (!state) {
      return;
    }

    this.map.delete(filterText);

    if (state.enabled !== true) {
      filterNotifier.emit("filterState.enabled",
                          filterText,
                          true,
                          state.enabled);
    }

    if (state.disabledSubscriptions && state.disabledSubscriptions.size > 0) {
      filterNotifier.emit("filterState.disabledSubscriptions",
                          filterText,
                          new Set(),
                          state.disabledSubscriptions);
    }

    if (state.hitCount != 0) {
      filterNotifier.emit("filterState.hitCount",
                          filterText,
                          0,
                          state.hitCount);
    }

    if (state.lastHit != 0) {
      filterNotifier.emit("filterState.lastHit", filterText, 0, state.lastHit);
    }
  }

  /**
   * Serializes the state of a filter.
   * @param {string} filterText The text of the filter.
   * @yields {string} The next line in the serialized representation of the
   *   state of the filter.
   * @see module:filterState.FilterState#fromObject
   * @package
   */
  *serialize(filterText) {
    let state = this.map.get(filterText);
    if (!state) {
      return;
    }

    yield "[Filter]";
    yield "text=" + filterText;

    if (state.disabled) {
      yield "disabled=true";
    }
    else if (typeof state.disabledSubscriptions === "object") {
      for (let disabledSubscription of state.disabledSubscriptions) {
        yield "disabledSubscriptions[]=" + disabledSubscription;
      }
    }

    if (state.hitCount != 0) {
      yield "hitCount=" + state.hitCount;
    }
    if (state.lastHit != 0) {
      yield "lastHit=" + state.lastHit;
    }
  }

  /**
   * Reads the state of a filter from an object representation.
   * @param {string} filterText The text of the filter.
   * @param {Object} object An object containing at least one of `disabled`,
   *   `hitCount`, and `lastHit` properties and their appropriate values.
   * @see module:filterState.FilterState#serialize
   * @package
   */
  fromObject(filterText, object) {
    if (!("disabled" in object ||
          "disabledSubscriptions" in object ||
          "hitCount" in object ||
          "lastHit" in object)) {
      return;
    }

    let state = new FilterStateEntry();
    if (String(object.disabled) == "true") {
      state.disabled = true;
    }
    else if (typeof object.disabledSubscriptions === "object") {
      state.disabledSubscriptions = new Set(object.disabledSubscriptions);
    }

    state.hitCount = parseInt(object.hitCount, 10) || 0;
    state.lastHit = parseInt(object.lastHit, 10) || 0;
    if (!state.isEmpty()) {
      this.map.set(filterText, state);
    }
  }

  _updateStateObject(filterText, doUpdate) {
    let state = this.map.get(filterText);
    if (!state) {
      state = new FilterStateEntry();
      this.map.set(filterText, state);
    }

    let oldHitCount = state.hitCount;
    let oldLastHit = state.lastHit;
    let oldEnabled = state.enabled;
    let oldDisabledSubscriptions = new Set(state.disabledSubscriptions);

    doUpdate(state);

    let newHitCount = state.hitCount;
    let newLastHit = state.lastHit;
    let newEnabled = state.enabled;
    let newDisabledSubscriptions = new Set(state.disabledSubscriptions);

    if (state.isEmpty()) {
      this.map.delete(filterText);
    }

    if (oldHitCount !== newHitCount) {
      filterNotifier.emit("filterState.hitCount",
                          filterText,
                          newHitCount,
                          oldHitCount);
    }

    if (oldLastHit !== newLastHit) {
      filterNotifier.emit("filterState.lastHit",
                          filterText,
                          newLastHit,
                          oldLastHit);
    }

    if (oldEnabled !== newEnabled) {
      filterNotifier.emit("filterState.enabled",
                          filterText,
                          newEnabled,
                          oldEnabled);
    }

    if (!disabledSubscriptionsEquals(oldDisabledSubscriptions,
                                     newDisabledSubscriptions)) {
      filterNotifier.emit("filterState.disabledSubscriptions",
                          filterText,
                          newDisabledSubscriptions,
                          oldDisabledSubscriptions);
    }
  }
}

/**
 * Represents the state for a single filter.
 * See {@link module:filterState.FilterState}
 */
class FilterStateEntry {
  constructor() {
    /**
     * The hit count of the filter.
     * @type {number}
     */
    this.hitCount = 0;

    /**
     * The last hit time of the filter in milliseconds since the Unix epoch.
     * @type {number}
     */
    this.lastHit = 0;
  }

  /**
   * Check if the state is empty, so we know if we can clean it up.
   * @returns {boolean}
   */
  isEmpty() {
    return this.hitCount === 0 &&
      this.lastHit === 0 &&
      !this.disabled &&
      !this.disabledSubscriptions;
  }

  /**
   * Check if a filter is disabled for a specified subscription.
   * @param {string} subscriptionUrl The subscription to check for
   * enabled / disabled state.
   * @returns {boolean}
   */
  isDisabledForSubscription(subscriptionUrl) {
    if (this.disabled === true) {
      return true;
    }
    return this.disabledSubscriptions &&
      this.disabledSubscriptions.has(subscriptionUrl);
  }

  /**
   * Sets the disabled state of a filter.
   * @param {string} subscriptionUrl The subscription to enable /
   * disable the filter in.
   * @param {boolean} disabled The new disabled state of the filter.
   */
  setDisabledForSubscription(subscriptionUrl, disabled) {
    delete this.disabled;

    if (!this.disabledSubscriptions && !disabled) {
      return;
    }

    if (!this.disabledSubscriptions) {
      this.disabledSubscriptions = new Set();
    }

    if (disabled) {
      this.disabledSubscriptions.add(subscriptionUrl);
    }
    else {
      this.disabledSubscriptions.delete(subscriptionUrl);
      if (this.disabledSubscriptions.size === 0) {
        delete this.disabledSubscriptions;
      }
    }
  }

  /**
   * Reset the disabled status of this filter to the default of
   * enabled for all subscriptions.
   */
  resetEnabled() {
    delete this.disabled;
    delete this.disabledSubscriptions;
  }

  /**
   * Representation of filter state for the deprecated global enabling
   * and disabling of filters, as well as the `filterState.enabled`
   * events.
   * @type {boolean}
   * @deprecated Prefer {@link isDisabledForSubscription}
   */
  get enabled() {
    return !this.disabled;
  }
  set enabled(value) {
    delete this.disabledSubscriptions;
    this.disabled = !value;
  }
}

/**
 * Checks if two sets of disabled subscription urls contain exactly
 * the same subscription urls.
 * @param {Set<string>} oldDisabledSubscriptions
 * @param {Set<string>} newDisabledSubscriptions
 * @returns {boolean}
 */
function disabledSubscriptionsEquals(oldDisabledSubscriptions,
                                     newDisabledSubscriptions) {
  if (oldDisabledSubscriptions.size !== newDisabledSubscriptions.size) {
    return false;
  }

  for (let old of oldDisabledSubscriptions) {
    if (!newDisabledSubscriptions.has(old)) {
      return false;
    }
  }
  return true;
}

/**
 * Maintains filter state.
 */
exports.FilterState = FilterState;


/***/ }),

/***/ "./core/lib/filterStorage.js":
/*!***********************************!*\
  !*** ./core/lib/filterStorage.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_356931__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file `filterStorage` object responsible for managing the user's
 * subscriptions and filters.
 */

const {IO} = __nested_webpack_require_356931__(/*! io */ "./sdk/api/io.js");
const {Prefs} = __nested_webpack_require_356931__(/*! prefs */ "./sdk/api/prefs.js");
const {isActiveFilter} = __nested_webpack_require_356931__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {Subscription, SpecialSubscription} = __nested_webpack_require_356931__(/*! ./subscriptionClasses */ "./core/lib/subscriptionClasses.js");
const {filterNotifier} = __nested_webpack_require_356931__(/*! ./filterNotifier */ "./core/lib/filterNotifier.js");
const {INIParser} = __nested_webpack_require_356931__(/*! ./iniParser */ "./core/lib/iniParser.js");
const {FilterState} = __nested_webpack_require_356931__(/*! ./filterState */ "./core/lib/filterState.js");
const {Synchronizer} = __nested_webpack_require_356931__(/*! ./synchronizer */ "./core/lib/synchronizer.js");
const {Features} = __nested_webpack_require_356931__(/*! ./features */ "./core/lib/features.js");

/**
 * The Error type returned by filter storage.
 *
 * @property {Object} detail Contains information about the error.
 * @property {string} [detail.text] The text of the filter for
     `filter_not_found`.
 * @property {Array.<string>} [detail.exist] The list of duplicate
 *   filters.
 */
class FilterStorageError extends Error {
  /** Construct a FilterParsingError
   * @constructor
   * @param {string} message The error message.
   * @param {Object} detail The `FilterStorageError` detail.
   */
  constructor(message, detail) {
    super(message);
    this.detail = detail;
  }
}

exports.FilterStorageError = FilterStorageError;

/**
 * @typedef {Object} Stats
 * @property {boolean} exists
 * @property {number} lastModified
 */

/**
 * A cache for all source files and backup stats.
 * @type {Map<string, Stats>}
 * @private
 */
let stats = new Map();

/**
 * An asynchronous guard for multiple backups renmaing operations. It gets
 * reassigned to a new Promise that rename all backups one more time.
 * @type {Promise<void>}
 * @private
 */
let backupQueue = Promise.resolve();

/**
 * Version number of the filter storage file format.
 * @type {number}
 */
const FORMAT_VERSION = 5;

/**
 * Reads the user's filters from disk, manages them in memory, and writes them
 * back to disk.
 */
class FilterStorage {
  /**
   * @typedef FilterStorageOptions
   * @type {object}
   * @property {?module:features.Features} features Enable specific features
   */
  /**
   * Construct a FilterStorage
   *
   * @param {?FilterStorageOptions} options The options to create the storage.
   */
  constructor(options) {
    /**
     * Will be set to `true` after the initial
     * `{@link module:filterStorage.FilterStorage#loadFromDisk loadFromDisk()}`
     * call completes.
     * @type {boolean}
     */
    this.initialized = false;

    /**
     * Will be set to `true` if no `patterns.ini` file exists.
     * @type {boolean}
     */
    this.firstRun = false;

    /** Activated features
     * @type {Features}
     */
    this.features = options ? options.features : Features.DEFAULT;
    Subscription.dnr = (this.features & Features.DNR) != 0;

    /**
     * Map of properties listed in the filter storage file before the sections
     * start. Right now this should be only the format version.
     * @type {Object}
     */
    this.fileProperties = Object.create(null);

    /**
     * Map of subscriptions already on the list, by their URL/identifier.
     * @type {Map.<string,module:subscriptionClasses.Subscription>}
     * @private
     */
    this._knownSubscriptions = new Map();

    /**
     * Map of subscriptions with metadata, by their URL/identifier.
     *
     * It can be used to answer "which subscriptions have metadata?".
     * @type {Map.<string,module:subscriptionClasses.Subscription>}
     * @private
     */
    this._metadataSubscriptions = new Map();

    /**
     * Will be set to `true` if
     * `{@link module:filterStorage.FilterStorage#saveToDisk saveToDisk()}`
     * is running (reentrance protection).
     * @type {boolean}
     * @private
     */
    this._saving = false;
    this._initSaving();

    /**
     * Will be set to `true` if a
     * `{@link module:filterStorage.FilterStorage#saveToDisk saveToDisk()}`
     * call arrives while
     * `{@link module:filterStorage.FilterStorage#saveToDisk saveToDisk()}`
     * is already running (delayed execution).
     * @type {boolean}
     * @private
     */
    this._needsSave = false;

    /**
     * This property is for testing purpose only and it should never be used
     * directly via code.
     * @type {Map<string, Stats>}
     * @private
     */
    this._stats = stats;

    this.synchronizer = new Synchronizer(this);
    this.filterState = new FilterState();
  }

  _initSaving() {
    if (this._saving) {
      const fs = this;
      this._savingPromise = new Promise((resolve, reject) => {
        fs._savingPromiseResolve = resolve;
        fs._savingPromiseReject = reject;
      });
    }
    else {
      if (this._savingPromiseResolve) {
        this._savingPromiseResolve();
      }

      this._savingPromise = null;
      this._savingPromiseResolve = null;
      this._savingPromiseReject = null;
    }
  }

  setSaving(newValue, skipInit = false) {
    if (newValue == this._saving) {
      return;
    }
    this._saving = newValue;
    if (!skipInit) {
      this._initSaving();
    }
  }

  /**
   * The version number of the `patterns.ini` format used.
   * @type {number}
   */
  get formatVersion() {
    return FORMAT_VERSION;
  }

  /**
   * The file containing the subscriptions.
   * @type {string}
   */
  static get sourceFile() {
    return "patterns.ini";
  }

  /**
   * Yields subscriptions in the storage.
   * @param {?string} [filterText] The filter text for which to look. If
   *   specified, the function yields only those subscriptions that contain the
   *   given filter text. By default the function yields all subscriptions.
   * @yields {module:subscriptionClasses.Subscription}
   */
  *subscriptions(filterText = null) {
    if (filterText == null) {
      yield* this._knownSubscriptions.values();
    }
    else {
      for (let subscription of this._knownSubscriptions.values()) {
        if (subscription.hasFilterText(filterText)) {
          yield subscription;
        }
      }
    }
  }

  /**
   * Returns the number of subscriptions in the storage.
   * @param {?string} [filterText] The filter text for which to look. If
   *   specified, the function counts only those subscriptions that contain the
   *   given filter text. By default the function counts all subscriptions.
   * @returns {number}
   */
  getSubscriptionCount(filterText = null) {
    if (filterText == null) {
      return this._knownSubscriptions.size;
    }

    let count = 0;
    for (let subscription of this._knownSubscriptions.values()) {
      if (subscription.hasFilterText(filterText)) {
        count++;
      }
    }
    return count;
  }

  /**
   * Finds the filter group that a filter should be added to by default. Will
   * return `null` if this group doesn't exist yet.
   * @param {Filter} filter
   * @returns {?module:subscriptionClasses.SpecialSubscription}
   */
  getGroupForFilter(filter) {
    let generalSubscription = null;
    for (let subscription of this._knownSubscriptions.values()) {
      // We ignore disabled subscriptions and subscriptions
      // without metadata
      if (
        subscription instanceof SpecialSubscription &&
        !subscription.disabled && !subscription.metadata
      ) {
        // Always prefer specialized subscriptions
        if (subscription.isDefaultFor(filter)) {
          return subscription;
        }

        // If this is a general subscription - store it as fallback
        if (!generalSubscription &&
            (!subscription.defaults || !subscription.defaults.length)) {
          generalSubscription = subscription;
        }
      }
    }
    return generalSubscription;
  }

  /**
   * Checks whether a given subscription is in the storage.
   * @param {module:subscriptionClasses.Subscription|string} subscription
   *   or the URL of the subscription.
   * @returns {boolean}
   */
  hasSubscription(subscription) {
    if (typeof subscription == "string") {
      return this._knownSubscriptions.has(subscription);
    }

    return this._knownSubscriptions.has(subscription.url);
  }

  /**
   * Get the the subscription from the storage.
   * @param {string} subscription The URL of the subscription.
   * @returns {module:subscriptionClasses.Subscription}
   */
  getSubscription(subscription) {
    return this._knownSubscriptions.get(subscription);
  }

  /**
   * Adds a subscription to the storage.
   * @param {module:subscriptionClasses.Subscription} subscription The
   *   subscription to be added.
   */
  addSubscription(subscription) {
    if (this._knownSubscriptions.has(subscription.url)) {
      return;
    }

    this._knownSubscriptions.set(subscription.url, subscription);

    filterNotifier.emit("subscription.added", subscription);
  }

  /**
   * Removes a subscription from the storage.
   * @param {module:subscriptionClasses.Subscription} subscription The
   *   subscription to be removed.
   */
  removeSubscription(subscription) {
    if (!this._knownSubscriptions.has(subscription.url)) {
      return;
    }

    this._knownSubscriptions.delete(subscription.url);
    this._metadataSubscriptions.delete(subscription.url);

    // This should be the last remaining reference to the Subscription
    // object.
    Subscription.knownSubscriptions.delete(subscription.url);

    filterNotifier.emit("subscription.removed", subscription);
  }

  /**
   * Removes all the subscriptions from the storage (fast, for testing).
   * @private
   */
  _clear() {
    this._knownSubscriptions.clear();
    this._metadataSubscriptions.clear();
    Subscription.knownSubscriptions.clear();
    this._stats.clear();

    // not using `setSaving(false)` as it might not resolve
    // possible saving promise if reSaving is in progress.
    this._saving = false;
    this._initSaving();

    this._needsSave = false;

    this.filterState = new FilterState();
  }

  /**
   * Replaces the list of filters in a subscription with a new list.
   * @param {module:subscriptionClasses.Subscription} subscription The
   *   subscription to be updated.
   * @param {Array.<string>} filterText The new filter text.
   */
  updateSubscriptionFilters(subscription, filterText) {
    let update = subscription.updateFilterText(filterText);
    filterNotifier.emit(
      "subscription.updated",
      subscription,
      update
    );
    if (this.features & Features.DNR) {
      filterNotifier.emit(
        "subscription.dnrUpdated",
        subscription,
        update
      );
    }
  }

  /**
   * Check the filters pass and return the list of the filters that exist.
   *
   * @param {Array.<Filter>} filters The filters to check.
   * @return {Array.<Filter>} The list of filters that exists. An empty
   *   list mean that none do exist.
   */
  filtersExist(filters) {
    let exist = [];

    for (let filter of filters) {
      for (let currentSubscription of this._knownSubscriptions.values()) {
        if (currentSubscription instanceof SpecialSubscription &&
            !currentSubscription.disabled &&
            currentSubscription.hasFilterText(filter.text)) {
          exist.push(filter);
        }
      }
    }

    return exist;
  }

  /**
   * Adds user-defined filters to the storage with metadata.
   *
   * @async
   * @param {Filter|Array<Filter>} filters Filter(s) to add. If the list
   *   contains duplicate entries, they'll be skipped.
   * @param {Object} metadata The metadata block.
   *
   * @return {Promise<module:subscriptionClasses.SpecialSubscription>} the
   *   subscription the filter is in, or throw an error if any of the filter
   *   is already present in a `SpecialSubscription`.
   */
  async addFiltersWithMetadata(filters, metadata) {
    let list = Array.isArray(filters) ? filters : [filters];

    let exist = this.filtersExist(list);
    if (exist.length != 0) {
      throw new FilterStorageError("storage_duplicate_filters", {exist});
    }

    let subscription = null;

    for (let filter of list) {
      if (!subscription) {
        subscription = SpecialSubscription.createForFilter(filter);
      }
      // We make sure we don't have a duplicate already from `filters`.
      else if (!subscription.hasFilterText(filter.text)) {
        subscription.addFilter(filter);
      }
    }

    this._metadataSubscriptions.set(subscription.url, subscription);
    this.addSubscription(subscription);

    for (let filter of list) {
      if (this.filterState.isDisabledForSubscription(
        filter.text, subscription.url)) {
        this.filterState.setDisabledForSubscription(
          filter.text, subscription.url, false);
      }
    }

    subscription.metadata = metadata;

    return subscription;
  }

  /**
   * Get the metadata for a filter.
   *
   * @async
   * @param {string} text The filter text.
   * @return {Promise<?Object>} The metadata if any found.
   *
   * This function will iterate through all the subscriptions with metadata
   * to find a `SpecialSubscription` that contains the filter text.
   */
  async getMetadataForFilter(text) {
    for (let currentSubscription of this._metadataSubscriptions.values()) {
      if (currentSubscription.hasFilterText(text)) {
        return currentSubscription.metadata;
      }
    }

    return null;
  }

  /**
   * Set the metadata for a filter that already has metadata.
   *
   * A filter can have metadata only if it was added using
   * `addFiltersWithMetadata()`. It is currently not possible to add metadata
   * to an existing custom filter that was added with `addFilter()`. In that
   * case, the function will return a `filter_not_found` error.
   *
   * @async
   * @param {string} text The filter text.
   * @param {Object} metadata The metadata.
   *
   * @return {Promise<module:subscriptionClasses.SpecialSubscription>} The
   *   subscription whose metadata was changed.
   */
  async setMetadataForFilter(text, metadata) {
    for (let currentSubscription of this._metadataSubscriptions.values()) {
      if (currentSubscription.hasFilterText(text)) {
        currentSubscription.metadata = metadata;
        return currentSubscription;
      }
    }

    throw new FilterStorageError("filter_not_found", {text});
  }

  /**
   * Checks and enables the filter for the subscription.
   * @param {string} filterText The filter text.
   * @param {string} subscriptionUrl The subscription URL to enable filter for.
   * @private
   */
  enableFilter(filterText, subscriptionUrl) {
    if (this.filterState.isDisabledForSubscription(
      filterText, subscriptionUrl)) {
      this.filterState.setDisabledForSubscription(
        filterText, subscriptionUrl, false);
    }
  }

  /**
   * Adds a user-defined filter to the storage.
   *
   * @async
   * @param {Filter} filter
   * @param {?module:subscriptionClasses.SpecialSubscription} [subscription]
   *   The subscription that the filter should be added to.
   * @param {number} [position] The position within the subscription at which
   *   the filter should be added. If not specified, the filter is added at the
   *   end of the subscription.
   *
   * @return {Promise<module:subscriptionClasses.SpecialSubscription>} The
   *   subscription the filter is in. Either existing or added.
   */
  async addFilter(filter, subscription, position) {
    if (!subscription) {
      for (let currentSubscription of this._knownSubscriptions.values()) {
        if (currentSubscription instanceof SpecialSubscription &&
            !currentSubscription.disabled &&
            currentSubscription.hasFilterText(filter.text)) {
          throw new FilterStorageError("storage_duplicate_filters",
                                       {exist: [filter]});  // No need to add
        }
      }
      subscription = this.getGroupForFilter(filter);
    }
    if (!subscription) {
      // No group for this filter exists, create one
      subscription = SpecialSubscription.createForFilter(filter);
      this.addSubscription(subscription);
      this.enableFilter(filter.text, subscription.url);
      return subscription;
    }

    if (typeof position == "undefined") {
      position = subscription.filterCount;
    }

    subscription.insertFilterTextAt(filter.text, position);
    this.enableFilter(filter.text, subscription.url);
    filterNotifier.emit("filter.added", filter, subscription, position);
    return subscription;
  }

  /**
   * Removes a user-defined filter from the storage.
   * @param {module:filterClasses.Filter} filter
   * @param {?module:subscriptionClasses.SpecialSubscription} [subscription]
   *   The subscription that the filter should be removed from. If not
   *   specified, the filter will be removed from all subscriptions.
   * @param {number} [position] The position within the subscription at which
   *   the filter should be removed. If not specified, all instances of the
   *   filter will be removed.
   */
  removeFilter(filter, subscription, position) {
    let subscriptions = (
      subscription ? [subscription] : this._knownSubscriptions.values()
    );
    for (let currentSubscription of subscriptions) {
      if (currentSubscription instanceof SpecialSubscription &&
          (currentSubscription == subscription ||
           currentSubscription.hasFilterText(filter.text))) {
        let positions = [];
        if (typeof position == "undefined") {
          let index = -1;
          do {
            index = currentSubscription.findFilterTextIndex(
              filter.text, index + 1);
            if (index >= 0) {
              positions.push(index);
            }
          } while (index >= 0);
        }
        else {
          positions.push(position);
        }

        for (let j = positions.length - 1; j >= 0; j--) {
          let currentPosition = positions[j];
          let currentFilterText =
            currentSubscription.filterTextAt(currentPosition);
          if (currentFilterText && currentFilterText == filter.text) {
            currentSubscription.deleteFilterAt(currentPosition);
            filterNotifier.emit(
              "filter.removed", filter, currentSubscription, currentPosition
            );
          }
        }
      }
    }
  }

  /**
   * Moves a user-defined filter to a new position.
   * @param {module:filterClasses.Filter} filter
   * @param {module:subscriptionClasses.SpecialSubscription} subscription The
   *   subscription where the filter is located.
   * @param {number} oldPosition The current position of the filter.
   * @param {number} newPosition The new position of the filter.
   */
  moveFilter(filter, subscription, oldPosition, newPosition) {
    if (!(subscription instanceof SpecialSubscription)) {
      return;
    }

    let currentFilterText = subscription.filterTextAt(oldPosition);
    if (!currentFilterText || currentFilterText != filter.text) {
      return;
    }

    newPosition = Math.min(Math.max(newPosition, 0),
                           subscription.filterCount - 1);
    if (oldPosition == newPosition) {
      return;
    }

    subscription.deleteFilterAt(oldPosition);
    subscription.insertFilterTextAt(filter.text, newPosition);
    filterNotifier.emit(
      "filter.moved", filter, subscription, oldPosition, newPosition
    );
  }

  /**
   * Increases the hit count for a filter by one.
   * @param {Filter} filter
   */
  increaseHitCount(filter) {
    if (!Prefs.savestats || !isActiveFilter(filter)) {
      return;
    }

    this.filterState.registerHit(filter.text);
  }

  /**
   * Resets hit count for some filters.
   * @param {?Array.<Filter>} [filters] The filters to be reset. If not
   *   specified, all filters will be reset.
   */
  resetHitCounts(filters) {
    if (filters) {
      for (let filter of filters) {
        this.filterState.resetHits(filter.text);
      }
    }
    else {
      for (let text of this.filterState.map.keys()) {
        this.filterState.resetHits(text);
      }
    }
  }

  /**
   * @callback TextSink
   * @param {string?} line
   */

  /**
   * Allows importing previously serialized filter data.
   * @param {boolean} silent If `true`, no "load" notification will be sent
   *   out.
   * @returns {TextSink} The function to be called for each line of data.
   *   Calling it with `null` as the argument finalizes the import and replaces
   *   existing data. No changes will be applied before finalization, so import
   *   can be "aborted" by forgetting this callback.
   * @package
   */
  importData(silent) {
    let parser = new INIParser(this.filterState);
    return line => {
      parser.process(line);
      if (line === null) {
        let knownSubscriptions = new Map();
        let metadataSubscriptions = new Map();
        for (let subscription of parser.subscriptions) {
          // Convert to the new terminology when loading.
          if (Array.isArray(subscription.defaults)) {
            subscription.defaults.forEach((type, i, arr) => {
              if (type == "whitelist") {
                arr[i] = "allowing";
              }
            });
          }
          knownSubscriptions.set(subscription.url, subscription);
          if (subscription.metadata) {
            metadataSubscriptions.set(subscription.url, subscription);
          }
        }

        this.fileProperties = parser.fileProperties;
        this._knownSubscriptions = knownSubscriptions;
        this._metadataSubscriptions = metadataSubscriptions;

        if (!silent) {
          filterNotifier.emit("load");
        }
      }
    };
  }

  /**
   * Loads all subscriptions from disk.
   * @returns {Promise} A promise resolved or rejected when loading is complete.
   * @package
   */
  async loadFromDisk() {
    let tryBackup = async backupIndex => {
      try {
        await this.restoreBackup(backupIndex, true);
      }
      catch (error) {
        // Give up
      }
    };

    try {
      let statData = await statFile(FilterStorage.sourceFile);

      if (!statData.exists) {
        this.firstRun = true;
        return;
      }

      let parser = this.importData(true);
      await IO.readFromFile(FilterStorage.sourceFile, parser);
      parser(null);
    }
    catch (error) {
      console.warn(error);
      await tryBackup(1);
    }

    this.initialized = true;
    filterNotifier.emit("load");
  }

  /**
   * Constructs the file name for a `patterns.ini` backup.
   * @param {number} backupIndex Number of the backup file (1 being the most
   *   recent).
   * @returns {string} Backup file name.
   * @package
   */
  static getBackupName(backupIndex) {
    let [name, extension] = FilterStorage.sourceFile.split(".", 2);
    return (name + "-backup" + backupIndex + "." + extension);
  }

  /**
   * Restores an automatically created backup.
   * @param {number} backupIndex Number of the backup to restore (1 being the
   *   most recent).
   * @param {boolean} silent If `true`, no "load" notification will be sent
   *   out.
   * @returns {Promise} A promise resolved or rejected when restoration is
   *   complete.
   * @package
   */
  async restoreBackup(backupIndex, silent) {
    let backupFile = FilterStorage.getBackupName(backupIndex);
    let parser = this.importData(silent);
    await IO.readFromFile(backupFile, parser);
    parser(null);
    return this.saveToDisk();
  }

  /**
   * Generator serializing filter data and yielding it line by line.
   * @yields {string}
   */
  *exportData() {
    // Do not persist external subscriptions
    let subscriptions = [];
    for (let subscription of this._knownSubscriptions.values()) {
      if (!(subscription instanceof SpecialSubscription &&
            subscription.filterCount == 0)) {
        subscriptions.push(subscription);
      }
    }

    yield "# Adblock Plus preferences";
    yield "version=" + this.formatVersion;

    let saved = new Set();

    // Save subscriptions
    for (let subscription of subscriptions) {
      yield* subscription.serialize();
      yield* subscription.serializeFilters();
    }

    // Save filter data
    for (let subscription of subscriptions) {
      for (let text of subscription.filterText()) {
        if (!saved.has(text)) {
          yield* this.filterState.serialize(text);
          saved.add(text);
        }
      }
    }
  }

  /**
   * Saves all subscriptions back to disk.
   * @param {boolean} [skipInitSavePromise=false] Skip init new saving promise
   * @returns {Promise} A promise resolved or rejected when saving is complete.
   * @package
   */
  async saveToDisk(skipInitSavePromise = false) {
    if (this._saving) {
      this._needsSave = true;
      return;
    }

    this.setSaving(true, skipInitSavePromise);
    try {
      let {patternsbackups} = Prefs;
      let isBackupRequired = async() => {
        // First check whether we need to create a backup
        if (patternsbackups <= 0) {
          return false;
        }

        let statData = await statFile(FilterStorage.sourceFile);
        if (!statData.exists) {
          return false;
        }

        let backupStatData = await statFile(FilterStorage.getBackupName(1));
        if (backupStatData.exists &&
            (Date.now() - backupStatData.lastModified) / 3600000 <
              Prefs.patternsbackupinterval) {
          return false;
        }

        return true;
      };

      if (await isBackupRequired()) {
        try {
          // if patternsbackups is 1 just create it, otherwise create a
          // backup-0 that will be shifted among others later on
          let i = patternsbackups > 1 ? 0 : 1;
          await renameFile(
            FilterStorage.sourceFile, FilterStorage.getBackupName(i)
          );

          // if there is more than a backup, backup-0 up to backup-X need to be
          // renamed but without blocking this callback
          if (patternsbackups > 1) {
            // keep queueing backups as these come, considering backup1 and
            // backup 0 are always safe thanks to the this._saving flag
            backupQueue = backupQueue.then(() => new Promise(resolve => {
              let renameAll = async index => {
                if (index > 0) {
                  try {
                    let source = FilterStorage.getBackupName(index - 1);
                    let dest = FilterStorage.getBackupName(index);
                    await renameFile(source, dest);
                  }
                  catch (error) {
                    // Expected error, backup file doesn't exist.
                  }
                  renameAll(index - 1);
                }
                else {
                  resolve();
                }
              };
              renameAll(patternsbackups);
            }));
          }
        }
        catch (error) {
          // This is actually an unexpected error that could happen only if
          // the disk had issues in renaming the source file.
          console.warn(error);
        }
      }
    }
    catch (error) {
      // Errors during backup creation shouldn't prevent writing filters.
      console.warn(error);
    }

    try {
      await IO.writeToFile(FilterStorage.sourceFile, this.exportData());
      stats.set(
        FilterStorage.sourceFile, {exists: true, lastModified: Date.now()}
      );
      filterNotifier.emit("save");
    }
    catch (error) {
      // If saving failed, report error but continue -
      // we still have to process flags.
      console.warn(error);
      stats.delete(FilterStorage.sourceFile);
    }

    // if it still needs reSaving, don't resolve current promise here and
    // skip creating new promise in internal `saveToDisk()` below
    this.setSaving(false, this._needsSave);

    if (this._needsSave) {
      this._needsSave = false;
      this.saveToDisk(true);
    }
  }

  async awaitSavingComplete() {
    if (!this._saving) {
      return;
    }

    await this._savingPromise;
  }

  /**
   * @typedef {Object} FileInfo
   * @property {number} index
   * @property {number} lastModified
   */

  /**
   * Returns a promise resolving in a list of existing backup files.
   * @returns {Promise.<Array.<FileInfo>>}
   * @package
   */
  async getBackupFiles() {
    let backups = [];

    let checkBackupFile = async index => {
      try {
        let statData = await statFile(FilterStorage.getBackupName(index));
        if (!statData.exists) {
          return backups;
        }

        backups.push({
          index,
          lastModified: statData.lastModified
        });

        return checkBackupFile(index + 1);
      }
      catch (error) {
        // Something went wrong, return whatever data we got so far.
        console.warn(error);
        return backups;
      }
    };

    return checkBackupFile(1);
  }

  /**
   * Clears the cache
   * @ignore
   */
  clearStats() {
    this._stats.clear();
  }
}

exports.FilterStorage = FilterStorage;

/**
 * Given a path, return its stats, if known, or a Stats object with properties
 * exists = false and lastModified = 0.
 * @param {string} path
 * @returns {Stats}
 */
async function statFile(path) {
  let known = stats.get(path);
  if (known) {
    return known;
  }

  try {
    known = await IO.statFile(path);
  }
  catch (error) {
    known = {exists: false, lastModified: 0};
  }
  stats.set(path, known);
  return known;
}

/**
 * Given a source path and a destination path, tries to rename the source and,
 * if it succeed, remove the source from the stats and set stats for dest.
 * @param {string} source
 * @param {string} dest
 */
async function renameFile(source, dest) {
  await IO.renameFile(source, dest);
  stats.delete(source);
  stats.set(dest, {exists: true, lastModified: Date.now()});
}


/***/ }),

/***/ "./core/lib/filters/index.js":
/*!***********************************!*\
  !*** ./core/lib/filters/index.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_387779__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/** @module */

const {contentTypes, RESOURCE_TYPES} = __nested_webpack_require_387779__(/*! ../contentTypes */ "./core/lib/contentTypes.js");

/**
 * Regular expression that content filters should match
 * @type {RegExp}
 */
const CONTENT_FILTER = /^([^/|@"!]*?)#([@?$])?#(.+)$/;
exports.CONTENT_FILTER = CONTENT_FILTER;

/**
 * Regular expression that options on a RegExp filter should match
 * @type {RegExp}
 */
const FILTER_OPTIONS = /\$(~?[\w-]+(?:=[^,]*)?(?:,~?[\w-]+(?:=[^,]*)?)*)$/;
exports.FILTER_OPTIONS = FILTER_OPTIONS;

// used to reduce possible short filters damage
const MIN_GENERIC_URL_FILTER_PATTERN_LENGTH = 4;

/**
 * Regular expression that matches an invalid Content Security Policy
 * @type {RegExp}
 */
const INVALID_CSP = /(;|^) ?(base-uri|referrer|report-to|report-uri|upgrade-insecure-requests)\b/i;
exports.INVALID_CSP = INVALID_CSP;

/**
 * The Error type returned by parse.
 *
 * For example `filter_unknown_option` will have `option`.
 * @property {Object} detail Contains information about the error.
 * @property {string} [detail.option] The option for `filter_unknown_option`.
 * @property {string} [detail.regexp] The regexp for `filter_invalid_regexp`.
 * @property {string} detail.text The text of the rejected filter.
 */
class FilterParsingError extends Error {
  /** Construct a FilterParsingError
   * @constructor
   * @param {string} message The error message.
   * @param {Object} detail The FilterParsingError detail. Contains at
   *   least `text`.
   */
  constructor(message, detail) {
    super(message);
    this.detail = detail;
  }
}

exports.FilterParsingError = FilterParsingError;

/**
 * @typedef {Object} ParsedFilter
 * @property {bool} blocking Whether it's a blocking filter or not.
 * @property {string} text The filter text.
 * @property {string} regexpSource The source of the matching RegExp.
 * @property {number} contentType The
 *   {@link module:contentTypes.contentTypes content types} for the filter.
 * @property {bool?} matchCase If the filter is case sensitive.
 * @property {Array<string>?} domains The domains to match
 *   (`$domains` option).
 * @property {Array<string>?} sitekeys The sitekeys to match.
 * @property {object?} headers The headers filtering.
 * @property {string?} rewrite The URL for to rewrite to.
 * @property {string?} csp The CSP directive.
 */

/**
 * Parse the filter text representation into a structure.
 *
 * This is meant to be called by
 * {module:filterClasses.URLFilter.fromText}
 *
 * @param {string} text the filter normalized text. Call normalize()
 *   on the text prior to this, unless it is already normalized.
 * @return {ParsedFilter|FilterParsingError}
 *   The parsed filter, or a FilterParsingError.
 */
exports.parse = function parse(text) {
  // exclude empty text, comments, and content filters
  if (text.length < 1) {
    return new FilterParsingError("filter_empty", {text});
  }

  if (text[0] === "!" || CONTENT_FILTER.test(text)) {
    return new FilterParsingError("invalid", {text});
  }

  // parse like an ABP URLFilter
  let blocking = true;
  let origText = text;
  if (text.startsWith("@@")) {
    blocking = false;
    text = text.substring(2);
  }

  let contentType = null;
  let matchCase = null;
  let domains = null;
  let sitekeys = null;
  let thirdParty = null;
  let csp = null;
  let rewrite = null;
  let header = null;
  let options;
  let match = text.includes("$") ? FILTER_OPTIONS.exec(text) : null;
  if (match) {
    text = match.input.substring(0, match.index);

    options = match[1].split(",");
    let cspSet = false;
    let headerSet = false;

    for (let option of options) {
      let value = null;
      let separatorIndex = option.indexOf("=");
      if (separatorIndex >= 0) {
        value = option.substring(separatorIndex + 1);
        option = option.substring(0, separatorIndex);
      }

      let inverse = option[0] == "~";
      if (inverse) {
        option = option.substring(1);
      }

      let optionUpperCase = option.toUpperCase();
      let type = contentTypes[optionUpperCase.replace(/-/, "_")];
      if (type) {
        if (inverse) {
          if (contentType == null) {
            contentType = RESOURCE_TYPES;
          }
          contentType &= ~type;
        }
        else if (type === contentTypes.CSP) {
          if (blocking && !value) {
            return new FilterParsingError("filter_invalid_csp",
                                          {text: origText});
          }
          cspSet = true;
          csp = value;
        }
        else if (type === contentTypes.HEADER) {
          if (blocking && !value) {
            return new FilterParsingError("filter_invalid_header",
                                          {text: origText});
          }
          headerSet = true;
          if (value) {
            let headerRaw = value.replace(/([^\\])\\x2c/g, "$1,")
                .replace(/\\\\x2c/g, "\\x2c");
            let equal = headerRaw.indexOf("=");
            if (equal == headerRaw.length - 1) {
              // This case is "key=" with no value
              header = {
                name: headerRaw.substring(0, equal).toLowerCase()
              };
            }
            else if (equal >= 0) {
              header = {
                name: headerRaw.substring(0, equal).toLowerCase(),
                value: headerRaw.substring(equal + 1)
              };
            }
            else {
              header = {
                name: headerRaw.toLowerCase()
              };
            }

            if (header.name.length == 0) {
              return new FilterParsingError("filter_invalid_header",
                                            {text: origText});
            }
            if (/^\/[\s\S]*\/$/.test(header.value)) {
              return new FilterParsingError("filter_invalid_header",
                                            {text: origText});
            }
          }
        }
        else {
          contentType |= type;
        }
      }
      else {
        switch (optionUpperCase) {
          case "MATCH-CASE":
            matchCase = !inverse;
            break;
          case "DOMAIN":
            if (!value) {
              return new FilterParsingError("filter_unknown_option",
                                            {option, text: origText});
            }
            domains = value;
            break;
          case "THIRD-PARTY":
            thirdParty = !inverse;
            break;
          case "SITEKEY":
            if (!value) {
              return new FilterParsingError("filter_unknown_option",
                                            {option, text: origText});
            }
            // Sitekeys are case-sensitive, they shouldn't be uppercased.
            sitekeys = value;
            break;
          case "REWRITE":
            if (value == null) {
              return new FilterParsingError("filter_unknown_option",
                                            {option, text: origText});
            }
            if (!value.startsWith("abp-resource:")) {
              return new FilterParsingError("filter_invalid_rewrite",
                                            {text: origText});
            }
            rewrite = value.substring("abp-resource:".length);
            break;
          default:
            return new FilterParsingError("filter_unknown_option",
                                          {option, text: origText});
        }
      }
    }
    if (cspSet || headerSet) {
      if (contentType == null) {
        contentType = RESOURCE_TYPES;
      }
      if (cspSet) {
        contentType |= contentTypes.CSP;
      }
      if (headerSet) {
        contentType |= contentTypes.HEADER;
      }
    }
  }

  let isGeneric = !sitekeys && !domains;
  if (isGeneric) {
    let minTextLength = MIN_GENERIC_URL_FILTER_PATTERN_LENGTH;
    let {length} = text;
    if (length > 0 && text[0] === "|") {
      minTextLength++;
      if (length > 1 && text[1] === "|") {
        minTextLength++;
      }
    }
    if (length < minTextLength && !text.includes("*")) {
      return new FilterParsingError("filter_url_not_specific_enough",
                                    {text: origText});
    }
  }
  // We expect filters to use Punycode for domains these days, so let's just
  // skip filters which don't. See #6647.
  else if (domains && /[^\x00-\x7F]/.test(domains)) {
    return new FilterParsingError("filter_invalid_domain", {text: origText});
  }

  if (blocking) {
    if (csp && INVALID_CSP.test(csp)) {
      return new FilterParsingError("filter_invalid_csp", {text: origText});
    }

    if (rewrite) {
      if (text.startsWith("||")) {
        if (!domains && thirdParty != false) {
          return new FilterParsingError("filter_invalid_rewrite",
                                        {text: origText});
        }
      }
      else if (text.startsWith("*")) {
        if (!domains) {
          return new FilterParsingError("filter_invalid_rewrite",
                                        {text: origText});
        }
      }
      else {
        return new FilterParsingError("filter_invalid_rewrite",
                                      {text: origText});
      }
    }
  }

  return {
    blocking,
    text: origText,
    regexpSource: text,
    contentType,
    matchCase,
    domains,
    thirdParty,
    sitekeys,
    header,
    rewrite,
    csp
  };
};

/**
 * Removes unnecessary whitespaces from filter text, will only return null if
 * the input parameter is null.
 *
 * @param {string} text
 * @param {boolean?} dontSanitize avoid expensive operations on text.
 * @return {string}
 */
exports.normalize = function(text, dontSanitize = false) {
  if (text === "") {
    return text;
  }

  // Remove line breaks, tabs etc
  text = text.replace(/[^\S ]+/g, "");

  if (dontSanitize) {
    return text.trim();
  }

  if (!text.includes(" ")) {
    return text;
  }

  // Don't remove spaces inside comments
  if (/^ *!/.test(text)) {
    return text.trim();
  }

  // Special treatment for content filters, right side is allowed to contain
  // spaces
  if (CONTENT_FILTER.test(text)) {
    let [, domains, separator, body] = /^(.*?)(#[@?$]?#?)(.*)$/.exec(text);
    return domains.replace(/ +/g, "") + separator + body.trim();
  }

  // For most regexp filters we strip all spaces, but $csp filter options
  // are allowed to contain single (non trailing) spaces.
  let strippedText = text.replace(/ +/g, "");
  if (!strippedText.includes("$") || !/\b(csp|header)=/i.test(strippedText)) {
    return strippedText;
  }

  let optionsMatch = FILTER_OPTIONS.exec(strippedText);
  if (!optionsMatch) {
    return strippedText;
  }

  // For $csp filters we must first separate out the options part of the
  // text, being careful to preserve its spaces.
  let beforeOptions = strippedText.substring(0, optionsMatch.index);
  let strippedDollarIndex = -1;
  let dollarIndex = -1;
  do {
    strippedDollarIndex = beforeOptions.indexOf("$", strippedDollarIndex + 1);
    dollarIndex = text.indexOf("$", dollarIndex + 1);
  }
  while (strippedDollarIndex != -1);
  let optionsText = text.substring(dollarIndex + 1);

  // Then we can normalize spaces in the options part safely
  let options = optionsText.split(",");
  for (let i = 0; i < options.length; i++) {
    let option = options[i];
    let optionMatch = /^ *(c *s *p|h *e *a *d *e *r) *=/i.exec(option);
    if (optionMatch) {
      options[i] = optionMatch[0].replace(/ +/g, "") +
                   option.substring(optionMatch[0].length).trim().replace(/ +/g, " ");
    }
    else {
      options[i] = option.replace(/ +/g, "");
    }
  }

  return beforeOptions + "$" + options.join();
};


/***/ }),

/***/ "./core/lib/filters/lists.js":
/*!***********************************!*\
  !*** ./core/lib/filters/lists.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



/** @module */

/**
 * Given some text containing a filter list, parse each line and return all
 * details.
 * @param {string} filters The filter list file/text to parse.
 * @returns {Object.<error?, lines?, params?, minVersion?>} All parsed details,
 *  if available. `lines` will contain the header in the first line.
 */
function parseFilterList(filters) {
  let lines = filters.split(/[\r\n]+/);
  // The filter list always start with a header, at minimum `[Adblock]`.
  let headerMatch = /\[Adblock(?:\s*Plus\s*([\d.]+)?)?\]/i.exec(lines[0]);

  if (!headerMatch) {
    return {error: "synchronize_invalid_data"};
  }

  let minVersion = headerMatch[1];

  let params = {
    redirect: null,
    homepage: null,
    title: null,
    version: null,
    expires: null,
    abtest: null,
    diffurl: null
  };

  for (let {hasOwnProperty} = Object.prototype, i = 1; i < lines.length; i++) {
    let match = /^\s*!\s*(.*?)\s*:\s*(.*)/.exec(lines[i]);
    if (!match) {
      break;
    }

    let keyword = match[1].toLowerCase();
    if (hasOwnProperty.call(params, keyword)) {
      params[keyword] = match[2];
      lines.splice(i--, 1);
    }
  }

  return {lines, params, minVersion};
}

exports.parseFilterList = parseFilterList;


/***/ }),

/***/ "./core/lib/filtersByDomain.js":
/*!*************************************!*\
  !*** ./core/lib/filtersByDomain.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * Map to be used instead when a filter has a blank `domains` property.
 * @type {Map.<string, boolean>}
 */
let defaultDomains = new Map([["", true]]);

let FilterMap =
/**
 * A `FilterMap` object contains a set of filters, each mapped to a boolean
 * value indicating whether the filter should be applied.
 *
 * It is used by
 * `{@link module:filtersByDomain.FiltersByDomain FiltersByDomain}`.
 *
 * @package
 */
exports.FilterMap = class FilterMap extends Map {};

/**
 * A `FiltersByDomain` object contains a set of domains, each mapped to a set
 * of filters along with a boolean value for each filter indicating whether the
 * filter should be applied to the domain.
 *
 * @package
 */
exports.FiltersByDomain = class FiltersByDomain extends Map {
  /**
   * Adds a filter and all of its domains to the object.
   *
   * @param {module:filterClasses.ActiveFilter} filter The filter.
   * @param {Map.<string, boolean>} [domains] The filter's domains. If not
   *   given, the `{@link module:filterClasses.ActiveFilter#domains domains}`
   *   property of `filter` is used.
   */
  add(filter, domains = filter.domains) {
    for (let [domain, include] of domains || defaultDomains) {
      if (!include && domain == "") {
        continue;
      }

      let map = this.get(domain);
      if (!map) {
        this.set(domain, include ? filter : new FilterMap([[filter, false]]));
      }
      else if (map.size == 1 && !(map instanceof FilterMap)) {
        if (filter != map) {
          this.set(domain, new FilterMap([[map, true], [filter, include]]));
        }
      }
      else {
        map.set(filter, include);
      }
    }
  }

  /**
   * Removes a filter and all of its domains from the object.
   *
   * @param {module:filterClasses.ActiveFilter} filter The filter.
   * @param {Map.<string, boolean>} [domains] The filter's domains. If not
   *   given, the `{@link module:filterClasses.ActiveFilter#domains domains}`
   *   property of `filter` is used.
   */
  remove(filter, domains = filter.domains) {
    for (let domain of (domains || defaultDomains).keys()) {
      let map = this.get(domain);
      if (map) {
        if (map.size > 1 || map instanceof FilterMap) {
          map.delete(filter);

          if (map.size == 0) {
            this.delete(domain);
          }
          else if (map.size == 1) {
            for (let [lastFilter, include] of map.entries()) {
              // Reduce Map { "example.com" => Map { filter => true } } to
              // Map { "example.com" => filter }
              if (include) {
                this.set(domain, lastFilter);
              }

              break;
            }
          }
        }
        else if (filter == map) {
          this.delete(domain);
        }
      }
    }
  }
};


/***/ }),

/***/ "./core/lib/index.js":
/*!***************************!*\
  !*** ./core/lib/index.js ***!
  \***************************/
/***/ ((module, __unused_webpack_exports, __nested_webpack_require_406297__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @module
 *
 * @borrows module:contentTypes.contentTypes as contentTypes
 * @borrows module:features.Features as Features
 * @borrows module:filterEngine.FilterEngine as FilterEngine
 * @borrows module:synchronizer.Synchronizer as Synchronizer
 * @borrows module:url.parseURL as parseURL
 */



const {contentTypes} = __nested_webpack_require_406297__(/*! ./contentTypes */ "./core/lib/contentTypes.js");
const {Features} = __nested_webpack_require_406297__(/*! ./features */ "./core/lib/features.js");
const {FilterEngine} = __nested_webpack_require_406297__(/*! ./filterEngine */ "./core/lib/filterEngine.js");
const {Synchronizer} = __nested_webpack_require_406297__(/*! ./synchronizer */ "./core/lib/synchronizer.js");
const {parseURL} = __nested_webpack_require_406297__(/*! ./url */ "./core/lib/url.js");

module.exports = {
  contentTypes,
  Features,
  FilterEngine,
  Synchronizer,
  parseURL
};


/***/ }),

/***/ "./core/lib/iniParser.js":
/*!*******************************!*\
  !*** ./core/lib/iniParser.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_408074__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file INI parsing.
 */

const {isActiveFilter, Filter} = __nested_webpack_require_408074__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {FilterState} = __nested_webpack_require_408074__(/*! ./filterState */ "./core/lib/filterState.js");
const {Subscription} = __nested_webpack_require_408074__(/*! ./subscriptionClasses */ "./core/lib/subscriptionClasses.js");

/**
 * Parses filter data.
 * @package
 */
exports.INIParser = class INIParser {
  /** @param {FilterState} filterState the filter state */
  constructor(filterState) {
    if (!(filterState instanceof FilterState)) {
      throw new Error("filterState must be a FilterState object");
    }

    /**
     * Properties of the filter data.
     * @type {Object}
     */
    this.fileProperties = {};

    /**
     * The list of subscriptions in the filter data.
     * @type {Array.<module:subscriptionClasses.Subscription>}
     */
    this.subscriptions = [];

    /** @type {module:filterState.FilterState} */
    this.filterState = filterState;

    this._wantObj = true;
    this._curObj = this.fileProperties;
    this._curSection = null;
  }

  /**
   * Processes a line of filter data.
   *
   * @param {string?} line The line of filter data to process. This may be
   *   `null`, which indicates the end of the filter data.
   */
  process(line) {
    let match = null;
    if (this._wantObj === true && (match = /^(\w+)=(.*)$/.exec(line))) {
      this._curObj[match[1]] = match[2];
    }
    else if (this._wantObj === true && (match = /^(\w+)\[]=(.*)$/.exec(line))) {
      if (!this._curObj[match[1]]) {
        this._curObj[match[1]] = [];
      }
      this._curObj[match[1]].push(match[2]);
    }
    else if (line === null || (match = /^\s*\[(.+)\]\s*$/.exec(line))) {
      if (this._curObj) {
        // Process current object before going to next section
        switch (this._curSection) {
          case "filter":
            if ("text" in this._curObj) {
              let {text} = this._curObj;
              if (isActiveFilter(Filter.fromText(text))) {
                this.filterState.fromObject(text, this._curObj);
              }
            }
            break;

          case "subscription":
            let subscription = Subscription.fromObject(this._curObj);
            if (subscription) {
              this.subscriptions.push(subscription);
            }
            break;

          case "subscription filters":
            if (this.subscriptions.length) {
              let currentSubscription = this.subscriptions[
              this.subscriptions.length - 1
              ];
              currentSubscription.updateFilterText(this._curObj);
            }
            break;
        }
      }

      if (line === null) {
        return;
      }

      this._curSection = match[1].toLowerCase();
      switch (this._curSection) {
        case "filter":
        case "subscription":
          this._wantObj = true;
          this._curObj = {};
          break;
        case "subscription filters":
          this._wantObj = false;
          this._curObj = [];
          break;
        default:
          this._wantObj = null;
          this._curObj = null;
      }
    }
    else if (this._wantObj === false && line) {
      this._curObj.push(line.replace(/\\\[/g, "["));
    }
  }
};


/***/ }),

/***/ "./core/lib/jsbn.js":
/*!**************************!*\
  !*** ./core/lib/jsbn.js ***!
  \**************************/
/***/ ((__unused_webpack_module, exports) => {

/*
 * Copyright (c) 2003-2005  Tom Wu
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * In addition, the following condition applies:
 *
 * All redistributions must retain an intact copy of this copyright notice
 * and disclaimer.
 */

// Basic JavaScript BN library - subset useful for RSA encryption.

// Modified by eyeo GmbH to better support going to and from JS binary
// strings (base 256) and our particular use case.

// Bits per digit
var dbits;

// JavaScript engine analysis
var canary = 0xdeadbeefcafe;
var j_lm = ((canary&0xffffff)==0xefcafe);

// (public) Constructor
let BigInteger = exports.BigInteger = function BigInteger(a,b,c) {
  if(a != null)
    if("number" == typeof a) this.fromNumber(a,b,c);
    else if(b == null && "string" != typeof a) this.fromString(a,256);
    else this.fromString(a,b);
};

// return new, unset BigInteger
function nbi() { return new BigInteger(null); }

// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
// We need to select the fastest one that works in this environment.

// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
function am1(i,x,w,j,c,n) {
  while(--n >= 0) {
    var v = x*this[i++]+w[j]+c;
    c = Math.floor(v/0x4000000);
    w[j++] = v&0x3ffffff;
  }
  return c;
}
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
function am2(i,x,w,j,c,n) {
  var xl = x&0x7fff, xh = x>>15;
  while(--n >= 0) {
    var l = this[i]&0x7fff;
    var h = this[i++]>>15;
    var m = xh*l+h*xl;
    l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
    c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
    w[j++] = l&0x3fffffff;
  }
  return c;
}
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
function am3(i,x,w,j,c,n) {
  var xl = x&0x3fff, xh = x>>14;
  while(--n >= 0) {
    var l = this[i]&0x3fff;
    var h = this[i++]>>14;
    var m = xh*l+h*xl;
    l = xl*l+((m&0x3fff)<<14)+w[j]+c;
    c = (l>>28)+(m>>14)+xh*h;
    w[j++] = l&0xfffffff;
  }
  return c;
}
if(j_lm && (typeof navigator != "undefined" && navigator.appName == "Microsoft Internet Explorer")) { /** MODIFIED **/
  BigInteger.prototype.am = am2;
  dbits = 30;
}
else if(j_lm && (typeof navigator != "undefined" && navigator.appName != "Netscape")) { /** MODIFIED **/
  BigInteger.prototype.am = am1;
  dbits = 26;
}
else { // Mozilla/Netscape seems to prefer am3
  BigInteger.prototype.am = am3;
  dbits = 28;
}

BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = ((1<<dbits)-1);
BigInteger.prototype.DV = (1<<dbits);

var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2,BI_FP);
BigInteger.prototype.F1 = BI_FP-dbits;
BigInteger.prototype.F2 = 2*dbits-BI_FP;

// Digit conversions
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr,vv;
rr = "0".charCodeAt(0);
for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;

function int2char(n) { return BI_RM.charAt(n); }
function intAt(s,i) {
  var c = BI_RC[s.charCodeAt(i)];
  return (c==null)?-1:c;
}

// (protected) copy this to r
function bnpCopyTo(r) {
  for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
  r.t = this.t;
  r.s = this.s;
}

// (protected) set from integer value x, -DV <= x < DV
function bnpFromInt(x) {
  this.t = 1;
  this.s = (x<0)?-1:0;
  if(x > 0) this[0] = x;
  else if(x < -1) this[0] = x+DV;
  else this.t = 0;
}

// return bigint initialized to value
function nbv(i) { var r = nbi(); r.fromInt(i); return r; }

// (protected) set from string and radix
function bnpFromString(s,b) {
  var k;
  if(b == 16) k = 4;
  else if(b == 8) k = 3;
  else if(b == 256) k = 8; // byte array
  else if(b == 2) k = 1;
  else if(b == 32) k = 5;
  else if(b == 4) k = 2;
  else { this.fromRadix(s,b); return; }
  this.t = 0;
  this.s = 0;
  var i = s.length, mi = false, sh = 0;
  while(--i >= 0) {
    var x = (k==8)?s.charCodeAt(i)&0xff:intAt(s,i);   /** MODIFIED **/
    if(x < 0) {
      if(s.charAt(i) == "-") mi = true;
      continue;
    }
    mi = false;
    if(sh == 0)
      this[this.t++] = x;
    else if(sh+k > this.DB) {
      this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
      this[this.t++] = (x>>(this.DB-sh));
    }
    else
      this[this.t-1] |= x<<sh;
    sh += k;
    if(sh >= this.DB) sh -= this.DB;
  }
  if(k == 8 && (s[0]&0x80) != 0) {
    this.s = -1;
    if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  }
  this.clamp();
  if(mi) BigInteger.ZERO.subTo(this,this);
}

// (protected) clamp off excess high words
function bnpClamp() {
  var c = this.s&this.DM;
  while(this.t > 0 && this[this.t-1] == c) --this.t;
}

// (public) return string representation in given radix
function bnToString(b) {
  if(this.s < 0) return "-"+this.negate().toString(b);
  var k;
  if(b == 16) k = 4;
  else if(b == 8) k = 3;
  else if(b == 256) k = 8; // byte array      /** MODIFIED **/
  else if(b == 2) k = 1;
  else if(b == 32) k = 5;
  else if(b == 4) k = 2;
  else return this.toRadix(b);
  var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  var p = this.DB-(i*this.DB)%k;
  if(i-- > 0) {
    if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = (k==8)?String.fromCharCode(d):int2char(d); }   /** MODIFIED **/
    while(i >= 0) {
      if(p < k) {
        d = (this[i]&((1<<p)-1))<<(k-p);
        d |= this[--i]>>(p+=this.DB-k);
      }
      else {
        d = (this[i]>>(p-=k))&km;
        if(p <= 0) { p += this.DB; --i; }
      }
      if(d > 0) m = true;
      if(m) r += (k==8)?String.fromCharCode(d):int2char(d);    /** MODIFIED **/
    }
  }
  return m?r:"0";
}

// (public) -this
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }

// (public) |this|
function bnAbs() { return (this.s<0)?this.negate():this; }

// (public) return + if this > a, - if this < a, 0 if equal
function bnCompareTo(a) {
  var r = this.s-a.s;
  if(r != 0) return r;
  var i = this.t;
  r = i-a.t;
  if(r != 0) return r;
  while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
  return 0;
}

// returns bit length of the integer x
function nbits(x) {
  var r = 1, t;
  if((t=x>>>16) != 0) { x = t; r += 16; }
  if((t=x>>8) != 0) { x = t; r += 8; }
  if((t=x>>4) != 0) { x = t; r += 4; }
  if((t=x>>2) != 0) { x = t; r += 2; }
  if((t=x>>1) != 0) { x = t; r += 1; }
  return r;
}

// (public) return the number of bits in "this"
function bnBitLength() {
  if(this.t <= 0) return 0;
  return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
}

// (protected) r = this << n*DB
function bnpDLShiftTo(n,r) {
  var i;
  for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
  for(i = n-1; i >= 0; --i) r[i] = 0;
  r.t = this.t+n;
  r.s = this.s;
}

// (protected) r = this >> n*DB
function bnpDRShiftTo(n,r) {
  for(var i = n; i < this.t; ++i) r[i-n] = this[i];
  r.t = Math.max(this.t-n,0);
  r.s = this.s;
}

// (protected) r = this << n
function bnpLShiftTo(n,r) {
  var bs = n%this.DB;
  var cbs = this.DB-bs;
  var bm = (1<<cbs)-1;
  var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  for(i = this.t-1; i >= 0; --i) {
    r[i+ds+1] = (this[i]>>cbs)|c;
    c = (this[i]&bm)<<bs;
  }
  for(i = ds-1; i >= 0; --i) r[i] = 0;
  r[ds] = c;
  r.t = this.t+ds+1;
  r.s = this.s;
  r.clamp();
}

// (protected) r = this >> n
function bnpRShiftTo(n,r) {
  r.s = this.s;
  var ds = Math.floor(n/this.DB);
  if(ds >= this.t) { r.t = 0; return; }
  var bs = n%this.DB;
  var cbs = this.DB-bs;
  var bm = (1<<bs)-1;
  r[0] = this[ds]>>bs;
  for(var i = ds+1; i < this.t; ++i) {
    r[i-ds-1] |= (this[i]&bm)<<cbs;
    r[i-ds] = this[i]>>bs;
  }
  if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
  r.t = this.t-ds;
  r.clamp();
}

// (protected) r = this - a
function bnpSubTo(a,r) {
  var i = 0, c = 0, m = Math.min(a.t,this.t);
  while(i < m) {
    c += this[i]-a[i];
    r[i++] = c&this.DM;
    c >>= this.DB;
  }
  if(a.t < this.t) {
    c -= a.s;
    while(i < this.t) {
      c += this[i];
      r[i++] = c&this.DM;
      c >>= this.DB;
    }
    c += this.s;
  }
  else {
    c += this.s;
    while(i < a.t) {
      c -= a[i];
      r[i++] = c&this.DM;
      c >>= this.DB;
    }
    c -= a.s;
  }
  r.s = (c<0)?-1:0;
  if(c < -1) r[i++] = this.DV+c;
  else if(c > 0) r[i++] = c;
  r.t = i;
  r.clamp();
}

// (protected) r = this * a, r != this,a (HAC 14.12)
// "this" should be the larger one if appropriate.
function bnpMultiplyTo(a,r) {
  var x = this.abs(), y = a.abs();
  var i = x.t;
  r.t = i+y.t;
  while(--i >= 0) r[i] = 0;
  for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
  r.s = 0;
  r.clamp();
  if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
}

// (protected) r = this^2, r != this (HAC 14.16)
function bnpSquareTo(r) {
  var x = this.abs();
  var i = r.t = 2*x.t;
  while(--i >= 0) r[i] = 0;
  for(i = 0; i < x.t-1; ++i) {
    var c = x.am(i,x[i],r,2*i,0,1);
    if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
      r[i+x.t] -= x.DV;
      r[i+x.t+1] = 1;
    }
  }
  if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
  r.s = 0;
  r.clamp();
}

// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m.  q or r may be null.
function bnpDivRemTo(m,q,r) {
  var pm = m.abs();
  if(pm.t <= 0) return;
  var pt = this.abs();
  if(pt.t < pm.t) {
    if(q != null) q.fromInt(0);
    if(r != null) this.copyTo(r);
    return;
  }
  if(r == null) r = nbi();
  var y = nbi(), ts = this.s, ms = m.s;
  var nsh = this.DB-nbits(pm[pm.t-1]);	// normalize modulus
  if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
  else { pm.copyTo(y); pt.copyTo(r); }
  var ys = y.t;
  var y0 = y[ys-1];
  if(y0 == 0) return;
  var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
  var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  y.dlShiftTo(j,t);
  if(r.compareTo(t) >= 0) {
    r[r.t++] = 1;
    r.subTo(t,r);
  }
  BigInteger.ONE.dlShiftTo(ys,t);
  t.subTo(y,y);	// "negative" y so we can replace sub with am later
  while(y.t < ys) y[y.t++] = 0;
  while(--j >= 0) {
    // Estimate quotient digit
    var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
    if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {	// Try it out
      y.dlShiftTo(j,t);
      r.subTo(t,r);
      while(r[i] < --qd) r.subTo(t,r);
    }
  }
  if(q != null) {
    r.drShiftTo(ys,q);
    if(ts != ms) BigInteger.ZERO.subTo(q,q);
  }
  r.t = ys;
  r.clamp();
  if(nsh > 0) r.rShiftTo(nsh,r);	// Denormalize remainder
  if(ts < 0) BigInteger.ZERO.subTo(r,r);
}

// (public) this mod a
function bnMod(a) {
  var r = nbi();
  this.abs().divRemTo(a,null,r);
  if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
  return r;
}

// Modular reduction using "classic" algorithm
function Classic(m) { this.m = m; }
function cConvert(x) {
  if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  else return x;
}
function cRevert(x) { return x; }
function cReduce(x) { x.divRemTo(this.m,null,x); }
function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;

// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
// justification:
//         xy == 1 (mod m)
//         xy =  1+km
//   xy(2-xy) = (1+km)(1-km)
// x[y(2-xy)] = 1-k^2m^2
// x[y(2-xy)] == 1 (mod m^2)
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
// JS multiply "overflows" differently from C/C++, so care is needed here.
function bnpInvDigit() {
  if(this.t < 1) return 0;
  var x = this[0];
  if((x&1) == 0) return 0;
  var y = x&3;		// y == 1/x mod 2^2
  y = (y*(2-(x&0xf)*y))&0xf;	// y == 1/x mod 2^4
  y = (y*(2-(x&0xff)*y))&0xff;	// y == 1/x mod 2^8
  y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;	// y == 1/x mod 2^16
  // last step - calculate inverse mod DV directly;
  // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  y = (y*(2-x*y%this.DV))%this.DV;		// y == 1/x mod 2^dbits
  // we really want the negative inverse, and -DV < y < DV
  return (y>0)?this.DV-y:-y;
}

// Montgomery reduction
function Montgomery(m) {
  this.m = m;
  this.mp = m.invDigit();
  this.mpl = this.mp&0x7fff;
  this.mph = this.mp>>15;
  this.um = (1<<(m.DB-15))-1;
  this.mt2 = 2*m.t;
}

// xR mod m
function montConvert(x) {
  var r = nbi();
  x.abs().dlShiftTo(this.m.t,r);
  r.divRemTo(this.m,null,r);
  if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
  return r;
}

// x/R mod m
function montRevert(x) {
  var r = nbi();
  x.copyTo(r);
  this.reduce(r);
  return r;
}

// x = x/R mod m (HAC 14.32)
function montReduce(x) {
  while(x.t <= this.mt2)	// pad x so am has enough room later
    x[x.t++] = 0;
  for(var i = 0; i < this.m.t; ++i) {
    // faster way of calculating u0 = x[i]*mp mod DV
    var j = x[i]&0x7fff;
    var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
    // use am to combine the multiply-shift-add into one call
    j = i+this.m.t;
    x[j] += this.m.am(0,u0,x,i,0,this.m.t);
    // propagate carry
    while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
  }
  x.clamp();
  x.drShiftTo(this.m.t,x);
  if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
}

// r = "x^2/R mod m"; x != r
function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

// r = "xy/R mod m"; x,y != r
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }

Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;

// (protected) true iff this is even
function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }

// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
function bnpExp(e,z) {
  if(e > 0xffffffff || e < 1) return BigInteger.ONE;
  var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  g.copyTo(r);
  while(--i >= 0) {
    z.sqrTo(r,r2);
    if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
    else { var t = r; r = r2; r2 = t; }
  }
  return z.revert(r);
}

// (public) this^e % m, 0 <= e < 2^32
function bnModPowInt(e,m) {
  var z;
  if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  return this.exp(e,z);
}

// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;

// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;

// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);


/***/ }),

/***/ "./core/lib/matcher.js":
/*!*****************************!*\
  !*** ./core/lib/matcher.js ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_429385__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Matcher class implementing matching addresses against
 *               a list of filters.
 */

const {RESOURCE_TYPES, SPECIAL_TYPES, ALLOWING_TYPES, contentTypes,
       enumerateTypes} = __nested_webpack_require_429385__(/*! ./contentTypes */ "./core/lib/contentTypes.js");
const {compilePatterns} = __nested_webpack_require_429385__(/*! ./patterns */ "./core/lib/patterns.js");
const {domainSuffixes, URLRequest} = __nested_webpack_require_429385__(/*! ./url */ "./core/lib/url.js");
const {Filter} = __nested_webpack_require_429385__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {FiltersByDomain, FilterMap} = __nested_webpack_require_429385__(/*! ./filtersByDomain */ "./core/lib/filtersByDomain.js");
const {Cache} = __nested_webpack_require_429385__(/*! ./caching */ "./core/lib/caching.js");

/**
 * Returns the amount of filters per map.
 * @param {Map} map
 * @param {string} keyword
 * @returns {number}
 */
let countFilters = (map, keyword) => {
  let list = map.get(keyword);
  if (!list) {
    return 0;
  }
  if (list instanceof Filter) {
    return 1;
  }
  return list.length;
};

/**
 * Returns a list of filters, if any, or an empty list.
 * @param {Map} map
 * @param {string} keyword
 * @returns {Array.<module:filterClasses.URLFilter>}
 */
let getFilters = (map, keyword) => {
  let list = map.get(keyword);
  if (!list) {
    return Array.prototype;
  }
  if (list instanceof Filter) {
    return [list];
  }
  return list;
};

/**
 * Checks if the keyword is bad for use.
 * @param {string} keyword
 * @returns {boolean}
 */
function isBadKeyword(keyword) {
  return keyword == "https" || keyword == "http" || keyword == "com" ||
         keyword == "js";
}

/**
 * Adds a filter by a given keyword to a map.
 * @param {module:filterClasses.URLFilter} filter
 * @param {string} keyword
 * @param {Map.<string,(module:filterClasses.URLFilter|
 *                      Array.<module:filterClasses.URLFilter>)>} map
 */
function addFilterByKeyword(filter, keyword, map) {
  // this dance is to avoid storing arrays for single filters
  let list = map.get(keyword);
  // when the keyword is known, promote as array if needed
  if (list) {
    if (list instanceof Filter) {
      map.set(keyword, [list, filter]);
    }
    else {
      list.push(filter);
    }
  }
  else {
    // store just the filter without the Array
    map.set(keyword, filter);
  }
}

/**
 * Removes a filter by a given keyword from a map.
 * @param {module:filterClasses.URLFilter} filter
 * @param {string} keyword
 * @param {Map.<string,(module:filterClasses.URLFilter|
 *                      Array.<module:filterClasses.URLFilter>)>} map
 */
function removeFilterByKeyword(filter, keyword, map) {
  // this dance is to normalize back the keyword entry, if any
  let list = map.get(keyword);
  if (list) {
    // when the value is a filter, remove the keyword if filter matches
    if (list instanceof Filter) {
      if (list == filter) {
        map.delete(keyword);
      }
    }
    // otherwise find the index and drop the array if the list has 1 item
    else {
      let i = list.findIndex(item => item === filter);
      if (i >= 0) {
        list.splice(i, 1);
        if (list.length === 1) {
          map.set(keyword, list[0]);
        }
      }
    }
  }
}

/**
 * Checks whether a filter matches a given URL request.
 *
 * @param {module:filterClasses.URLFilter} filter The filter.
 * @param {module:url.URLRequest} request The URL request.
 * @param {number} typeMask A mask specifying the content type of the URL
 *   request.
 * @param {?string} [sitekey] An optional public key associated with the
 *   URL request.
 * @param {?Array} [collection] An optional list to which to append the filter
 *   if it matches. If omitted, the function directly returns the filter if it
 *   matches.
 *
 * @returns {?module:filterClasses.URLFilter} The filter if it matches and
 *   `collection` is omitted; otherwise `null`.
 */
function matchFilter(filter, request, typeMask, sitekey, collection) {
  if (filter.matches(request, typeMask, sitekey)) {
    if (!collection) {
      return filter;
    }

    collection.push(filter);
  }

  return null;
}

/**
 * Checks whether a particular filter is slow.
 * @param {module:filterClasses.URLFilter} filter
 * @returns {boolean}
 */
exports.isSlowFilter = function isSlowFilter(filter) {
  return !filter.urlPattern.hasKeywords();
};

let Matcher =
/**
 * Blocking/allowing filter matching
 */
exports.Matcher = class Matcher {
  constructor() {
    /**
     * Lookup table for keywords by their associated filter
     * @type {Map.<module:filterClasses.URLFilter,string>}
     * @private
     */
    this._keywordByFilter = new Map();

    /**
     * Lookup table for simple filters by their associated keyword
     * @type {Map.<string,(module:filterClasses.URLFilter|
     *                     Array.<module:filterClasses.URLFilter>)>}
     * @private
     */
    this._simpleFiltersByKeyword = new Map();

    /**
     * Lookup table for complex filters by their associated keyword
     * @type {Map.<string,(module:filterClasses.URLFilter|
     *                     Array.<module:filterClasses.URLFilter>)>}
     * @private
     */
    this._complexFiltersByKeyword = new Map();

    /**
     * Lookup table of compiled patterns for simple filters by their associated
     * keyword
     * @type {Map.<string,?module:patterns~CompiledPatterns>}
     * @private
     */
    this._compiledPatternsByKeyword = new Map();

    /**
     * Compiled patterns for generic complex filters with no associated
     * keyword.
     * @type {?module:patterns~CompiledPatterns|boolean}
     * @private
     */
    this._keywordlessCompiledPatterns = false;

    /**
     * Lookup table of domain maps for complex filters by their associated
     * keyword
     * @type {Map.<string,
     *             Map.<string,
     *                  (module:filterClasses.URLFilter|
     *                   Map.<module:filterClasses.URLFilter,boolean>)>>}
     * @private
     */
    this._filterDomainMapsByKeyword = new Map();

    /**
     * Lookup table of type-specific lookup tables for complex filters by their
     * associated keyword
     * @type {Map.<string,
     *             Map.<string,
     *                  (module:filterClasses.URLFilter|
     *                   Array.<module:filterClasses.URLFilter>)>>}
     * @private
     */
    this._filterMapsByType = new Map();
  }

  /**
   * Removes all known filters
   */
  clear() {
    this._keywordByFilter.clear();
    this._simpleFiltersByKeyword.clear();
    this._complexFiltersByKeyword.clear();
    this._compiledPatternsByKeyword.clear();
    this._keywordlessCompiledPatterns = false;
    this._filterDomainMapsByKeyword.clear();
    this._filterMapsByType.clear();
  }

  /**
   * Adds a filter to the matcher
   * @param {module:filterClasses.URLFilter} filter
   */
  add(filter) {
    if (this._keywordByFilter.has(filter)) {
      return;
    }

    // Look for a suitable keyword
    let keyword = this.findKeyword(filter);
    let simple = filter.contentType == RESOURCE_TYPES && filter.isGeneric();

    addFilterByKeyword(filter, keyword, simple ? this._simpleFiltersByKeyword :
        this._complexFiltersByKeyword);

    this._keywordByFilter.set(filter, keyword);

    if (simple) {
      if (this._compiledPatternsByKeyword.size > 0) {
        this._compiledPatternsByKeyword.delete(keyword);
      }

      return;
    }

    if (keyword == "") {
      this._keywordlessCompiledPatterns = false;
    }

    for (let type of enumerateTypes(filter.contentType, SPECIAL_TYPES)) {
      let map = this._filterMapsByType.get(type);
      if (!map) {
        this._filterMapsByType.set(type, map = new Map());
      }

      addFilterByKeyword(filter, keyword, map);
    }

    let {domains} = filter;

    let filtersByDomain = this._filterDomainMapsByKeyword.get(keyword);
    if (!filtersByDomain) {
      // In most cases, there is only one pure generic filter to a keyword.
      // Instead of Map { "foo" => Map { "" => Map { filter => true } } }, we
      // can just reduce it to Map { "foo" => filter } and save a lot of
      // memory.
      if (!domains) {
        this._filterDomainMapsByKeyword.set(keyword, filter);
        return;
      }

      filtersByDomain = new FiltersByDomain();
      this._filterDomainMapsByKeyword.set(keyword, filtersByDomain);
    }
    else if (!(filtersByDomain instanceof FiltersByDomain)) {
      filtersByDomain = new FiltersByDomain([["", filtersByDomain]]);
      this._filterDomainMapsByKeyword.set(keyword, filtersByDomain);
    }

    filtersByDomain.add(filter, domains);
  }

  /**
   * Removes a filter from the matcher
   * @param {module:filterClasses.URLFilter} filter
   */
  remove(filter) {
    let keyword = this._keywordByFilter.get(filter);
    if (typeof keyword == "undefined") {
      return;
    }

    let simple = filter.contentType == RESOURCE_TYPES && filter.isGeneric();

    removeFilterByKeyword(
      filter,
      keyword,
      simple ?
        this._simpleFiltersByKeyword :
        this._complexFiltersByKeyword
    );

    this._keywordByFilter.delete(filter);

    if (simple) {
      if (this._compiledPatternsByKeyword.size > 0) {
        this._compiledPatternsByKeyword.delete(keyword);
      }

      return;
    }

    if (keyword == "") {
      this._keywordlessCompiledPatterns = false;
    }

    for (let type of enumerateTypes(filter.contentType, SPECIAL_TYPES)) {
      let map = this._filterMapsByType.get(type);
      if (map) {
        removeFilterByKeyword(filter, keyword, map);
      }
    }

    let filtersByDomain = this._filterDomainMapsByKeyword.get(keyword);
    if (filtersByDomain) {
      // Because of the memory optimization in the add function, most of the
      // time this will be a filter rather than a map.
      if (!(filtersByDomain instanceof FiltersByDomain)) {
        this._filterDomainMapsByKeyword.delete(keyword);
        return;
      }

      filtersByDomain.remove(filter);

      if (filtersByDomain.size == 0) {
        this._filterDomainMapsByKeyword.delete(keyword);
      }
      else if (filtersByDomain.size == 1) {
        for (let [lastDomain, map] of filtersByDomain.entries()) {
          // Reduce Map { "foo" => Map { "" => filter } } to
          // Map { "foo" => filter }
          if (lastDomain == "" && !(map instanceof FilterMap)) {
            this._filterDomainMapsByKeyword.set(keyword, map);
          }

          break;
        }
      }
    }
  }

  /**
   * Checks whether a filter exists in the matcher
   * @param {module:filterClasses.URLFilter} filter
   * @returns {boolean}
   */
  has(filter) {
    return this._keywordByFilter.has(filter);
  }

  /**
   * Chooses a keyword to be associated with the filter.
   *
   * Because it will perform some internal optimizations, there is no
   * guarantee that this function will always return the same result when
   * called with the same filter.
   *
   * @param {module:filterClasses.Filter} filter
   * @returns {string} keyword or an empty string if no keyword could be found
   * @protected
   */
  findKeyword(filter) {
    let result = "";

    let candidates = filter.urlPattern.keywordCandidates();
    if (!candidates) {
      return result;
    }

    let resultCount = 0xFFFFFF;
    let resultLength = 0;

    for (let i = 0, l = candidates.length; i < l; i++) {
      let candidate = candidates[i].substring(1);

      if (isBadKeyword(candidate)) {
        continue;
      }

      let simpleCount = countFilters(this._simpleFiltersByKeyword, candidate);
      let complexCount = countFilters(this._complexFiltersByKeyword,
                                      candidate);

      let count = simpleCount + complexCount;

      if (count < resultCount ||
          (count == resultCount && candidate.length > resultLength)) {
        result = candidate;
        resultCount = count;
        resultLength = candidate.length;
      }
    }

    return result;
  }

  _matchFiltersByDomain(filtersByDomain, request, typeMask, sitekey,
                        specificOnly, collection) {
    let excluded = null;

    let domain = request.documentHostname || "";
    for (let suffix of domainSuffixes(domain, !specificOnly)) {
      let map = filtersByDomain.get(suffix);
      if (map) {
        if (map instanceof FilterMap) {
          for (let [filter, include] of map.entries()) {
            if (!include) {
              if (excluded) {
                excluded.add(filter);
              }
              else {
                excluded = new Set([filter]);
              }
            }
            else if (
              (!excluded || !excluded.has(filter)) &&
              matchFilter(filter, request, typeMask, sitekey, collection)
            ) {
              return filter;
            }
          }
        }
        else if ((!excluded || !excluded.has(map)) &&
                 matchFilter(map, request, typeMask, sitekey, collection)) {
          return map;
        }
      }
    }

    return null;
  }

  _checkEntryMatchSimpleQuickCheck(keyword, request, filters) {
    let compiled = this._compiledPatternsByKeyword.get(keyword);
    if (typeof compiled == "undefined") {
      compiled = compilePatterns(filters);
      this._compiledPatternsByKeyword.set(keyword, compiled);
    }

    // If compilation failed (e.g. too many filters), return true because this
    // is only a pre-check.
    return !compiled || compiled.test(request);
  }

  _checkEntryMatchSimple(keyword, request, collection) {
    let filters = getFilters(this._simpleFiltersByKeyword, keyword);
    let {length} = filters;
    if (length) {
      // For simple filters where there's more than one filter to the keyword,
      // we do a quick check using a single compiled pattern that combines all
      // the patterns. This is a lot faster for requests that are not going to
      // be blocked (i.e. most requests).
      if (length === 1 ||
          this._checkEntryMatchSimpleQuickCheck(keyword, request, filters)) {
        for (let filter of filters) {
          // Simple filters match any resource type.
          if (matchFilter(filter, request, RESOURCE_TYPES, null, collection)) {
            return filter;
          }
        }
      }
    }

    return null;
  }

  _checkEntryMatchForType(keyword, request, typeMask, sitekey, specificOnly,
                          collection) {
    let filtersForType = this._filterMapsByType.get(typeMask & SPECIAL_TYPES);
    if (filtersForType) {
      for (let filter of getFilters(filtersForType, keyword)) {
        if (specificOnly && filter.isGeneric()) {
          continue;
        }

        if (matchFilter(filter, request, typeMask, sitekey, collection)) {
          return filter;
        }
      }
    }

    return null;
  }

  _checkEntryMatchByDomain(keyword, request, typeMask, sitekey, specificOnly,
                           collection) {
    let filtersByDomain = this._filterDomainMapsByKeyword.get(keyword);
    if (filtersByDomain) {
      if (filtersByDomain instanceof FiltersByDomain) {
        if (keyword == "" && !specificOnly) {
          let compiled = this._keywordlessCompiledPatterns;

          // If the value is false, it indicates that we need to initialize it
          // to either a CompiledPatterns object or null.
          if (compiled == false) {
            // Compile all the patterns from the generic filters into a single
            // object. It is worth doing this for the keywordless generic
            // complex filters because they must be checked against every
            // single URL request that has not already been blocked by one of
            // the simple filters (i.e. most URL requests).
            let map = filtersByDomain.get("");
            if (map instanceof FilterMap) {
              compiled = compilePatterns([...map.keys()]);
            }

            this._keywordlessCompiledPatterns = compiled || null;
          }

          // We can skip the generic filters if none of them pass the test.
          if (compiled && !compiled.test(request)) {
            specificOnly = true;
          }
        }

        return this._matchFiltersByDomain(
          filtersByDomain, request, typeMask, sitekey, specificOnly, collection
        );
      }

      // Because of the memory optimization in the add function, most of the
      // time this will be a filter rather than a map.

      // Also see #7312: If it's a single filter, it's always the equivalent of
      // Map { "" => Map { filter => true } } (i.e. applies to any domain). If
      // the specific-only flag is set, we skip it.
      if (!specificOnly) {
        return matchFilter(
          filtersByDomain, request, typeMask, sitekey, collection
        );
      }
    }

    return null;
  }

  /**
   * Checks whether the entries for a particular keyword match a URL
   * @param {string} keyword
   * @param {module:url.URLRequest} request
   * @param {number} typeMask
   * @param {?string} [sitekey]
   * @param {boolean} [specificOnly]
   * @param {?Array.<module:filterClasses.Filter>} [collection] An optional
   *   list of filters to which to append any results. If specified, the
   *   function adds *all* matching filters to the list; if omitted,
   *   the function directly returns the first matching filter.
   * @returns {?module:filterClasses.Filter}
   * @protected
   */
  checkEntryMatch(keyword, request, typeMask, sitekey, specificOnly,
                  collection) {
    // We need to skip the simple (location-only) filters if the type mask does
    // not contain any resource types.
    if (!specificOnly && (typeMask & RESOURCE_TYPES) != 0) {
      let filter = this._checkEntryMatchSimple(keyword, request, collection);
      if (filter) {
        return filter;
      }
    }

    // If the type mask contains a special type (first condition) and it is
    // the only type in the mask (second condition with OTHER exception),
    // we can use the type-specific map, which typically contains a lot fewer
    // filters. This enables faster lookups for allowing types like $document,
    // $elemhide, and so on, as well as other special types like $csp.
    if ((typeMask & SPECIAL_TYPES) != 0 && (
      (typeMask & typeMask - 1) == 0 ||
      (typeMask & RESOURCE_TYPES) == contentTypes.OTHER)) {
      return this._checkEntryMatchForType(
        keyword, request, typeMask, sitekey, specificOnly, collection
      );
    }


    return this._checkEntryMatchByDomain(
      keyword, request, typeMask, sitekey, specificOnly, collection
    );
  }

  /**
   * @see #match
   * @deprecated
   * @inheritdoc
   */
  matchesAny(url, typeMask, docDomain, sitekey, specificOnly) {
    return this.match(url, typeMask, docDomain, sitekey, specificOnly);
  }

  /**
   * Tests whether the URL matches any of the known filters
   * @param {URL|module:url~URLInfo|string} url
   *   URL to be tested
   * @param {number} typeMask
   *   bitmask of content / request types to match
   * @param {?string} [docDomain]
   *   domain name of the document that loads the URL
   * @param {?string} [sitekey]
   *   public key provided by the document
   * @param {boolean} [specificOnly]
   *   should be `true` if generic matches should be ignored
   * @returns {?module:filterClasses.URLFilter}
   *   matching filter or `null`
   */
  match(url, typeMask, docDomain, sitekey, specificOnly) {
    let request = URLRequest.from(url, docDomain);
    let candidates = request.lowerCaseHref.match(/[a-z0-9%]{2,}|$/g);

    for (let i = 0, l = candidates.length; i < l; i++) {
      if (isBadKeyword(candidates[i])) {
        continue;
      }

      let result = this.checkEntryMatch(
        candidates[i], request, typeMask, sitekey, specificOnly
      );
      if (result) {
        return result;
      }
    }

    return null;
  }
};

class CombinedMatcher {
  constructor() {
    /**
     * Matcher for blocking rules.
     * @type {module:matcher.Matcher}
     * @private
     */
    this._blocking = new Matcher();

    /**
     * Matcher for exception rules.
     * @type {module:matcher.Matcher}
     * @private
     */
    this._allowing = new Matcher();

    /**
     * Lookup table of previous match results
     * @type {module:caching.Cache.<string, ?(module:filterClasses.URLFilter|
     *                                        MatcherSearchResults)>}
     * @private
     */
    this._resultCache = new Cache(10000);
  }

  /**
   * @see module:matcher.Matcher#clear
   */
  clear() {
    this._blocking.clear();
    this._allowing.clear();
    this._resultCache.clear();
  }

  /**
   * @see module:matcher.Matcher#add
   * @param {module:filterClasses.Filter} filter
   */
  add(filter) {
    if (filter.type == "allowing") {
      this._allowing.add(filter);
    }
    else {
      this._blocking.add(filter);
    }

    this._resultCache.clear();
  }

  /**
   * @see module:matcher.Matcher#remove
   * @param {module:filterClasses.Filter} filter
   */
  remove(filter) {
    if (filter.type == "allowing") {
      this._allowing.remove(filter);
    }
    else {
      this._blocking.remove(filter);
    }

    this._resultCache.clear();
  }

  /**
   * @see module:matcher.Matcher#has
   * @param {module:filterClasses.Filter} filter
   * @returns {boolean}
   */
  has(filter) {
    if (filter.type == "allowing") {
      return this._allowing.has(filter);
    }
    return this._blocking.has(filter);
  }

  /**
   * @see module:matcher.Matcher#findKeyword
   * @param {module:filterClasses.Filter} filter
   * @returns {string} keyword
   * @protected
   */
  findKeyword(filter) {
    if (filter.type == "allowing") {
      return this._allowing.findKeyword(filter);
    }
    return this._blocking.findKeyword(filter);
  }

  _matchInternal(url, typeMask, docDomain, sitekey, specificOnly,
                 exhaustiveSearch) {
    let request = URLRequest.from(url, docDomain);
    let candidates = request.lowerCaseHref.match(/[a-z0-9%]{2,}|$/g)
        .filter(candidate => !isBadKeyword(candidate));
    let typeIsOnlyAllowing = (typeMask & ~ALLOWING_TYPES) == 0;

    let allowingHit = null;
    let blockingHit = null;

    let findAllowing = () => {
      for (let i = 0, l = candidates.length; !allowingHit && i < l; i++) {
        allowingHit = this._allowing.checkEntryMatch(
          candidates[i], request, typeMask, sitekey
        );
      }
    };

    let findBlocking = () => {
      for (let i = 0, l = candidates.length; !blockingHit && i < l; i++) {
        blockingHit = this._blocking.checkEntryMatch(
          candidates[i], request, typeMask, sitekey, specificOnly
        );
      }
    };

    if (exhaustiveSearch) {
      findAllowing();
      if (!allowingHit && !typeIsOnlyAllowing) {
        findBlocking();
      }
    }
    else if (typeIsOnlyAllowing) {
      findAllowing();
    }
    else {
      findBlocking();
      if (blockingHit) {
        findAllowing();
      }
    }

    return allowingHit || blockingHit;
  }

  _searchInternal(url, typeMask, docDomain, sitekey, specificOnly, filterType) {
    let hits = {};

    let searchBlocking = filterType == "blocking" || filterType == "all";
    let searchAllowing = filterType == "allowing" || filterType == "all";

    if (searchBlocking) {
      hits.blocking = [];
    }

    if (searchAllowing) {
      hits.allowing = [];
    }

    // If the type mask includes no types other than allowing types, we
    // can skip the blocking filters.
    if ((typeMask & ~ALLOWING_TYPES) == 0) {
      searchBlocking = false;
    }

    let request = URLRequest.from(url, docDomain);
    let candidates = request.lowerCaseHref.match(/[a-z0-9%]{2,}|$/g);

    for (let i = 0, l = candidates.length; i < l; i++) {
      if (isBadKeyword(candidates[i])) {
        continue;
      }

      if (searchBlocking) {
        this._blocking.checkEntryMatch(
          candidates[i],
          request,
          typeMask,
          sitekey,
          specificOnly,
          hits.blocking
        );
      }


      if (searchAllowing) {
        this._allowing.checkEntryMatch(
          candidates[i], request, typeMask, sitekey, false, hits.allowing
        );
      }
    }

    return hits;
  }

  /**
   * @see #match
   * @deprecated
   * @inheritdoc
   */
  matchesAny(url, typeMask, docDomain, sitekey, specificOnly) {
    return this.match(url, typeMask, docDomain, sitekey, specificOnly);
  }

  /**
   * Tests whether the URL matches any of the known filters
   *
   * If both a blocking and an allowing filter matches, the allowing filter is
   * prioritized.
   *
   * If only an allowing filter matches, then the allowing filter will not be
   * returned unless it is one of the `{@link module:contentTypes.ALLOWING_TYPES
   * ALLOWING_TYPES}` used for exception rules only, or if `exhaustiveSearch` is
   * true. In other words, the allowing filter is only returned if it is
   * expected to change blocking behaviour.
   *
   * @param {URL|module:url~URLInfo|string} url
   *   URL to be tested
   * @param {number} typeMask
   *   bitmask of content / request types to match
   * @param {?string} [docDomain]
   *   domain name of the document that loads the URL
   * @param {?string} [sitekey]
   *   public key provided by the document
   * @param {boolean} [specificOnly]
   *   should be `true` if generic matches should be ignored
   * @param {boolean} [exhaustiveSearch=false]
   *   should return a matched allowing filter, even if the filter will have no
   *   effect on blocking behaviour
   * @returns {?module:filterClasses.URLFilter}
   *   matching filter or `null`
   */
  match(url, typeMask, docDomain, sitekey, specificOnly,
        exhaustiveSearch = false) {
    let key = `${url} ${typeMask} ${docDomain} ${sitekey} ${specificOnly} ${exhaustiveSearch}`;
    let result = this._resultCache.get(key);
    if (typeof result != "undefined") {
      return result;
    }

    result = this._matchInternal(
      url, typeMask, docDomain, sitekey, specificOnly, exhaustiveSearch
    );

    this._resultCache.set(key, result);

    return result;
  }

  /**
   * @typedef {Object} MatcherSearchResults
   * @property {Array.<module:filterClasses.BlockingFilter>} [blocking] List of
   *   blocking filters found.
   * @property {Array.<module:filterClasses.AllowingFilter>} [allowing] List
   *   of allowing filters found.
   */

  /**
   * Searches all blocking and allowing filters and returns results matching
   * the given parameters.
   *
   * @param {URL|module:url~URLInfo|string} url
   * @param {number} typeMask
   * @param {?string} [docDomain]
   * @param {?string} [sitekey]
   * @param {boolean} [specificOnly]
   * @param {string} [filterType] The types of filters to look for. This can be
   *   `"blocking"`, `"allowing"`, or `"all"` (default).
   *
   * @returns {MatcherSearchResults}
   */
  search(url, typeMask, docDomain, sitekey, specificOnly, filterType = "all") {
    let key = `* ${url} ${typeMask} ${docDomain} ${sitekey} ` +
              `${specificOnly} ${filterType}`;

    let result = this._resultCache.get(key);
    if (typeof result != "undefined") {
      return result;
    }

    result = this._searchInternal(
      url, typeMask, docDomain, sitekey, specificOnly, filterType
    );

    this._resultCache.set(key, result);

    return result;
  }

  /**
   * Tests whether the URL is allowlisted
   * @see module:matcher.Matcher#match
   * @inheritdoc
   * @returns {boolean}
   */
  isAllowlisted(url, typeMask, docDomain, sitekey) {
    return !!this._allowing.match(url, typeMask, docDomain, sitekey);
  }
}

/**
 * Combines a matcher for blocking and exception rules, automatically sorts
 * rules into two `{@link module:matcher.Matcher Matcher}` instances.
 */
exports.CombinedMatcher = CombinedMatcher;

/**
 * Create the `{@link module:matcher~CombinedMatcher CombinedMatcher}`
 * instance that should usually be used.
 * @returns {module:matcher.CombinedMatcher}
 */
exports.newDefaultMatcher = function() {
  return new CombinedMatcher();
};


/***/ }),

/***/ "./core/lib/notifications.js":
/*!***********************************!*\
  !*** ./core/lib/notifications.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_458393__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Handles notifications.
 */

const {Prefs} = __nested_webpack_require_458393__(/*! prefs */ "./sdk/api/prefs.js");

const {MILLIS_IN_MINUTE, MILLIS_IN_HOUR, MILLIS_IN_DAY} = __nested_webpack_require_458393__(/*! ./time */ "./core/lib/time.js");
const {Downloader, Downloadable} = __nested_webpack_require_458393__(/*! ./downloader */ "./core/lib/downloader.js");
const {compareVersions} = __nested_webpack_require_458393__(/*! ./versions */ "./core/lib/versions.js");
const {analytics} = __nested_webpack_require_458393__(/*! ./analytics */ "./core/lib/analytics.js");
const {EventEmitter} = __nested_webpack_require_458393__(/*! ./events */ "./core/lib/events.js");

const INITIAL_DELAY = 1 * MILLIS_IN_MINUTE;
const CHECK_INTERVAL = 1 * MILLIS_IN_HOUR;
const EXPIRATION_INTERVAL = 1 * MILLIS_IN_DAY;

let getPreferredMillis = (field, fallback) =>
                          field in Prefs ? Prefs[field] : fallback;

/**
 * The default locale for the localization of notification texts.
 * @type {string}
 * @default
 */
const DEFAULT_LOCALE = "en-US";

/**
 * Returns the numerical severity of a notification.
 * @param {Object} notification The notification.
 * @returns {number} The numerical severity of the notification.
 */
function getNumericalSeverity(notification) {
  switch (notification.type) {
    case "information":
      return 0;
    case "newtab":
    case "relentless":
      return 1;
    case "critical":
      return 2;
  }

  return 0;
}

/**
 * Saves notification data to preferences.
 * @param {string} [key] The key to save.
 */
function saveNotificationData(key = "notificationdata") {
  // JSON values aren't saved unless they are assigned a different object.
  Prefs[key] = JSON.parse(JSON.stringify(Prefs[key]));
}

/**
 * Localizes a notification text.
 *
 * @param {Object} translations The set of translations from which to select
 *   the localization.
 * @param {string} locale The locale string to use for the selection. If no
 *   localized version is found in the `translations` object for the given
 *   locale, the
 *   {@link module:notifications~DEFAULT_LOCALE default locale} is used.
 *
 * @returns {*} The localized text; `undefined` if no localized version is
 *   found in the `translations` object.
 */
function localize(translations, locale) {
  if (locale in translations) {
    return translations[locale];
  }

  let languagePart = locale.substring(0, locale.indexOf("-"));
  if (languagePart && languagePart in translations) {
    return translations[languagePart];
  }

  return translations[DEFAULT_LOCALE];
}

function isValidNotification(notification) {
  // Only notifications that are meant to be opened in a new tab must
  // contain at least one URL to open.
  if (notification.type == "newtab" &&
      !(notification.links && notification.links.length > 0)) {
    return false;
  }

  return true;
}

/**
 * `{@link module:notifications.notifications}` implementation.
 *
 * It also emits the named events `downloaded`, `ignored-category-added` and
 * `ignored-category-removed` built with `{@link module:events.EventEmitter
 *                                               EventEmitter}`
 */
class Notifications extends EventEmitter {
  /**
   * @hideconstructor
   */
  constructor() {
    super();

    /**
     * Whether the fetching of notifications has been started.
     * @private
     */
    this._started = false;

    /**
     * Whether all ignorable notifications should be ignored.
     * @type {boolean}
     */
    this.ignored = false;

    /**
     * The locale for the localization of notification texts.
     * @type {string}
     * @default {@link module:notifications~DEFAULT_LOCALE}
     */
    this.locale = DEFAULT_LOCALE;

    /**
     * The number to consider when performing the blockedTotalMin and
     * blockedTotalMax target checks.
     *
     * This property needs to be initialized at startup and updated
     * whenever a blocking filter matches. If set to null (default),
     * notifications using these target checks are ignored.
     *
     * If the deprecated preferences Prefs.show_statsinpopup and
     * Prefs.blocked_total exist they take precedence over this property.
     * @type {?number}
     */
    this.numBlocked = null;

    /**
     * Listeners for notifications to be shown.
     * @type {Set.<function>}
     * @private
     */
    this._showListeners = new Set();

    /**
     * Local notifications added via
     * `{@link module:notifications~Notifications#addNotification
     *         addNotification()}`.
     * @type {Set.<Object>}
     * @private
     */
    this._localNotifications = new Set();

    /**
     * The object providing actual downloading functionality.
     * @type {module:downloader.Downloader}
     * @private
     */
    this._downloader = new Downloader(this._getDownloadables.bind(this));

    this._downloader.onExpirationChange = this._onExpirationChange.bind(this);
    this._downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this);
    this._downloader.onDownloadError = this._onDownloadError.bind(this);
    this._onBlockedTotal = this._onBlockedTotal.bind(this);
  }

  /**
   * Starts fetching notifications.
   *
   * No notifications are fetched until this function has been called at least
   * once.
   */
  start() {
    if (this._started) {
      return;
    }

    Prefs.on("blocked_total", this._onBlockedTotal);

    this._downloader.scheduleChecks(
      getPreferredMillis("notifications_check_interval", CHECK_INTERVAL),
      getPreferredMillis("notifications_initial_delay", INITIAL_DELAY)
    );
    this._started = true;
  }

  /**
   * Stops fetching notifications.
   */
  stop() {
    this._started = false;
    this._downloader.unscheduleChecks();

    Prefs.off("blocked_total", this._onBlockedTotal);
  }

  /**
   * Sets an alternative storage backend for storing local
   * notifications. By default, local notifications are stored in
   * memory.
   *
   * The new storage backend is expected to provide similar
   * functionality to a Set. Notifications will be added to it,
   * deleted from it, and iterated over.
   *
   * @param {object} storageBackend
   * @param {function} storageBackend.add Add a new notification.
   * @param {function} storageBackend.delete Remove a notification.
   * @param {function} storageBackend.Symbol.iterator Returns an iterable of all
   *   local notifications.
   */
  setLocalNotificationStorage(storageBackend) {
    if (this._localNotifications == storageBackend) {
      return;
    }

    for (let notification of this._localNotifications) {
      storageBackend.add(notification);
    }

    this._localNotifications = storageBackend;
  }

  /**
   * Yields a `{@link module:downloader.Downloadable Downloadable}` instance
   * for the notifications download.
   * @yields {module:downloader.Downloadable}
   * @private
   */
  *_getDownloadables() {
    let {notificationurl: url, notificationdata} = Prefs;

    let downloadable = new Downloadable(url);

    if (analytics.isTrusted(url)) {
      downloadable.firstVersion = analytics.getFirstVersion();
    }

    if (typeof notificationdata.lastError == "number") {
      downloadable.lastError = notificationdata.lastError;
    }
    if (typeof notificationdata.lastCheck == "number") {
      downloadable.lastCheck = notificationdata.lastCheck;
    }

    if (typeof notificationdata.data == "object" &&
        "version" in notificationdata.data) {
      downloadable.lastVersion = notificationdata.data.version;
    }

    if (typeof notificationdata.softExpiration == "number") {
      downloadable.softExpiration = notificationdata.softExpiration;
    }
    if (typeof notificationdata.hardExpiration == "number") {
      downloadable.hardExpiration = notificationdata.hardExpiration;
    }
    if (typeof notificationdata.downloadCount == "number") {
      downloadable.downloadCount = notificationdata.downloadCount;
    }

    yield downloadable;
  }

  _onExpirationChange(downloadable) {
    Prefs.notificationdata.lastCheck = downloadable.lastCheck;
    Prefs.notificationdata.softExpiration = downloadable.softExpiration;
    Prefs.notificationdata.hardExpiration = downloadable.hardExpiration;

    saveNotificationData();
  }

  _onDownloadSuccess(downloadable, responseText, errorCallback,
                     redirectCallback) {
    try {
      let data = JSON.parse(responseText);

      if (typeof data.version == "string" &&
          analytics.isTrusted(downloadable.redirectURL || downloadable.url)) {
        analytics.recordVersion(data.version);
      }

      let notifications = [];
      for (let notification of data.notifications) {
        if (!isValidNotification(notification)) {
          console.warn(`Invalid notification with ID "${notification.id}"`);
          continue;
        }

        if ("severity" in notification) {
          if (!("type" in notification)) {
            notification.type = notification.severity;
          }
          delete notification.severity;
        }

        notifications.push(notification);
      }
      data.notifications = notifications;

      Prefs.notificationdata.data = data;
    }
    catch (error) {
      console.warn(error);
      errorCallback("synchronize_invalid_data");
      return;
    }

    let expirationInterval = getPreferredMillis(
      "notifications_expiration_interval",
      EXPIRATION_INTERVAL
    );

    Prefs.notificationdata.lastError = 0;
    Prefs.notificationdata.downloadStatus = "synchronize_ok";
    [
      Prefs.notificationdata.softExpiration,
      Prefs.notificationdata.hardExpiration
    ] = this._downloader.processExpirationInterval(expirationInterval);
    Prefs.notificationdata.downloadCount = downloadable.downloadCount;

    saveNotificationData();

    this.emit("downloaded");
    this.showNext();
  }

  _onDownloadError(downloadable, downloadURL, error, responseStatus,
                   redirectCallback) {
    Prefs.notificationdata.lastError = Date.now();
    Prefs.notificationdata.downloadStatus = error;

    saveNotificationData();
  }

  _onBlockedTotal() {
    this.showNext();
  }

  /**
   * Adds a listener for notifications to be shown.
   * @param {function} listener Listener to be invoked when a notification is
   *   to be shown.
   */
  addShowListener(listener) {
    this._showListeners.add(listener);
  }

  /**
   * Removes the supplied listener.
   * @param {function} listener Listener that was added via
   *   `{@link module:notifications~Notifications#addShowListener
   *           addShowListener()}`.
   */
  removeShowListener(listener) {
    this._showListeners.delete(listener);
  }

  /**
   * Returns whether user preferences indicate that notifications
   * should be ignored.
   * @return {boolean}
   */
  shouldIgnoreNotifications() {
    return this.ignored ||
      Prefs.notifications_ignoredcategories.includes("*");
  }

  /**
   * Returns all local and remote notifications.
   * @returns {Array.<Object>} All local and remote notifications.
   * @private
   */
  _getNotifications() {
    let remoteNotifications = [];
    if (typeof Prefs.notificationdata.data == "object" &&
        Prefs.notificationdata.data.notifications instanceof Array) {
      remoteNotifications = Prefs.notificationdata.data.notifications;
    }

    return [...this._localNotifications, ...remoteNotifications];
  }

  /**
   * Determines which notification is to be shown next.
   * @returns {?object} The notification to be shown, or `null` if there is
   *   none.
   * @private
   */
  _getNextToShow() {
    let notifications = this._getNotifications();
    if (notifications.length == 0) {
      return null;
    }

    const {addonName, addonVersion, application, applicationVersion,
           platform, platformVersion} = __nested_webpack_require_458393__(/*! info */ "./sdk/api/info.js");

    let {numBlocked} = this;
    // Compatibility for legacy adblockpluschrome
    if ("blocked_total" in Prefs) {
      numBlocked = Prefs.blocked_total;
    }
    if (Prefs.show_statsinpopup === false) {
      numBlocked = null;
    }

    let targetChecks = {
      extension: v => v == addonName,
      extensionMinVersion:
        v => compareVersions(addonVersion, v) >= 0,
      extensionMaxVersion:
        v => compareVersions(addonVersion, v) <= 0,
      application: v => v == application,
      applicationMinVersion:
        v => compareVersions(applicationVersion, v) >= 0,
      applicationMaxVersion:
        v => compareVersions(applicationVersion, v) <= 0,
      platform: v => v == platform,
      platformMinVersion:
        v => compareVersions(platformVersion, v) >= 0,
      platformMaxVersion:
        v => compareVersions(platformVersion, v) <= 0,
      blockedTotalMin: v => numBlocked != null && numBlocked >= v,
      blockedTotalMax: v => numBlocked != null && numBlocked <= v,
      locales: v => v.includes(this.locale)
    };

    let notificationToShow = null;
    for (let notification of notifications) {
      if (notification.type != "critical") {
        let shown;
        if (typeof Prefs.notificationdata.shown == "object") {
          shown = Prefs.notificationdata.shown[notification.id];
        }

        if (typeof shown != "undefined") {
          if (typeof notification.interval == "number") {
            if (shown + notification.interval > Date.now()) {
              continue;
            }
          }
          else if (shown) {
            continue;
          }
        }

        if (notification.type != "relentless" &&
            this.shouldIgnoreNotifications()) {
          continue;
        }
      }

      if (notification.targets instanceof Array) {
        let match = false;

        for (let target of notification.targets) {
          let keys = Object.keys(target);
          if (keys.every(
            key => Object.prototype.hasOwnProperty.call(targetChecks, key) &&
                   targetChecks[key](target[key]))
          ) {
            match = true;
            break;
          }
        }

        if (!match) {
          continue;
        }
      }

      if (!notificationToShow || getNumericalSeverity(notification) >
                                 getNumericalSeverity(notificationToShow)) {
        notificationToShow = notification;
      }
    }

    return notificationToShow;
  }

  /**
   * Shows a notification once.
   * @param {Object} notification The notification to show.
   * @param {Object} [options]
   * @param {boolean} [options.ignorable=false] If true, user preference will
   *   be considered to determine whether notification should be shown.
   */
  showNotification(notification, options = {}) {
    if (options.ignorable && this.shouldIgnoreNotifications()) {
      return;
    }

    for (let showListener of this._showListeners) {
      showListener(notification);
    }
  }

  /**
   * Invokes the listeners added via
   * `{@link module:notifications~Notifications#addShowListener
   *         addShowListener()}` with the next notification to be shown.
   *
   * This method should be called whenever a page loads.
   */
  showNext() {
    let notification = this._getNextToShow();
    if (notification) {
      for (let showListener of this._showListeners) {
        showListener(notification);
      }
    }
  }

  /**
   * Marks a notification as shown.
   * @param {string} id The ID of the notification to be marked as shown.
   */
  markAsShown(id) {
    let notifications = this._getNotifications();

    // Ignore if there's no notification with the given ID.
    if (!notifications.some(notification => notification.id == id)) {
      return;
    }

    let now = Date.now();
    let data = Prefs.notificationdata;

    if (data.shown instanceof Array) {
      let newShown = {};
      for (let oldId of data.shown) {
        newShown[oldId] = now;
      }
      data.shown = newShown;
    }

    if (typeof data.shown != "object") {
      data.shown = {};
    }

    data.shown[id] = now;

    saveNotificationData();
  }

  /**
   * Localizes the texts of the given notification based on the
   * {@link module:notifications~Notifications#locale locale}.
   * @param {Object} notification The notification.
   * @returns {Object} The localized texts.
   */
  getLocalizedTexts(notification) {
    let textKeys = ["title", "message"];
    let localizedTexts = {};

    for (let key of textKeys) {
      if (key in notification) {
        if (typeof notification[key] == "string") {
          localizedTexts[key] = notification[key];
        }
        else {
          localizedTexts[key] = localize(notification[key], this.locale);
        }
      }
    }

    return localizedTexts;
  }

  /**
   * Adds a local notification.
   * @param {Object} notification The notification to add.
   */
  addNotification(notification) {
    if (!isValidNotification(notification)) {
      throw new Error(`Invalid notification with ID "${notification.id}"`);
    }

    this._localNotifications.add(notification);
  }

  /**
   * Removes an existing local notification.
   * @param {Object} notification The notification to remove.
   */
  removeNotification(notification) {
    this._localNotifications.delete(notification);
  }

  /**
   * Toggles whether notifications of a specific category should be ignored.
   * @param {string} category The notification category identifier.
   * @param {boolean} [forceValue] Whether to force the specified value.
   */
  toggleIgnoreCategory(category, forceValue) {
    let categories = Prefs.notifications_ignoredcategories;
    let index = categories.indexOf(category);
    if (index == -1 && forceValue != false) {
      categories.push(category);
      Prefs.notifications_ignoredcategories = categories;
      this.emit("ignored-category-added", category);
    }
    else if (index != -1 && forceValue != true) {
      categories.splice(index, 1);
      Prefs.notifications_ignoredcategories = categories;
      this.emit("ignored-category-removed", category);
    }

    saveNotificationData("notifications_ignoredcategories");
  }

  /**
   * Returns the number of times the notifications data have been downloaded.
   * @returns {number}
   */
  getDownloadCount() {
    return Prefs.notificationdata.downloadCount || 0;
  }

  /**
   * Returns the list of ignored categories.
   * @returns {Array.<string>}
   */
  getIgnoredCategories() {
    return Prefs.notifications_ignoredcategories;
  }
}

/**
 * Regularly fetches notifications and decides which notification to show.
 * @type {module:notifications~Notifications}
 */
exports.notifications = new Notifications();


/***/ }),

/***/ "./core/lib/patterns.js":
/*!******************************!*\
  !*** ./core/lib/patterns.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * The maximum number of patterns that
 * `{@link module:patterns.compilePatterns compilePatterns()}` will compile
 * into regular expressions.
 * @type {number}
 */
const COMPILE_PATTERNS_MAX = 100;

/**
 * Regular expression used to match the `^` suffix in an otherwise literal
 * pattern.
 * @type {RegExp}
 */
let separatorRegExp = /[\x00-\x24\x26-\x2C\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/;

let filterToRegExp =
/**
 * Converts filter text into regular expression string
 * @param {string} text as in Filter()
 * @return {string} regular expression representation of filter text
 * @package
 */
exports.filterToRegExp = function filterToRegExp(text) {
  // remove multiple wildcards
  text = text.replace(/\*+/g, "*");

  // remove leading wildcard
  if (text[0] == "*") {
    text = text.substring(1);
  }

  // remove trailing wildcard
  if (text[text.length - 1] == "*") {
    text = text.substring(0, text.length - 1);
  }

  return text
    // remove anchors following separator placeholder
    .replace(/\^\|$/, "^")
    // escape special symbols
    .replace(/\W/g, "\\$&")
    // replace wildcards by .*
    .replace(/\\\*/g, ".*")
    // process separator placeholders (all ANSI characters but alphanumeric
    // characters and _%.-)
    .replace(/\\\^/g, `(?:${separatorRegExp.source}|$)`)
    // process extended anchor at expression start
    .replace(/^\\\|\\\|/, "^[\\w\\-]+:\\/+(?:[^\\/]+\\.)?")
    // process anchor at expression start
    .replace(/^\\\|/, "^")
    // process anchor at expression end
    .replace(/\\\|$/, "$");
};

/**
 * Regular expression used to match the `||` prefix in an otherwise literal
 * pattern.
 * @type {RegExp}
 */
let extendedAnchorRegExp = new RegExp(filterToRegExp("||") + "$");

/**
 * Regular expression for matching a keyword in a filter.
 * @type {RegExp}
 */
let keywordRegExp = /[^a-z0-9%*][a-z0-9%]{2,}(?=[^a-z0-9%*])/;

/**
 * Regular expression for matching all keywords in a filter.
 * @type {RegExp}
 */
let allKeywordsRegExp = new RegExp(keywordRegExp, "g");

/**
 * A `CompiledPatterns` object represents the compiled version of multiple URL
 * request patterns. It is returned by
 * `{@link module:patterns.compilePatterns compilePatterns()}`.
 */
class CompiledPatterns {
  /**
   * Creates an object with the given regular expressions for case-sensitive
   * and case-insensitive matching respectively.
   * @param {?RegExp} [caseSensitive]
   * @param {?RegExp} [caseInsensitive]
   * @private
   */
  constructor(caseSensitive, caseInsensitive) {
    this._caseSensitive = caseSensitive;
    this._caseInsensitive = caseInsensitive;
  }

  /**
   * Tests whether the given URL request matches the patterns used to create
   * this object.
   * @param {module:url.URLRequest} request
   * @returns {boolean}
   */
  test(request) {
    return ((this._caseSensitive &&
             this._caseSensitive.test(request.href)) ||
            (this._caseInsensitive &&
             this._caseInsensitive.test(request.lowerCaseHref)));
  }
}

/**
 * Compiles patterns from the given filters into a single
 * `{@link module:patterns~CompiledPatterns CompiledPatterns}` object.
 *
 * @param {module:filterClasses.URLFilter|
 *         Set.<module:filterClasses.URLFilter>} filters
 *   The filters. If the number of filters exceeds
 *   `{@link module:patterns~COMPILE_PATTERNS_MAX COMPILE_PATTERNS_MAX}`, the
 *   function returns `null`.
 *
 * @returns {?module:patterns~CompiledPatterns}
 *
 * @package
 */
exports.compilePatterns = function compilePatterns(filters) {
  let list = Array.isArray(filters) ? filters : [filters];

  // If the number of filters is too large, it may choke especially on low-end
  // platforms. As a precaution, we refuse to compile. Ideally we would check
  // the length of the regular expression source rather than the number of
  // filters, but this is far more straightforward and practical.
  if (list.length > COMPILE_PATTERNS_MAX) {
    return null;
  }

  let caseSensitive = "";
  let caseInsensitive = "";

  for (let filter of filters) {
    let source = filter.urlPattern.regexpSource;

    if (filter.matchCase) {
      caseSensitive += source + "|";
    }
    else {
      caseInsensitive += source + "|";
    }
  }

  let caseSensitiveRegExp = null;
  let caseInsensitiveRegExp = null;

  try {
    if (caseSensitive) {
      caseSensitiveRegExp = new RegExp(caseSensitive.slice(0, -1));
    }

    if (caseInsensitive) {
      caseInsensitiveRegExp = new RegExp(caseInsensitive.slice(0, -1));
    }
  }
  catch (error) {
    // It is possible in theory for the regular expression to be too large
    // despite COMPILE_PATTERNS_MAX
    return null;
  }

  return new CompiledPatterns(caseSensitiveRegExp, caseInsensitiveRegExp);
};

/**
 * Patterns for matching against URLs.
 *
 * Internally, this may be a RegExp or match directly against the
 * pattern for simple literal patterns.
 */
exports.Pattern = class Pattern {
  /**
   * @param {string} pattern pattern that requests URLs should be
   * matched against in filter text notation
   * @param {bool} matchCase `true` if comparisons must be case
   * sensitive
   */
  constructor(pattern, matchCase) {
    this.matchCase = matchCase || false;

    if (!this.matchCase) {
      pattern = pattern.toLowerCase();
    }

    if (pattern.length >= 2 &&
        pattern[0] == "/" &&
        pattern[pattern.length - 1] == "/") {
      // The filter is a regular expression - convert it immediately to
      // catch syntax errors
      pattern = pattern.substring(1, pattern.length - 1);
      this._regexp = new RegExp(pattern);
    }
    else {
      // Patterns like /foo/bar/* exist so that they are not treated as regular
      // expressions. We drop any superfluous wildcards here so our
      // optimizations can kick in.
      pattern = pattern.replace(/^\*+/, "").replace(/\*+$/, "");

      // No need to convert this filter to regular expression yet, do it on
      // demand
      this.pattern = pattern;
    }
  }

  /**
   * Checks whether the pattern is a string of literal characters with
   * no wildcards or any other special characters.
   *
   * If the pattern is prefixed with a `||` or suffixed with a `^` but otherwise
   * contains no special characters, it is still considered to be a literal
   * pattern.
   *
   * @returns {boolean}
   */
  isLiteralPattern() {
    return typeof this.pattern !== "undefined" &&
      !/[*^|]/.test(this.pattern.replace(/^\|{1,2}/, "").replace(/[|^]$/, ""));
  }

  /**
   * Regular expression to be used when testing against this pattern.
   *
   * null if the pattern is matched without using regular expressions.
   * @type {RegExp}
   */
  get regexp() {
    if (typeof this._regexp == "undefined") {
      this._regexp = this.isLiteralPattern() ?
        null : new RegExp(filterToRegExp(this.pattern));
    }
    return this._regexp;
  }

  /**
   * Pattern in regular expression notation. This will have a value
   * even if `regexp` returns null.
   * @type {string}
   */
  get regexpSource() {
    return this._regexp ? this._regexp.source : filterToRegExp(this.pattern);
  }

  /**
   * Checks whether the given URL request matches this filter's pattern.
   * @param {module:url.URLRequest} request The URL request to check.
   * @returns {boolean} `true` if the URL request matches.
   */
  matchesLocation(request) {
    let location = this.matchCase ? request.href : request.lowerCaseHref;
    let regexp = this.regexp;
    if (regexp) {
      return regexp.test(location);
    }

    let pattern = this.pattern;
    let startsWithAnchor = pattern[0] == "|";
    let startsWithExtendedAnchor = startsWithAnchor && pattern[1] == "|";
    let endsWithSeparator = pattern[pattern.length - 1] == "^";
    let endsWithAnchor = !endsWithSeparator &&
        pattern[pattern.length - 1] == "|";

    if (startsWithExtendedAnchor) {
      pattern = pattern.substr(2);
    }
    else if (startsWithAnchor) {
      pattern = pattern.substr(1);
    }

    if (endsWithSeparator || endsWithAnchor) {
      pattern = pattern.slice(0, -1);
    }

    let index = location.indexOf(pattern);

    while (index != -1) {
      // The "||" prefix requires that the text that follows does not start
      // with a forward slash.
      if ((startsWithExtendedAnchor ?
           location[index] != "/" &&
           extendedAnchorRegExp.test(location.substring(0, index)) :
           startsWithAnchor ?
           index == 0 :
           true) &&
          (endsWithSeparator ?
           !location[index + pattern.length] ||
           separatorRegExp.test(location[index + pattern.length]) :
           endsWithAnchor ?
           index == location.length - pattern.length :
           true)) {
        return true;
      }

      if (pattern == "") {
        return true;
      }

      index = location.indexOf(pattern, index + 1);
    }

    return false;
  }

  /**
   * Checks whether the pattern has keywords
   * @returns {boolean}
   */
  hasKeywords() {
    return this.pattern && keywordRegExp.test(this.pattern);
  }

  /**
   * Finds all keywords that could be associated with this pattern
   * @returns {string[]}
   */
  keywordCandidates() {
    if (!this.pattern) {
      return null;
    }
    return this.pattern.toLowerCase().match(allKeywordsRegExp);
  }
};


/***/ }),

/***/ "./core/lib/polyfill.js":
/*!******************************!*\
  !*** ./core/lib/polyfill.js ***!
  \******************************/
/***/ (() => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



// Promise.prototype.finally is not supported in Firefox < 58
if (!Promise.prototype.finally) {
  Promise.prototype.finally = function(fn) {
    return this.then(fn, fn);
  };
}


/***/ }),

/***/ "./core/lib/profiler.js":
/*!******************************!*\
  !*** ./core/lib/profiler.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_489153__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/* eslint no-console: "off" */
/* global self */

/** @module */



const {performance, PerformanceObserver} = __nested_webpack_require_489153__(/*! perf_hooks */ "perf_hooks");

/**
 * Default profiler("...") returned object when profile mode is disabled.
 * @type {Profiler}
 * @private
 */
let noopProfiler = {
  start() {},
  mark() {},
  end() {},
  toString() {
    return "{start(){},mark(){},end(){}}";
  }
};

let inactiveProfiling = true;
let obs = null;

/** Enable or disable profiling
 *
 * @param {bool} enable the profiling is enabled. If true it will
 * create a PerformanceObserver and start observing, profiler() will then
 * create a proper profiler object. If false, observing is cancelled and
 * the profiler object will be a noop.
 * @param {?Function} reporter The reporter function called by the observer.
 * If falsy, the default reporter will be used.
 */
function enableProfiling(enable, reporter) {
  inactiveProfiling = !enable;
  if (enable) {
    performance.mark("start_profile");
    if (!reporter) {
      reporter = list => {
        for (let entry of list.getEntriesByType("measure")) {
          console.log(`${entry.name}: ${entry.duration}ms`);
        }
      };
    }
    obs = new PerformanceObserver(reporter);

    obs.observe({entryTypes: ["measure"]});
  }
  else if (obs) {
    obs.disconnect();
    obs = null;
  }
}

/**
 * Create a profiler object with `start()` `mark()` and `end()` methods to
 * either start, keep marking a specific profiled name, or ending it.
 *
 * @example
 * let {mark, end} = profiler('console.log');
 * mark();
 * console.log(1, 2, 3);
 * end();
 *
 * @param {string} id the unique ID to profile.
 * @returns {Profiler} The profiler with `start()`, `mark()` and
 * `end(clear = false)` methods.
 * @private
 */
function profiler(id) {
  if (inactiveProfiling) {
    return noopProfiler;
  }

  return {
    id,
    start() {
      performance.mark(`${id}:start`);
      performance.measure(`${id}:startup`, "start_profile", `${id}:start`);
    },
    mark(event) {
      performance.mark(`${id}:${event}`);
      performance.measure(
        `${id}:${event}_measure`, "start_profile", `${id}:${event}`
      );
    },
    end() {
      performance.mark(`${id}:end`);
      performance.measure(id, "start_profile", `${id}:end`);
    }
  };
}

function isProfilingEnabled() {
  return !inactiveProfiling;
}

exports.profiler = profiler;
exports.enable = enableProfiling;
exports.isEnabled = isProfilingEnabled;


/***/ }),

/***/ "./core/lib/recommendations.js":
/*!*************************************!*\
  !*** ./core/lib/recommendations.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_492584__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * A `Recommendation` object represents a recommended filter subscription.
 */
class Recommendation {
  /**
   * Creates a `Recommendation` object from the given source object.
   * @param {object} source The source object.
   * @private
   */
  constructor(source) {
    this._source = source;
  }

  /**
   * The id (UUID) of the subscription.
   * If the id is not null, there is a 1:1 relationship with `id` : `url`.
   * @type {?string}
   */
  get id() {
    return this._source.id;
  }

  /**
   * The required subscription ids.
   * @type {?Array.<string>}
   */
  get requires() {
    return this._source.requires;
  }

  /**
   * The type of the recommended filter subscription.
   * @type {string}
   */
  get type() {
    return this._source.type;
  }

  /**
   * The languages of the recommended filter subscription.
   * @type {Array.<string>}
   */
  get languages() {
    return this._source.languages ? [...this._source.languages] : [];
  }

  /**
   * The title of the recommended filter subscription.
   * @type {string}
   */
  get title() {
    return this._source.title;
  }

  /**
   * The URL of the recommended filter subscription.
   * @type {string}
   */
  get url() {
    return this._source.url;
  }

  /**
   * The home page of the recommended filter subscription.
   * @type {string}
   */
  get homepage() {
    return this._source.homepage;
  }

  /**
   * The manifest v2 URL
   * @type {?string}
   */
  get mv2URL() {
    return this._source.mv2_url;
  }

  /**
   * Where this recommendation will get updates from.
   * @type {?string}
   */
  get diffURL() {
    return this._source.diff_url;
  }

  /**
   * Expiration interval from the subscription header.
   * Usually the number of days or hours between expirations.
   * @example "1 days"
   * @example "6 hours"
   * @type {?string}
   */
  get expires() {
    return this._source.expires;
  }

  /**
   * True if this subscription can load filters that require privileged access,
   * like snippets.
   * @type {?bool}
   */
  get privileged() {
    return this._source.privileged;
  }
}

let _recommendations = null;

/**
 * Set the recommendations. This is required. It should be done before
 * any other operation on subscriptions, and shouldn't be called more
 * than once.
 *
 * @param {object} recommendations The available recommended subscriptions.
 */
exports.setRecommendations = function(recommendations) {
  _recommendations = recommendations;
};

/**
 * Returns an array of
 * `{@link module:recommendations~Recommendation Recommendation}` objects
 * representing recommended filter subscriptions.
 *
 * @returns {Array.<module:recommendations~Recommendation>} An array of objects
 *  representing recommended filter subscriptions.
 */
exports.recommendations = function recommendations() {
  if (!_recommendations) {
    _recommendations = __nested_webpack_require_492584__(/*! ../data/subscriptions.json */ "./core/data/subscriptions.json");
  }

  return _recommendations.map(source => new Recommendation(source));
};

exports.Recommendation = Recommendation;


/***/ }),

/***/ "./core/lib/rsa.js":
/*!*************************!*\
  !*** ./core/lib/rsa.js ***!
  \*************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_496576__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/* global crypto, TextEncoder */

/** @module */



const Rusha = __nested_webpack_require_496576__(/*! ./rusha.js */ "./core/lib/rusha.js");
const {BigInteger} = __nested_webpack_require_496576__(/*! ./jsbn.js */ "./core/lib/jsbn.js");

/**
 * @file Provides ASN.1 sitekeys verifications.
 */

let base64ToArrayBuffer =
/**
 * Converts a base64 string to an array buffer byte array.
 * @param {string} base64 Base64 encoded string.
 * @return {Uint8Array} The same data, encoded as an array buffer.
 */
exports.base64ToArrayBuffer = function base64ToArrayBuffer(base64) {
  let binaryString = atob(base64);
  return Uint8Array.from(binaryString, c => c.charCodeAt(0));
};

/**
 * Converts an array buffer byte array into a base64 string.
 * @param {Uint8Array} buffer Byte array of any data.
 * @return {string} The same data, encoded as a base64 string.
 */
exports.arrayBufferToBase64 = function arrayBufferToBase64(buffer) {
  let binary = "";
  let bytes = new Uint8Array(buffer);
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }

  return btoa(binary);
};

/**
 * Checks whether the signature is valid for the given public key and data.
 * The verification is based on ASN.1 over SHA-1. This procedure is known as
 * RSA_PKCS1_SHA1 and it is the default kind of procedure, in OpenSSL, when
 * SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE is used to create the key/signature pair.
 * @param {string} key a base 64 public key used to verify.
 * @param {string} signature a base 64 signature used to verify.
 * @param {string} data a unique identifier of the resource to verify.
 * @returns {Promise<boolean>} resolves with true if the signature is valid
 */
exports.verifySignature = async function verifySignature(key, signature, data) {
  let signAlgorithm = {
    name: "RSASSA-PKCS1-v1_5",
    hash: {name: "SHA-1"}
  };
  try {
    return await crypto.subtle.verify(
      signAlgorithm,
      await crypto.subtle.importKey(
        "spki",
        base64ToArrayBuffer(key),
        signAlgorithm,
        true,
        ["verify"]
      ),
      base64ToArrayBuffer(signature),
      new TextEncoder().encode(data)
    );
  }
  catch ({message}) {
    console.warn("Invalid encrypted signature: " + message);
    return false;
  }
};

// Define ASN.1 templates for the data structures used
function seq(...args) {
  return {type: 0x30, children: args};
}
function obj(id) {
  return {type: 0x06, content: id};
}
function bitStr(contents) {
  return {type: 0x03, encapsulates: contents};
}
function intResult(id) {
  return {type: 0x02, out: id};
}
function octetResult(id) {
  return {type: 0x04, out: id};
}

// See http://www.cryptopp.com/wiki/Keys_and_Formats#RSA_PublicKey
// 2A 86 48 86 F7 0D 01 01 01 means 1.2.840.113549.1.1.1
let publicKeyTemplate = seq(
  seq(obj("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01"), {}),
  bitStr(seq(intResult("n"), intResult("e")))
);

// See http://tools.ietf.org/html/rfc3447#section-9.2 step 2
// 2B 0E 03 02 1A means 1.3.14.3.2.26
let signatureTemplate = seq(
  seq(obj("\x2B\x0E\x03\x02\x1A"), {}),
  octetResult("sha1")
);

/**
 * Reads ASN.1 data matching the template passed in. This will throw an
 * exception if the data format doesn't match the template. On success an
 * object containing result properties is returned.
 * @see http://luca.ntop.org/Teaching/Appunti/asn1.html for info on the format.
 * @param {string} data
 * @param {Object} templ
 * @returns {Object}
 */
function readASN1(data, templ) {
  let pos = 0;
  function next() {
    return data.charCodeAt(pos++);
  }

  function readLength() {
    let len = next();
    if (len & 0x80) {
      let cnt = len & 0x7F;
      if (cnt > 2 || cnt == 0) {
        throw "Unsupported length";
      }

      len = 0;
      for (let i = 0; i < cnt; i++) {
        len += next() << (cnt - 1 - i) * 8;
      }
      return len;
    }
    return len;
  }

  function readNode(curTempl) {
    let type = next();
    let len = readLength();
    if ("type" in curTempl && curTempl.type != type) {
      throw "Unexpected type";
    }
    if ("content" in curTempl &&
        curTempl.content != data.substring(pos, pos + len)) {
      throw "Unexpected content";
    }
    if ("out" in curTempl) {
      out[curTempl.out] = new BigInteger(data.substring(pos, pos + len), 256);
    }
    if ("children" in curTempl) {
      let i;
      let end;
      for (i = 0, end = pos + len; pos < end; i++) {
        if (i >= curTempl.children.length) {
          throw "Too many children";
        }
        readNode(curTempl.children[i]);
      }
      if (i < curTempl.children.length) {
        throw "Too few children";
      }
      if (pos > end) {
        throw "Children too large";
      }
    }
    else if ("encapsulates" in curTempl) {
      if (next() != 0) {
        throw "Encapsulation expected";
      }
      readNode(curTempl.encapsulates);
    }
    else {
      pos += len;
    }
  }

  let out = {};
  readNode(templ);
  if (pos != data.length) {
    throw "Too much data";
  }
  return out;
}

/**
 * Reads a BER-encoded RSA public key. On success returns an object with the
 * properties n and e (the components of the key), otherwise null.
 * @param {string} key
 * @return {?Object}
 */
function readPublicKey(key) {
  try {
    return readASN1(atob(key), publicKeyTemplate);
  }
  catch (e) {
    console.warn("Invalid RSA public key: " + e);
    return null;
  }
}

let rusha;

/**
 * Checks whether the signature is valid for the given public key and data.
 * The verification is based on ASN.1 over SHA-1. This procedure is known as
 * RSA_PKCS1_SHA1 and it is the default kind of procedure, in OpenSSL, when
 * SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE is used to create the key/signature pair.
 *
 * This function is synchronous, and so does not return a
 * promise. It's recommended to use the asynchronous version,
 * `{@link module:rsa.verifySignature verifySignature}`, if possible.
 * @param {string} key a base 64 public key used to verify.
 * @param {string} signature a base 64 signature used to verify.
 * @param {string} data a unique identifier of the resource to verify.
 * @returns {boolean} true if the signature is valid.
 */
exports.verifySignatureSync =
function verifySignatureSync(key, signature, data) {
  if (typeof rusha == "undefined") {
    rusha = new Rusha();
  }

  let keyData = readPublicKey(key);
  if (!keyData) {
    return false;
  }

  // We need the exponent as regular number
  keyData.e = parseInt(keyData.e.toString(16), 16);

  // Decrypt signature data using RSA algorithm
  let sigInt = new BigInteger(atob(signature), 256);
  let digest = sigInt.modPowInt(keyData.e, keyData.n).toString(256);

  try {
    let pos = 0;
    let next = () => digest.charCodeAt(pos++);

    // Skip padding, see http://tools.ietf.org/html/rfc3447#section-9.2 step 5
    if (next() != 1) {
      throw "Wrong padding in signature digest";
    }
    while (next() == 255) {}
    if (digest.charCodeAt(pos - 1) != 0) {
      throw "Wrong padding in signature digest";
    }

    // Rest is an ASN.1 structure, get the SHA1 hash from it and compare to
    // the real one
    let {sha1} = readASN1(digest.substring(pos), signatureTemplate);
    let expected = new BigInteger(rusha.digest(data), 16);
    return (sha1.compareTo(expected) == 0);
  }
  catch (e) {
    console.warn("Invalid encrypted signature: " + e);
    return false;
  }
};


/***/ }),

/***/ "./core/lib/rusha.js":
/*!***************************!*\
  !*** ./core/lib/rusha.js ***!
  \***************************/
/***/ ((module, exports, __nested_webpack_require_504866__) => {

(function () {
    var /*
 * Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
 * as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
 * (http://github.com/srijs/rusha)
 *
 * Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
 *
 * Copyright (c) 2013 Sam Rijs (http://awesam.de).
 * Released under the terms of the MIT license as follows:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
    util = {
        getDataType: function (data) {
            if (typeof data === 'string') {
                return 'string';
            }
            if (data instanceof Array) {
                return 'array';
            }
            if (typeof __nested_webpack_require_504866__.g !== 'undefined' && __nested_webpack_require_504866__.g.Buffer && __nested_webpack_require_504866__.g.Buffer.isBuffer(data)) {
                return 'buffer';
            }
            if (data instanceof ArrayBuffer) {
                return 'arraybuffer';
            }
            if (data.buffer instanceof ArrayBuffer) {
                return 'view';
            }
            if (data instanceof Blob) {
                return 'blob';
            }
            throw new Error('Unsupported data type.');
        }
    };
    function Rusha(chunkSize) {
        'use strict';
        var // Private object structure.
        self$2 = { fill: 0 };
        var // Calculate the length of buffer that the sha1 routine uses
        // including the padding.
        padlen = function (len) {
            for (len += 9; len % 64 > 0; len += 1);
            return len;
        };
        var padZeroes = function (bin, len) {
            for (var i$2 = len >> 2; i$2 < bin.length; i$2++)
                bin[i$2] = 0;
        };
        var padData = function (bin, chunkLen, msgLen) {
            bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3);
            // To support msgLen >= 2 GiB, use a float division when computing the
            // high 32-bits of the big-endian message length in bits.
            bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen / (1 << 29) | 0;
            bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3;
        };
        var // Convert a binary string and write it to the heap.
        // A binary string is expected to only contain char codes < 256.
        convStr = function (H8, H32, start, len, off) {
            var str = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
            if (j > 0) {
                switch (om) {
                case 0:
                    H8[off + 3 | 0] = str.charCodeAt(start);
                case 1:
                    H8[off + 2 | 0] = str.charCodeAt(start + 1);
                case 2:
                    H8[off + 1 | 0] = str.charCodeAt(start + 2);
                case 3:
                    H8[off | 0] = str.charCodeAt(start + 3);
                }
            }
            for (i$2 = om; i$2 < j; i$2 = i$2 + 4 | 0) {
                H32[off + i$2 >> 2] = str.charCodeAt(start + i$2) << 24 | str.charCodeAt(start + i$2 + 1) << 16 | str.charCodeAt(start + i$2 + 2) << 8 | str.charCodeAt(start + i$2 + 3);
            }
            switch (lm) {
            case 3:
                H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2);
            case 2:
                H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1);
            case 1:
                H8[off + j + 3 | 0] = str.charCodeAt(start + j);
            }
        };
        var // Convert a buffer or array and write it to the heap.
        // The buffer or array is expected to only contain elements < 256.
        convBuf = function (H8, H32, start, len, off) {
            var buf = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
            if (j > 0) {
                switch (om) {
                case 0:
                    H8[off + 3 | 0] = buf[start];
                case 1:
                    H8[off + 2 | 0] = buf[start + 1];
                case 2:
                    H8[off + 1 | 0] = buf[start + 2];
                case 3:
                    H8[off | 0] = buf[start + 3];
                }
            }
            for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
                H32[off + i$2 >> 2] = buf[start + i$2] << 24 | buf[start + i$2 + 1] << 16 | buf[start + i$2 + 2] << 8 | buf[start + i$2 + 3];
            }
            switch (lm) {
            case 3:
                H8[off + j + 1 | 0] = buf[start + j + 2];
            case 2:
                H8[off + j + 2 | 0] = buf[start + j + 1];
            case 1:
                H8[off + j + 3 | 0] = buf[start + j];
            }
        };
        var convBlob = function (H8, H32, start, len, off) {
            var blob = this, i$2, om = off % 4, lm = len % 4, j = len - lm;
            var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len)));
            if (j > 0) {
                switch (om) {
                case 0:
                    H8[off + 3 | 0] = buf[0];
                case 1:
                    H8[off + 2 | 0] = buf[1];
                case 2:
                    H8[off + 1 | 0] = buf[2];
                case 3:
                    H8[off | 0] = buf[3];
                }
            }
            for (i$2 = 4 - om; i$2 < j; i$2 = i$2 += 4 | 0) {
                H32[off + i$2 >> 2] = buf[i$2] << 24 | buf[i$2 + 1] << 16 | buf[i$2 + 2] << 8 | buf[i$2 + 3];
            }
            switch (lm) {
            case 3:
                H8[off + j + 1 | 0] = buf[j + 2];
            case 2:
                H8[off + j + 2 | 0] = buf[j + 1];
            case 1:
                H8[off + j + 3 | 0] = buf[j];
            }
        };
        var convFn = function (data) {
            switch (util.getDataType(data)) {
            case 'string':
                return convStr.bind(data);
            case 'array':
                return convBuf.bind(data);
            case 'buffer':
                return convBuf.bind(data);
            case 'arraybuffer':
                return convBuf.bind(new Uint8Array(data));
            case 'view':
                return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
            case 'blob':
                return convBlob.bind(data);
            }
        };
        var slice = function (data, offset) {
            switch (util.getDataType(data)) {
            case 'string':
                return data.slice(offset);
            case 'array':
                return data.slice(offset);
            case 'buffer':
                return data.slice(offset);
            case 'arraybuffer':
                return data.slice(offset);
            case 'view':
                return data.buffer.slice(offset);
            }
        };
        var // Precompute 00 - ff strings
        precomputedHex = new Array(256);
        for (var i = 0; i < 256; i++) {
            precomputedHex[i] = (i < 16 ? '0' : '') + i.toString(16);
        }
        var // Convert an ArrayBuffer into its hexadecimal string representation.
        hex = function (arrayBuffer) {
            var binarray = new Uint8Array(arrayBuffer);
            var res = new Array(arrayBuffer.byteLength);
            for (var i$2 = 0; i$2 < res.length; i$2++) {
                res[i$2] = precomputedHex[binarray[i$2]];
            }
            return res.join('');
        };
        var ceilHeapSize = function (v) {
            // The asm.js spec says:
            // The heap object's byteLength must be either
            // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
            // Also, byteLengths smaller than 2^16 are deprecated.
            var p;
            if (// If v is smaller than 2^16, the smallest possible solution
                // is 2^16.
                v <= 65536)
                return 65536;
            if (// If v < 2^24, we round up to 2^n,
                // otherwise we round up to 2^24 * n.
                v < 16777216) {
                for (p = 1; p < v; p = p << 1);
            } else {
                for (p = 16777216; p < v; p += 16777216);
            }
            return p;
        };
        var // Initialize the internal data structures to a new capacity.
        init = function (size) {
            if (size % 64 > 0) {
                throw new Error('Chunk size must be a multiple of 128 bit');
            }
            self$2.maxChunkLen = size;
            self$2.padMaxChunkLen = padlen(size);
            // The size of the heap is the sum of:
            // 1. The padded input message size
            // 2. The extended space the algorithm needs (320 byte)
            // 3. The 160 bit state the algoritm uses
            self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20));
            self$2.h32 = new Int32Array(self$2.heap);
            self$2.h8 = new Int8Array(self$2.heap);
            self$2.core = new Rusha._core({
                Int32Array: Int32Array,
                DataView: DataView
            }, {}, self$2.heap);
            self$2.buffer = null;
        };
        // Initialize the data structures according
        // to a chunk size.
        init(chunkSize || 64 * 1024);
        var initState = function (heap, padMsgLen) {
            var io = new Int32Array(heap, padMsgLen + 320, 5);
            io[0] = 1732584193;
            io[1] = -271733879;
            io[2] = -1732584194;
            io[3] = 271733878;
            io[4] = -1009589776;
        };
        var padChunk = function (chunkLen, msgLen) {
            var padChunkLen = padlen(chunkLen);
            var view = new Int32Array(self$2.heap, 0, padChunkLen >> 2);
            padZeroes(view, chunkLen);
            padData(view, chunkLen, msgLen);
            return padChunkLen;
        };
        var // Write data to the heap.
        write = function (data, chunkOffset, chunkLen) {
            convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, 0);
        };
        var // Initialize and call the RushaCore,
        // assuming an input buffer of length len * 4.
        coreCall = function (data, chunkOffset, chunkLen, msgLen, finalize) {
            var padChunkLen = chunkLen;
            if (finalize) {
                padChunkLen = padChunk(chunkLen, msgLen);
            }
            write(data, chunkOffset, chunkLen);
            self$2.core.hash(padChunkLen, self$2.padMaxChunkLen);
        };
        var getRawDigest = function (heap, padMaxChunkLen) {
            var io = new Int32Array(heap, padMaxChunkLen + 320, 5);
            var out = new Int32Array(5);
            var arr = new DataView(out.buffer);
            arr.setInt32(0, io[0], false);
            arr.setInt32(4, io[1], false);
            arr.setInt32(8, io[2], false);
            arr.setInt32(12, io[3], false);
            arr.setInt32(16, io[4], false);
            return out;
        };
        var // Calculate the hash digest as an array of 5 32bit integers.
        rawDigest = this.rawDigest = function (str) {
            var msgLen = str.byteLength || str.length || str.size || 0;
            initState(self$2.heap, self$2.padMaxChunkLen);
            var chunkOffset = 0, chunkLen = self$2.maxChunkLen, last;
            for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) {
                coreCall(str, chunkOffset, chunkLen, msgLen, false);
            }
            coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true);
            return getRawDigest(self$2.heap, self$2.padMaxChunkLen);
        };
        // The digest and digestFrom* interface returns the hash digest
        // as a hex string.
        this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str) {
            return hex(rawDigest(str).buffer);
        };
    }
    ;
    // The low-level RushCore module provides the heart of Rusha,
    // a high-speed sha1 implementation working on an Int32Array heap.
    // At first glance, the implementation seems complicated, however
    // with the SHA1 spec at hand, it is obvious this almost a textbook
    // implementation that has a few functions hand-inlined and a few loops
    // hand-unrolled.
    Rusha._core = function RushaCore(stdlib, foreign, heap) {
        'use asm';
        var H = new stdlib.Int32Array(heap);
        function hash(k, x) {
            // k in bytes
            k = k | 0;
            x = x | 0;
            var i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0;
            y0 = H[x + 320 >> 2] | 0;
            y1 = H[x + 324 >> 2] | 0;
            y2 = H[x + 328 >> 2] | 0;
            y3 = H[x + 332 >> 2] | 0;
            y4 = H[x + 336 >> 2] | 0;
            for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) {
                z0 = y0;
                z1 = y1;
                z2 = y2;
                z3 = y3;
                z4 = y4;
                for (j = 0; (j | 0) < 64; j = j + 4 | 0) {
                    t1 = H[i + j >> 2] | 0;
                    t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
                    y4 = y3;
                    y3 = y2;
                    y2 = y1 << 30 | y1 >>> 2;
                    y1 = y0;
                    y0 = t0;
                    H[k + j >> 2] = t1;
                }
                for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) {
                    t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
                    t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0;
                    y4 = y3;
                    y3 = y2;
                    y2 = y1 << 30 | y1 >>> 2;
                    y1 = y0;
                    y0 = t0;
                    H[j >> 2] = t1;
                }
                for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) {
                    t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
                    t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0;
                    y4 = y3;
                    y3 = y2;
                    y2 = y1 << 30 | y1 >>> 2;
                    y1 = y0;
                    y0 = t0;
                    H[j >> 2] = t1;
                }
                for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) {
                    t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
                    t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0;
                    y4 = y3;
                    y3 = y2;
                    y2 = y1 << 30 | y1 >>> 2;
                    y1 = y0;
                    y0 = t0;
                    H[j >> 2] = t1;
                }
                for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) {
                    t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31;
                    t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0;
                    y4 = y3;
                    y3 = y2;
                    y2 = y1 << 30 | y1 >>> 2;
                    y1 = y0;
                    y0 = t0;
                    H[j >> 2] = t1;
                }
                y0 = y0 + z0 | 0;
                y1 = y1 + z1 | 0;
                y2 = y2 + z2 | 0;
                y3 = y3 + z3 | 0;
                y4 = y4 + z4 | 0;
            }
            H[x + 320 >> 2] = y0;
            H[x + 324 >> 2] = y1;
            H[x + 328 >> 2] = y2;
            H[x + 332 >> 2] = y3;
            H[x + 336 >> 2] = y4;
        }
        return { hash: hash };
    };
    exports = Rusha;
    if (// If we'e running in Node.JS, export a module.
        true) {
        module.exports = Rusha;
    } else {}
    if (// If we're running in a webworker, accept
        // messages containing a jobid and a buffer
        // or blob object, and return the hash result.
        typeof FileReaderSync !== 'undefined') {
        var reader = new FileReaderSync(), hasher = new Rusha(4 * 1024 * 1024);
        self.onmessage = function onMessage(event) {
            var hash, data = event.data.data;
            try {
                hash = hasher.digest(data);
                self.postMessage({
                    id: event.data.id,
                    hash: hash
                });
            } catch (e) {
                self.postMessage({
                    id: event.data.id,
                    error: e.name
                });
            }
        };
    }
}());


/***/ }),

/***/ "./core/lib/snippets.js":
/*!******************************!*\
  !*** ./core/lib/snippets.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_523095__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Snippets implementation.
 */

const {EventEmitter} = __nested_webpack_require_523095__(/*! ./events */ "./core/lib/events.js");

let singleCharacterEscapes = new Map([
  ["n", "\n"], ["r", "\r"], ["t", "\t"]
]);

/**
 * `{@link module:snippets.snippets snippets}` implementation.
 */
class Snippets extends EventEmitter {
  /**
   * @hideconstructor
   */
  constructor() {
    super();

    /**
     * All known snippet filters.
     * @type {Set.<module:filterClasses.SnippetFilter>}
     * @private
     */
    this._filters = new Set();
  }

  /**
   * Removes all known snippet filters.
   */
  clear() {
    let {_filters} = this;

    if (_filters.size == 0) {
      return;
    }

    _filters.clear();

    this.emit("snippets.filtersCleared");
  }

  /**
   * Adds a new snippet filter.
   * @param {module:filterClasses.SnippetFilter} filter
   */
  add(filter) {
    let {_filters} = this;
    let {size} = _filters;

    _filters.add(filter);

    if (size != _filters.size) {
      this.emit("snippets.filterAdded", filter);
    }
  }

  /**
   * Removes an existing snippet filter.
   * @param {module:filterClasses.SnippetFilter} filter
   */
  remove(filter) {
    let {_filters} = this;
    let {size} = _filters;

    _filters.delete(filter);

    if (size != _filters.size) {
      this.emit("snippets.filterRemoved", filter);
    }
  }

  /**
   * Checks whether a snippet filter exists.
   * @param {module:filterClasses.SnippetFilter} filter
   * @returns {boolean}
   */
  has(filter) {
    return this._filters.has(filter);
  }

  /**
   * Returns a list of all snippet filters active on the given domain.
   * @param {string} domain The domain.
   * @returns {Array.<module:filterClasses.SnippetFilter>} A list of snippet
   *   filters.
   */
  getFilters(domain) {
    let result = [];

    for (let filter of this._filters) {
      if (filter.isActiveOnDomain(domain)) {
        result.push(filter);
      }
    }

    return result;
  }

  /**
   * Returns a list of all snippet filters active on the given domain.
   * @param {string} domain The domain.
   * @returns {Array.<module:filterClasses.SnippetFilter>} A list of snippet
   *   filters.
   *
   * @deprecated Use <code>{@link module:snippets~Snippets#getFilters}</code>
   *   instead.
   * @see module:snippets~Snippets#getFilters
   */
  getFiltersForDomain(domain) {
    return this.getFilters(domain);
  }
}

/**
 * Container for snippet filters.
 */
exports.Snippets = Snippets;

let parseScript =
/**
 * Parses a script and returns a list of all its commands and their arguments.
 * @param {string} script The script.
 * @returns {Array.<string[]>} A list of commands and their arguments.
 * @package
 */
exports.parseScript = function parseScript(script) {
  let tree = [];

  let escape = false;
  let withinQuotes = false;

  let unicodeEscape = null;

  let quotesClosed = false;

  let call = [];
  let argument = "";

  for (let character of script.trim() + ";") {
    let afterQuotesClosed = quotesClosed;
    quotesClosed = false;

    if (unicodeEscape != null) {
      unicodeEscape += character;

      if (unicodeEscape.length == 4) {
        let codePoint = parseInt(unicodeEscape, 16);
        if (!isNaN(codePoint)) {
          argument += String.fromCodePoint(codePoint);
        }

        unicodeEscape = null;
      }
    }
    else if (escape) {
      escape = false;

      if (character == "u") {
        unicodeEscape = "";
      }
      else {
        argument += singleCharacterEscapes.get(character) || character;
      }
    }
    else if (character == "\\") {
      escape = true;
    }
    else if (character == "'") {
      withinQuotes = !withinQuotes;

      if (!withinQuotes) {
        quotesClosed = true;
      }
    }
    else if (withinQuotes || character != ";" && !/\s/.test(character)) {
      argument += character;
    }
    else {
      if (argument || afterQuotesClosed) {
        call.push(argument);
        argument = "";
      }

      if (character == ";" && call.length > 0) {
        tree.push(call);
        call = [];
      }
    }
  }

  return tree;
};

/**
 * Compiles a script against a given list of libraries, passed as JSON
 * serialized string, or a an array of strings, into executable code.
 * @param {string|Array.<string>} scripts One or more scripts to convert into
 *  executable code.
 * @param {string} isolatedSnippetsLibrary The stringified bundle to be executed
 * in the isolated content script context.
 * @param {string} injectedSnippetsLibrary The stringified bundle to be injected
 * and executed in the main context.
 * @param {string|Array.<string>} injectedSnippetsList An array containing the
 * available injectable snippets.
 * @param {object} [environment] An object containing environment variables.
 * @returns {string} Executable code.
 */
exports.compileScript = function compileScript(scripts,
                                               isolatedSnippetsLibrary,
                                               injectedSnippetsLibrary,
                                               injectedSnippetsList,
                                               environment = {}) {
  let isolatedLib = JSON.stringify(isolatedSnippetsLibrary);
  let injectedLib = JSON.stringify(injectedSnippetsLibrary);
  let jsonEnv = JSON.stringify(environment);
  return `
    "use strict";
    (() => 
    {
      let scripts = ${JSON.stringify([].concat(scripts).map(parseScript))};

      let isolatedLib = ${isolatedLib};
      let imports = Object.create(null);
      let injectedSnippetsCount = 0;
      let loadLibrary = new Function("exports", "environment", isolatedLib);
      loadLibrary(imports, ${jsonEnv});
      const isolatedSnippets = imports.snippets;

      let injectedLib = ${injectedLib};
      let injectedSnippetsList = ${JSON.stringify(injectedSnippetsList)};
      let executable = "(() => {";
      executable += "let environment = ${jsonEnv.replace(/[\\"]/g, "\\$&")};";
      executable += injectedLib;

      let {hasOwnProperty} = Object.prototype;
      for (let script of scripts)
      {
        for (let [name, ...args] of script)
        {
          if (hasOwnProperty.call(isolatedSnippets, name))
          {
            let value = isolatedSnippets[name];
            if (typeof value == "function")
              value(...args);
          }
          if (injectedSnippetsList.includes(name))
          {
            executable += stringifyFunctionCall(name, ...args);
            injectedSnippetsCount++;
          }
        }
      }

      executable += "})();";

      if (injectedSnippetsCount > 0)
        injectSnippetsInMainContext(executable);

      function stringifyFunctionCall(func, ...params)
      {
        // Call JSON.stringify on the arguments to avoid any arbitrary code
        // execution.
        const f = "snippets['" + func + "']";
        const parameters = params.map(JSON.stringify).join(",");
        return f + "(" + parameters + ");";
      }

      function injectSnippetsInMainContext(exec)
      {
        // injecting phase
        let script = document.createElement("script");
        script.type = "application/javascript";
        script.async = false;

        // Firefox 58 only bypasses site CSPs when assigning to 'src',
        // while Chrome 67 and Microsoft Edge (tested on 44.17763.1.0)
        // only bypass site CSPs when using 'textContent'.
        if (typeof netscape != "undefined" && typeof browser != "undefined")
        {
          let url = URL.createObjectURL(new Blob([exec]));
          script.src = url;
          document.documentElement.appendChild(script);
          URL.revokeObjectURL(url);
        }
        else
        {
          script.textContent = exec;
          document.documentElement.appendChild(script);
        }

        document.documentElement.removeChild(script);
      }
    })();
  `;
};


/***/ }),

/***/ "./core/lib/subscriptionClasses.js":
/*!*****************************************!*\
  !*** ./core/lib/subscriptionClasses.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_531973__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Definition of Subscription class and its subclasses.
 */

const {recommendations} = __nested_webpack_require_531973__(/*! ./recommendations */ "./core/lib/recommendations.js");
const {isActiveFilter, Filter} = __nested_webpack_require_531973__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {filterNotifier} = __nested_webpack_require_531973__(/*! ./filterNotifier */ "./core/lib/filterNotifier.js");
const {Downloader} = __nested_webpack_require_531973__(/*! ./downloader */ "./core/lib/downloader.js");
const {profiler} = __nested_webpack_require_531973__(/*! ./profiler */ "./core/lib/profiler.js");

let _recommendationsByURL = null;

/**
 * Clean the maps cache
 * @ignore
 */
exports._clean = function() {
  _recommendationsByURL = null;
  _urlByMv2URL = null;
};

/**
 * Subscription recommendation by URL.
 *
 * If `Subscription.dnr` is falsey then the mv2URL is the actual URL
 * as we would have with manifest v2.
 *
 * @returns {Map.<string, Recommendation>}
 */
function recommendationsByURL() {
  if (_recommendationsByURL) {
    return _recommendationsByURL;
  }

  _recommendationsByURL = new Map();

  for (let recommendation of recommendations()) {
    if (Subscription.dnr && recommendation.url) {
      _recommendationsByURL.set(recommendation.url, recommendation);
    }
    else if (recommendation.mv2URL) {
      _recommendationsByURL.set(recommendation.mv2URL, recommendation);
    }
  }
  return _recommendationsByURL;
}

let _urlByMv2URL = null;

/**
 * Subscription URL by mv2_url.
 *
 * @returns {Map.<string, string>}
 */
function urlByMv2URL() {
  if (_urlByMv2URL) {
    return _urlByMv2URL;
  }

  _urlByMv2URL = new Map();
  for (let recommendation of recommendations()) {
    if (recommendation.mv2URL) {
      _urlByMv2URL.set(recommendation.mv2URL, recommendation.url);
    }
  }
  return _urlByMv2URL;
}

let Subscription =
/**
 * The `Subscription` class represents a filter subscription.
 * @abstract
 */
exports.Subscription = class Subscription {
  /**
   * Creates a `Subscription` object.
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   * @private
   */
  constructor(url, title) {
    /**
     * The URL of the subscription.
     * @type {string}
     * @see module:subscriptionClasses.Subscription#url
     * @private
     */
    this._url = url;

    /**
     * Whether the URL of the subscription is a valid subscription URL.
     * @type {boolean}
     * @private
     * @see module:subscriptionClasses.Subscription#valid
     */
    this._urlValid = Subscription.isValidURL(url);

    let recommendation = recommendationsByURL().get(url);
    /**
     * The type of the subscription.
     * @type {?string}
     * @default <code>null</code>
     * @private
     * @see module:subscriptionClasses.Subscription#type
     */
    this._type = recommendation ? recommendation.type : null;

    /**
     * The id (UUID) of the subscription.
     * @type {?string}
     * @default <code>null</code>
     * @private
     */
    this._id = recommendation ? recommendation.id : null;

    /**
     * Filter text contained in the subscription.
     * @type {Array.<string>}
     * @private
     */
    this._filterText = [];

    /**
     * A searchable index of filter text in the subscription.
     * @type {Set.<string>}
     * @private
     */
    this._filterTextIndex = new Set();

    /**
     * The title of the subscription.
     * @type {?string}
     * @default <code>null</code>
     * @private
     * @see module:subscriptionClasses.Subscription#title
     */
    this._title = null;

    if (title) {
      this._title = title;
    }

    this._privileged = recommendation ? recommendation.privileged : false;

    /**
     * Whether the title of the subscription is non-editable.
     * @type {boolean}
     * @default <code>false</code>
     * @private
     * @see module:subscriptionClasses.Subscription#fixedTitle
     */
    this._fixedTitle = false;

    /**
     * Whether the subscription is disabled.
     * @type {boolean}
     * @default <code>false</code>
     * @private
     * @see module:subscriptionClasses.Subscription#disabled
     */
    this._disabled = false;

    Subscription.knownSubscriptions.set(url, this);
  }

  /**
   * The id (UUID) of the subscription.
   * @type {string}
   */
  get id() {
    return this._id;
  }

  /**
   * The URL of the subscription.
   * @type {string}
   */
  get url() {
    return this._url;
  }

  /**
   * Whether the subscription is valid.
   * @type {boolean}
   * @package
   */
  get valid() {
    // This should return a value based on Subscription#_urlValid after
    // https://gitlab.com/eyeo/adblockplus/abpui/adblockplusui/-/issues/753
    return true;
  }

  /**
   * The type of the subscription.
   * @type {?string}
   * @default <code>null</code>
   */
  get type() {
    return this._type;
  }

  /**
   * True if this subscription can load filters that require
   * privileged access, like snippets. Defaults to the result of the type being
   * "circumvention" if this value is null
   * @type {bool}
   */
  get privileged() {
    if (this._privileged == null) {
      return this._type === "circumvention";
    }

    return this._privileged;
  }

  set privileged(value) {
    if (value !== this._privileged) {
      let oldValue = this._privileged;
      this._privileged = value;
      filterNotifier.emit("subscription.privileged", this, value, oldValue);
    }
  }

  /**
   * The title of the subscription.
   * @type {string}
   */
  get title() {
    return this._title;
  }

  set title(value) {
    if (value != this._title) {
      let oldValue = this._title;
      this._title = value;
      filterNotifier.emit("subscription.title", this, value, oldValue);
    }
  }

  /**
   * Whether the title of the subscription is non-editable.
   * @type {boolean}
   * @default <code>false</code>
   */
  get fixedTitle() {
    return this._fixedTitle;
  }

  set fixedTitle(value) {
    if (value != this._fixedTitle) {
      let oldValue = this._fixedTitle;
      this._fixedTitle = value;
      filterNotifier.emit("subscription.fixedTitle", this, value, oldValue);
    }
  }

  /**
   * Whether the subscription is downloadable.
   * @type {boolean}
   * @default <code>false</code>
   */
  get downloadable() {
    return false;
  }

  /**
   * Whether the subscription is disabled.
   * @type {boolean}
   * @default <code>false</code>
   */
  get disabled() {
    return this._disabled;
  }

  set disabled(value) {
    if (value != this._disabled) {
      let oldValue = this._disabled;
      this._disabled = value;
      filterNotifier.emit("subscription.disabled", this, value, oldValue);
    }
  }

  /**
   * The number of filters in the subscription.
   * @type {number}
   * @default <code>0</code>
   */
  get filterCount() {
    return this._filterText.length;
  }

  /**
   * Returns an iterator that yields the text for each filter in the
   * subscription.
   * @returns {Iterator.<string>}
   */
  filterText() {
    return this._filterText[Symbol.iterator]();
  }

  // Lots of this fromSynchronizer._onDownloadSuccess()
  /**
   * Set parameters for CountableSubscriptions.
   *
   * @param {object} params The params from the filter list. `params` is
   *   the `params` field as returned by
   *   `{@link module:filters/lists.parseFilterList parseFilterList()}`.
   */
  setParams(params) {
    if (params.homepage) {
      let url;
      try {
        url = new URL(params.homepage);
      }
      catch (e) {
        url = null;
      }

      if (url && (url.protocol == "http:" || url.protocol == "https:")) {
        this.homepage = url.href;
      }
    }

    if (params.title) {
      this.title = params.title;
      this.fixedTitle = true;
    }
    else {
      this.fixedTitle = false;
    }

    if (params.version) {
      this.version = parseInt(params.version, 10);
    }

    if (this.type) {
      this.abtest = params.abtest;
    }

    if (params.diffURL) {
      this.diffURL = params.diffURL;
    }
  }

  /**
   * Set the filter text, and reset the index. Call this before adding
   * to the storage.
   *
   * The filter texts will be normalized with `{@link
   * module:filterClasses.Filter#normalize Filter.normalize()}` like
   * if they were loaded from a filter list.
   *
   * It is important to not call this beside the initialisation of the
   * subscription as it doesn't notify of changes
   *
   * @param {Array.<string>} text The text strings.
   * @param {object?} params The filter list params if any. `params` is
   *   the `params` field as returned by
   *   `{@link module:filters/lists.parseFilterList parseFilterList()}`.
   *
   * An error will be thrown if `text` isn't an array.
   */
  setFilterText(text, params = null) {
    if (!Array.isArray(text)) {
      throw new Error("setFilterText() must be called with an Array");
    }

    this._filterText = text.map(t => Filter.normalize(t));
    this._filterTextIndex = new Set(this._filterText);

    if (params) {
      this.setParams(params);
    }
  }

  /**
   * Checks whether the subscription has the given filter text.
   * @param {string} filterText The filter text.
   * @returns {boolean} Whether the subscription has the filter text.
   * @package
   */
  hasFilterText(filterText) {
    return this._filterTextIndex.has(filterText);
  }

  /**
   * Returns the filter text at the given `0`-based index.
   * @param {number} index The `0`-based index. If the index is out of bounds,
   *   the return value is `null`.
   * @returns {?module:filterClasses.Filter} The filter text.
   */
  filterTextAt(index) {
    return this._filterText[index] || null;
  }

  /**
   * Returns the `0`-based index of the given filter.
   *
   * @param {module:filterClasses.Filter} filter The filter.
   * @param {number} [fromIndex] The `0`-based index from which to start the
   *   search.
   *
   * @returns {number} The `0`-based index at which the filter is found. If the
   *   filter is not found in the subscription, the return value is `-1`.
   *
   * @see {@link findFilterTextIndex} if you only have a filter text.
   * @deprecated
   */
  findFilterIndex(filter, fromIndex = 0) {
    return this.findFilterTextIndex(filter.text, fromIndex);
  }

  /**
   * Returns the `0`-based index of the given filter.
   *
   * @param {string} filterText The filter text..
   * @param {number} [fromIndex] The `0`-based index from which to start the
   *   search.
   *
   * @returns {number} The `0`-based index at which the filter is
   *   found. If the filter is not found in the subscription, the
   *   return value is `-1`.
   */
  findFilterTextIndex(filterText, fromIndex = 0) {
    return this._filterText.indexOf(filterText, fromIndex);
  }

  /**
   * Removes all filters from the subscription.
   */
  clearFilters() {
    this._filterText = [];
    this._filterTextIndex.clear();
  }

  /**
   * Adds a filter to the subscription.
   * @param {module:filterClasses.Filter} filter The filter.
   *
   * @see {@link addFilterText} if you only have a filter text.
   * @deprecated
   */
  addFilter(filter) {
    this.addFilterText(filter.text);
  }

  /**
   * Adds a filter text to the subscription.
   * @param {string} text The filter text.
   */
  addFilterText(text) {
    this._filterText.push(text);
    this._filterTextIndex.add(text);
  }

  /**
   * Inserts a filter into the subscription at the given `0`-based index.
   *
   * @param {module:filterClasses.Filter} filter The filter.
   * @param {number} index The `0`-based index. If the index is out of bounds,
   *   the filter is inserted at the beginning or at the end accordingly.
   * @see {@link insertFilterTextAt} if you only have a filter text.
   * @deprecated
   */
  insertFilterAt(filter, index) {
    this.insertFilterTextAt(filter.text, index);
  }

  /**
   * Inserts a filter into the subscription at the given `0`-based index.
   *
   * @param {string} filterText The filter text.
   * @param {number} index The `0`-based index. If the index is out of bounds,
   *   the filter is inserted at the beginning or at the end accordingly.
   */
  insertFilterTextAt(filterText, index) {
    this._filterText.splice(index, 0, filterText);
    this._filterTextIndex.add(filterText);
  }

  /**
   * Deletes a filter from the subscription at the given `0`-based index.
   * @param {number} index The `0`-based index. If the index is out of bounds,
   *   no filter is deleted.
   */
  deleteFilterAt(index) {
    // Ignore index if out of bounds on the negative side, for consistency.
    if (index < 0) {
      return;
    }

    let [filterText] = this._filterText.splice(index, 1);
    if (!this._filterText.includes(filterText)) {
      this._filterTextIndex.delete(filterText);
    }
  }

  /**
   * Updates the filter text of the subscription.
   * @param {Array.<string>} filterText The new filter text.
   * @returns {{added: Array.<string>, removed: Array.<string>}} An object
   *   containing two lists of the text of added and removed filters
   *   respectively.
   * @package
   */
  updateFilterText(filterText) {
    let added = [];
    let removed = [];

    if (this._filterText.length == 0) {
      added = [...filterText];
    }
    else if (filterText.length > 0) {
      for (let text of filterText) {
        if (!this._filterTextIndex.has(text)) {
          added.push(text);
        }
      }
    }

    this._filterTextIndex = new Set(filterText);

    if (filterText.length == 0) {
      removed = [...this._filterText];
    }
    else if (this._filterText.length > 0) {
      for (let text of this._filterText) {
        if (!this._filterTextIndex.has(text)) {
          removed.push(text);
        }
      }
    }

    this._filterText = [...filterText];

    return {added, removed};
  }

  /**
   * Serializes the subscription for writing out on disk.
   * @yields {string}
   * @package
   */
  *serialize() {
    let {url, _title, _fixedTitle, _disabled, _id} = this;

    yield "[Subscription]";
    yield "url=" + url;

    if (_title) {
      yield "title=" + _title;
    }
    if (_fixedTitle) {
      yield "fixedTitle=true";
    }
    if (_disabled) {
      yield "disabled=true";
    }
    if (_id) {
      yield "id=" + _id;
    }
  }

  /**
   * Serializes the subscription's filter text for writing out on disk.
   * @yields {string}
   * @package
   */
  *serializeFilters() {
    let {_filterText} = this;

    yield "[Subscription filters]";

    for (let text of _filterText) {
      yield text.replace(/\[/g, "\\[");
    }
  }

  /**
   * Returns a string representing the subscription.
   * @returns {string}
   */
  toString() {
    return [...this.serialize()].join("\n");
  }
};

/**
 * Cache for known filter subscriptions that maps subscription URLs to
 * subscription objects.
 * @type {Map.<string, module:subscriptionClasses.Subscription>}
 * @package
 */
exports.Subscription.knownSubscriptions = new Map();
/**
 * We operate in DNR mode. Default is false.
 * @type {bool}
 * @package
 */
exports.Subscription.dnr = false;

/**
 * Returns the subscription object for a subscription URL.
 *
 * Every subscription URL maps to its own unique object. If no such object
 * exists, a new one is created internally; otherwise the existing object is
 * used.
 *
 * If `Subscription.dnr` is true, it will remap `mv2_url` to the canonical
 * `url` if necessary.
 *
 * @param {string} url The subscription URL.
 *
 * @returns {module:subscriptionClasses.Subscription} A subscription
 * object (can be any subclass thereof.
 */
exports.Subscription.fromURL = function(url) {
  let subscription = Subscription.knownSubscriptions.get(url);
  if (subscription) {
    return subscription;
  }

  if (url[0] != "~") {
    let downloadable = true;
    let title = null;
    let params = null;
    let updatableThroughDiffs = false;

    if (Subscription.dnr) {
      // In DNR we check if we got a mv2 URL and remap.
      let actualUrl = urlByMv2URL().get(url);
      if (actualUrl) {
        subscription = Subscription.knownSubscriptions.get(actualUrl);
        if (subscription) {
          return subscription;
        }

        url = actualUrl;
      }

      let recommendation = recommendationsByURL().get(url);
      if (recommendation) {
        // In DNR we use the recommendation title.
        title = recommendation.title;

        // All the known subscriptions are considered to be either
        // user countable or diff updatable
        downloadable = false;
        // We have to set the params like if the list was downloaded.
        params = {
          homepage: recommendation.homepage,
          // The effect of setting title here is that it will make the
          // fixedTitle property to be true.
          // This is the equivalent of the title being set by the
          // filter list.
          title
        };

        if (recommendation.diffURL) {
          params.diffURL = recommendation.diffURL;
          updatableThroughDiffs = true;
        }
      }
    }

    if (downloadable) {
      subscription = new FullUpdatableSubscription(url, title);
    }
    else if (updatableThroughDiffs) {
      subscription = new DiffUpdatableSubscription(url, title, params);
    }
    else {
      subscription = new CountableSubscription(url, title, params);
    }

    return subscription;
  }

  return new SpecialSubscription(url);
};

/**
 * Deserializes a subscription.
 * @param {Object} obj A map of serialized properties and their values.
 * @returns {module:subscriptionClasses.Subscription} A subscription object.
 * @package
 */
exports.Subscription.fromObject = function(obj) {
  let result;
  if (obj.url[0] != "~") {
    // URL is valid - this is a regular subscription
    // Unless indicated otherwise it is downloadable.
    if (("downloadable" in obj) && (obj.downloadable == "false")){
      if ("diffURL" in obj) {
        result = new DiffUpdatableSubscription(obj.url, obj.title);
      }
      else {
        result = new CountableSubscription(obj.url, obj.title);
      }
    }
    else {
      result = new FullUpdatableSubscription(obj.url, obj.title);
    }

    if (result.type) {
      result.abtest = obj.abtest;
    }

    if ("diffURL" in obj) {
      result.diffURL = obj.diffURL;
    }
    if ("downloadStatus" in obj) {
      result._downloadStatus = obj.downloadStatus;
    }
    if ("lastSuccess" in obj) {
      result.lastSuccess = parseInt(obj.lastSuccess, 10) || 0;
    }
    if ("lastCheck" in obj) {
      result._lastCheck = parseInt(obj.lastCheck, 10) || 0;
    }
    if ("expires" in obj) {
      result.expires = parseInt(obj.expires, 10) || 0;
    }
    if ("softExpiration" in obj) {
      result.softExpiration = parseInt(obj.softExpiration, 10) || 0;
    }
    if ("errors" in obj) {
      result._errors = parseInt(obj.errors, 10) || 0;
    }
    if ("version" in obj) {
      result.version = parseInt(obj.version, 10) || 0;
    }
    if ("requiredVersion" in obj) {
      result.requiredVersion = obj.requiredVersion;
    }
    if ("homepage" in obj) {
      result._homepage = obj.homepage;
    }
    if ("lastDownload" in obj) {
      result._lastDownload = parseInt(obj.lastDownload, 10) || 0;
    }
    if ("downloadCount" in obj) {
      result.downloadCount = parseInt(obj.downloadCount, 10) || 0;
    }
  }
  else {
    result = new SpecialSubscription(obj.url, obj.title);
    if ("defaults" in obj) {
      result.defaults = obj.defaults.split(" ");
    }
    if ("metadata" in obj) {
      result._metadata = JSON.parse(obj.metadata);
    }
  }
  if ("id" in obj) {
    result._id = obj.id;
  }
  if ("fixedTitle" in obj) {
    result._fixedTitle = (obj.fixedTitle == "true");
  }
  if ("disabled" in obj) {
    result._disabled = (obj.disabled == "true");
  }

  return result;
};

/**
 * Checks whether a URL is a valid subscription URL.
 * @param {string} url The URL.
 * @returns {boolean} Whether the URL is a valid subscription URL.
 */
exports.Subscription.isValidURL = function isValidURL(url) {
  return url.startsWith("~user~") || Downloader.isValidURL(url);
};

let SpecialSubscription =
/**
 * The `SpecialSubscription` class represents a special filter subscription.
 *
 * This type of subscription is used for keeping user-defined filters.
 * @extends module:subscriptionClasses.Subscription
 */
exports.SpecialSubscription = class SpecialSubscription extends Subscription {
  /**
   * Creates a `SpecialSubscription` object.
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   * @private
   */
  constructor(url, title) {
    super(url, title);

    /**
     * Filter types that should be added to this subscription by default.
     *
     * Entries should correspond to keys in
     * `{@link module:subscriptionClasses.SpecialSubscription.defaultsMap}`.
     *
     * @type {?Array.<string>}
     *
     * @package
     */
    this.defaults = null;

    this._metadata = null;
  }

  get privileged() {
    return true;
  }

  /**
   * Checks whether the given filter should be added to this subscription by
   * default.
   * @param {Filter} filter The filter.
   * @returns {boolean} Whether the filter should be added to this subscription
   *   by default.
   * @package
   */
  isDefaultFor(filter) {
    if (this.defaults && this.defaults.length) {
      for (let type of this.defaults) {
        if (SpecialSubscription.defaultsMap.get(type).includes(filter.type)) {
          return true;
        }
        if (!isActiveFilter(filter) && type == "blocking") {
          return true;
        }
      }
    }

    return false;
  }

  /**
   * Set the metadata block for the special subscription
   *
   * @param {object} [value] The metadata
   */
  set metadata(value) {
    let oldValue = this._metadata;
    this._metadata = value;
    filterNotifier.emit("subscription.metadata", this, value, oldValue);
  }

  /**
   * Get the metadata block.
   * @return {?object} the metadata object or null
   */
  get metadata() {
    return this._metadata;
  }

  /**
   * Serializes the subscription for writing out on disk.
   * @yields {string}
   * @package
   */
  *serialize() {
    let {defaults, _lastDownload, _metadata} = this;

    yield* super.serialize();

    if (defaults) {
      yield "defaults=" +
            defaults.map(
              // remap for the stored format.
              type => type == "allowing" ? "whitelist" : type
            ).filter(
              type => SpecialSubscription.defaultsMap.has(type)
            ).join(" ");
    }
    // Metadata is encoded as a JSON on a single line.
    // This should be safe.
    if (_metadata) {
      yield "metadata=" + JSON.stringify(_metadata);
    }

    if (_lastDownload) {
      yield "lastDownload=" + _lastDownload;
    }
  }
};

/**
 * A map of filter types.
 * @type {Map.<string, Array.<string>>}
 * @package
 */
exports.SpecialSubscription.defaultsMap = new Map([
  ["allowing", ["allowing"]],
  // deprecated terminology
  ["whitelist", ["allowing"]],
  ["blocking", ["blocking"]],
  ["elemhide", ["elemhide", "elemhideexception", "elemhideemulation"]]
]);

/**
 * Creates a new special subscription.
 * @param {string} [title] The title of the subscription.
 * @returns {module:subscriptionClasses.SpecialSubscription} A new special
 *   subscription.
 * @package
 */
exports.SpecialSubscription.create = function(title) {
  let url;
  do {
    url = "~user~" + Math.round(Math.random() * 1000000);
  }
  while (Subscription.knownSubscriptions.has(url));
  return new SpecialSubscription(url, title);
};

/**
 * Creates a new special subscription and adds the given filter to it.
 *
 * Once created, the subscription acts as the default for all filters of the
 * {@link module:filterClasses.Filter#type type}.
 *
 * @param {module:filterClasses.Filter} filter The filter.
 *
 * @returns {module:subscriptionClasses.SpecialSubscription} A new special
 *   subscription.
 *
 * @package
 */
exports.SpecialSubscription.createForFilter = function(filter) {
  let subscription = SpecialSubscription.create();
  subscription.addFilter(filter);
  for (let [type, mappedTypes] of SpecialSubscription.defaultsMap) {
    if (mappedTypes.includes(filter.type)) {
      subscription.defaults = [type];
    }
  }
  if (!subscription.defaults) {
    subscription.defaults = ["blocking"];
  }
  return subscription;
};

let RegularSubscription =
/**
 * The `RegularSubscription` class represents a regular filter subscription
 * that is not by default downloaded off the internet.
 * `CountableSubscription` is a subclass of this.
 *
 * In a manifest v2 context it shouldn't be encountered. In manifest v3, it's
 * the default.
 *
 * @extends module:subscriptionClasses.Subscription
 */
exports.RegularSubscription = class RegularSubscription extends Subscription {
  /**
   * Creates a `RegularSubscription` object.
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   * @private
   */
  constructor(url, title) {
    super(url, title || url);

    /**
     * The homepage of the subscription.
     * @type {?string}
     * @default <code>null</code>
     * @private
     * @see module:subscriptionClasses.RegularSubscription#homepage
     */
    this._homepage = null;

    /**
     * The last time the subscription was downloaded, in seconds since the
     * beginning of the Unix epoch.
     * @type {number}
     * @default <code>0</code>
     * @private
     * @see module:subscriptionClasses.RegularSubscription#lastDownload
     */
    this._lastDownload = 0;

    let recommendation = recommendationsByURL().get(url);
    /**
     * The languages that apply for this subscription.
     * @type {?Array.<string>}
     */
    this._languages = recommendation ? recommendation.languages : null;
  }

  /**
   * The homepage of the subscription.
   * @type {?string}
   * @default <code>null</code>
   */
  get homepage() {
    return this._homepage;
  }

  set homepage(value) {
    if (value != this._homepage) {
      let oldValue = this._homepage;
      this._homepage = value;
      filterNotifier.emit("subscription.homepage", this, value, oldValue);
    }
  }

  /**
   * The languages that apply for this subscription.
   * @type {?Array.<string>}
   * @default <code>null</code>
   */
  get languages() {
    return this._languages;
  }

  /**
   * The last time the subscription was downloaded, in seconds since the
   * beginning of the Unix epoch.
   * @type {number}
   * @default <code>0</code>
   */
  get lastDownload() {
    return this._lastDownload;
  }

  set lastDownload(value) {
    if (value != this._lastDownload) {
      let oldValue = this._lastDownload;
      this._lastDownload = value;
      filterNotifier.emit("subscription.lastDownload", this, value, oldValue);
    }
  }

  /**
   * Serializes the subscription for writing out on disk.
   * @yields {string}
   * @package
   */
  *serialize() {
    let {_homepage, _lastDownload} = this;

    yield* super.serialize();

    // To keep compatibility downloadable is true if missing
    if (!this.downloadable) {
      yield "downloadable=false";
    }
    if (_homepage) {
      yield "homepage=" + _homepage;
    }
    if (_lastDownload) {
      yield "lastDownload=" + _lastDownload;
    }
  }
};

/**
 * Once initialized, the shared Synchronizer singleton will be stored in here.
 * @type {module:synchronizer.Synchronizer}
 */
let synchronizer = null;

let CountableSubscription =
/**
 * The `CountableSubscription` class represents a regular filter
 * subscription which will indicate it to the remote `url` it is in
 * use by issuing a `HEAD` http request instead of a `GET`.
 *
 * However it will have its property `downloadable` still set to
 * `false`.
 *
 * @extends module:subscriptionClasses.RegularSubscription
 */
exports.CountableSubscription =
class CountableSubscription extends RegularSubscription {
  /**
   * Allows downloadable subscriptions to update themselves once re-enabled,
   * via receiving the Synchronizer singleton.
   * @param {module:synchronizer~Synchronizer} reference the Synchronizer
   */
  static useSynchronizer(reference) {
    synchronizer = reference;
  }

  /**
   * Creates a `CountableSubscription` object.
   *
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   * @param {?object} [params] The params to pass to
   *    `{@link Subscription.setParams}`. Can be omitted or `null`.
   * @private
   */
  constructor(url, title, params) {
    super(url, title);

    if (params) {
      this.setParams(params);
    }

    /**
     * The status of the last download.
     * @type {?string}
     * @default <code>null</code>
     * @private
     * @see module:subscriptionClasses.CountableSubscription#downloadStatus
     */
    this._downloadStatus = null;

    /**
     * The last time the subscription was considered for an update, in seconds
     * since the beginning of the Unix epoch.
     * @type {number}
     * @default <code>0</code>
     * @private
     * @see module:subscriptionClasses.CountableSubscription#lastCheck
     */
    this._lastCheck = 0;

    /**
     * The number of download failures since the last successful download.
     * @type {number}
     * @default <code>0</code>
     * @private
     * @see module:subscriptionClasses.CountableSubscription#errors
     */
    this._errors = 0;

    /**
     * The last time the subscription was successfully downloaded, in seconds
     * since the beginning of the Unix epoch.
     * @type {number}
     * @default <code>0</code>
     */
    this.lastSuccess = 0;

    /**
     * The hard expiration time of the subscription, in seconds since the
     * beginning of the Unix epoch.
     *
     * Updates should be downloaded if `{@link
     * module:subscriptionClasses.CountableSubscription#softExpiration}`
     * or `expires` are in the past.
     * @type {number}
     * @default <code>0</code>
     */
    this.expires = 0;

    /**
     * The soft expiration time of the subscription, in seconds since the
     * beginning of the Unix epoch.
     *
     * Updates should be downloaded if `softExpiration` or
     * `{@link module:subscriptionClasses.CountableSubscription#expires}`
     * are in the past.
     * @type {number}
     * @default <code>0</code>
     */
    this.softExpiration = 0;

    /**
     * The version of the subscription data that was retrieved on last
     * successful download.
     * @type {number}
     * @default <code>0</code>
     */
    this.version = 0;

    /**
     * The minimal Adblock Plus version required for the subscription.
     * @type {?string}
     * @default <code>null</code>
     */
    this.requiredVersion = null;

    /**
     * The number of times the subscription has been downloaded.
     * @type {number}
     * @default <code>0</code>
     */
    this.downloadCount = 0;

    this._p = profiler(`CountableSubscription@${url}`);
    this._p.start();
  }

  /**
   * Whether this is a countable subscription, i.e. a subscription that
   * will connect to the URL. A downloadable subscription is countable,
   * but not the other way around.
   *
   * @type {boolean}
   * @default <code>true</code>
   */
  get countable() {
    return true;
  }

  /**
   * Whether the subscription is disabled. Once re-enabled, it ensures the
   * synchronizer downloads latest version of this subscription.
   * @type {boolean}
   * @default <code>false</code>
   */
  get disabled() {
    return super.disabled;
  }

  set disabled(value) {
    let {_disabled} = this;
    super.disabled = value;
    if (synchronizer && _disabled && !value) {
      synchronizer.execute(this);
    }
  }

  /**
   * The status of the last download.
   *
   * A message ID which can have the following values: `synchronize_ok`,
   * `synchronize_connection_error` or `synchronize_invalid_url`. If the
   * initial download is not completed yet, then it is null.
   *
   * @type {?string}
   * @default <code>null</code>
   */
  get downloadStatus() {
    return this._downloadStatus;
  }

  set downloadStatus(value) {
    let oldValue = this._downloadStatus;
    this._downloadStatus = value;
    filterNotifier.emit("subscription.downloadStatus", this, value, oldValue);
  }

  /**
   * The last time the subscription was considered for an update, in seconds
   * since the beginning of the Unix epoch.
   *
   * This is used to increase the soft expiration time if the user doesn't use
   * Adblock Plus for some time.
   *
   * @type {number}
   * @default <code>0</code>
   */
  get lastCheck() {
    return this._lastCheck;
  }

  set lastCheck(value) {
    if (value != this._lastCheck) {
      let oldValue = this._lastCheck;
      this._lastCheck = value;
      filterNotifier.emit("subscription.lastCheck", this, value, oldValue);
    }
  }

  /**
   * The number of download failures since the last successful download.
   * @type {number}
   * @default <code>0</code>
   */
  get errors() {
    return this._errors;
  }

  set errors(value) {
    if (value != this._errors) {
      let oldValue = this._errors;
      this._errors = value;
      filterNotifier.emit("subscription.errors", this, value, oldValue);
    }
  }

  /**
   * Serializes the subscription for writing out on disk.
   * @yields {string}
   * @package
   */
  *serialize() {
    let {downloadStatus, lastSuccess, lastCheck, expires,
         softExpiration, errors, version, requiredVersion,
         downloadCount} = this;

    yield* super.serialize();

    if (downloadStatus) {
      yield "downloadStatus=" + downloadStatus;
    }
    if (lastSuccess) {
      yield "lastSuccess=" + lastSuccess;
    }
    if (lastCheck) {
      yield "lastCheck=" + lastCheck;
    }
    if (expires) {
      yield "expires=" + expires;
    }
    if (softExpiration) {
      yield "softExpiration=" + softExpiration;
    }
    if (errors) {
      yield "errors=" + errors;
    }
    if (version) {
      yield "version=" + version;
    }
    if (requiredVersion) {
      yield "requiredVersion=" + requiredVersion;
    }
    if (downloadCount) {
      yield "downloadCount=" + downloadCount;
    }
  }

  /**
   * Put a benchmarking event
   * @param {string} event benchmarking event
   */
  mark(event) {
    this._p.mark(event);
  }
};

let FullUpdatableSubscription =
/**
 * The `FullUpdatableSubscription` class represents a regular filter
 * subscription whose content (filter text) is downloaded from a filter list
 * off the internet from `url` with a full update.
 *
 * It will have its property `downloadable` set to `true`.
 *
 * @extends module:subscriptionClasses.CountableSubscription
 */
exports.FullUpdatableSubscription =
class FullUpdatableSubscription extends CountableSubscription {
  /** Construct a new FullUpdatableSubscription
   *
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   *
   * @private
   */
  constructor(url, title) {
    super(url, title);
  }

  /**
   * Whether the subscription is downloadable.
   * @type {boolean}
   * @default <code>true</code>
   */
  get downloadable() {
    return true;
  }
};

let DiffUpdatableSubscription =
/**
 * The `DiffUpdatableSubscription` class represents a regular filter
 * subscription whose content (filter text) is downloaded from a filter list
 * off the internet from `url`. The key difference between this and a
 * `{@link CountableSubscription}` is that this class has a diffurl
 * from where updates will be handled
 *
 * It will have its `downloadable` property set to `false`.
 *
 * @extends module:subscriptionClasses.CountableSubscription
 */
exports.DiffUpdatableSubscription =
class DiffUpdatableSubscription extends CountableSubscription {
  /**
   * Construct a new DiffUpdatableSubscription
   * @param {string} url The URL of the subscription.
   * @param {string} [title] The title of the subscription.
   * @param {?object} [params] The params to pass to
   *    `{@link Subscription.setParams}`. Can be omitted or `null`.
   * @private
   */
  constructor(url, title, params) {
    super(url, title);

    if (params) {
      this.setParams(params);
    }
  }

  /**
   * Serializes the subscription for writing out on disk.
   * @yields {string}
   * @package
   */
  *serialize() {
    let {diffURL} = this;

    yield* super.serialize();

    if (diffURL) {
      yield "diffURL=" + diffURL;
    }
  }

  /**
   * Updatable subscriptions should not be downloadable as they will rather
   * support getting diffs from a diffURL.
   *
   * @type {boolean}
   * @default <code>true</code>
   */
  get downloadable() {
    return false;
  }

  /**
   * The location where this subscription's content is downloaded from.
   *
   * @type {String}
   */
  get diffURL() {
    return this._diffURL;
  }

  set diffURL(value) {
    let oldValue = this._diffURL;
    this._diffURL = value;
    filterNotifier.emit("subscription.diffURL", this, value, oldValue);
  }
};


/***/ }),

/***/ "./core/lib/synchronizer.js":
/*!**********************************!*\
  !*** ./core/lib/synchronizer.js ***!
  \**********************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_569969__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * @file Manages synchronization of filter subscriptions.
 */

const {Prefs} = __nested_webpack_require_569969__(/*! prefs */ "./sdk/api/prefs.js");

const {MILLIS_IN_SECOND, MILLIS_IN_MINUTE, MILLIS_IN_HOUR,
       MILLIS_IN_DAY} = __nested_webpack_require_569969__(/*! ./time */ "./core/lib/time.js");
const {Downloader, Downloadable} = __nested_webpack_require_569969__(/*! ./downloader */ "./core/lib/downloader.js");
const {Filter} = __nested_webpack_require_569969__(/*! ./filterClasses */ "./core/lib/filterClasses.js");
const {filterNotifier} = __nested_webpack_require_569969__(/*! ./filterNotifier */ "./core/lib/filterNotifier.js");
const {Subscription,
       CountableSubscription} = __nested_webpack_require_569969__(/*! ./subscriptionClasses */ "./core/lib/subscriptionClasses.js");
const {analytics} = __nested_webpack_require_569969__(/*! ./analytics */ "./core/lib/analytics.js");
const {parseFilterList} = __nested_webpack_require_569969__(/*! ./filters/lists.js */ "./core/lib/filters/lists.js");
const {recommendations} = __nested_webpack_require_569969__(/*! ./recommendations */ "./core/lib/recommendations.js");

const INITIAL_DELAY = 1 * MILLIS_IN_MINUTE;
const CHECK_INTERVAL = 1 * MILLIS_IN_HOUR;
const DEFAULT_EXPIRATION_INTERVAL = 5 * MILLIS_IN_DAY;

let getPreferredMillis = (field, fallback) =>
                          field in Prefs ? Prefs[field] : fallback;

/**
 * Downloads filter subscriptions whenever necessary.
 */
class Synchronizer {
  /**
   * Construct a new synchronizer.
   * @param {FilterStorage} [filterStorage] The associated filter storage.
   */
  constructor(filterStorage) {
    if (filterStorage == null || typeof filterStorage != "object") {
      throw Error("filterStorage must be a valid object");
    }

    /**
     * Whether the downloading of subscriptions has been started.
     * @private
     */
    this._started = false;

    /**
     * The object providing actual downloading functionality.
     * @type {module:downloader.Downloader}
     */
    this._downloader = new Downloader(this._getDownloadables.bind(this));

    this._downloader.onExpirationChange = this._onExpirationChange.bind(this);
    this._downloader.onDownloadStarted = this._onDownloadStarted.bind(this);
    this._downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this);
    this._downloader.onDownloadError = this._onDownloadError.bind(this);

    this._filterStorage = filterStorage;

    // allow subscription to update themselves once re-enabled if needed.
    CountableSubscription.useSynchronizer(this);
  }

  /**
   * Starts downloading subscriptions.
   *
   * No subscriptions are downloaded until this function has been called at
   * least once.
   */
  start() {
    if (this._started) {
      return;
    }

    this._downloader.scheduleChecks(
      getPreferredMillis("subscriptions_check_interval", CHECK_INTERVAL),
      getPreferredMillis("subscriptions_initial_delay", INITIAL_DELAY)
    );
    this._started = true;
  }

  /**
   * Clear any further downloader scheduled check and set its internal state
   * as not started.
   */
  stop() {
    this._started = false;
    this._downloader.unscheduleChecks();
  }

  /**
   * Checks whether a subscription is currently being downloaded.
   * @param {string} url  URL of the subscription
   * @returns {boolean}
   */
  isExecuting(url) {
    return this._downloader.isDownloading(url);
  }

  /**
   * Starts the download of a subscription if it is downloadable.
   *
   * @param {module:subscriptionClasses.CountableSubscription} subscription
   *   Subscription to be downloaded
   * @param {boolean} manual
   *   `true` for a manually started download (should not trigger fallback
   *   requests)
   */
  execute(subscription, manual) {
    this._downloader.download(this._getDownloadable(subscription, manual));
  }

  /**
   * Yields `{@link module:downloader.Downloadable Downloadable}` instances for
   * all subscriptions that can be downloaded.
   * @yields {module:downloader.Downloadable}
   */
  *_getDownloadables() {
    if (!Prefs.subscriptions_autoupdate) {
      return;
    }

    for (let subscription of this._filterStorage.subscriptions()) {
      if (subscription instanceof CountableSubscription) {
        yield this._getDownloadable(subscription, false);
      }
    }
  }

  /**
   * Creates a `{@link module:downloader.Downloadable Downloadable}` instance
   * for a subscription.
   * @param {module:subscriptionClasses.Subscription} subscription
   * @param {boolean} manual
   * @returns {module:downloader.Downloadable}
   */
  _getDownloadable(subscription, manual) {
    let {url, lastDownload, lastSuccess, lastCheck, version, softExpiration,
         expires, downloadCount, disabled, downloadable,
         countable, diffURL} = subscription;

    let result;

    // If this is a DiffUpdatable subscription, use the diff URL and set the
    // original URL. We need to set this original URL or it will not be
    // available in the download success callback.
    if (diffURL) {
      result = new Downloadable(diffURL);
      result.originalUrl = url;
    }
    else {
      result = new Downloadable(url);
    }

    if (analytics.isTrusted(url)) {
      result.firstVersion = analytics.getFirstVersion();
    }

    if (lastDownload != lastSuccess) {
      result.lastError = lastDownload * MILLIS_IN_SECOND;
    }

    result.lastCheck = lastCheck * MILLIS_IN_SECOND;
    result.lastVersion = version;
    result.softExpiration = softExpiration * MILLIS_IN_SECOND;
    result.hardExpiration = expires * MILLIS_IN_SECOND;
    result.manual = manual;
    result.downloadCount = downloadCount;
    result.disabled = disabled;
    if (!diffURL && (disabled || (countable && !downloadable))) {
      result.method = "HEAD";
    }

    return result;
  }

  _onExpirationChange(downloadable) {
    let subscription = Subscription.fromURL(
      downloadable.originalUrl || downloadable.url);
    subscription.lastCheck = Math.round(
      downloadable.lastCheck / MILLIS_IN_SECOND
    );
    subscription.softExpiration = Math.round(
      downloadable.softExpiration / MILLIS_IN_SECOND
    );
    subscription.expires = Math.round(
      downloadable.hardExpiration / MILLIS_IN_SECOND
    );
  }

  _onDownloadStarted(downloadable) {
    let subscription = Subscription.fromURL(
      downloadable.originalUrl || downloadable.url);
    filterNotifier.emit("subscription.downloading", subscription);
    subscription.mark("downloading.started");
  }

  _onDownloadSuccess(downloadable, responseText, errorCallback,
                     redirectCallback) {
    // if it has originalUrl, it means that it's a diffUpdatable subscription
    let isDiffUpdatable = (downloadable.originalUrl != null);

    let subscription = Subscription.fromURL(downloadable.redirectURL ||
      (isDiffUpdatable ? downloadable.originalUrl : downloadable.url));
    subscription.mark("downloading.finished");
    subscription.mark("parsing.started");

    let isHEAD = downloadable.method === "HEAD";

    let {error, lines, params,
         minVersion} = isHEAD || isDiffUpdatable ?
           {params: {}} : parseFilterList(responseText);

    if (error) {
      return errorCallback(error);
    }

    if (params.redirect) {
      return redirectCallback(params.redirect);
    }

    subscription.mark("parsing.finished");

    // Handle redirects
    if (downloadable.redirectURL &&
        downloadable.redirectURL != downloadable.url) {
      let oldSubscription = Subscription.fromURL(
        downloadable.originalUrl || downloadable.url);
      subscription.title = oldSubscription.title;
      subscription.disabled = oldSubscription.disabled;
      subscription.lastCheck = oldSubscription.lastCheck;

      let listed = this._filterStorage.hasSubscription(oldSubscription);
      if (listed) {
        this._filterStorage.removeSubscription(oldSubscription);
      }

      Subscription.knownSubscriptions.delete(oldSubscription.url);

      if (listed) {
        this._filterStorage.addSubscription(subscription);
      }
    }

    // The download actually succeeded
    subscription.lastSuccess = subscription.lastDownload = Math.round(
      Date.now() / MILLIS_IN_SECOND
    );
    subscription.downloadStatus = "synchronize_ok";
    subscription.downloadCount = downloadable.downloadCount;
    subscription.errors = 0;

    // Process parameters
    if (params.homepage) {
      let url;
      try {
        url = new URL(params.homepage);
      }
      catch (e) {
        url = null;
      }

      if (url && (url.protocol == "http:" || url.protocol == "https:")) {
        subscription.homepage = url.href;
      }
    }

    if (params.title) {
      subscription.title = params.title;
      subscription.fixedTitle = true;
    }
    else {
      subscription.fixedTitle = false;
    }

    if (params.version) {
      subscription.version = parseInt(params.version, 10);
    }
    else {
      subscription.version = isHEAD || isDiffUpdatable ?
        downloadable.lastVersion : 0;
    }

    if ((params.version || isDiffUpdatable) &&
        analytics.isTrusted(downloadable.redirectURL || downloadable.url)) {
      analytics.recordVersion(subscription.version.toString());
    }

    if (subscription.type) {
      subscription.abtest = params.abtest;
    }

    let headExpInterval = getPreferredMillis(
      "subscriptions_head_expiration_interval",
      MILLIS_IN_DAY
    );

    let defaultExpInterval = getPreferredMillis(
      "subscriptions_default_expiration_interval",
      DEFAULT_EXPIRATION_INTERVAL
    );

    let expirationInterval = isHEAD ? headExpInterval : defaultExpInterval;

    if (isDiffUpdatable) {
      params.expires =
        [...recommendations()].find(
          recommendation => recommendation.url === downloadable.originalUrl
        ).expires;
    }
    if (params.expires) {
      let match = /^(\d+)\s*(h)?/.exec(params.expires);
      if (match) {
        let interval = parseInt(match[1], 10);
        if (match[2]) {
          expirationInterval = interval * MILLIS_IN_HOUR;
        }
        else {
          expirationInterval = interval * MILLIS_IN_DAY;
        }
      }
    }

    let [
      softExpiration,
      hardExpiration
    ] = this._downloader.processExpirationInterval(expirationInterval);
    subscription.softExpiration = Math.round(softExpiration / MILLIS_IN_SECOND);
    subscription.expires = Math.round(hardExpiration / MILLIS_IN_SECOND);

    if (minVersion) {
      subscription.requiredVersion = minVersion;
    }
    else {
      delete subscription.requiredVersion;
    }

    // In case of HEAD request (disabled subscription) notify an update so that
    // the last version of the subscription will be stored for the next time.
    if (isHEAD) {
      filterNotifier.emit("subscription.updated", subscription);
    }
    else if (isDiffUpdatable) {
      const responseObject = JSON.parse(responseText);
      const added = responseObject.filters.add;
      const removed = responseObject.filters.remove;

      filterNotifier.emit("subscription.diffReceived", subscription, {added, removed});
    }
    else {
      this._processFilters(subscription, lines);
    }
  }

  _onDownloadError(downloadable, downloadURL, error, responseStatus,
                   redirectCallback) {
    let subscription = Subscription.fromURL(
      downloadable.originalUrl || downloadable.url);
    subscription.mark("downloading.finished");
    subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND);
    subscription.downloadStatus = error;

    // Request fallback URL if necessary - for automatic updates only
    if (!downloadable.manual) {
      subscription.errors++;

      if (redirectCallback &&
          subscription.errors >= Prefs.subscriptions_fallbackerrors &&
          /^https?:\/\//i.test(subscription.url)) {
        subscription.errors = 0;

        let fallbackURL = Prefs.subscriptions_fallbackurl;
        const {addonVersion} = __nested_webpack_require_569969__(/*! info */ "./sdk/api/info.js");
        fallbackURL = fallbackURL.replace(/%VERSION%/g,
                                          encodeURIComponent(addonVersion));
        fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g,
                                          encodeURIComponent(subscription.url));
        fallbackURL = fallbackURL.replace(/%URL%/g,
                                          encodeURIComponent(downloadURL));
        fallbackURL = fallbackURL.replace(/%ERROR%/g,
                                          encodeURIComponent(error));
        fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g,
                                          encodeURIComponent(responseStatus));

        let initObj = {
          cache: "no-store",
          credentials: "omit",
          referrer: "no-referrer",
          method: downloadable.method
        };

        fetch(fallbackURL, initObj).then(response => response.text())
          .then(responseText => {
            if (!this._filterStorage.hasSubscription(subscription)) {
              return;
            }

            let match = /^(\d+)(?:\s+(\S+))?$/.exec(responseText);
            if (match && match[1] == "301" &&    // Moved permanently
              match[2] && /^https?:\/\//i.test(match[2])) {
              redirectCallback(match[2]);
            }
            // Gone
            else if (match && match[1] == "410") {
              let data = "[Adblock]\n" +
              [...subscription.filterText()].join("\n");
              redirectCallback("data:text/plain," + encodeURIComponent(data));
            }
          });
      }
    }
  }

  /**
   * Given a valid subscription and some text, it parses all filters and add
   * these in bulk to the specified subscription.
   * @param {module:subscriptionClasses.Subscription} subscription The
   *  Subscription to use as reference for manually added filters.
   * @param {string} filters The filters file/text to add.
   * @param {function} errorCallback A callback invoked if errors occur.
   */
  addSubscriptionFilters(
    subscription, filters, errorCallback
  ) {
    let {error, lines} = parseFilterList(filters);
    if (error) {
      errorCallback(error);
    }
    else {
      this._processFilters(subscription, lines);
    }
  }

  /**
   * Given a list of parsed filters, normalize each line and update the
   * subscription.
   * @private
   * @param {module:subscriptionClasses.Subscription} subscription The
   *  Subscription to use as reference for manually added filters.
   * @param {string[]} lines The parsed filters lines. The first line
   will be skipped over as it is supposed to contain the header.
  */
  _processFilters(subscription, lines) {
    subscription.mark("processing.started");

    lines.shift();
    let filterText = [];
    for (let line of lines) {
      line = Filter.normalize(line);
      if (line) {
        filterText.push(line);
      }
    }

    this._filterStorage.updateSubscriptionFilters(subscription, filterText);

    subscription.mark("processing.finished");
  }
}

exports.Synchronizer = Synchronizer;


/***/ }),

/***/ "./core/lib/time.js":
/*!**************************!*\
  !*** ./core/lib/time.js ***!
  \**************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



/**
 * Number of milliseconds in a second.
 * @const {number}
 * @default 1000
 * @package
 */
exports.MILLIS_IN_SECOND = 1000;

/**
 * Number of milliseconds in a minute.
 * @const {number}
 * @default 60000
 * @package
 */
exports.MILLIS_IN_MINUTE = 60000;

/**
 * Number of milliseconds in an hour.
 * @const {number}
 * @default 3600000
 * @package
 */
exports.MILLIS_IN_HOUR = 3600000;

/**
 * Number of milliseconds in a day.
 * @const {number}
 * @default 86400000
 * @package
 */
exports.MILLIS_IN_DAY = 86400000;


/***/ }),

/***/ "./core/lib/url.js":
/*!*************************!*\
  !*** ./core/lib/url.js ***!
  \*************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_587329__) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



const {Cache} = __nested_webpack_require_587329__(/*! ./caching */ "./core/lib/caching.js");

const {icannPublicSuffixes} = __nested_webpack_require_587329__(/*! ../data/icannPublicSuffixList.js */ "./core/data/icannPublicSuffixList.js");
const {nonIcannPublicSuffixes} = __nested_webpack_require_587329__(/*! ../data/nonIcannPublicSuffixList.js */ "./core/data/nonIcannPublicSuffixList.js");

// ensure no conflict ever happens with inherited properties
Object.setPrototypeOf(icannPublicSuffixes, null);
Object.setPrototypeOf(nonIcannPublicSuffixes, null);

/**
 * Cache of domain maps.
 *
 * The domains part of filter text (e.g. `example.com,~mail.example.com`) is
 * often repeated across filters. This cache enables deduplication of the
 * `Map` objects that specify on which domains the filter does and does not
 * apply, which reduces memory usage and improves performance.
 *
 * @type {Map.<string, Map.<string, boolean>>}
 */
let domainsCache = new Cache(1000);

/**
 * A `URLInfo` object represents information about a URL.
 *
 * It is returned by `{@link module:url.parseURL parseURL()}`.
 */
class URLInfo {
  /**
   * Creates a `URLInfo` object.
   *
   * @param {string} href The entire URL.
   * @param {string} protocol The protocol scheme of the URL, including the
   *   final `:`.
   * @param {string} [hostname] The hostname of the URL.
   *
   * @private
   */
  constructor(href, protocol, hostname = "") {
    this._href = href;
    this._protocol = protocol;
    this._hostname = hostname;
  }

  /**
   * The entire URL.
   * @type {string}
   */
  get href() {
    return this._href;
  }

  /**
   * The protocol scheme of the URL, including the final `:`.
   * @type {string}
   */
  get protocol() {
    return this._protocol;
  }

  /**
   * The hostname of the URL.
   * @type {string}
   */
  get hostname() {
    return this._hostname;
  }

  /**
   * Returns the entire URL.
   * @returns {string} The entire URL.
   */
  toString() {
    return this._href;
  }
}

let parseURL =
/**
 * Parses a URL to extract the protocol and the hostname.
 *
 * __This is a lightweight alternative to the native `URL` object intended for
 * use primarily within Adblock Plus. Unlike the `URL` object, the `parseURL()`
 * function is not robust and will give incorrect results for invalid URLs. Use
 * this function with valid,
 * [normalized](https://url.spec.whatwg.org/#concept-basic-url-parser),
 * properly encoded (IDNA, etc.) URLs only.__
 *
 * @param {string} url The URL.
 *
 * @returns {module:url~URLInfo} Information about the URL.
 *
 * @public
 */
exports.parseURL = function parseURL(url) {
  let match = /^([^:]+:)(?:\/\/(?:[^/]*@)?(\[[^\]]*\]|[^:/]+))?/.exec(url);

  if (!match) {
    throw new Error(`Failed to parse invalid URL "${url}"`);
  }

  return new URLInfo(url, match[1], match[2]);
};

let domainSuffixes =
/**
 * Yields all suffixes for a domain.
 *
 * For example, given the domain `www.example.com`, this function yields
 * `www.example.com`, `example.com`, and `com`, in that order.
 *
 * If the domain ends with a dot, the dot is ignored.
 *
 * @param {string} domain The domain.
 * @param {boolean} [includeBlank] Whether to include the blank suffix at the
 *   end.
 *
 * @generator
 * @yields {string} The next suffix for the domain.
 *
 * @package
 */
exports.domainSuffixes = function* domainSuffixes(
  domain, includeBlank = false
) {
  // Since any IP address is already expected to be normalized, there's no need
  // to validate it.
  if (isIPAddress(domain)) {
    yield domain;
  }
  else {
    if (domain[domain.length - 1] == ".") {
      domain = domain.substring(0, domain.length - 1);
    }

    while (domain != "") {
      yield domain;

      let dotIndex = domain.indexOf(".");
      domain = dotIndex == -1 ? "" : domain.substr(dotIndex + 1);
    }
  }

  if (includeBlank) {
    yield "";
  }
};

/**
 * Checks whether the given hostname refers to
 * {@link https://en.wikipedia.org/wiki/Localhost localhost}.
 *
 * If the hostname is `localhost`, `127.0.0.1`, or `[::1]`, the function
 * returns `true`; otherwise, it returns `false`.
 *
 * @param {string} hostname The hostname.
 *
 * @returns {boolean} Whether the hostname refers to localhost.
 *
 * @package
 */
exports.isLocalhost = function isLocalhost(hostname) {
  return hostname == "localhost" || hostname == "127.0.0.1" ||
         hostname == "[::1]";
};

/**
 * Checks whether the given hostname is an IP address.
 *
 * Unlike `{@link module:url~isValidIPv4Address isValidIPv4Address()}`, this
 * function only checks whether the hostname _looks like_ an IP address. Use
 * this function with valid, normalized, properly encoded (IDNA) hostnames
 * only.
 *
 * @param {string} hostname An IDNA-encoded hostname.
 *
 * @returns {boolean} Whether the hostname is an IP address.
 */
function isIPAddress(hostname) {
  // Does it look like an IPv6 address?
  if (hostname[0] == "[" && hostname[hostname.length - 1] == "]") {
    return true;
  }

  // Note: The first condition helps us avoid the more expensive regular
  // expression match for most hostnames.
  return hostname[hostname.length - 1] >= 0 &&
         /^\d+\.\d+\.\d+\.\d+$/.test(hostname);
}

/**
 * Checks whether a given address is a valid IPv4 address.
 *
 * Only a normalized IPv4 address is considered valid. e.g. `0x7f.0x0.0x0.0x1`
 * is invalid, whereas `127.0.0.1` is valid.
 *
 * @param {string} address The address to check.
 *
 * @returns {boolean} Whether the address is a valid IPv4 address.
 */
function isValidIPv4Address(address) {
  return /^(((2[0-4]|1[0-9]|[1-9])?[0-9]|25[0-5])\.){4}$/.test(address + ".");
}

/**
 * Checks whether a given hostname is valid.
 *
 * This function is used for filter validation.
 *
 * A hostname occurring in a filter must be normalized. For example,
 * <code>&#x1f642;</code> (slightly smiling face) should be normalized to
 * `xn--938h`; otherwise this function returns `false` for such a hostname.
 * Similarly, IP addresses should be normalized.
 *
 * @param {string} hostname The hostname to check.
 *
 * @returns {boolean} Whether the hostname is valid.
 */
exports.isValidHostname = function isValidHostname(hostname) {
  if (isValidIPv4Address(hostname)) {
    return true;
  }

  // This does not in fact validate the IPv6 address but it's alright for now.
  if (hostname[0] == "[" && hostname[hostname.length - 1] == "]") {
    return true;
  }

  // Based on
  // https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
  if (hostname[hostname.length - 1] == ".") {
    hostname = hostname.substring(0, hostname.length - 1);
  }

  if (hostname.length > 253) {
    return false;
  }

  let labels = hostname.split(".");
  for (let [index, label] of labels.entries()) {
    // Wildcards support
    if (label == "*" && index == (labels.length - 1)) {
      return true;
    }
    if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(label)) {
      return false;
    }
  }

  // Based on https://tools.ietf.org/html/rfc3696#section-2
  if (!/\D/.test(labels[labels.length - 1])) {
    return false;
  }

  return true;
};

let getBaseDomain =
/**
 * Gets the base domain for the given hostname.
 *
 * @param {string} hostname
 *
 * @returns {string}
 *
 * @package
 */
exports.getBaseDomain = function getBaseDomain(hostname) {
  let slices = [];
  let cutoff = NaN;

  for (let suffix of domainSuffixes(hostname)) {
    slices.push(suffix);

    let offset = icannPublicSuffixes[suffix];
    if (!(typeof offset == "number")) {
      offset = nonIcannPublicSuffixes[suffix];
    }

    if (typeof offset == "number") {
      cutoff = slices.length - 1 - offset;
      break;
    }
  }

  if (isNaN(cutoff)) {
    return slices.length > 2 ? slices[slices.length - 2] : hostname;
  }

  if (cutoff <= 0) {
    return hostname;
  }

  return slices[cutoff];
};

/**
 * Checks whether a request's origin is different from its document's origin.
 *
 * @param {string} requestHostname The IDNA-encoded hostname of the request.
 * @param {string} documentHostname The IDNA-encoded hostname of the document.
 *
 * @returns {boolean}
 */
function isThirdParty(requestHostname, documentHostname) {
  if (requestHostname[requestHostname.length - 1] == ".") {
    requestHostname = requestHostname.substring(0, requestHostname.length - 1);
  }

  if (documentHostname[documentHostname.length - 1] == ".") {
    documentHostname =
      documentHostname.substring(0, documentHostname.length - 1);
  }

  if (requestHostname == documentHostname) {
    return false;
  }

  if (!requestHostname || !documentHostname) {
    return true;
  }

  if (isIPAddress(requestHostname) || isIPAddress(documentHostname)) {
    return true;
  }

  return getBaseDomain(requestHostname) != getBaseDomain(documentHostname);
}

let URLRequest =
/**
 * The `URLRequest` class represents a URL request.
 */
exports.URLRequest = class URLRequest {
  /**
   * @private
   */
  constructor() {}

  /**
   * The URL of the request.
   * @type {string}
   */
  get href() {
    return this._href;
  }

  /**
   * Information about the URL of the request.
   * @type {module:url~URLInfo}
   * @package
   */
  get urlInfo() {
    if (!this._urlInfo) {
      this._urlInfo = parseURL(this._href);
    }

    return this._urlInfo;
  }

  /**
   * The hostname of the document making the request.
   * @type {?string}
   */
  get documentHostname() {
    return this._documentHostname == null ? null : this._documentHostname;
  }

  /**
   * Whether this is a third-party request.
   * @type {boolean}
   */
  get thirdParty() {
    if (typeof this._thirdParty == "undefined") {
      this._thirdParty = this._documentHostname == null ? false :
        isThirdParty(this.urlInfo.hostname,
          this._documentHostname);
    }

    return this._thirdParty;
  }

  /**
   * Returns the URL of the request.
   * @returns {string}
   */
  toString() {
    return this._href;
  }

  /**
   * The lower-case version of the URL of the request.
   * @type {string}
   * @package
   */
  get lowerCaseHref() {
    if (this._lowerCaseHref == null) {
      this._lowerCaseHref = this._href.toLowerCase();
    }

    return this._lowerCaseHref;
  }
};

/**
 * Returns a `{@link module:url.URLRequest URLRequest}` object for the given
 * URL.
 *
 * @param {string|module:url~URLInfo|URL} url The URL. If this is a `string`,
 *   it must be a canonicalized URL (see
 *   `{@link module:url.parseURL parseURL()}`).
 * @param {?string} [documentHostname] The IDNA-encoded hostname of the
 *   document making the request.
 *
 * @returns {module:url.URLRequest}
 */
exports.URLRequest.from = function(url, documentHostname = null) {
  let request = new URLRequest();

  if (typeof url == "string") {
    request._href = url;
  }
  else {
    request._urlInfo = url instanceof URLInfo ? url :
      new URLInfo(url.href, url.protocol, url.hostname);
    request._href = url.href;
  }

  if (documentHostname != null) {
    request._documentHostname = documentHostname;
  }

  return request;
};

/**
 * Parses the domains part of a filter text
 * (e.g. `example.com,~mail.example.com`) into a `Map` object.
 *
 * @param {string} source The domains part of a filter text.
 * @param {string} separator The string used to separate two or more domains in
 *   the domains part of a filter text.
 *
 * @returns {?Map.<string, boolean>}
 *
 * @package
 */
exports.parseDomains = function parseDomains(source, separator) {
  let domains = domainsCache.get(source);
  if (typeof domains != "undefined") {
    return domains;
  }

  if (source[0] != "~" && !source.includes(separator)) {
    // Fast track for the common one-domain scenario.
    domains = new Map([["", false], [source, true]]);
  }
  else {
    domains = null;

    let hasIncludes = false;
    for (let domain of source.split(separator)) {
      if (domain == "") {
        continue;
      }

      let include;
      if (domain[0] == "~") {
        include = false;
        domain = domain.substring(1);
      }
      else {
        include = true;
        hasIncludes = true;
      }

      if (!domains) {
        domains = new Map();
      }

      domains.set(domain, include);
    }

    if (domains) {
      domains.set("", !hasIncludes);
    }
  }

  domainsCache.set(source, domains);

  return domains;
};

exports.hasWildcard = function hasWildcard(string) {
  return string.includes("*");
};

/**
 * Checks whether domain URL matches wildcards mask.
 * Note: PSL is taken into account (base domain is checked actually).
 * @param {string} domain domain to check (assuming it's lower-cased)
 * @param {string} domainWithWildcards domain mask (assuming it's lower-cased)
 * @returns {boolean} `true` if domain matches the mask
 */
exports.matchesWildcards = function matchesWildcards(
  domain, domainWithWildcards) {
  // cut off the wildcard. Luckily we know exactly where it is already.
  let expectedPrefix = domainWithWildcards.slice(0, -1);

  for (let suffix of domainSuffixes(domain)) {
    if (!suffix.startsWith(expectedPrefix)) {
      continue;
    }
    let expectedTld = suffix.slice(expectedPrefix.length);
    if (typeof icannPublicSuffixes[expectedTld] == "number") {
      return true;
    }
  }

  return false;
};

exports.isValidDomainWildcard = function isValidDomainWildcard(domain) {
  // ? are not supported
  if (domain.includes("?")) {
    return false;
  }

  // multiple * are not supported
  let asteriskCount = (domain.match(/\*/g) || []).length;
  if (asteriskCount > 1) {
    return false;
  }

  if (asteriskCount == 1) {
    let pos = domain.indexOf("*");

    // * must be the last character in the string
    if (pos < (domain.length - 1)) {
      return false;
    }

    // but not the only character in the string
    if (domain.length == 1) {
      return false;
    }

    // * must be preceeded with .
    if (pos > 0 && domain[pos - 1] != ".") {
      return false;
    }
  }

  return true;
};


/***/ }),

/***/ "./core/lib/versions.js":
/*!******************************!*\
  !*** ./core/lib/versions.js ***!
  \******************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module */



function parseVersionComponent(comp) {
  if (comp == "*") {
    return Infinity;
  }
  return parseInt(comp, 10) || 0;
}

/**
 * Compares two versions.
 *
 * @param {string} v1 The first version.
 * @param {string} v2 The second version.
 *
 * @returns {number} `-1` if `v1` is older than `v2`; `1` if `v1` is newer than
 *   `v2`; otherwise `0`.
 *
 * @package
 */
exports.compareVersions = function compareVersions(v1, v2) {
  let regexp = /^(.*?)([a-z].*)?$/i;
  let [, head1, tail1] = regexp.exec(v1);
  let [, head2, tail2] = regexp.exec(v2);
  let components1 = head1.split(".");
  let components2 = head2.split(".");

  for (let i = 0; i < components1.length ||
                  i < components2.length; i++) {
    let result = parseVersionComponent(components1[i]) -
                 parseVersionComponent(components2[i]) || 0;

    if (result < 0) {
      return -1;
    }
    else if (result > 0) {
      return 1;
    }
  }

  // Compare version suffix (e.g. 0.1alpha < 0.1b1 < 01.b2 < 0.1).
  // However, note that this is a simple string comparision, meaning: b10 < b2
  if (tail1 == tail2) {
    return 0;
  }
  if (!tail1 || tail2 && tail1 > tail2) {
    return 1;
  }
  return -1;
};


/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/native.js":
/*!******************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/native.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_604405__) => {

"use strict";
__nested_webpack_require_604405__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_604405__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  randomUUID
});

/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/regex.js":
/*!*****************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/regex.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_605136__) => {

"use strict";
__nested_webpack_require_605136__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_605136__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);

/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/rng.js":
/*!***************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/rng.js ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_605855__) => {

"use strict";
__nested_webpack_require_605855__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_605855__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ rng)
/* harmony export */ });
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
  // lazy load so that environments that need to polyfill have a chance to do so
  if (!getRandomValues) {
    // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
    getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);

    if (!getRandomValues) {
      throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
    }
  }

  return getRandomValues(rnds8);
}

/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/stringify.js":
/*!*********************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/stringify.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_607228__) => {

"use strict";
__nested_webpack_require_607228__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_607228__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "unsafeStringify": () => (/* binding */ unsafeStringify)
/* harmony export */ });
/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_607228__(/*! ./validate.js */ "./node_modules/uuid/dist/esm-browser/validate.js");

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */

const byteToHex = [];

for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 0x100).toString(16).slice(1));
}

function unsafeStringify(arr, offset = 0) {
  // Note: Be careful editing this code!  It's been tuned for performance
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}

function stringify(arr, offset = 0) {
  const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID.  If this throws, it's likely due to one
  // of the following:
  // - One or more input array values don't map to a hex octet (leading to
  // "undefined" in the uuid)
  // - Invalid input values for the RFC `version` or `variant` fields

  if (!(0,_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) {
    throw TypeError('Stringified UUID is invalid');
  }

  return uuid;
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (stringify);

/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/v4.js":
/*!**************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/v4.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_609543__) => {

"use strict";
__nested_webpack_require_609543__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_609543__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _native_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_609543__(/*! ./native.js */ "./node_modules/uuid/dist/esm-browser/native.js");
/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_609543__(/*! ./rng.js */ "./node_modules/uuid/dist/esm-browser/rng.js");
/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_609543__(/*! ./stringify.js */ "./node_modules/uuid/dist/esm-browser/stringify.js");




function v4(options, buf, offset) {
  if (_native_js__WEBPACK_IMPORTED_MODULE_0__["default"].randomUUID && !buf && !options) {
    return _native_js__WEBPACK_IMPORTED_MODULE_0__["default"].randomUUID();
  }

  options = options || {};
  const rnds = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_1__["default"])(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`

  rnds[6] = rnds[6] & 0x0f | 0x40;
  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided

  if (buf) {
    offset = offset || 0;

    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }

    return buf;
  }

  return (0,_stringify_js__WEBPACK_IMPORTED_MODULE_2__.unsafeStringify)(rnds);
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (v4);

/***/ }),

/***/ "./node_modules/uuid/dist/esm-browser/validate.js":
/*!********************************************************!*\
  !*** ./node_modules/uuid/dist/esm-browser/validate.js ***!
  \********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __nested_webpack_require_611370__) => {

"use strict";
__nested_webpack_require_611370__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_611370__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _regex_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_611370__(/*! ./regex.js */ "./node_modules/uuid/dist/esm-browser/regex.js");


function validate(uuid) {
  return typeof uuid === 'string' && _regex_js__WEBPACK_IMPORTED_MODULE_0__["default"].test(uuid);
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);

/***/ }),

/***/ "./node_modules/webextension-polyfill/dist/browser-polyfill.js":
/*!*********************************************************************!*\
  !*** ./node_modules/webextension-polyfill/dist/browser-polyfill.js ***!
  \*********************************************************************/
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else { var mod; }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (module) {
  /* webextension-polyfill - v0.8.0 - Tue Apr 20 2021 11:27:38 */

  /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */

  /* vim: set sts=2 sw=2 et tw=80: */

  /* This Source Code Form is subject to the terms of the Mozilla Public
   * License, v. 2.0. If a copy of the MPL was not distributed with this
   * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  "use strict";

  if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) {
    const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received.";
    const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; // Wrapping the bulk of this polyfill in a one-time-use function is a minor
    // optimization for Firefox. Since Spidermonkey does not fully parse the
    // contents of a function until the first time it's called, and since it will
    // never actually need to be called, this allows the polyfill to be included
    // in Firefox nearly for free.

    const wrapAPIs = extensionAPIs => {
      // NOTE: apiMetadata is associated to the content of the api-metadata.json file
      // at build time by replacing the following "include" with the content of the
      // JSON file.
      const apiMetadata = {
        "alarms": {
          "clear": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "clearAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "get": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "bookmarks": {
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getChildren": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getRecent": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getSubTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTree": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeTree": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "browserAction": {
          "disable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "enable": {
            "minArgs": 0,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "getBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getBadgeText": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "openPopup": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setBadgeBackgroundColor": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setBadgeText": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "browsingData": {
          "remove": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "removeCache": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCookies": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeDownloads": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFormData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeHistory": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeLocalStorage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePasswords": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removePluginData": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "settings": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "commands": {
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "contextMenus": {
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "cookies": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAllCookieStores": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "set": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "devtools": {
          "inspectedWindow": {
            "eval": {
              "minArgs": 1,
              "maxArgs": 2,
              "singleCallbackArg": false
            }
          },
          "panels": {
            "create": {
              "minArgs": 3,
              "maxArgs": 3,
              "singleCallbackArg": true
            },
            "elements": {
              "createSidebarPane": {
                "minArgs": 1,
                "maxArgs": 1
              }
            }
          }
        },
        "downloads": {
          "cancel": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "download": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "erase": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFileIcon": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "open": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "pause": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeFile": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "resume": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "extension": {
          "isAllowedFileSchemeAccess": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "isAllowedIncognitoAccess": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "history": {
          "addUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "deleteRange": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "deleteUrl": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getVisits": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "search": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "i18n": {
          "detectLanguage": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAcceptLanguages": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "identity": {
          "launchWebAuthFlow": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "idle": {
          "queryState": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "management": {
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getSelf": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "setEnabled": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "uninstallSelf": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "notifications": {
          "clear": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPermissionLevel": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        },
        "pageAction": {
          "getPopup": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getTitle": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "hide": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setIcon": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "setPopup": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "setTitle": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          },
          "show": {
            "minArgs": 1,
            "maxArgs": 1,
            "fallbackToNoCallback": true
          }
        },
        "permissions": {
          "contains": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "request": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "runtime": {
          "getBackgroundPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getPlatformInfo": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "openOptionsPage": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "requestUpdateCheck": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "sendMessage": {
            "minArgs": 1,
            "maxArgs": 3
          },
          "sendNativeMessage": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "setUninstallURL": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "sessions": {
          "getDevices": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getRecentlyClosed": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "restore": {
            "minArgs": 0,
            "maxArgs": 1
          }
        },
        "storage": {
          "local": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          },
          "managed": {
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            }
          },
          "sync": {
            "clear": {
              "minArgs": 0,
              "maxArgs": 0
            },
            "get": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "getBytesInUse": {
              "minArgs": 0,
              "maxArgs": 1
            },
            "remove": {
              "minArgs": 1,
              "maxArgs": 1
            },
            "set": {
              "minArgs": 1,
              "maxArgs": 1
            }
          }
        },
        "tabs": {
          "captureVisibleTab": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "create": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "detectLanguage": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "discard": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "duplicate": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "executeScript": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 0
          },
          "getZoom": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getZoomSettings": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goBack": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "goForward": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "highlight": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "insertCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "move": {
            "minArgs": 2,
            "maxArgs": 2
          },
          "query": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "reload": {
            "minArgs": 0,
            "maxArgs": 2
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "removeCSS": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "sendMessage": {
            "minArgs": 2,
            "maxArgs": 3
          },
          "setZoom": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "setZoomSettings": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "update": {
            "minArgs": 1,
            "maxArgs": 2
          }
        },
        "topSites": {
          "get": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "webNavigation": {
          "getAllFrames": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "getFrame": {
            "minArgs": 1,
            "maxArgs": 1
          }
        },
        "webRequest": {
          "handlerBehaviorChanged": {
            "minArgs": 0,
            "maxArgs": 0
          }
        },
        "windows": {
          "create": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "get": {
            "minArgs": 1,
            "maxArgs": 2
          },
          "getAll": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getCurrent": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "getLastFocused": {
            "minArgs": 0,
            "maxArgs": 1
          },
          "remove": {
            "minArgs": 1,
            "maxArgs": 1
          },
          "update": {
            "minArgs": 2,
            "maxArgs": 2
          }
        }
      };

      if (Object.keys(apiMetadata).length === 0) {
        throw new Error("api-metadata.json has not been included in browser-polyfill");
      }
      /**
       * A WeakMap subclass which creates and stores a value for any key which does
       * not exist when accessed, but behaves exactly as an ordinary WeakMap
       * otherwise.
       *
       * @param {function} createItem
       *        A function which will be called in order to create the value for any
       *        key which does not exist, the first time it is accessed. The
       *        function receives, as its only argument, the key being created.
       */


      class DefaultWeakMap extends WeakMap {
        constructor(createItem, items = undefined) {
          super(items);
          this.createItem = createItem;
        }

        get(key) {
          if (!this.has(key)) {
            this.set(key, this.createItem(key));
          }

          return super.get(key);
        }

      }
      /**
       * Returns true if the given object is an object with a `then` method, and can
       * therefore be assumed to behave as a Promise.
       *
       * @param {*} value The value to test.
       * @returns {boolean} True if the value is thenable.
       */


      const isThenable = value => {
        return value && typeof value === "object" && typeof value.then === "function";
      };
      /**
       * Creates and returns a function which, when called, will resolve or reject
       * the given promise based on how it is called:
       *
       * - If, when called, `chrome.runtime.lastError` contains a non-null object,
       *   the promise is rejected with that value.
       * - If the function is called with exactly one argument, the promise is
       *   resolved to that value.
       * - Otherwise, the promise is resolved to an array containing all of the
       *   function's arguments.
       *
       * @param {object} promise
       *        An object containing the resolution and rejection functions of a
       *        promise.
       * @param {function} promise.resolve
       *        The promise's resolution function.
       * @param {function} promise.reject
       *        The promise's rejection function.
       * @param {object} metadata
       *        Metadata about the wrapped method which has created the callback.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function}
       *        The generated callback function.
       */


      const makeCallback = (promise, metadata) => {
        return (...callbackArgs) => {
          if (extensionAPIs.runtime.lastError) {
            promise.reject(new Error(extensionAPIs.runtime.lastError.message));
          } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) {
            promise.resolve(callbackArgs[0]);
          } else {
            promise.resolve(callbackArgs);
          }
        };
      };

      const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments";
      /**
       * Creates a wrapper function for a method with the given name and metadata.
       *
       * @param {string} name
       *        The name of the method which is being wrapped.
       * @param {object} metadata
       *        Metadata about the method being wrapped.
       * @param {integer} metadata.minArgs
       *        The minimum number of arguments which must be passed to the
       *        function. If called with fewer than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {integer} metadata.maxArgs
       *        The maximum number of arguments which may be passed to the
       *        function. If called with more than this number of arguments, the
       *        wrapper will raise an exception.
       * @param {boolean} metadata.singleCallbackArg
       *        Whether or not the promise is resolved with only the first
       *        argument of the callback, alternatively an array of all the
       *        callback arguments is resolved. By default, if the callback
       *        function is invoked with only a single argument, that will be
       *        resolved to the promise, while all arguments will be resolved as
       *        an array if multiple are given.
       *
       * @returns {function(object, ...*)}
       *       The generated wrapper function.
       */


      const wrapAsyncFunction = (name, metadata) => {
        return function asyncFunctionWrapper(target, ...args) {
          if (args.length < metadata.minArgs) {
            throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
          }

          if (args.length > metadata.maxArgs) {
            throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
          }

          return new Promise((resolve, reject) => {
            if (metadata.fallbackToNoCallback) {
              // This API method has currently no callback on Chrome, but it return a promise on Firefox,
              // and so the polyfill will try to call it with a callback first, and it will fallback
              // to not passing the callback if the first call fails.
              try {
                target[name](...args, makeCallback({
                  resolve,
                  reject
                }, metadata));
              } catch (cbError) {
                console.warn(`${name} API method doesn't seem to support the callback parameter, ` + "falling back to call it without a callback: ", cbError);
                target[name](...args); // Update the API method metadata, so that the next API calls will not try to
                // use the unsupported callback anymore.

                metadata.fallbackToNoCallback = false;
                metadata.noCallback = true;
                resolve();
              }
            } else if (metadata.noCallback) {
              target[name](...args);
              resolve();
            } else {
              target[name](...args, makeCallback({
                resolve,
                reject
              }, metadata));
            }
          });
        };
      };
      /**
       * Wraps an existing method of the target object, so that calls to it are
       * intercepted by the given wrapper function. The wrapper function receives,
       * as its first argument, the original `target` object, followed by each of
       * the arguments passed to the original method.
       *
       * @param {object} target
       *        The original target object that the wrapped method belongs to.
       * @param {function} method
       *        The method being wrapped. This is used as the target of the Proxy
       *        object which is created to wrap the method.
       * @param {function} wrapper
       *        The wrapper function which is called in place of a direct invocation
       *        of the wrapped method.
       *
       * @returns {Proxy<function>}
       *        A Proxy object for the given method, which invokes the given wrapper
       *        method in its place.
       */


      const wrapMethod = (target, method, wrapper) => {
        return new Proxy(method, {
          apply(targetMethod, thisObj, args) {
            return wrapper.call(thisObj, target, ...args);
          }

        });
      };

      let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
      /**
       * Wraps an object in a Proxy which intercepts and wraps certain methods
       * based on the given `wrappers` and `metadata` objects.
       *
       * @param {object} target
       *        The target object to wrap.
       *
       * @param {object} [wrappers = {}]
       *        An object tree containing wrapper functions for special cases. Any
       *        function present in this object tree is called in place of the
       *        method in the same location in the `target` object tree. These
       *        wrapper methods are invoked as described in {@see wrapMethod}.
       *
       * @param {object} [metadata = {}]
       *        An object tree containing metadata used to automatically generate
       *        Promise-based wrapper functions for asynchronous. Any function in
       *        the `target` object tree which has a corresponding metadata object
       *        in the same location in the `metadata` tree is replaced with an
       *        automatically-generated wrapper function, as described in
       *        {@see wrapAsyncFunction}
       *
       * @returns {Proxy<object>}
       */

      const wrapObject = (target, wrappers = {}, metadata = {}) => {
        let cache = Object.create(null);
        let handlers = {
          has(proxyTarget, prop) {
            return prop in target || prop in cache;
          },

          get(proxyTarget, prop, receiver) {
            if (prop in cache) {
              return cache[prop];
            }

            if (!(prop in target)) {
              return undefined;
            }

            let value = target[prop];

            if (typeof value === "function") {
              // This is a method on the underlying object. Check if we need to do
              // any wrapping.
              if (typeof wrappers[prop] === "function") {
                // We have a special-case wrapper for this method.
                value = wrapMethod(target, target[prop], wrappers[prop]);
              } else if (hasOwnProperty(metadata, prop)) {
                // This is an async method that we have metadata for. Create a
                // Promise wrapper for it.
                let wrapper = wrapAsyncFunction(prop, metadata[prop]);
                value = wrapMethod(target, target[prop], wrapper);
              } else {
                // This is a method that we don't know or care about. Return the
                // original method, bound to the underlying object.
                value = value.bind(target);
              }
            } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) {
              // This is an object that we need to do some wrapping for the children
              // of. Create a sub-object wrapper for it with the appropriate child
              // metadata.
              value = wrapObject(value, wrappers[prop], metadata[prop]);
            } else if (hasOwnProperty(metadata, "*")) {
              // Wrap all properties in * namespace.
              value = wrapObject(value, wrappers[prop], metadata["*"]);
            } else {
              // We don't need to do any wrapping for this property,
              // so just forward all access to the underlying object.
              Object.defineProperty(cache, prop, {
                configurable: true,
                enumerable: true,

                get() {
                  return target[prop];
                },

                set(value) {
                  target[prop] = value;
                }

              });
              return value;
            }

            cache[prop] = value;
            return value;
          },

          set(proxyTarget, prop, value, receiver) {
            if (prop in cache) {
              cache[prop] = value;
            } else {
              target[prop] = value;
            }

            return true;
          },

          defineProperty(proxyTarget, prop, desc) {
            return Reflect.defineProperty(cache, prop, desc);
          },

          deleteProperty(proxyTarget, prop) {
            return Reflect.deleteProperty(cache, prop);
          }

        }; // Per contract of the Proxy API, the "get" proxy handler must return the
        // original value of the target if that value is declared read-only and
        // non-configurable. For this reason, we create an object with the
        // prototype set to `target` instead of using `target` directly.
        // Otherwise we cannot return a custom object for APIs that
        // are declared read-only and non-configurable, such as `chrome.devtools`.
        //
        // The proxy handlers themselves will still use the original `target`
        // instead of the `proxyTarget`, so that the methods and properties are
        // dereferenced via the original targets.

        let proxyTarget = Object.create(target);
        return new Proxy(proxyTarget, handlers);
      };
      /**
       * Creates a set of wrapper functions for an event object, which handles
       * wrapping of listener functions that those messages are passed.
       *
       * A single wrapper is created for each listener function, and stored in a
       * map. Subsequent calls to `addListener`, `hasListener`, or `removeListener`
       * retrieve the original wrapper, so that  attempts to remove a
       * previously-added listener work as expected.
       *
       * @param {DefaultWeakMap<function, function>} wrapperMap
       *        A DefaultWeakMap object which will create the appropriate wrapper
       *        for a given listener function when one does not exist, and retrieve
       *        an existing one when it does.
       *
       * @returns {object}
       */


      const wrapEvent = wrapperMap => ({
        addListener(target, listener, ...args) {
          target.addListener(wrapperMap.get(listener), ...args);
        },

        hasListener(target, listener) {
          return target.hasListener(wrapperMap.get(listener));
        },

        removeListener(target, listener) {
          target.removeListener(wrapperMap.get(listener));
        }

      });

      const onRequestFinishedWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }
        /**
         * Wraps an onRequestFinished listener function so that it will return a
         * `getContent()` property which returns a `Promise` rather than using a
         * callback API.
         *
         * @param {object} req
         *        The HAR entry object representing the network request.
         */


        return function onRequestFinished(req) {
          const wrappedReq = wrapObject(req, {}
          /* wrappers */
          , {
            getContent: {
              minArgs: 0,
              maxArgs: 0
            }
          });
          listener(wrappedReq);
        };
      }); // Keep track if the deprecation warning has been logged at least once.

      let loggedSendResponseDeprecationWarning = false;
      const onMessageWrappers = new DefaultWeakMap(listener => {
        if (typeof listener !== "function") {
          return listener;
        }
        /**
         * Wraps a message listener function so that it may send responses based on
         * its return value, rather than by returning a sentinel value and calling a
         * callback. If the listener function returns a Promise, the response is
         * sent when the promise either resolves or rejects.
         *
         * @param {*} message
         *        The message sent by the other end of the channel.
         * @param {object} sender
         *        Details about the sender of the message.
         * @param {function(*)} sendResponse
         *        A callback which, when called with an arbitrary argument, sends
         *        that value as a response.
         * @returns {boolean}
         *        True if the wrapped listener returned a Promise, which will later
         *        yield a response. False otherwise.
         */


        return function onMessage(message, sender, sendResponse) {
          let didCallSendResponse = false;
          let wrappedSendResponse;
          let sendResponsePromise = new Promise(resolve => {
            wrappedSendResponse = function (response) {
              if (!loggedSendResponseDeprecationWarning) {
                console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack);
                loggedSendResponseDeprecationWarning = true;
              }

              didCallSendResponse = true;
              resolve(response);
            };
          });
          let result;

          try {
            result = listener(message, sender, wrappedSendResponse);
          } catch (err) {
            result = Promise.reject(err);
          }

          const isResultThenable = result !== true && isThenable(result); // If the listener didn't returned true or a Promise, or called
          // wrappedSendResponse synchronously, we can exit earlier
          // because there will be no response sent from this listener.

          if (result !== true && !isResultThenable && !didCallSendResponse) {
            return false;
          } // A small helper to send the message if the promise resolves
          // and an error if the promise rejects (a wrapped sendMessage has
          // to translate the message into a resolved promise or a rejected
          // promise).


          const sendPromisedResult = promise => {
            promise.then(msg => {
              // send the message value.
              sendResponse(msg);
            }, error => {
              // Send a JSON representation of the error if the rejected value
              // is an instance of error, or the object itself otherwise.
              let message;

              if (error && (error instanceof Error || typeof error.message === "string")) {
                message = error.message;
              } else {
                message = "An unexpected error occurred";
              }

              sendResponse({
                __mozWebExtensionPolyfillReject__: true,
                message
              });
            }).catch(err => {
              // Print an error on the console if unable to send the response.
              console.error("Failed to send onMessage rejected reply", err);
            });
          }; // If the listener returned a Promise, send the resolved value as a
          // result, otherwise wait the promise related to the wrappedSendResponse
          // callback to resolve and send it as a response.


          if (isResultThenable) {
            sendPromisedResult(result);
          } else {
            sendPromisedResult(sendResponsePromise);
          } // Let Chrome know that the listener is replying.


          return true;
        };
      });

      const wrappedSendMessageCallback = ({
        reject,
        resolve
      }, reply) => {
        if (extensionAPIs.runtime.lastError) {
          // Detect when none of the listeners replied to the sendMessage call and resolve
          // the promise to undefined as in Firefox.
          // See https://github.com/mozilla/webextension-polyfill/issues/130
          if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) {
            resolve();
          } else {
            reject(new Error(extensionAPIs.runtime.lastError.message));
          }
        } else if (reply && reply.__mozWebExtensionPolyfillReject__) {
          // Convert back the JSON representation of the error into
          // an Error instance.
          reject(new Error(reply.message));
        } else {
          resolve(reply);
        }
      };

      const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => {
        if (args.length < metadata.minArgs) {
          throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
        }

        if (args.length > metadata.maxArgs) {
          throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
        }

        return new Promise((resolve, reject) => {
          const wrappedCb = wrappedSendMessageCallback.bind(null, {
            resolve,
            reject
          });
          args.push(wrappedCb);
          apiNamespaceObj.sendMessage(...args);
        });
      };

      const staticWrappers = {
        devtools: {
          network: {
            onRequestFinished: wrapEvent(onRequestFinishedWrappers)
          }
        },
        runtime: {
          onMessage: wrapEvent(onMessageWrappers),
          onMessageExternal: wrapEvent(onMessageWrappers),
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 1,
            maxArgs: 3
          })
        },
        tabs: {
          sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
            minArgs: 2,
            maxArgs: 3
          })
        }
      };
      const settingMetadata = {
        clear: {
          minArgs: 1,
          maxArgs: 1
        },
        get: {
          minArgs: 1,
          maxArgs: 1
        },
        set: {
          minArgs: 1,
          maxArgs: 1
        }
      };
      apiMetadata.privacy = {
        network: {
          "*": settingMetadata
        },
        services: {
          "*": settingMetadata
        },
        websites: {
          "*": settingMetadata
        }
      };
      return wrapObject(extensionAPIs, staticWrappers, apiMetadata);
    };

    if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) {
      throw new Error("This script should only be loaded in a browser extension.");
    } // The build process adds a UMD wrapper around this file, which makes the
    // `module` variable available.


    module.exports = wrapAPIs(chrome);
  } else {
    module.exports = browser;
  }
});


/***/ }),

/***/ "perf_hooks":
/*!***********************!*\
  !*** external "self" ***!
  \***********************/
/***/ ((module) => {

"use strict";
module.exports = self;

/***/ }),

/***/ "./sdk/api/allowlisting.js":
/*!*********************************!*\
  !*** ./sdk/api/allowlisting.js ***!
  \*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_651998__) => {

"use strict";
__nested_webpack_require_651998__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_651998__.d(__webpack_exports__, {
/* harmony export */   "allowlistPage": () => (/* binding */ allowlistPage),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_651998__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_651998__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_651998__(/*! adblockpluscore/lib/time.js */ "./core/lib/time.js");
/* harmony import */ var adblockpluscore_lib_rsa_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_651998__(/*! adblockpluscore/lib/rsa.js */ "./core/lib/rsa.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_651998__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_651998__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_651998__(/*! ./filters.js */ "./sdk/api/filters.js");
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_651998__(/*! ./types.js */ "./sdk/api/types.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */











// Allowlisting depends on comparing timestamps which may be generated on
// different clocks on different servers across the internet. One day everyone
// will have perfectly synchronized clocks. Today however, we need some
// tolerance for if the two clocks are out of sync. Based on
// https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/maximum-tolerance-for-computer-clock-synchronization,
// Microsoft seems to expect 5 min to be a reasonable tolerance for clock
// skewing in Windows systems. This is also in the same order of magnitude the
// hour window we have for the timstamp to be valid.
const CLOCK_SKEW_TOLERANCE = 5 * adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_2__.MILLIS_IN_MINUTE;

// Note that this is a default implementation, but it might be
// replaced using `setAllowlistingCallback`. Don't rely on this
// behaviour.
let allowlistingCallback = function(domain) {
  return _filters_js__WEBPACK_IMPORTED_MODULE_6__["default"].add([`@@||${domain}^$document`]);
};
let dispatchUnauthorized = () => {};

let authorizedPublicKeys = [];
let publicKeysUpdated = Promise.resolve();

let algorithm = {
  name: "RSASSA-PKCS1-v1_5",
  modulusLength: 4096,
  publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  hash: {name: "SHA-512"}
};

function getAllowData(domain, timestamp) {
  let str = `${domain},${timestamp}`;
  return (new TextEncoder()).encode(str);
}

async function verifySignature(data, signature, pubKey) {
  return crypto.subtle.verify(
    algorithm,
    pubKey,
    signature,
    data
  );
}

function verifyTimestamp(timestamp) {
  if (typeof timestamp != "number" || isNaN(timestamp)) {
    return false;
  }

  let now = Date.now();

  let inTheFuture = timestamp > now + CLOCK_SKEW_TOLERANCE;
  let tooOld = timestamp < now - adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_2__.MILLIS_IN_HOUR - CLOCK_SKEW_TOLERANCE;
  return !inTheFuture && !tooOld;
}

async function verifyAnySignatures(domain, timestamp, signature) {
  if (typeof signature != "string") {
    return false;
  }

  await publicKeysUpdated;

  let data = getAllowData(domain, timestamp);
  let abSignature = (0,adblockpluscore_lib_rsa_js__WEBPACK_IMPORTED_MODULE_3__.base64ToArrayBuffer)(signature);
  for (let key of authorizedPublicKeys) {
    if (await verifySignature(data, abSignature, key)) {
      return true;
    }
  }
  return false;
}

async function succeedAllowlisting(domain) {
  await allowlistingCallback(domain);
  return true;
}

function failAllowlisting(error) {
  dispatchUnauthorized(error);
  return false;
}

async function allowlistPage(tabId, frameId, timestamp, signature) {
  let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_5__.getFrameInfo)(tabId, frameId);
  if (!frame) {
    return failAllowlisting({
      reason: "invalid_frame",
      request: {domain: null, timestamp, signature}
    });
  }

  let domain = frame.hostname;
  let request = {domain, timestamp, signature};

  if (frameId != 0) {
    return failAllowlisting({
      reason: "invalid_frame",
      request
    });
  }

  let urlInfo = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__.parseURL)(frame.url);
  let alreadyAllowlistedDomain = _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.defaultMatcher.isAllowlisted(
    `${urlInfo.protocol}//${domain}`,
    adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_0__.contentTypes.DOCUMENT,
    domain,
    frame.sitekey
  );
  if (alreadyAllowlistedDomain) {
    return failAllowlisting({
      reason: "already_allowlisted",
      request
    });
  }

  let validTimestamp = verifyTimestamp(timestamp);
  if (!validTimestamp) {
    return failAllowlisting({
      reason: "invalid_timestamp",
      request
    });
  }

  let validSignature = await verifyAnySignatures(domain, timestamp, signature);
  if (!validSignature) {
    return failAllowlisting({
      reason: "invalid_signature",
      request
    });
  }

  return await succeedAllowlisting(domain);
}

async function setAuthorizedKeys(keys) {
  let newAuthorizedPublicKeys = [];
  for (let key of keys) {
    let abKey = (0,adblockpluscore_lib_rsa_js__WEBPACK_IMPORTED_MODULE_3__.base64ToArrayBuffer)(key);
    let importedKey = await crypto.subtle.importKey(
      "spki",
      abKey,
      algorithm,
      false,
      ["verify"]
    );
    newAuthorizedPublicKeys.push(importedKey);
  }
  authorizedPublicKeys = newAuthorizedPublicKeys;
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * Updates the list of public keys used to verify allowlisting
   * requests. If there are any invalid keys, the list of authorized
   * keys keeps its previous value.
   *
   * Any allowlisting requests that come in while this function is in
   * progress will wait for it to finish before verifying any
   * signatures.
   *
   * @param {[string]} keys The new set of public keys. The keys
   *   should be base64 encoded strings, in SPKI format. The keys must
   *   additionally use the RSASSA-PKCS1-v1_5 algorithm, SHA512 hash
   *   and 4096 bit long modulus.
   * @return {Promise} Promise that resolves when the keys have been
   *   updated, or rejects if any of the keys are invalid.
   */
  async setAuthorizedKeys(keys) {
    let resultPromise = setAuthorizedKeys(keys);
    publicKeysUpdated = resultPromise.catch(() => {});
    return await resultPromise;
  },

  /**
   * @callback allowlistingCallback
   * @param {string} domain The domain to allowlist.
   */

  /**
   * Set the function called when allowlisting succeeds.
   *
   * If the callback is not set, it has a default implementation that
   * adds an allowlisting filter for the allowlisted domain.
   *
   * @param {allowlistingCallback} callback The user defined function
   *   that will be called. This function should return a promise that
   *   resolves after adding the appropriate allowlisting filters.
   */
  setAllowlistingCallback(callback) {
    allowlistingCallback = callback;
  },

  /**
   * @typedef {Object} AllowlistingAuthorizationError
   * @property {string} reason The reason a request to allowlist was
   *   rejected. Can be "invalid_frame", "already_allowlisted",
   *   "invalid_timestamp", or "invalid_signature".
   * @property {Object} request The rejected request.
   * @property {string} [request.domain] The domain of the page that
   *   the request came from. This is also the domain that the request
   *   would have allowlisted if it was valid. If this is null, it
   *   means that the frame's domain could not be determined.
   * @property {*} request.timestamp The timestamp in the
   *   request. For a valid request this is a number, but the request
   *   may have been invalid so it might not be a number.
   * @property {*} request.signature The signature in the
   *   request. For a valid request, this is string, but the request
   *   may have been invalid so it might not be a string.
   */

  /**
   * Emitted when an allowlisting request is rejected.
   * @event
   * @type {EventDispatcher<AllowlistingAuthorizationError>}
   */
  onUnauthorized: new _types_js__WEBPACK_IMPORTED_MODULE_7__.EventDispatcher(
    dispatch => {
      dispatchUnauthorized = dispatch;
    },
    () => {
      dispatchUnauthorized = () => {};
    }
  )
});


/***/ }),

/***/ "./sdk/api/browser-features.js":
/*!*************************************!*\
  !*** ./sdk/api/browser-features.js ***!
  \*************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_661741__) => {

"use strict";
__nested_webpack_require_661741__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_661741__.d(__webpack_exports__, {
/* harmony export */   "isRunningInServiceWorker": () => (/* binding */ isRunningInServiceWorker)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_661741__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



let manifest = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getManifest();

function isRunningInServiceWorker() {
  return !!(manifest.background && manifest.background.service_worker);
}


/***/ }),

/***/ "./sdk/api/content-filter.js":
/*!***********************************!*\
  !*** ./sdk/api/content-filter.js ***!
  \***********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_663275__) => {

"use strict";
__nested_webpack_require_663275__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_663275__.d(__webpack_exports__, {
/* harmony export */   "applyContentFilters": () => (/* binding */ applyContentFilters),
/* harmony export */   "injectCSS": () => (/* binding */ injectCSS),
/* harmony export */   "removeCSS": () => (/* binding */ removeCSS),
/* harmony export */   "setSnippetLibrary": () => (/* binding */ setSnippetLibrary)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_663275__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_663275__(/*! adblockpluscore/lib/elemHide.js */ "./core/lib/elemHide.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_663275__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var adblockpluscore_lib_snippets_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_663275__(/*! adblockpluscore/lib/snippets.js */ "./core/lib/snippets.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_663275__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_663275__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_663275__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _debugging_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_663275__(/*! ./debugging.js */ "./sdk/api/debugging.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */












let isolatedLib;
let injectedLib;

function setSnippetLibrary({isolatedCode, injectedCode}) {
  isolatedLib = isolatedCode;
  injectedLib = injectedCode;
}

function generateStylesheet(tabId, previousFrame, frame) {
  let specificOnly = (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICHIDE) != 0;
  let trace = (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_6__.tracingEnabled)(tabId);

  let previousStylesheet;
  if (previousFrame &&
      !(previousFrame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) &&
      !(previousFrame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.ELEMHIDE)) {
    previousStylesheet = _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.elemHide.getStyleSheet(
      previousFrame.hostname,
      specificOnly,
      trace);
  }
  else {
    previousStylesheet = {
      selectors: []
    };
  }

  let styleSheet;
  if (!(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) &&
      !(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.ELEMHIDE)) {
    styleSheet = _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.elemHide.getStyleSheet(
      frame.hostname,
      specificOnly,
      trace);
  }
  else {
    styleSheet = {
      selectors: []
    };
  }

  styleSheet.removedSelectors = previousStylesheet.selectors.filter(
    element => !styleSheet.selectors.includes(element));
  styleSheet.removedCode = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__.createStyleSheet)(styleSheet.removedSelectors);

  styleSheet.addedSelectors = styleSheet.selectors.filter(
    element => !previousStylesheet.selectors.includes(element));
  styleSheet.addedCode = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__.createStyleSheet)(styleSheet.addedSelectors);

  if (_debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.elemHide) {
    let declarationBlock = "{";
    for (let [property, value] of _debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.cssProperties) {
      declarationBlock += `${property}: ${value} !important;`;
    }
    declarationBlock += "}";

    styleSheet.code = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__.createStyleSheet)(
      styleSheet.selectors, declarationBlock);
    styleSheet.removedCode = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__.createStyleSheet)(
      styleSheet.removedSelectors, declarationBlock);
    styleSheet.addedCode = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_1__.createStyleSheet)(
      styleSheet.addedSelectors, declarationBlock);
  }

  return styleSheet;
}

async function executeSnippets(tabId, frameId, previousFrame, frame) {
  let details = {tabId, frameIds: [frameId]};
  let filters = _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.snippets.getFilters(frame.hostname);
  let scripts = filters.map(({script}) => script);
  let environment = {};
  if (_debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.elemHide) {
    environment.debugCSSProperties = _debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.snippetsCssProperties;
  }

  let isolatedDependencies = [];
  let isolated = [];
  let main = [];

  for (let script of scripts) {
    for (let [snippet, ...args] of (0,adblockpluscore_lib_snippets_js__WEBPACK_IMPORTED_MODULE_3__.parseScript)(script)) {
      if (isolatedLib.has(snippet)) {
        let dependency = isolatedLib.get(snippet);
        if (dependency) {
          isolatedDependencies.push(dependency);
        }
        isolated.push([snippet, ...args]);
      }
      if (injectedLib.has(snippet)) {
        main.push([snippet, ...args]);
      }
    }
  }

  let execute = [];
  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting && webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.executeScript) {
    if (isolated.length > 0) {
      if (isolatedDependencies.length) {
        let isolatedDepsPromises = [];
        for (let dependency of isolatedDependencies) {
          isolatedDepsPromises.push(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.executeScript({
            target: details,
            world: "ISOLATED",
            func: dependency
          }));
        }
        await Promise.all(isolatedDepsPromises);
      }

      execute.push(
        webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.executeScript({
          target: details,
          world: "ISOLATED",
          func: isolatedLib,
          args: [environment, ...isolated]
        })
      );
    }

    if (main.length > 0) {
      execute.push(
        webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.executeScript({
          target: details,
          world: "MAIN",
          func: injectedLib,
          args: [environment, ...main]
        })
      );
    }
  }
  else {
    if (isolated.length > 0) {
      const args = JSON.stringify([environment, ...isolated]);
      let code = "";
      // prepend all dependencies before the snippets
      if (isolatedDependencies.length) {
        for (const cb of isolatedDependencies) {
          code += `(${cb})();`;
        }
      }
      code += `(${isolatedLib}).apply(null,${args})`;
      execute.push(
        webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.executeScript(
          tabId,
          {
            frameId,
            code,
            matchAboutBlank: true,
            runAt: "document_start"
          }));
    }

    if (main.length > 0) {
      const args = JSON.stringify([environment, ...main]);
      // stringify injectedLib to escape backticks
      let code = JSON.stringify(injectedLib.toString());
      code = `"(${code.slice(1, -1)}).apply(null,${JSON.stringify(args).slice(1, -1)});"`;
      let executable =
        `function injectSnippetsInMainContext(executable)
          {
            // injecting phases
            let script = document.createElement("script");
            script.type = "application/javascript";
            script.async = false;

            // Firefox 58 only bypasses site CSPs when assigning to 'src',
            // while Chrome 67 and Microsoft Edge (tested on 44.17763.1.0)
            // only bypass site CSPs when using 'textContent'.
            if (typeof netscape != "undefined" && typeof browser != "undefined")
            {
              let url = URL.createObjectURL(new Blob([executable]));
              script.src = url;
              document.documentElement.appendChild(script);
              URL.revokeObjectURL(url);
            }
            else
            {
              script.textContent = executable;
              document.documentElement.appendChild(script);
            }

            document.documentElement.removeChild(script);
          };
          {
            const executable = ${code};
            injectSnippetsInMainContext(executable);
          }`;
      execute.push(
        webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.executeScript(
          tabId,
          {
            frameId,
            code: executable,
            matchAboutBlank: true,
            runAt: "document_start"
          }));
    }
  }

  let request = {tabId, frameId, url: frame.url};
  Promise.all(execute).then(() => filters.forEach(filter => {
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_6__.logItem)(request, filter, {
      docDomain: frame.hostname,
      method: "snippet"
    });
  }), () => {});
}

async function applyContentFilters(tabId, frameId, previousFrame) {
  let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_5__.getFrameInfo)(tabId, frameId);
  let emulatedPatterns = [];
  let tracedSelectors;

  if (frame) {
    let styleSheet = generateStylesheet(tabId, previousFrame, frame);

    if (previousFrame && !(previousFrame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT)) {
      await removeCSS(tabId, frameId, styleSheet.removedCode);
    }

    if (!(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT)) {
      executeSnippets(tabId, frameId, previousFrame, frame);
    }

    if (!(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) &&
      !(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.ELEMHIDE)) {
      injectCSS(tabId, frameId, styleSheet.addedCode);

      for (let {selector, text} of _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.elemHideEmulation.getFilters(
        frame.hostname)) {
        emulatedPatterns.push({selector, text});
      }

      if ((0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_6__.tracingEnabled)(tabId)) {
        tracedSelectors = [];
        for (let selector of styleSheet.addedSelectors) {
          tracedSelectors.push([selector, null]);
        }
        for (let exception of styleSheet.exceptions) {
          tracedSelectors.push([exception.selector, exception.text]);
        }
      }
    }
  }

  let cssProperties;
  if (_debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.elemHide) {
    cssProperties = _debugging_js__WEBPACK_IMPORTED_MODULE_7__.debugOptions.cssProperties;
  }
  return {emulatedPatterns, cssProperties, tracedSelectors};
}

function injectCSS(tabId, frameId, code) {
  let result;

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting && webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.insertCSS) {
    result = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.insertCSS({
      target: {tabId, frameIds: [frameId]},
      css: code,
      origin: "USER"
    });
  }
  else {
    result = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.insertCSS(
      tabId,
      {
        code,
        cssOrigin: "user",
        frameId,
        matchAboutBlank: true,
        runAt: "document_start"
      }
    );
  }

  result.catch(() => {}); // Fails if tab or frame no longer exists
}

async function removeCSS(tabId, frameId, code) {
  let result;

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting && webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.removeCSS) {
    result = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.scripting.removeCSS({
      target: {tabId, frameIds: [frameId]},
      css: code,
      origin: "USER"
    });
  }
  else if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.removeCSS) {
    result = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.removeCSS(
      tabId,
      {
        code,
        cssOrigin: "user",
        frameId,
        matchAboutBlank: true
      }
    );
  }
  else {
    result = Promise.resolve();
  }

  try {
    await result;
  }
  catch (e) {
    // Fails if tab or frame no longer exists
  }
}


/***/ }),

/***/ "./sdk/api/core.js":
/*!*************************!*\
  !*** ./sdk/api/core.js ***!
  \*************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_676895__) => {

"use strict";
__nested_webpack_require_676895__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_676895__.d(__webpack_exports__, {
/* harmony export */   "filterEngine": () => (/* binding */ filterEngine)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_676895__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_676895__(/*! adblockpluscore */ "./core/lib/index.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





let filterEngine = new adblockpluscore__WEBPACK_IMPORTED_MODULE_1__.FilterEngine((function() {
  let features;

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    features = adblockpluscore__WEBPACK_IMPORTED_MODULE_1__.Features.DNR;
  }

  return {features};
})());


/***/ }),

/***/ "./sdk/api/debugging.js":
/*!******************************!*\
  !*** ./sdk/api/debugging.js ***!
  \******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_678677__) => {

"use strict";
__nested_webpack_require_678677__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_678677__.d(__webpack_exports__, {
/* harmony export */   "LOG_COLOR_BLUE": () => (/* binding */ LOG_COLOR_BLUE),
/* harmony export */   "LOG_COLOR_BLUE_BRIGHT": () => (/* binding */ LOG_COLOR_BLUE_BRIGHT),
/* harmony export */   "LOG_COLOR_CYAN": () => (/* binding */ LOG_COLOR_CYAN),
/* harmony export */   "LOG_COLOR_GREEN": () => (/* binding */ LOG_COLOR_GREEN),
/* harmony export */   "LOG_COLOR_MAGENTA": () => (/* binding */ LOG_COLOR_MAGENTA),
/* harmony export */   "LOG_COLOR_RED": () => (/* binding */ LOG_COLOR_RED),
/* harmony export */   "LOG_COLOR_YELLOW": () => (/* binding */ LOG_COLOR_YELLOW),
/* harmony export */   "LOG_LEVEL_ERROR": () => (/* binding */ LOG_LEVEL_ERROR),
/* harmony export */   "LOG_LEVEL_INFO": () => (/* binding */ LOG_LEVEL_INFO),
/* harmony export */   "LOG_LEVEL_WARNING": () => (/* binding */ LOG_LEVEL_WARNING),
/* harmony export */   "debugOptions": () => (/* binding */ debugOptions),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "emitLogEvent": () => (/* binding */ emitLogEvent),
/* harmony export */   "error": () => (/* binding */ error),
/* harmony export */   "info": () => (/* binding */ info),
/* harmony export */   "loadDebugOptions": () => (/* binding */ loadDebugOptions),
/* harmony export */   "log": () => (/* binding */ log),
/* harmony export */   "saveDebugOptions": () => (/* binding */ saveDebugOptions),
/* harmony export */   "warn": () => (/* binding */ warn)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_678677__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/* harmony import */ var adblockpluscore_lib_filterStorage_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_678677__(/*! adblockpluscore/lib/filterStorage.js */ "./core/lib/filterStorage.js");
/* harmony import */ var _io_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_678677__(/*! ./io.js */ "./sdk/api/io.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_678677__(/*! ./info.js */ "./sdk/api/info.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_678677__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_678677__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var _sitekey_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_678677__(/*! ./sitekey.js */ "./sdk/api/sitekey.js");
/* harmony import */ var _subscriptions_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_678677__(/*! ./subscriptions.js */ "./sdk/api/subscriptions.js");
/* eslint-disable no-console */
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */












let defaultDebugOptions = {
  elemHide: false,
  cssProperties: [["background", "#e67370"], ["outline", "solid red"]],
  snippetsCssProperties: [
    ["background", "repeating-linear-gradient(to bottom, #e67370 0," +
     "#e67370 9px, white 9px, white 10px)"],
    ["outline", "solid red"]]
};

let listeners = [];

class DebugEventDispatcher {
  addListener(listener) {
    listeners.push(listener);
  }

  removeListener(listener) {
    let index = listeners.findIndex(existingListener =>
      existingListener == listener
    );

    if (index != -1) {
      listeners.splice(index, 1);
    }
  }
}

/**
 * @ignore
 */
const LOG_LEVEL_INFO = 0;

/**
 * @ignore
 */
const LOG_LEVEL_WARNING = 1;

/**
 * @ignore
 */
const LOG_LEVEL_ERROR = 2;

/**
 * @ignore
 */
const LOG_COLOR_RED = "\x1b[31m";

/**
 * @ignore
 */
const LOG_COLOR_GREEN = "\x1b[32m";

/**
 * @ignore
 */
const LOG_COLOR_YELLOW = "\x1b[33m";

/**
 * @ignore
 */
const LOG_COLOR_BLUE = "\x1b[34m";

/**
 * @ignore
 */
const LOG_COLOR_MAGENTA = "\x1b[35m";

/**
 * @ignore
 */
const LOG_COLOR_CYAN = "\x1b[36m";

/**
 * @ignore
 */
const LOG_COLOR_BLUE_BRIGHT = "\x1b[94m";

const LEVEL_TO_COLOR = new Map([
  // no color for "LOG_LEVEL_INFO" level (using default)
  [LOG_LEVEL_WARNING, LOG_COLOR_YELLOW],
  [LOG_LEVEL_ERROR, LOG_COLOR_RED]
]);

class ConsoleLogger {
  constructor(
    printTimeStamp = true,
    colorize = true,
    levelToColor = LEVEL_TO_COLOR
  ) {
    this._printTimeStamp = printTimeStamp;
    this._colorize = colorize;
    this._levelToColor = levelToColor;
  }

  colorizeMessage(message, color) {
    return color ? `${color}${message}\x1b[0m` : message;
  }

  padStartZero(value, length = 2) {
    return String(value).padStart(length, "0");
  }

  formatTime(ts) {
    return this.padStartZero(ts.getHours()) + ":" +
      this.padStartZero(ts.getMinutes()) + ":" +
      this.padStartZero(ts.getSeconds()) + "." +
      this.padStartZero(ts.getMilliseconds(), 3);
  }

  getListener() {
    return ({message, level, timeStamp, color}) => {
      // Using default level color if no specific color is passed
      let _color = color || this._levelToColor.get(level);
      let colorizedMessage = this._colorize ?
        this.colorizeMessage(message, _color) :
        message;
      let output = this._printTimeStamp ?
        `${this.formatTime(timeStamp)}: ${colorizedMessage}` :
        colorizedMessage;

      switch (level) {
        case LOG_LEVEL_INFO:
          console.info(output);
          break;

        case LOG_LEVEL_WARNING:
          console.warn(output);
          break;

        case LOG_LEVEL_ERROR:
          console.error(output);
          break;
      }
    };
  }
}

const CONSOLE_LOGGER = new ConsoleLogger().getListener();

/**
 * @ignore
 */
function emitLogEvent({message, level, color, timeStamp = new Date()}) {
  for (let listener of listeners) {
    listener({message, level, timeStamp, color});
  }
}

/**
 * Outputs 'information' message
 * @ignore
 * @param {string} message Log message
 * @param {*} color Log output color
 */
function info(message, color) {
  emitLogEvent({message, level: LOG_LEVEL_INFO, color});
}

/**
 * Outputs 'log' message
 * @ignore
 * @param {string} message Log message
 * @param {*} color Log output color
 */
function log(message, color) {
  emitLogEvent({message, level: LOG_LEVEL_INFO, color}); // also "info" level
}

/**
 * Outputs 'warning' message
 * @ignore
 * @param {string} message Log message
 * @param {*} color Log output color
 */
function warn(message, color) {
  emitLogEvent({message, level: LOG_LEVEL_WARNING, color});
}

/**
 * Outputs 'error' message
 * @ignore
 * @param {string} message Log message
 * @param {*} color Log output color
 */
function error(message, color) {
  emitLogEvent({message, level: LOG_LEVEL_ERROR, color});
}

/**
 * @ignore
 */
let debugOptions;

const STORAGE_KEY = "ewe:debugOptions";
let savingPromise = Promise.resolve(null);
let storage = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].storage.local;

/**
 * @ignore
 */
async function saveDebugOptions() {
  await savingPromise;

  let obj = {};
  obj[STORAGE_KEY] = JSON.stringify(debugOptions);
  savingPromise = storage.set(obj);
  await savingPromise;
}

/**
 * @ignore
 */
async function loadDebugOptions() {
  let obj = await storage.get(STORAGE_KEY);
  if (!obj || !obj[STORAGE_KEY]) {
    debugOptions = JSON.parse(JSON.stringify(defaultDebugOptions));
    return;
  }

  debugOptions = JSON.parse(obj[STORAGE_KEY]);
}

let initializationPromise;

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * @ignore
   * Represents a debug log output entry.
   * @typedef {Object} LogEntry
   * @property {string} message Output message.
   * @property {number} level Log level.
   *                          Can be one of `LOG_LEVEL_...` values.
   * @property {Date} timeStamp Timestamp.
   * @property {string|null} color Specific color (ANSI terminal color).
   *                         Can be one of `LOG_COLOR_...` values or `null`.
   */

  /**
   * AddonInfo assigned during start.
   * @type {Object}
   * @property {string} name
   * @property {string} version
   */
  get addonInfo() {
    return {
      name: _info_js__WEBPACK_IMPORTED_MODULE_3__.addonName,
      version: _info_js__WEBPACK_IMPORTED_MODULE_3__.addonVersion,
      bundledSubscriptions: _info_js__WEBPACK_IMPORTED_MODULE_3__.addonBundledSubscriptions,
      bundledSubscriptionsPath: _info_js__WEBPACK_IMPORTED_MODULE_3__.addonBundledSubscriptionsPath,
      manifestVersion: _info_js__WEBPACK_IMPORTED_MODULE_3__.manifestVersion
    };
  },

  /**
   * Causes elements targeted by element hiding, element hiding emulation,
   * or snippets to be highlighted instead of hidden.
   * @param {boolean} enabled Enables or disables debug mode.
   * @returns {Promise} A promise that will resolve once the settings
   *    are saved.
   */
  async setElementHidingDebugMode(enabled) {
    await this.start();
    debugOptions.elemHide = enabled;
    await saveDebugOptions();
  },

  /**
   * Updates the element hiding debug style.
   * @param {Array} cssProperties The css properties for
   *                              the debug element.
   * @param {Array} snippetsCssProperties The css properties for
   *                                      the debug snippet element.
   * @returns {Promise} A promise that will resolve once the settings
   *    are saved.
   */
  async setElementHidingDebugStyle(cssProperties, snippetsCssProperties) {
    await this.start();

    if (cssProperties) {
      debugOptions.cssProperties = cssProperties;
    }

    if (snippetsCssProperties) {
      debugOptions.snippetsCssProperties = snippetsCssProperties;
    }

    await saveDebugOptions();
  },

  /**
   * Resets all of the debug options to their default state.
   * @returns {Promise}
   */
  async clearDebugOptions() {
    await this.start();
    debugOptions = JSON.parse(JSON.stringify(defaultDebugOptions));
    await saveDebugOptions();
  },

  /**
   * @ignore
   * @param {string} text
   */
  async isInFilterStorage(text) {
    let contents = [];
    await _io_js__WEBPACK_IMPORTED_MODULE_2__.IO.readFromFile(adblockpluscore_lib_filterStorage_js__WEBPACK_IMPORTED_MODULE_1__.FilterStorage.sourceFile,
                          line => contents.push(line));
    return contents.some(line => line.includes(text));
  },

  /**
   * @ignore
   * Used internally. Returns a list of warnings in the context of validating
   * that a user has provided the appropriate files to the extension.
   * @param {Array<Recommendation>} [addonInfo.bundledSubscriptions]
   *   A list of subscriptions provided by the integrator.
   * @param {string} [addonInfo.bundledSubscriptionsPath]
   *   A path to subscription files provided by the integrator.
   * @return {Array<String>}
   */
  validateSubscriptions: _subscriptions_js__WEBPACK_IMPORTED_MODULE_7__.validate,

  /**
   * @ignore
   * Used internally. Waits for any pending save actions to complete.
   * @return {Promise} The promise that is resolved once the filter storage
   *   module has saved all items.
   */
  async ensureEverythingHasSaved() {
    await _prefs_js__WEBPACK_IMPORTED_MODULE_5__.awaitSavingComplete();
    await _core_js__WEBPACK_IMPORTED_MODULE_4__.filterEngine.filterStorage.awaitSavingComplete();
    await _sitekey_js__WEBPACK_IMPORTED_MODULE_6__._awaitSavingComplete();
  },

  /**
   * @ignore
   * Initialize debugging.
   */
  async start() {
    if (!initializationPromise) {
      initializationPromise = loadDebugOptions();
    }
    return initializationPromise;
  },

  /**
   * @ignore
   * Return the promise for saving the debugging options.
   * @return {Promise}
   */
  async ensureSaved() {
    await savingPromise;
  },

  /**
   * Emitted when having debug output.
   * @event
   * @type {EventDispatcher<LogEntry>}
   */
  onLogEvent: new DebugEventDispatcher(),

  /**
   * Configurable logger (class) that outputs to console
   */
  ConsoleLogger,

  /**
   * Default logger instance that outputs to console
   */
  CONSOLE_LOGGER
});



/***/ }),

/***/ "./sdk/api/diagnostics.js":
/*!********************************!*\
  !*** ./sdk/api/diagnostics.js ***!
  \********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_691466__) => {

"use strict";
__nested_webpack_require_691466__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_691466__.d(__webpack_exports__, {
/* harmony export */   "BlockableEventDispatcher": () => (/* binding */ BlockableEventDispatcher),
/* harmony export */   "logHiddenElements": () => (/* binding */ logHiddenElements),
/* harmony export */   "logItem": () => (/* binding */ logItem),
/* harmony export */   "loggingEnabled": () => (/* binding */ loggingEnabled),
/* harmony export */   "tracingEnabled": () => (/* binding */ tracingEnabled)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_691466__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_691466__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_691466__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_691466__(/*! ./filters.js */ "./sdk/api/filters.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_691466__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */







let listeners = [];
let defaultOptions = {includeElementHiding: false,
                      includeUnmatched: false,
                      filterType: "blocking",
                      tabId: null};

/**
 * The BlockableEventDispatcher class allows users to listen to
 * filters and requests.
 * @hideconstructor
 */
class BlockableEventDispatcher {
  /**
  * @typedef {Object} BlockableEventOptions
  * @param {boolean} [includeElementHiding=false]
  *   Whether or not element hiding filters accounting for dynamic DOM changes
  *   should also be emitted. This event is emitted after the page has been
  *   fully loaded, and the element hiding filters have been applied. The
  *   expected delay between the filter being applied and the event being
  *   emitted is around two seconds.
  *   Note that this will enable element hiding tracing, which degrades
  *   performance and should only be used to enable ad-hoc diagnostics.
  * @param {boolean} [includeUnmatched=false] Whether or not unmatched requests
  *   should also be emitted. This event is generally emitted after a request is
  *   fully completed. Note that blockable item events may refer to either
  *   requests or documents. Unmatched events only refer to requests. This has
  *   the potentially confusing implication that there may be allowing document
  *   events (eg a $genericblock allowing filter being activated for a document)
  *   as well as an unmatched event for the request that actually loaded the
  *   HTML of the document.
  * @param {string} [filterType="blocking"]
  *   The type of filters to emit. Can be "blocking", "allowing", or "all".
  * @param {Number} [tabId=null]
  *   The tab to filter events for. Element hiding tracing will be limited to
  *   this tab (if `includeElementHiding` is set). If set to `null` events for
  *   all tabs will be considered, and are subject to element hiding tracing
  *   (if `includeElementHiding` is set) which will degrade performance. Note
  *   that in Manifest V3 extensions we expect event listeners to be attached in
  *   the first turn of the event loop. However, it's difficult to have a tabId
  *   in the first turn of the event loop since the tabs APIs are async. This
  *   may make this option unsuitable for MV3.
  */

  /**
   * Attaches a listener function to an event. This listener will be called
   * when the Blockable event is emitted.
   * @param {function} listener The user defined function that will be called
   *                            once the specified event is emitted.
   * @param {BlockableEventOptions} options The filtering conditions to apply
   *                                        when the event is emitted.
   * @example
   * // Logs all blocked requests
   * EWE.reporting.onBlockableItem.addListener(console.log);
   * @example
   * // Log all blockable items of a specific tab for debugging purposes
   * EWE.reporting.onBlockableItem.addListener(
   *   console.log,
   *   {includeElementHiding: true,
   *    includeUnmatched: true,
   *    filterType: "all", tabId}
   * );
   */
  addListener(listener, options) {
    listeners.push({listener, options: {...defaultOptions, ...options}});
  }

  /**
   * Removes the added function. This means the listener will no
   * longer be called by the emitted event.
   * @param {function} listener The user defined function to be removed.
   * @param {Object} options The filtering conditions to apply when
   *                         the event is emitted.
   */
  removeListener(listener, options) {
    let {includeElementHiding, includeUnmatched,
         filterType, tabId} = {...defaultOptions, ...options};

    let index = listeners.findIndex(obj =>
      obj.listener == listener &&
      obj.options.includeElementHiding == includeElementHiding &&
      obj.options.includeUnmatched == includeUnmatched &&
      obj.options.filterType == filterType &&
      obj.options.tabId == tabId
    );

    if (index != -1) {
      listeners.splice(index, 1);
    }
  }
}

function logItem(request, filter, matchInfo = {}) {
  for (let {listener, options} of listeners) {
    let {includeElementHiding, includeUnmatched, filterType, tabId} = options;

    if (tabId != null && tabId != request.tabId) {
      continue;
    }

    if (filter) {
      if (!includeElementHiding && (filter.type == "elemhide" ||
                                    filter.type == "elemhideexception" ||
                                    filter.type == "elemhideemulation")) {
        continue;
      }

      if (filterType != "all" &&
          filterType == "allowing" != (filter.type == "allowing" ||
                                       filter.type == "elemhideexception")) {
        continue;
      }
    }

    if (!includeUnmatched && !filter) {
      continue;
    }

    listener({request, filter: filter && (0,_filters_js__WEBPACK_IMPORTED_MODULE_3__.convertFilter)(filter), matchInfo});
  }
}

function logHiddenElements(selectors, filters, sender) {
  let request = {
    tabId: sender.tab.id,
    frameId: sender.frameId,
    url: sender.url || _frame_state_js__WEBPACK_IMPORTED_MODULE_4__.BLANK_PAGE_URL
  };
  let {hostname} = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__.parseURL)(request.url);
  let matchInfo = {
    docDomain: hostname,
    method: "elemhide"
  };

  if (selectors.length > 0) {
    // The same filter can be listed in multiple subscriptions
    // or can be added by user, so we need to exclude the duplicates.
    let loggedElemHideFilters = [];
    for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.filterStorage.subscriptions()) {
      if (subscription.disabled) {
        continue;
      }

      for (let text of subscription.filterText()) {
        let filter = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_0__.Filter.fromText(text);

        if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_0__.ElemHideFilter &&
            selectors.includes(filter.selector) &&
            filter.isActiveOnDomain(hostname) &&
            !loggedElemHideFilters.includes(filter.text)) {
          loggedElemHideFilters.push(filter.text);
          logItem(request, filter, matchInfo);
        }
      }
    }
  }

  for (let text of filters) {
    logItem(request, adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_0__.Filter.fromText(text), matchInfo);
  }
}

function loggingEnabled(tabId) {
  return listeners.some(({options}) =>
    (options.tabId == null || options.tabId == tabId)
  );
}

function tracingEnabled(tabId) {
  return listeners.some(({options}) =>
    options.includeElementHiding &&
    (options.tabId == null || options.tabId == tabId)
  );
}


/***/ }),

/***/ "./sdk/api/dnr-filters.js":
/*!********************************!*\
  !*** ./sdk/api/dnr-filters.js ***!
  \********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_700426__) => {

"use strict";
__nested_webpack_require_700426__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_700426__.d(__webpack_exports__, {
/* harmony export */   "_dnrSubscriptionUpdate": () => (/* binding */ _dnrSubscriptionUpdate),
/* harmony export */   "addFilters": () => (/* binding */ addFilters),
/* harmony export */   "applyFilterTextUpdate": () => (/* binding */ applyFilterTextUpdate),
/* harmony export */   "clearIsDnrSubscriptionUpdating": () => (/* binding */ clearIsDnrSubscriptionUpdating),
/* harmony export */   "clearRulesetUpdates": () => (/* binding */ clearRulesetUpdates),
/* harmony export */   "disableDynamicRules": () => (/* binding */ disableDynamicRules),
/* harmony export */   "dnrSubscriptionUpdate": () => (/* binding */ dnrSubscriptionUpdate),
/* harmony export */   "dynamicRulesAvailable": () => (/* binding */ dynamicRulesAvailable),
/* harmony export */   "enableAllDisabledStaticRules": () => (/* binding */ enableAllDisabledStaticRules),
/* harmony export */   "enableFilters": () => (/* binding */ enableFilters),
/* harmony export */   "getDynamicFilters": () => (/* binding */ getDynamicFilters),
/* harmony export */   "getDynamicUserFilters": () => (/* binding */ getDynamicUserFilters),
/* harmony export */   "getMetadataForFilter": () => (/* binding */ getMetadataForFilter),
/* harmony export */   "init": () => (/* binding */ init),
/* harmony export */   "isDnrSubscriptionUpdating": () => (/* binding */ isDnrSubscriptionUpdating),
/* harmony export */   "migrateCustomFilters": () => (/* binding */ migrateCustomFilters),
/* harmony export */   "removeAllDynamicFilters": () => (/* binding */ removeAllDynamicFilters),
/* harmony export */   "removeOrDisableFilters": () => (/* binding */ removeOrDisableFilters),
/* harmony export */   "removeSubscriptionsDynamicFilters": () => (/* binding */ removeSubscriptionsDynamicFilters),
/* harmony export */   "restoreDynamicRules": () => (/* binding */ restoreDynamicRules),
/* harmony export */   "setMetadataForFilter": () => (/* binding */ setMetadataForFilter),
/* harmony export */   "testSetDynamicRulesAvailable": () => (/* binding */ testSetDynamicRulesAvailable),
/* harmony export */   "validateFilter": () => (/* binding */ validateFilter)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_700426__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/subscriptionClasses.js */ "./core/lib/subscriptionClasses.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/filterNotifier.js */ "./core/lib/filterNotifier.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_700426__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var adblockpluscore_lib_dnr_index_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/dnr/index.js */ "./core/lib/dnr/index.js");
/* harmony import */ var adblockpluscore_lib_dnr_mapper_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_700426__(/*! adblockpluscore/lib/dnr/mapper.js */ "./core/lib/dnr/mapper.js");
/* harmony import */ var _subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_700426__(/*! ./subscriptions-utils.js */ "./sdk/api/subscriptions-utils.js");
/* harmony import */ var _subscriptions_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_700426__(/*! ./subscriptions.js */ "./sdk/api/subscriptions.js");
/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_10__ = __nested_webpack_require_700426__(/*! ../errors.js */ "./sdk/errors.js");
/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_11__ = __nested_webpack_require_700426__(/*! ./filters.js */ "./sdk/api/filters.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_12__ = __nested_webpack_require_700426__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _filter_diffs_js__WEBPACK_IMPORTED_MODULE_13__ = __nested_webpack_require_700426__(/*! ./filter-diffs.js */ "./sdk/api/filter-diffs.js");
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_14__ = __nested_webpack_require_700426__(/*! ./types.js */ "./sdk/api/types.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_15__ = __nested_webpack_require_700426__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_16__ = __nested_webpack_require_700426__(/*! ./info.js */ "./sdk/api/info.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





















let highestRuleId = 1;

// Filter text to related details (enabled, rule ids, subscription ids, etc) map
let dynamicFilters = new Map();

// Subscription id to last diff update map
let lastDiffUpdates = null;

let initializationPromise;

let getRulesFromFilter = () => {};
if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
  getRulesFromFilter = (0,adblockpluscore_lib_dnr_index_js__WEBPACK_IMPORTED_MODULE_6__.createConverter)({
    isRegexSupported: webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.isRegexSupported
  });
}

async function restoreDynamicRules(subscriptionId) {
  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.subscriptions()) {
    if (subscription.id == subscriptionId) {
      ensureRulesetUpdatesLoaded();

      let lastUpdate = lastDiffUpdates.get(subscription.id);
      if (lastUpdate) {
        await _dnrSubscriptionUpdate(subscription, lastUpdate, true);
      }

      break;
    }
  }
}

async function disableDynamicRules(subscriptionId) {
  let subscriptionDynRules = findDynamicFilters(subscriptionId);
  let {removedDynamicFilters, removeRuleIds} = removeDynamicFilters(
    subscriptionId, [...subscriptionDynRules.keys()]);
  removedDynamicFilters.forEach(text => dynamicFilters.delete(text));
  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules({removeRuleIds});
}

// returns a set of filters (texts) that relate to requested subscription
function findDynamicFilters(subscriptionId) {
  let result = new Set();

  for (let [text, detail] of dynamicFilters.entries()) {
    if (detail && detail.subscriptionIds) {
      let index = detail.subscriptionIds.indexOf(subscriptionId);
      if (index !== -1) {
        result.add(text);
      }
    }
  }

  return result;
}

/**
 * Remove the dynamic filters for a subscription.
 *
 * @param {String} subscriptionId The subscription id.
 * @param {Array<String>} filters The filter text array to remove.
 *
 * @return {Object} The rules that were removed.
 *
 * @private
 */
function removeDynamicFilters(subscriptionId, filters) {
  let removedDynamicFilters = filters.filter(text => {
    let detail = dynamicFilters.get(text);
    if (detail && detail.subscriptionIds) {
      let index = detail.subscriptionIds.indexOf(subscriptionId);
      if (index !== -1) {
        detail.subscriptionIds.splice(index, 1);
      }
      return detail.subscriptionIds.length == 0;
    }
    return false;
  });

  let removeRuleIds = removedDynamicFilters.flatMap(text => {
    let detail = dynamicFilters.get(text);
    return detail ? detail.ruleIds : [];
  });

  return {removedDynamicFilters, removeRuleIds};
}

// URLs of the subscriptions that are currently updating
let dnrSubscriptionUpdating = new Set();

function isDnrSubscriptionUpdating(url) {
  return dnrSubscriptionUpdating.has(url);
}

function clearIsDnrSubscriptionUpdating() {
  dnrSubscriptionUpdating.clear();
}

/**
 * Update a DNR subscription.
 *
 * @param {Subscription} subscription The subscription updated.
 * @param {?object} updates The list of added and removed filter text. If
 *   falsey then nothing happens.
 *
 * @private
 */
async function dnrSubscriptionUpdate(subscription, updates) {
  if (isDnrSubscriptionUpdating(subscription.url)) {
    return;
  }
  dnrSubscriptionUpdating.add(subscription.url);

  try {
    await _dnrSubscriptionUpdate(subscription, updates);
  }
  catch (e) {
    if (e.type === _errors_js__WEBPACK_IMPORTED_MODULE_10__.ERROR_TOO_MANY_FILTERS){
      subscription.downloadStatus = "synchronize_diff_too_many_filters";
      e.rulesAvailable = await dynamicRulesAvailable();
    }
    else {
      subscription.downloadStatus = "synchronize_diff_error";
    }
    // Here we have to decide what to do with this error
    // Some options:
    //  * add the entire error object as a new property of the subscription
    //  * create a new event under EWE.subscription to notify the error
    //  * leave it as it is, the "too_many_filters" status will be enough
  }
  finally {
    dnrSubscriptionUpdating.delete(subscription.url);
  }
}

async function removeSubscriptionsDynamicFilters() {
  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.subscriptions()) {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_2__.SpecialSubscription) {
      continue;
    }

    await disableDynamicRules(subscription.id);
  }
}

async function enableAllDisabledStaticRules() {
  // Requires Chrome 111+ API
  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateStaticRules) {
    return;
  }

  let disableRuleIds = [];
  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.subscriptions()) {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_2__.SpecialSubscription) {
      continue;
    }

    let enableRuleIds =
      await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.getDisabledRuleIds({
        rulesetId: subscription.id
      });

    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateStaticRules({
      rulesetId: subscription.id,
      disableRuleIds,
      enableRuleIds
    });
  }
}

async function _dnrSubscriptionUpdate(
  subscription, updates, skipEmitting) {
  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest || !updates) {
    return;
  }

  // For now we only want to handle subscriptions that are in the
  // recommendations.
  if (!subscription.type) {
    return;
  }

  // We don't have the Chrome 111+ API to update the static rules
  // but this subscription isn't downloadable. So we just can't update.
  if (!subscription.downloadable &&
      !webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateStaticRules) {
    return;
  }

  // Determine if we need to update static rules.
  let needUpdateStaticRules = !subscription.downloadable;

  let {added, removed} = updates;

  // With some path of code the filter engine might not be initialized
  // if the service worker got awaken.
  await _initializer_js__WEBPACK_IMPORTED_MODULE_12__["default"].start();

  let rollbackCallback = null;
  let filterTextToRuleIdsMapper = null; // to static rules ids

  // The already disabled static rules ids.
  let disabledStaticRulesIds = null;

  // This will contain the text of all the dynamic filters for the subscription
  // and it will be updated to remove those that are still here.
  let knownDynamicFilters = new Set();

  if (needUpdateStaticRules) {
    filterTextToRuleIdsMapper = new adblockpluscore_lib_dnr_mapper_js__WEBPACK_IMPORTED_MODULE_7__.DnrMapper(
      async() => await (0,_subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_8__.getSubscriptionRulesetMap)(subscription.id)
    );
    disabledStaticRulesIds =
      await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.getDisabledRuleIds({
        rulesetId: subscription.id
      });

    ensureRulesetUpdatesLoaded();

    let lastUpdate = lastDiffUpdates.get(subscription.id);

    // All the dynamic filters for this subscription must be removed.
    knownDynamicFilters = findDynamicFilters(subscription.id);

    rollbackCallback = async() => {
      if (!lastUpdate) {
        lastUpdate = {added: [], removed: []};
      }
      await _dnrSubscriptionUpdate(subscription, lastUpdate);
    };
  }

  let filters = await processFilterTexts(
    added, subscription.id, filterTextToRuleIdsMapper);
  if (knownDynamicFilters.size != 0) {
    filters.relateToThisSubscription.forEach(
      text => knownDynamicFilters.delete(text));
  }

  // Adding subscription.id into existing filter
  for (let text of filters.relateToOtherSubscriptions) {
    let filter = dynamicFilters.get(text);
    knownDynamicFilters.delete(text);
    filter.subscriptionIds.push(subscription.id);
  }

  // A union of what is explicitly listed in `removed`
  // and dynamic filters that we had for this subscription previously
  // and not listed in `added` anymore
  let dynamicFiltersToRemove = removed.concat(...knownDynamicFilters.keys());

  // Removing subscription.id from existing filters that are removed.
  let {removedDynamicFilters, removeRuleIds} =
      removeDynamicFilters(subscription.id, dynamicFiltersToRemove);

  if (filters.add.length - removeRuleIds.length >
      await dynamicRulesAvailable()) {
    if (rollbackCallback) {
      await rollbackCallback();
    }
    throw new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError(_errors_js__WEBPACK_IMPORTED_MODULE_10__.ERROR_TOO_MANY_FILTERS);
  }

  // Empty array cause exceptions. Make it `undefined`.
  if (removeRuleIds.length == 0) {
    removeRuleIds = void 0;
  }

  let subscriptionActive = (await _subscriptions_js__WEBPACK_IMPORTED_MODULE_9__["default"].has(subscription.url)) &&
      !subscription.disabled;
  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules(
    {addRules: subscriptionActive ? filters.add : void 0, removeRuleIds}
  );

  if (needUpdateStaticRules) {
    if (removed.length > 0) {
      await filterTextToRuleIdsMapper.load();
    }

    let disableRuleIds = removed.flatMap(text => {
      let ids = filterTextToRuleIdsMapper.get(text);
      return ids ? ids : [];
    });
    // Empty array cause exceptions. Make it `undefined`.
    if (disableRuleIds.length == 0) {
      disableRuleIds = void 0;
    }

    let enableRuleIds = [...filters.staticRulesToEnable];
    // Reenable the disabled rules to reset the state:
    // `browser.declarativeNetRequest.updateStaticRules` will handle this
    // properly.
    enableRuleIds.push(...disabledStaticRulesIds);

    // This is Chrome 111+ only.
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateStaticRules({
      rulesetId: subscription.id,
      disableRuleIds,
      enableRuleIds
    });
  }

  removedDynamicFilters.forEach(text => dynamicFilters.delete(text));

  if (subscriptionActive) {
    filters.details.forEach(details => {
      let {useFilterEngine, filter, ruleIds, enabled} = details;

      setHighestRuleId(ruleIds);
      dynamicFilters.set(filter.text,
                         {ruleIds, useFilterEngine, enabled, metadata: {},
                          subscriptionIds: [subscription.id]});
    });
  }

  let storageUpdate = await applyFilterTextUpdate(subscription, updates);

  lastDiffUpdates.set(subscription.id, updates);
  storeRulesetUpdates();
  storeDynamicFilters();

  if (!skipEmitting) {
    // `dnrSubscriptionUpdate()` is currently used for some internal routines,
    // eg. restoring the dynamic rules for the subscription, which does not
    // mean there was a subscription update actually (EE-163), so we might
    // skip emitting the event.
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.emit("subscription.updated", subscription, storageUpdate);
  }
}

/**
 * Apply the filter text update to the subscription.
 *
 * @param {object} subscription The subscription to apply the update to
 * @param {FilterDiffs} updates The update to apply.
 */
async function applyFilterTextUpdate(subscription, updates) {
  ensureRulesetUpdatesLoaded();

  // apply the update to the storage
  let base = lastDiffUpdates.get(subscription.id);
  let storageUpdate;
  if (base) {
    storageUpdate = (0,_filter_diffs_js__WEBPACK_IMPORTED_MODULE_13__.calculateDiff)(base, updates);
  }
  else {
    storageUpdate = {
      added: updates.added,
      removed: updates.removed
    };
  }

  for (let text of storageUpdate.removed) {
    let index = subscription.findFilterTextIndex(text);
    if (index >= 0) {
      subscription.deleteFilterAt(index);
    }
  }

  for (let text of storageUpdate.added) {
    subscription.addFilterText(text);
  }

  await _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.saveToDisk();
  return storageUpdate;
}

function validateFilter(filter) {
  if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.InvalidFilter) {
    return new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError("invalid_filter", filter.reason, filter.option);
  }

  if ((0,adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.isActiveFilter)(filter) && filter.domains) {
    for (let domain of filter.domains.keys()) {
      if (domain && !(0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_3__.isValidHostname)(domain)) {
        return new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError("invalid_domain", domain);
      }
    }
  }

  return null;
}

async function removeAllDynamicFilters() {
  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    return;
  }

  dynamicFilters = new Map();
  _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.dynamic_filters = [];

  let rules = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.getDynamicRules();
  if (rules.length == 0) {
    return;
  }

  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: rules.map(r => r.id)
  });

  return rules;
}

function setHighestRuleId(ruleIds) {
  if (!ruleIds) {
    return;
  }

  for (let id of ruleIds) {
    if (highestRuleId < id) {
      highestRuleId = id;
    }
  }
}

function storeDynamicFilters() {
  let storageArray = [];
  storageArray.push(...dynamicFilters);
  _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.dynamic_filters = storageArray;
}

function storeRulesetUpdates() {
  let storageArray = [];
  storageArray.push(...lastDiffUpdates);
  _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.ruleset_updates = storageArray;
}

function ensureRulesetUpdatesLoaded() {
  if (!lastDiffUpdates) {
    loadRulesetUpdates();
  }
}

function loadRulesetUpdates() {
  let rulesetUpdatesArray = _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.ruleset_updates;
  if (!Array.isArray(rulesetUpdatesArray)) {
    rulesetUpdatesArray = [];
  }

  lastDiffUpdates = new Map(rulesetUpdatesArray);
}

function clearRulesetUpdates() {
  ensureRulesetUpdatesLoaded();
  lastDiffUpdates.clear();
  _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.ruleset_updates = [];
}

function init() {
  if (!initializationPromise) {
    initializationPromise = (async() => {
      if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
        return;
      }

      let dynamicFilterArray = _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.dynamic_filters;
      if (Array.isArray(dynamicFilterArray) &&
          dynamicFilterArray.length > 0) {
        dynamicFilters = new Map(dynamicFilterArray);
      }
      else {
        // DNR rules persist after the extension is uninstalled. The same cannot
        // be said for storage. To be safe, if we have no record of dynamic
        // filters let's clear any DNR rules too.
        await removeAllDynamicFilters();
      }

      for (let {ruleIds} of dynamicFilters.values()) {
        setHighestRuleId(ruleIds);
      }

      adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on("subscription.dnrUpdated", dnrSubscriptionUpdate);
      adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on("subscription.diffReceived", dnrSubscriptionUpdate);
    })();
  }

  return initializationPromise;
}

async function getRules(filter) {
  let ruleIds = [];
  let filterRules = [];

  // "sitekey" option is not supported in DNR
  if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.URLFilter && !filter.sitekeys) {
    let result = await getRulesFromFilter(filter.text);
    if (result.name == "Error") {
      let {option} = result.detail;
      throw new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError(result.message, result.detail.text, option);
    }

    for (let rule of result) {
      let id = ++highestRuleId;
      rule.id = id;
      ruleIds.push(id);
      filterRules.push(rule);
    }
  }

  return {filterRules, ruleIds};
}

/**
 * @typedef {Object} FilterDetails
 * @property {Filter} filter The filter object
 * @property {Array.<number>} ruleIds The rule ids for the filter in
 *   the dynamic ruleset.
 * @property {boolean} enabled Whether the filter is enabled or
 *   disabled.
 *
 * @typedef {Object} ProcessedFilters
 * @property {Array.<Object>} add Rules to add to the dynamic ruleset
 * @property {Array.<string>} exist Filters that exists.
 * @property {Array.<string>} existOnOtherSubscription Filters that
 *   exist on other subscriptions.
 * @property {Array.<number>} staticRulesToEnable Static rules to enable.
 * @property {Array.<FilterDetails>} details Details of the filters.
 */
/**
 * Process the filter texts.
 *
 * @param {Array.<string>} texts The array of filter texts.
 * @param {?string} subscriptionId The optional subscription ID.
 * @param {?mapper} mapper The DNR mapper for the subscription. If null then
 *   this doesn't check for static rules to enable or disable.
 *
 * @ignore
 * @returns {ProcessedFilters} The processed filters.
 */
async function processFilterTexts(texts, subscriptionId = null, mapper = null) {
  let details = [];
  let add = [];

  // known filter texts that relate to this subscription
  let relateToThisSubscription = [];

  // known filter texts that relate to other subscriptions
  let relateToOtherSubscriptions = [];

  let staticRulesToEnable = [];
  let processedFilterTexts = new Set();

  texts = texts.map(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.normalize);
  for (let text of texts) {
    // skip processing possible filter text duplicates
    if (processedFilterTexts.has(text)) {
      continue;
    }

    let filterDetails = dynamicFilters.get(text);
    let filterIsKnown = (filterDetails != null);
    if (filterDetails) {
      let subscriptionIds = filterDetails.subscriptionIds || [null];
      if (subscriptionIds.includes(subscriptionId)) {
        relateToThisSubscription.push(text);
      }
      else {
        relateToOtherSubscriptions.push(text);
      }
    }

    if (mapper) {
      await mapper.load();
      let staticRuleIds = mapper.get(text);
      if (staticRuleIds) {
        staticRulesToEnable.push(...staticRuleIds);
        filterIsKnown = true;
      }
    }

    if (filterIsKnown) {
      continue;
    }

    let filter = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.fromText(text);
    let error = validateFilter(filter);
    if (error) {
      throw error;
    }

    if (!_core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.filterState.isEnabled(text)) {
      details.push({filter, ruleIds: [], enabled: false});
    }
    else {
      let {filterRules, ruleIds} = await getRules(filter);
      if (filterRules) {
        add.push(...filterRules);
      }
      details.push({filter, ruleIds, enabled: true});
    }

    processedFilterTexts.add(text);
  }

  return {
    add,
    relateToThisSubscription,
    relateToOtherSubscriptions,
    staticRulesToEnable,
    details
  };
}

let TESTING_MAX_DYNAMIC_RULES = 0;

/**
 * For testing purpose, set the a maximum number of dynamic
 * rules. This value is used by `dynamicRulesAvailable()`.
 * @param {number} num The maximum number of dynamic rules. A value of
 *   `0` just unset it and uses the "system" default which is
 *   `browser.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES`
 *   on Chromium < 121/Firefox or
 *   `browser.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES`
 *   on more recent versions.
 *
 * @private
 */
function testSetDynamicRulesAvailable(num) {
  TESTING_MAX_DYNAMIC_RULES = num;
}

async function dynamicRulesAvailable() {
  let {declarativeNetRequest} = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__;
  if (!declarativeNetRequest) {
    return Infinity;
  }

  let maxRules = TESTING_MAX_DYNAMIC_RULES > 0 ?
      TESTING_MAX_DYNAMIC_RULES :
      (0,_info_js__WEBPACK_IMPORTED_MODULE_16__.isFirefox)() ?
        declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES :
        (0,_info_js__WEBPACK_IMPORTED_MODULE_16__.getBrowserVersion)()[0] < 121 ? // Chromium or edge: EE-315
          declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES :
          declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES;

  let used = (await declarativeNetRequest.getDynamicRules()).length +
               (await declarativeNetRequest.getSessionRules()).length;
  return maxRules - used;
}

async function addFilters(texts, metadata) {
  await init();
  let filters = await processFilterTexts(texts);
  if (filters.relateToThisSubscription.length > 0) {
    throw new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError(_errors_js__WEBPACK_IMPORTED_MODULE_10__.ERROR_DUPLICATE_FILTERS);
  }

  let {length} = filters.add;
  if (length > 0) {
    // always false when !browser.declarativeNetRequest
    if (length > await dynamicRulesAvailable()) {
      throw new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError(_errors_js__WEBPACK_IMPORTED_MODULE_10__.ERROR_TOO_MANY_FILTERS);
    }

    // so that this would throw the right error in case
    // browser.declarativeNetRequest doesn't exist or if
    // the API returned a different error instead
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules({
      addRules: filters.add
    });
  }

  for (let text of filters.relateToOtherSubscriptions) {
    let filter = dynamicFilters.get(text);
    if (!filter.subscriptionIds) {
      filter.subscriptionIds = [];
    }
    filter.subscriptionIds.push(null);
  }

  let subscription;
  for (let filterDetails of filters.details) {
    let {filter, ruleIds, enabled} = filterDetails;
    subscription = await _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.addFilter(filter, subscription);

    setHighestRuleId(ruleIds);
    dynamicFilters.set(filter.text, {ruleIds, enabled, metadata,
                                     subscriptionIds: [null]});
  }

  storeDynamicFilters();
}

function setMetadataForFilter(text, metadata) {
  let details = dynamicFilters.get(text);
  if (!details) {
    throw new _types_js__WEBPACK_IMPORTED_MODULE_14__.FilterError(_errors_js__WEBPACK_IMPORTED_MODULE_10__.ERROR_FILTER_NOT_FOUND);
  }

  let oldMetadata = details.metadata;
  details.metadata = metadata;
  _filters_js__WEBPACK_IMPORTED_MODULE_11__.onChangedFilter.emit({...adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.fromText(text), metadata, oldMetadata},
                       "metadata");

  storeDynamicFilters();
}

function getMetadataForFilter(text) {
  let details = dynamicFilters.get(text);
  if (!details) {
    return null;
  }

  let metadata = details.metadata;
  return (typeof metadata != "undefined") ? metadata : null;
}

async function removeOrDisableFilters(texts, remove = true) {
  await init();

  let filtersToRemove = texts.map(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.normalize);
  let ruleIdsToRemove = [];
  for (let text of filtersToRemove) {
    if (!dynamicFilters.has(text)) {
      continue;
    }

    for (let ruleId of dynamicFilters.get(text).ruleIds) {
      ruleIdsToRemove.push(ruleId);
    }

    let details = dynamicFilters.get(text);

    if (remove) {
      // Removing existing filter
      if (details) {
        if (!details.subscriptionIds) {
          details.subscriptionIds = [];
        }

        let index = details.subscriptionIds.indexOf(null);
        if (index !== -1) {
          details.subscriptionIds.splice(index, 1);
        }
      }
      // Removing filter only if subscriptionIds array is empty
      if (details.subscriptionIds && details.subscriptionIds.length == 0) {
        _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.removeFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.fromText(text));
        dynamicFilters.delete(text);
      }
      else if (!details.enabled) {
        await enableFilters([text]);
      }
    }
    else {
      // Disabling filter
      _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.filterState.setEnabled(text, false);

      details.enabled = false;
      details.ruleIds = [];
      dynamicFilters.set(text, details);
    }
  }

  if (ruleIdsToRemove.length > 0) {
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: ruleIdsToRemove
    });
  }

  storeDynamicFilters();
}

async function enableFilters(texts) {
  await init();

  let rules = [];

  for (let text of texts) {
    let normalized = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.normalize(text);
    let details = dynamicFilters.get(normalized);

    if (!details || details.enabled) {
      continue;
    }

    let filter = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.fromText(normalized);
    _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.filterState.setEnabled(filter.text, true);

    let {filterRules, ruleIds} = await getRules(filter);
    rules.push(...filterRules);

    setHighestRuleId(ruleIds);
    dynamicFilters.set(filter.text, {ruleIds, enabled: true});
  }

  if (rules.length == 0) {
    return;
  }

  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest.updateDynamicRules({
    addRules: rules
  });

  storeDynamicFilters();
}

async function getDynamicFilters() {
  await init();
  return dynamicFilters;
}

async function getDynamicUserFilters() {
  await init();
  let dynamicUserFilters = new Map();

  for (let [filterText, details] of dynamicFilters.entries()) {
    if (!details.subscriptionIds || details.subscriptionIds.includes(null)) {
      dynamicUserFilters.set(filterText, details);
    }
  }
  return dynamicUserFilters;
}

async function migrateCustomFilters() {
  let filters = [];

  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.subscriptions()) {
    if (!(subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_2__.SpecialSubscription)) {
      continue;
    }

    for (let text of subscription.filterText()) {
      filters.push({
        text,
        metadata: subscription.metadata,
        disabled: _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.filterState.isDisabledForSubscription(text, subscription.url)
      });
    }
  }

  for (let filter of filters) {
    try {
      _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.filterStorage.removeFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.Filter.fromText(filter.text));
      await addFilters([filter.text], filter.metadata);
      if (filter.disabled) {
        await (0,_filters_js__WEBPACK_IMPORTED_MODULE_11__.disableFilter)(filter.text);
      }
    }
    catch (e) {
      let errors = _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_filter_errors;
      errors.push({error: e.message, filter});
      _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_filter_errors = errors;
    }
  }
}


/***/ }),

/***/ "./sdk/api/dnr-request-reporter.js":
/*!*****************************************!*\
  !*** ./sdk/api/dnr-request-reporter.js ***!
  \*****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_733761__) => {

"use strict";
__nested_webpack_require_733761__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_733761__.d(__webpack_exports__, {
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_733761__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_733761__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_733761__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_733761__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _request_filter_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_733761__(/*! ./request-filter.js */ "./sdk/api/request-filter.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_733761__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_733761__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_733761__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */












function getContext(details) {
  let contentType = (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.getRequestContentType)(details);

  if (details.type == "main_frame" || details.type == "sub_frame") {
    let parentFrame = (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.getParentFrameInfoFromWebrequestDetails)(details);
    let {hostname: parentHostname} = parentFrame || {};
    let initiator = details.documentUrl || (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.sanitizeInitiator)(details.initiator);
    // In cross-origin requests, Chrome's initiator has the correct url domain
    let urlInfo = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_7__.parseURL)(initiator || details.url);
    let hostname = parentHostname || urlInfo.hostname;

    let docDomain = details.type == "main_frame" ? null : hostname;

    let specificOnlyFilter = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
      details.url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.GENERICBLOCK, hostname, null
    );
    let allowingDocumentFilter = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
      details.url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.DOCUMENT, hostname, null
    );
    if (!allowingDocumentFilter && parentFrame &&
        parentFrame.allowingDocumentFilter) {
      allowingDocumentFilter = parentFrame.allowingDocumentFilter;
    }

    let specificOnly = !!specificOnlyFilter;

    return {
      allowingDocumentFilter,
      specificOnly,
      docDomain,
      contentType
    };
  }

  let frame = (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.getFrameInfoFromWebrequestDetails)(details);
  if (!frame) {
    let allowingDocumentFilter = null;
    let specificOnly = false;
    let docDomain = null;

    let documentUrl = details.documentUrl ||
        (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.sanitizeInitiator)(details.initiator);
    if (documentUrl) {
      let urlInfo = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_7__.parseURL)(documentUrl);
      docDomain = urlInfo.hostname;

      allowingDocumentFilter = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
        documentUrl, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.DOCUMENT, docDomain, null
      );

      specificOnly = Boolean(_core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
        documentUrl, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.GENERICBLOCK, docDomain, null
      ));
    }

    return {
      allowingDocumentFilter,
      specificOnly,
      docDomain,
      contentType
    };
  }

  let allowingDocumentFilter = frame.allowingDocumentFilter;
  let specificOnly = (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.GENERICBLOCK) != 0;
  let docDomain = frame.hostname;

  return {
    allowingDocumentFilter,
    specificOnly,
    docDomain,
    contentType
  };
}

async function onBeforeRedirect(details) {
  if (!(0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.loggingEnabled)(details.tabId)) {
    return;
  }

  await _initializer_js__WEBPACK_IMPORTED_MODULE_3__["default"].start();

  if (!details.redirectUrl.startsWith("data:")) {
    return;
  }

  let {
    allowingDocumentFilter,
    specificOnly,
    docDomain,
    contentType
  } = getContext(details);

  if (allowingDocumentFilter) {
    // Our filters would have allowlisted this, so the redirect isn't
    // our filters. Nothing to log here.
    return;
  }

  let potentialFilters = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.search(
    details.url, contentType, docDomain, null, specificOnly, "blocking"
  );
  for (let filter of potentialFilters.blocking) {
    if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__.BlockingFilter && typeof filter.rewrite == "string") {
      let rewrittenUrl = filter.rewriteUrl(details.url);
      if (rewrittenUrl == details.redirectUrl) {
        let matchInfo = {
          docDomain, specificOnly, method: "request", rewrittenUrl
        };
        (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, filter, matchInfo);
        return;
      }
    }
  }
}

async function onErrorOccurred(details) {
  if (!(0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.loggingEnabled)(details.tabId)) {
    return;
  }

  await _initializer_js__WEBPACK_IMPORTED_MODULE_3__["default"].start();

  let {
    allowingDocumentFilter,
    specificOnly,
    docDomain,
    contentType
  } = getContext(details);

  if (allowingDocumentFilter) {
    // Our filters would have allowlisted this, so the error event
    // isn't from our filters blocking something. Nothing to log here.
    return;
  }

  let potentialFilters = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.search(
    details.url, contentType, docDomain, null, specificOnly, "blocking"
  );
  for (let filter of potentialFilters.blocking) {
    let matchInfo = {docDomain, specificOnly, method: "request"};
    if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__.BlockingFilter && typeof filter.rewrite != "string") {
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, filter, matchInfo);
      return;
    }
  }
}

async function onCompleted(details) {
  if (!(0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.loggingEnabled)(details.tabId)) {
    return;
  }

  await _initializer_js__WEBPACK_IMPORTED_MODULE_3__["default"].start();

  let {
    allowingDocumentFilter,
    specificOnly,
    docDomain,
    contentType
  } = getContext(details);

  if (allowingDocumentFilter) {
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, allowingDocumentFilter, {
      docDomain,
      method: "allowing",
      specificOnly
    });
    return;
  }

  let filter = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
    details.url, contentType, docDomain, null, specificOnly, true
  );
  if (filter) {
    let matchInfo = {docDomain, specificOnly, method: "request"};
    if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__.AllowingFilter) {
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, filter, matchInfo);
    }
    return;
  }

  if (details.type == "main_frame" || details.type == "sub_frame") {
    // CSP filters could apply in this case

    let cspTypeMask = adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_5__.contentTypes.CSP | (0,_request_filter_js__WEBPACK_IMPORTED_MODULE_4__.getRequestContentType)(details);
    let hostname = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_7__.parseURL)(details.url).hostname;
    let cspMatchInfo = {docDomain: docDomain || hostname,
                        specificOnly, method: "csp"};

    let allowingCspFilter = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.match(
      details.url, cspTypeMask, docDomain, null, specificOnly, true
    );
    if (allowingCspFilter && allowingCspFilter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__.AllowingFilter) {
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, allowingCspFilter, cspMatchInfo);
      return;
    }

    let cspFilters = _core_js__WEBPACK_IMPORTED_MODULE_2__.filterEngine.defaultMatcher.search(
      details.url, cspTypeMask, hostname, null, specificOnly, "blocking"
    );

    let appliedCspFilters = false;
    for (let cspFilter of cspFilters.blocking) {
      let cspFilterWasApplied = details.responseHeaders.some(header => {
        return header.name.toLowerCase() == "content-security-policy" &&
          header.value == cspFilter.csp;
      });
      if (cspFilterWasApplied) {
        (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, cspFilter, cspMatchInfo);
        appliedCspFilters = true;
      }
    }

    if (appliedCspFilters) {
      return;
    }
  }

  let matchInfo = {
    docDomain,
    method: "unmatched",
    specificOnly
  };
  (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_1__.logItem)(details, null, matchInfo);
}

let started = false;

/**
 * Starts listening for filters to log onBlockableItem events. Actual
 * blocking should be done using the declarativeNetRequest API.
 */
function start() {
  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest || started) {
    return;
  }

  let eventArgs = {
    types: Object.values(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.ResourceType),
    urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]
  };

  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onBeforeRedirect.addListener(onBeforeRedirect, eventArgs);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onErrorOccurred.addListener(onErrorOccurred, eventArgs);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onCompleted.addListener(onCompleted, eventArgs, ["responseHeaders"]);

  started = true;
}


/***/ }),

/***/ "./sdk/api/filter-diffs.js":
/*!*********************************!*\
  !*** ./sdk/api/filter-diffs.js ***!
  \*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_745391__) => {

"use strict";
__nested_webpack_require_745391__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_745391__.d(__webpack_exports__, {
/* harmony export */   "calculateDiff": () => (/* binding */ calculateDiff)
/* harmony export */ });
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * A difference from filters.
 * @typedef {Object} FilterDiffs
 * @property {?string} type The type. Only the value "diff" is
 *   supported, and denote this is a difference from the static
 *   filtering rules.
 * @property {Array<string>} added Added filters.
 * @property {Array<string>} removed Removed filters.
 */

/**
 * Calculate the difference by removing the base
 * from the update.
 *
 * @param {FilterDiffs} base The base diff, ie the state of the already
 *   applied update. Must be of type `diff`.
 * @param {FilterDiffs} update The update. Must be of type `diff`.
 * @return {FilterDiffs}
 * @throws {Error} Will throw an error if the updates are not of type
 *   "diff".
 */
function calculateDiff(base, update) {
  let updateAdded = new Set(update.added);
  let updateRemoved = new Set(update.removed);
  let baseAdded = new Set(base.added);
  let baseRemoved = new Set(base.removed);

  // Symmetric difference of the added sets.
  base.added.forEach(element => {
    if (updateAdded.has(element)) {
      updateAdded.delete(element);
      baseAdded.delete(element);
    }
  });
  // Symmetric difference of the removed sets.
  base.removed.forEach(element => {
    if (updateRemoved.has(element)) {
      updateRemoved.delete(element);
      baseRemoved.delete(element);
    }
  });

  // What is no longer removed must be added back.
  let added = [...updateAdded.keys()].concat(...baseRemoved.keys());

  // What is no longer added must be removed.
  let removed = [...updateRemoved.keys()].concat(...baseAdded.keys());

  return {added, removed};
}


/***/ }),

/***/ "./sdk/api/filters.js":
/*!****************************!*\
  !*** ./sdk/api/filters.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_748108__) => {

"use strict";
__nested_webpack_require_748108__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_748108__.d(__webpack_exports__, {
/* harmony export */   "convertFilter": () => (/* binding */ convertFilter),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "disableFilter": () => (/* binding */ disableFilter),
/* harmony export */   "onChangedFilter": () => (/* binding */ onChangedFilter)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_748108__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/subscriptionClasses.js */ "./core/lib/subscriptionClasses.js");
/* harmony import */ var adblockpluscore_lib_matcher_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/matcher.js */ "./core/lib/matcher.js");
/* harmony import */ var adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/filterNotifier.js */ "./core/lib/filterNotifier.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_748108__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_748108__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_748108__(/*! ./types.js */ "./sdk/api/types.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_748108__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/* harmony import */ var _dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__ = __nested_webpack_require_748108__(/*! ./dnr-filters.js */ "./sdk/api/dnr-filters.js");
/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_11__ = __nested_webpack_require_748108__(/*! ../errors.js */ "./sdk/errors.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_12__ = __nested_webpack_require_748108__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

















/**
 * @ignore
 * @param {*} filter Filter object
 * @returns {*} Plain filter object
 */
function convertFilter(filter) {
  return {
    text: filter.text,
    enabled: typeof filter.disabled == "undefined" ? null : !filter.disabled,
    slow: filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.URLFilter && (0,adblockpluscore_lib_matcher_js__WEBPACK_IMPORTED_MODULE_4__.isSlowFilter)(filter),
    type: filter.type,
    thirdParty: filter.thirdParty != null ? filter.thirdParty : null,
    selector: filter.selector || null,
    csp: filter.csp || null
  };
}

function makeFilterListener(dispatch) {
  return filter => dispatch(convertFilter(filter));
}

function makeSubListener(dispatch) {
  return subscription => {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.SpecialSubscription) {
      for (let text of subscription.filterText()) {
        dispatch(convertFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(text)));
      }
    }
  };
}

async function disable(texts) {
  if (!Array.isArray(texts)) {
    texts = [texts];
  }

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.removeOrDisableFilters)(texts, false);
    return;
  }

  for (let text of texts) {
    let normalized = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.normalize(text);
    _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.filterStorage.filterState.setEnabled(normalized, false);
  }
}

/**
 * @ignore
 */
const disableFilter = disable;

let onChanged = new _types_js__WEBPACK_IMPORTED_MODULE_8__.EventDispatcher(dispatch => {
  adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("filterState.enabled", (text, enabled) => {
    dispatch({...convertFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(text)), enabled}, "enabled");
  });

  adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("subscription.metadata", (subscription, value, oldValue) => {
    for (let filter of subscription.filterText()) {
      dispatch({
        ...convertFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(filter)),
        metadata: value, oldMetadata: oldValue
      }, "metadata");
    }
  });
});

/**
 * @ignore
 */
let onChangedFilter = onChanged;

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * Represents a single filter rule and its state.
   * @typedef {Object} Filter
   * @property {string} text A {@link https://help.eyeo.com/adblockplus/how-to-write-filters|filter}
   *                         rule that specifies what content
   *                         to block or to allow. Used to identify a filter.
   * @property {boolean|null} enabled Indicates whether this filter would
   *                                  be applied. Filters are enabled by
   *                                  default. For comment filters returned
   *                                  value is null.
   * @property {boolean} slow Indicates that this filter is not subject to an
   *                          internal optimization. Filters that are
   *                          considered slow should be avoided. Only URLFilters
   *                          can be slow.
   * @property {string} type The filter {@link https://gitlab.com/eyeo/adblockplus/abc/adblockpluscore/-/jobs/artifacts/0.6.0/file/build/docs/module-filterClasses.Filter.html?job=docs#type|type}
   * @property {boolean|null} thirdParty True when the filter applies to
   *                          third-party, false to first-party, null otherwise.
   * @property {string|null} selector CSS selector for the HTML elements that
   *                                  will be hidden.
   * @property {string|null} csp Content Security Policy to be injected.
   */

  /**
   * Adds one or multiple filters from texts.
   * @param {string|[string]} texts The filter rules to be added.
   * @param {?Object} metadata Extra data to associate with a filter.
   * @return {Promise}
   * @throws {FilterError|Error} The first filter to add that either failed
   *   validation (FilterError) or that is not supported by the DNR (Error).
   *   An error will be thrown for duplicated filters.
   *   If the reason is "filter_invalid_wildcard" that means filter either has
   *   more than 1 "*" or "*" is placed in an unsupported place.
   */
  async add(texts, metadata) {
    if (!Array.isArray(texts)) {
      texts = [texts];
    }

    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.addFilters)(texts, metadata);
      return;
    }

    let filters = [];
    for (let text of texts) {
      let normalized = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.normalize(text);
      let filter = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(normalized);
      let error = (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.validateFilter)(filter);

      if (error) {
        throw error;
      }

      filters.push(filter);
    }

    let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine;

    if (!metadata) {
      if (filterStorage.filtersExist(filters).length > 0) {
        throw new _types_js__WEBPACK_IMPORTED_MODULE_8__.FilterError(_errors_js__WEBPACK_IMPORTED_MODULE_11__.ERROR_DUPLICATE_FILTERS);
      }

      for (let filter of filters) {
        await filterStorage.addFilter(filter);
      }
    }
    else {
      try {
        await filterStorage.addFiltersWithMetadata(filters, metadata);
      }
      catch (e) {
        throw new _types_js__WEBPACK_IMPORTED_MODULE_8__.FilterError(e.message);
      }
    }
  },

  /**
   * Set an extra data associated with an added filter.
   * @param {string} text filter text to set metadata for.
   * @param {Object} metadata Extra data to associate with a filter.
   * @returns {Promise<void>} Nothing is done for not added filter.
   * @throws {FilterError} An error will be thrown for not added filter.
   */
  async setMetadata(text, metadata) {
    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.setMetadataForFilter)(text, metadata);
      return;
    }

    let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine;

    try {
      await filterStorage.setMetadataForFilter(text, metadata);
    }
    catch (e) {
      if (e.message == _errors_js__WEBPACK_IMPORTED_MODULE_11__.ERROR_FILTER_NOT_FOUND) {
        // filter might be added without a metadata first,
        // so we're trying to make it working in a non-surprising way:
        // by removing the existing filter and readding it with a metadata.
        let filter = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.normalize(text));
        if (filterStorage.filtersExist([filter]).length > 0) {
          await filterStorage.removeFilter(filter);
          await this.add([text], metadata);
          return;
        }
      }
      throw new _types_js__WEBPACK_IMPORTED_MODULE_8__.FilterError(e.message);
    }
  },

  /**
   * Returns an extra data associated with a filter.
   * @param {string} text The filter text to get metadata for.
   * @return {Promise<?Object>}
   */
  async getMetadata(text) {
    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      return (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.getMetadataForFilter)(text);
    }

    return await _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.filterStorage.getMetadataForFilter(text);
  },

  /**
   * Returns an array of user filter objects.
   * @return {Promise<Array<Filter>>}
   */
  async getUserFilters() {
    let result = [];

    for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.filterStorage.subscriptions()) {
      if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.SpecialSubscription) {
        for (let text of subscription.filterText()) {
          result.push(convertFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(text)));
        }
      }
    }

    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      for (let [text, details] of (await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.getDynamicUserFilters)()).entries()) {
        if (!result.find(filter => filter.text == text)) {
          let filter = convertFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(text));
          filter.enabled = filter.type == "comment" ? null : details.enabled;

          result.push(filter);
        }
      }
    }

    return result;
  },

  /**
   * Returns the allowing filters that will be effective
   * when the given document will be reloaded.
   * @param {number} tabId The id of the tab to lookup.
   * @param {Object} [options]
   * @param {number} [options.frameId=0] The id of the frame to lookup.
   * @param {Array<string>} [options.types=["document"]] The types of filters
   *   to consider. These can be any of "document", "elemhide", "genericblock",
   *   and "generichide".
   * @return {Promise<Array<string>>}
   */
  async getAllowingFilters(tabId, options = {}) {
    let {frameId, types} = {frameId: 0, types: ["document"], ...options};
    let filters = new Set();
    let mask = types.reduce((a, b) => a | adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_6__.contentTypes[b.toUpperCase()], 0);

    for (let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_9__.getFrameInfo)(tabId, frameId); frame;
         frame = frame.parent) {
      let parentHostname = frame.parent && frame.parent.hostname;
      let docDomain = parentHostname || frame.hostname;
      let matches = _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.defaultMatcher.search(
        frame.url, mask, docDomain, frame.sitekey, false, "allowing");

      for (let filter of matches.allowing) {
        filters.add(filter.text);
      }
    }

    return Array.from(filters);
  },

  /**
   * Returns whether a particular resource is allowlisted.
   * @param {string} url The resource's url.
   * @param {string} type The resource's content type. Can be one of
   *   "background", "csp", "document", "dtd", "elemhide", "font",
   *   "genericblock", "generichide", "header", "image", "media", "object",
   *   "other", "ping", "popup", "script", "stylesheet", "subdocument",
   *   "webbundle", "webrtc", "websocket", "xbl", "xmlhttprequest".
   * @param {number} tabId The id of resource's tab.
   * @param {number} frameId=0 The id of the resource's frame.
   * @return {Promise<bool>}
   */
  async isResourceAllowlisted(url, type, tabId, frameId = 0) {
    let mask = adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_6__.contentTypes[type.toUpperCase()];
    let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_9__.getFrameInfo)(tabId, frameId) || {};
    let matcher = _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.defaultMatcher;

    // The docDomain for a frame is the hostname of the parent frame
    // (the loader). For top-level frames we use the current URL's hostname.
    let docDomain = frame.hostname || (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__.parseURL)(url).hostname;
    if (matcher.isAllowlisted(url, mask, docDomain, frame.sitekey)) {
      return true;
    }

    for (; frame; frame = frame.parent) {
      if (!frame.url) {
        break;
      }

      let parentHostname = frame.parent && frame.parent.hostname;
      docDomain = parentHostname || frame.hostname;
      if (matcher.isAllowlisted(frame.url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_6__.contentTypes.DOCUMENT,
                                docDomain, frame.sitekey)) {
        return true;
      }
    }

    return false;
  },

  /**
   * Enables one or multiple filters. The filters effects
   * will again be applied.
   * @param {string|[string]} texts The filter rules to be enabled.
   * @return {Promise}
   */
  async enable(texts) {
    if (!Array.isArray(texts)) {
      texts = [texts];
    }

    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.enableFilters)(texts);
      return;
    }

    for (let text of texts) {
      let normalized = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.normalize(text);
      _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.filterStorage.filterState.setEnabled(normalized, true);
    }
  },

  /**
   * Disables one or multiple filters. The filters will no longer have
   * any effect but will be returned by `filters.getUserFilters()`.
   * @param {string|[string]} texts The filter rules to be disabled.
   * @return {Promise}
   */
  disable,

  /**
   * Removes one or multiple filters. The filters will no longer have
   * any effect and won't be returned by `filters.getUserFilters()`.
   * @param {string|[string]} texts The filter rules to be removed.
   * @return {Promise}
   */
  async remove(texts) {
    if (!Array.isArray(texts)) {
      texts = [texts];
    }

    if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
      await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.removeOrDisableFilters)(texts, true);
      return;
    }

    for (let text of texts) {
      let normalized = adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.normalize(text);
      _core_js__WEBPACK_IMPORTED_MODULE_7__.filterEngine.filterStorage.removeFilter(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(normalized));
    }
  },

  /**
   * Validates a list of filters.
   * @param {string} text Filter to be validated
   * @return {null|FilterError}
   */
  validate(text) {
    return (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.validateFilter)(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_2__.Filter.fromText(text));
  },

  /**
   * Emitted when a new filter is added.
   * @event
   * @type {EventDispatcher<Filter>}
   */
  onAdded: new _types_js__WEBPACK_IMPORTED_MODULE_8__.EventDispatcher(dispatch => {
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("filter.added", makeFilterListener(dispatch));
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("subscription.added", makeSubListener(dispatch));
  }),

  /**
   * Emitted when a filter is either enabled or disabled.
   * The property name "enabled" or
   * "metadata" and optionally "oldMetadata" is provided.
   * @event
   * @type {EventDispatcher<Filter, string>}
   */
  onChanged,

  /**
   * Emitted when a filter is removed.
   * @event
   * @type {EventDispatcher<Filter>}
   */
  onRemoved: new _types_js__WEBPACK_IMPORTED_MODULE_8__.EventDispatcher(dispatch => {
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("filter.removed", makeFilterListener(dispatch));
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_5__.filterNotifier.on("subscription.removed", makeSubListener(dispatch));
  }),

  /**
   * Returns an array of MV2 to MV3 migration errors and the related filters.
   * @return {Promise<array<Filter, string>>} The migration errors.
   */
  async getMigrationErrors() {
    return _prefs_js__WEBPACK_IMPORTED_MODULE_12__.Prefs.migration_filter_errors;
  },

  /**
   * Clears the migration errors.
   * @return {Promise}
   */
  async clearMigrationErrors() {
    _prefs_js__WEBPACK_IMPORTED_MODULE_12__.Prefs.migration_filter_errors = [];
  }
});


/***/ }),

/***/ "./sdk/api/frame-state.js":
/*!********************************!*\
  !*** ./sdk/api/frame-state.js ***!
  \********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_767695__) => {

"use strict";
__nested_webpack_require_767695__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_767695__.d(__webpack_exports__, {
/* harmony export */   "BLANK_PAGE_URL": () => (/* binding */ BLANK_PAGE_URL),
/* harmony export */   "TOP_LEVEL_FRAME_ID": () => (/* binding */ TOP_LEVEL_FRAME_ID),
/* harmony export */   "getFrameInfo": () => (/* binding */ getFrameInfo),
/* harmony export */   "isTopLevelFrameId": () => (/* binding */ isTopLevelFrameId),
/* harmony export */   "isValidChildFrameId": () => (/* binding */ isValidChildFrameId),
/* harmony export */   "isValidFrameId": () => (/* binding */ isValidFrameId),
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_767695__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_767695__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_767695__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_767695__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_767695__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _sitekey_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_767695__(/*! ./sitekey.js */ "./sdk/api/sitekey.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */










/**
 * The URL that browsers use to represent an empty page, about:blank.
 */
const BLANK_PAGE_URL = "about:blank";

/**
 * The frameId of the top level frame on each tab.
 */
const TOP_LEVEL_FRAME_ID = 0;

/**
 * Checks if a frameId corresponds to the top level frame on a tab.
 * @param {number} frameId
 * @return {boolean}
 */
function isTopLevelFrameId(frameId) {
  return frameId == TOP_LEVEL_FRAME_ID;
}

/**
 * Checks if a frameId corresponds to a frame on a tab.
 * @param {number} frameId
 * @return {boolean}
 */
function isValidFrameId(frameId) {
  return frameId >= TOP_LEVEL_FRAME_ID;
}

/**
 * Checks if a frameId corresponds to an iframe.
 * @param {number} frameId
 * @return {boolean}
 */
function isValidChildFrameId(frameId) {
  return frameId > TOP_LEVEL_FRAME_ID;
}

/**
 * All known currently active frames, that can be looked up by
 * `tabId`, and then by `frameId` (`[tabId, [frameId, FrameInfo]]`).
 *
 * Maintaining this state is the central reason for the code in this
 * file. When we start up EWE, we scan all existing tabs for their
 * frames. After that, we hook into various browser events to try to
 * keep it up to date as things change.
 *
 * @type {Map<number, Map<number, FrameInfo>>}
 */
let state = new Map();
let startupPromise;

/**
 * Manages tracking state that is tied to a single specific frame.
 *
 * A simple webpage will have a single frame in a tab. However, when
 * we look at sites with advertising and embedded trackers, they often
 * have many <iframe> elements. Each iframe may have slightly
 * different state, but generally a frame will inherit settings from
 * the frame that it's on (its parent frame).
 *
 * This state is mostly used in applying frame-level allowing filters
 * (eg `$document` filters), but is also used to hold parameters like
 * what hostname to use when checking if filters match a request, and
 * whether or not a sitekey is involved. This needs to be done
 * statefully because we inherit some state from parent frames.
 *
 * We sometimes need access to this data synchronously (for example to
 * do request filtering), but the functions to fetch this data from
 * the browser on demand are asynchronous. The events where we need to
 * make decisions based on the frame usually have some of the frame's
 * state, like the URL of the frame, but don't have the sitekey and
 * don't have all of the information about the parents of the frame.
 *
 * @property {number} tabId The id of the tab.
 * @property {string} url The url of the frame.
 * @property {string} hostname The hostname part of the frame's
 *   URL. If the URL isn't a normal HTTP URL (for example if it's
 *   about:blank) then this will be the parent frame's hostname. If
 *   that also doesn't have a normal HTTP hostname, then this will
 *   default to an empty string.
 * @property {?string} sitekey The sitekey associated with a frame, if
 *   there is one. These sitekeys are read from the
 *   `onHeadersReceived` event. This is inherited from the parent
 *   frame if this frame doesn't have a sitekey of its own.
 * @property {boolean} headersReceived True if we've received an
 *   `onHeadersReceived` event for this frame and have checked it for
 *   sitekeys. If this is false, it could mean that we don't have
 *   enough information yet to make blocking decisions, because a
 *   sitekey might still arrive with the headers.
 * @property {?FrameInfo} parent The frame that this from is on. Null
 *   if this is the top-level frame on a tab.
 * @property {number} allowlisted Bitfield where each set bit is the
 *   content type of an allowlisting filter applied to the frame. This
 *   includes filters that turn of ad filtering entirely, like
 *   `$document` filters, but also includes filters that modify how we
 *   look up request filters like `$genericblock`.
 * @property {?Filter} allowingDocumentFilter The `$document` filter
 *   that is being applied to this frame, if any. This is useful for
 *   logging, for example if a request is allowed because of this
 *   filter. If you just need to check if there is a `$document` filter
 *   applied to the frame or not, you can also check
 *   `frame.allowlisted`.
 *
 * @param {number} tabId The tabId of the tab that the this frame is on.
 * @param {number} frameId The frameId of this frame.
 * @param {?FrameInfo} parent The frame that this from is on. Null
 *   if this is the top-level frame on a tab.
 * @param {string} url The url of the frame.
 * @hideconstructor
 */
class FrameInfo {
  constructor(tabId, frameId, parent, url) {
    this.tabId = tabId;
    this.frameId = frameId;
    this.parent = parent;

    initializeFrameWithUrl(this, url);
    findAllowlistingFilters(this);
  }
}

/**
 * Get a text description of the allowing filter added.
 * @param {number} typeMask Bitset to filter types you want to name.
 * @param {Filter} filter The filter with the allowing reason you want
 *   to name.
 * @return {string} Content type name of the allowing filter just
 *   added.
 */
function getAllowingReason(typeMask, filter) {
  for (let type in adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes) {
    if (typeMask & filter.contentType & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes[type]) {
      return type.toLowerCase();
    }
  }
}

function initializeFrameWithUrl(frame, url) {
  let {
    allowlisted: parentAllowlisted,
    sitekey: parentSitekey,
    allowingDocumentFilter: parentAllowingDocumentFilter,
    hostname: parentHostname
  } = frame.parent || {};

  let urlInfo = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_1__.parseURL)(url);
  frame.url = url;
  frame.hostname = urlInfo.hostname || parentHostname || "";

  let sitekey = (0,_sitekey_js__WEBPACK_IMPORTED_MODULE_5__.getSitekey)(frame.tabId, frame.frameId, url);
  frame.sitekey = sitekey || parentSitekey;
  frame.headersReceived = (!!sitekey) || sitekey === null;

  // allowlisted and allowingDocumentFilter start with their parent
  // value, but may have extra allowing filters added when we call
  // findAllowlistingFilters
  frame.allowlisted = parentAllowlisted || 0;
  frame.allowingDocumentFilter = parentAllowingDocumentFilter;
}

/**
 * Checks if the matcher has any allowing filters that should be
 * applied to this frame, and updates `frame.allowlisted` and
 * `frame.allowingDocumentFilter` accordingly.
 *
 * This can only ever add extra allowing filters. It's also safe to
 * call multiple times on the same frame. This would normally be
 * called on a new frame to find its allowing filters, but should also
 * be called whenever a frame is updated in such a way that there
 * could be new allowing filters, for example when a sitekey is added
 * to an existing frame.
 *
 * @param {FrameInfo} frame The frame that will be checked for new
 *   filters, and will be updated.
 * @param {number} tabId The tabId of the tab the frame is on. Used for
 *   logging.
 * @param {number} frameId The frameId of the frame. Used for logging.
 */
function findAllowlistingFilters(frame) {
  let {tabId, frameId, url} = frame;
  let details = {tabId, frameId, url};
  // The docDomain for a frame is the hostname of the parent frame
  // (the loader). For top-level frames we use the current URL's hostname.
  let parentHostname = frame.parent && frame.parent.hostname;
  let matchInfo = {docDomain: parentHostname || frame.hostname,
                   method: "allowing"};

  // This loop will keep trying to find new types of allowing filters
  // for the frame until the matcher doesn't return any more.
  while (true) {
    let typeMask = ~frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.ALLOWING_TYPES;
    let filter = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine.defaultMatcher.match(
      frame.url, typeMask, matchInfo.docDomain, frame.sitekey
    );

    if (!filter) {
      break;
    }

    frame.allowlisted |= filter.contentType & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.ALLOWING_TYPES;
    // We need to hold onto document allowing filters because we might
    // need it for logging blockable requests later.
    if (filter.contentType & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) {
      frame.allowingDocumentFilter = filter;
    }

    let allowingReason = getAllowingReason(typeMask, filter);
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_4__.logItem)(details, filter, {...matchInfo, allowingReason});
  }
}

/**
 * Builds the frame state from scratch using the tabs API.
 *
 * This is called on startup, and in MV3 whenever the service worker
 * starts up. The only shortcoming is that this can't find sitekeys
 * for existing frames, since those are read from headers.
 * @async
 * @return {Promise} Resolves when all frames have been scanned.
 */
async function discoverExistingFrames() {
  let tabs = await _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].tabs.query({});
  await Promise.all(tabs.map(({id: tabId}) =>
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].webNavigation.getAllFrames({tabId}).then(rawFrames => {
      if (!rawFrames) {
        return;
      }

      // Sort the frames so that we'll add parent frames before the
      // child frames.
      rawFrames.sort((a, b) => a.frameId - b.frameId);

      let frames = new Map();
      state.set(tabId, frames);

      for (let {frameId, parentFrameId, url} of rawFrames) {
        let parent = isValidFrameId(parentFrameId) ?
            frames.get(parentFrameId) :
            null;

        // Chrome unfortunately has a bug where getAllFrames doesn't
        // always return all parent frames
        // (https://bugs.chromium.org/p/chromium/issues/detail?id=725917).
        // Not much we can do about it, but if we can't see the
        // required parent frame we can fall back to the root frame.
        if (isValidChildFrameId(parentFrameId) && !parent) {
          parent = frames.get(TOP_LEVEL_FRAME_ID);
        }

        // Yandex gives undefined or an empty string here sometimes,
        // for example when browsing to pages that Yandex treats
        // specially like their own website.
        if (!url) {
          url = BLANK_PAGE_URL;
        }

        frames.set(frameId, new FrameInfo(tabId, frameId, parent, url));
      }
    })
  ));
}

function onSitekeyReceived(tabId, frameId, url, sitekey) {
  let frame = getFrameInfo(tabId, frameId);
  let isSameFrame = frame && frame.url == url;
  if (isSameFrame) {
    frame.headersReceived = true;
  }

  if (sitekey) {
    // Sometimes the onHeadersReceived event comes after the
    // onCommitted event. This seems to be common when loading
    // iframes: the browser will show the iframe and then start
    // loading its contents. When this happens, we may get a sitekey
    // for a frame that's already being shown, and that may mean we
    // need to add some new allowlisting filters based on that
    // sitekey.
    if (isSameFrame && frame.sitekey != sitekey) {
      frame.sitekey = sitekey;
      findAllowlistingFilters(frame);
    }
  }
}


/**
 * Updates the frame state to reflect that a new frame is being shown.
 *
 * This can broadly be thought of in two categories:
 *
 * 1. The browser has navigated to the new page. Specifically, this is
 *    on the `webNavigation.onCommitted` event, which fires when the
 *    browser has decided to switch to the new document. We will
 *    usually have received headers for the document already by this
 *    point, but not always.
 * 2. The site is a single page application, and has updated its
 *    contents using Javascript and updated its URL with the history
 *    API.
 *
 * @param {Object} details Details object as provided by the
 *   webNavigation API events.
 * @param {number} details.tabId The tabId of the tab that the updated
 *   frame is on.
 * @param {number} details.frameId The frameId of the updated frame.
 * @param {number} [details.parentFrameId=-1] The frameId of the frame
 *   that the updated frame is on. -1 if the updated frame is the
 *   top-level frame.
 * @param {string} details.url The new url of the frame.
 * @param {Object} [options={}]
 * @param {boolean} [options.historyStateUpdated=false] True if this
 *   was triggered by a history state update, rather than by a full
 *   page navigation.
 * @param {boolean} [options.errorOccurred=false] True if this was
 *   triggered by a `webNavigation.onErrorOccurred` event rather than
 *   a `webNavigation.onCommitted` event.
 * @return {FrameInfo} The newly created frame state.
 */
function recordFrameFromNavigationEvent(
  {tabId, frameId, parentFrameId = -1, url},
  {historyStateUpdated = false, errorOccurred = false} = {}) {
  // Yandex gives undefined or an empty string here sometimes,
  // for example when browsing to pages that Yandex treats
  // specially like their own website.
  if (!url) {
    url = BLANK_PAGE_URL;
  }

  let frames = state.get(tabId);

  // We generally need to throw away any existing frame state for the
  // whole tab when a new top-level frame is committed to the
  // tab. This is because all previous frame state was on the old
  // top-level frame. However, if this was a history API update, those
  // frames could still be there on the page so we can't clear them out.
  if (!frames || (isTopLevelFrameId(frameId) && !historyStateUpdated)) {
    frames = new Map();
    state.set(tabId, frames);
  }
  let frame = frames.get(frameId);
  let parent = isValidFrameId(parentFrameId) ? frames.get(parentFrameId) : null;

  // Same as discoverExistingFrames, if we expect a parent but our
  // frame state doesn't seem to have that parent, falling back to the
  // root frame is better than nothing. This might happen due to this
  // bug: https://bugs.chromium.org/p/chromium/issues/detail?id=725917.
  if (isValidChildFrameId(parentFrameId) && !parent) {
    parent = frames.get(TOP_LEVEL_FRAME_ID);
  }

  // If the frame had an error instead of loading, we don't want to
  // use the URL from the error. Otherwise unscrupulous websites could
  // embed their advert in an iframe that has an allowlisted URL, but
  // doesn't actually contain the contents of that URL.
  if (errorOccurred) {
    if (frame) {
      url = frame.url;
    }
    else if (parent) {
      url = parent.url;
    }
  }

  // We might get multiple calls to `recordFrameFromNavigationEvent`
  // for iframes. This is because we need to listen to several
  // different events to hear about all frames, including onCommitted
  // and onBeforeNavigate and onErrorOccurred. To avoid duplicate
  // onBlockableItem events, we check if the frame we already have is
  // the same.
  if (!frame || isTopLevelFrameId(frameId) ||
      frame.url != url || frame.parent != parent) {
    frame = new FrameInfo(tabId, frameId, parent, url);
    frames.set(frameId, frame);
  }
  return frame;
}

function onBeforeNavigate(details) {
  // We know the current frame information is about to become
  // outdated, so we just delete the existing data.
  let frames = state.get(details.tabId);
  if (frames) {
    // Firefox can trigger "onBeforeNavigate" multiple times,
    // so we need to filter out only the actually changed navigations.
    let frame = frames.get(details.frameId);
    if (frame && frame.url != details.url) {
      // We need to skip processing the frame state events for now
      // (such as allowlisted for document) as it will be done later during
      // the `onCommited`, but we also want to avoid allowlisting for some
      // resources that refer to this tabId/frameId as the URL is changed,
      // and the allowlisting state is currently undetermined.
      frame.isChangingURL = true;
      initializeFrameWithUrl(frame, details.url);
    }
  }

  // If an iframe's URL is "about:srcdoc", that means its contents is
  // actually specified using the srcdoc attribute. Some browsers
  // don't actually emit the webNavigation.onCommitted event for these
  // frames, so we need to use a different event to get them into our
  // frame state.
  if (details.url == "about:srcdoc") {
    recordFrameFromNavigationEvent(details);
  }
}

function onCommitted(details) {
  let frame = recordFrameFromNavigationEvent(details);
  findAllowlistingFilters(frame);
  frame.isChangingURL = false;
}

function onErrorOccurred(details) {
  // On Chrome, errored iframes are never committed, but they are
  // still on the page and their contents can still be manipulated
  // with Javascript so we need them in our frame state.
  // See https://bugs.chromium.org/p/chromium/issues/detail?id=725917
  //
  // Firefox's docs don't mention parentFrameId on this event, but
  // Chrome's do, and it does appear to be there in practice. Check
  // for it before proceeding in case some browsers don't, since it's
  // very important to have the parent frame to record frame state
  // changes.
  if (isValidChildFrameId(details.frameId) &&
      typeof details.parentFrameId == "number") {
    recordFrameFromNavigationEvent(details, {errorOccurred: true});
  }
}

async function onHistoryStateUpdated(details) {
  recordFrameFromNavigationEvent(details, {historyStateUpdated: true});
}

function handleOnRemoved(tabId) {
  state.delete(tabId);
  (0,_sitekey_js__WEBPACK_IMPORTED_MODULE_5__.clearTabSitekeys)(tabId);
}

function onRemoved(tabId) {
  handleOnRemoved(tabId);
}

function onReplaced(addedTabId, removedTabId) {
  handleOnRemoved(removedTabId);
}

/**
 * Gets the state for a frame if we have it. If parentFrameId and
 * initiator are also provided, this function may also construct the
 * frame and add it to the frame state.
 *
 * @param {number} tabId The tabId of the tab the frame is on.
 * @param {number} frameId The frameId of the frame.
 * @param {?Object} [metadata] Additional metadata about the web
 *   request context that lead to asking for frame info, which might
 *   be used to create a FrameInfo if one doesn't exist already.
 * @param {?number} metadata.parentFrameId The frameId of the parent of the
 *   frame being requested. If this is set, it could be used to
 *   create the frame if it isn't already in the frame state.
 * @param {?string} metadata.initiator If getting the frame info is
 *   triggered by a web request, this should be the URL that initiated
 *   the request. If this is set, it can be used to provide a
 *   temporary frame state for use with service workers. In Firefox
 *   APIs, there is not an initiator but there is a documentUrl which
 *   can fulfil the same purpose.
 * @param {?string} metadata.documentUrl If getting the frame info is
 *   triggered by a web request, this should be the URL of the frame
 *   that initiated the request. If this is set, it could be used to
 *   create the frame if it isn't already in the frame state. This may
 *   not be available in Chrome. In Chrome, if initiator is provided,
 *   it can also be used to construct a FrameInfo, but this is not
 *   ideal since the initiator only contains the domain part of the
 *   URL.
 * @returns {?FrameInfo}
 */
function getFrameInfo(tabId, frameId,
                             {parentFrameId, initiator, documentUrl} = {}) {
  // tabId is -1 if the request came from a service worker, so we
  // construct a temporary frame state for it to use. We don't store
  // a tabId of -1 in our frame state, so we don't even need to check
  // it before returning.
  if (initiator && tabId == -1) {
    return new FrameInfo(tabId, frameId, null, initiator);
  }

  let frames = state.get(tabId);
  if (frames) {
    let frame = frames.get(frameId);
    if (frame) {
      return frame;
    }
  }

  // Sometimes the webRequest API can trigger for resources in a frame
  // before the onCommitted event for the frame. In this case, it
  // should be safe to construct the frame state early.
  if (documentUrl && typeof parentFrameId == "number") {
    return recordFrameFromNavigationEvent({
      tabId,
      frameId,
      parentFrameId,
      url: documentUrl
    });
  }
}

async function start() {
  if (!startupPromise) {
    (0,_sitekey_js__WEBPACK_IMPORTED_MODULE_5__.addListener)(onSitekeyReceived);

    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].webNavigation.onBeforeNavigate.addListener(onBeforeNavigate);
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].webNavigation.onCommitted.addListener(onCommitted);
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].webNavigation.onErrorOccurred.addListener(onErrorOccurred);
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].webNavigation.onHistoryStateUpdated.addListener(
      onHistoryStateUpdated);
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].tabs.onRemoved.addListener(onRemoved);
    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].tabs.onReplaced.addListener(onReplaced);

    startupPromise = discoverExistingFrames();
  }

  await startupPromise;
}


/***/ }),

/***/ "./sdk/api/idb.js":
/*!************************!*\
  !*** ./sdk/api/idb.js ***!
  \************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_791138__) => {

"use strict";
__nested_webpack_require_791138__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_791138__.d(__webpack_exports__, {
/* harmony export */   "openDatabase": () => (/* binding */ openDatabase)
/* harmony export */ });
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

const DB_NAME = "EWE";
const DB_VERSION = 1;

function openDatabase() {
  return new Promise((resolve, reject) => {
    let request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = event => {
      let db = event.target.result;
      db.createObjectStore("file-entries");
      db.createObjectStore("file-contents", {autoIncrement: true});
    };

    request.onsuccess = event => resolve(event.target.result);
    request.onerror = event => reject(event.target.error);
  });
}


/***/ }),

/***/ "./sdk/api/index.js":
/*!**************************!*\
  !*** ./sdk/api/index.js ***!
  \**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_792766__) => {

"use strict";
__nested_webpack_require_792766__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_792766__.d(__webpack_exports__, {
/* harmony export */   "allowlisting": () => (/* reexport safe */ _allowlisting_js__WEBPACK_IMPORTED_MODULE_20__["default"]),
/* harmony export */   "checkAndInitSubscriptions": () => (/* binding */ checkAndInitSubscriptions),
/* harmony export */   "clearSkipInitRulesets": () => (/* binding */ clearSkipInitRulesets),
/* harmony export */   "debugging": () => (/* binding */ wrappedDebugging),
/* harmony export */   "filters": () => (/* binding */ wrappedFilters),
/* harmony export */   "notifications": () => (/* reexport safe */ _notifications_js__WEBPACK_IMPORTED_MODULE_21__.notifications),
/* harmony export */   "reporting": () => (/* binding */ wrappedReporting),
/* harmony export */   "snippets": () => (/* binding */ snippets),
/* harmony export */   "start": () => (/* binding */ start),
/* harmony export */   "subscriptions": () => (/* binding */ wrappedSubscriptions),
/* harmony export */   "telemetry": () => (/* binding */ wrappedTelemetry),
/* harmony export */   "testing": () => (/* binding */ wrappedTesting)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_792766__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_792766__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _message_responder_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_792766__(/*! ./message-responder.js */ "./sdk/api/message-responder.js");
/* harmony import */ var _popup_blocker_background_page_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_792766__(/*! ./popup-blocker-background-page.js */ "./sdk/api/popup-blocker-background-page.js");
/* harmony import */ var _popup_blocker_service_worker_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_792766__(/*! ./popup-blocker-service-worker.js */ "./sdk/api/popup-blocker-service-worker.js");
/* harmony import */ var _request_filter_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_792766__(/*! ./request-filter.js */ "./sdk/api/request-filter.js");
/* harmony import */ var _dnr_request_reporter_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_792766__(/*! ./dnr-request-reporter.js */ "./sdk/api/dnr-request-reporter.js");
/* harmony import */ var _sitekey_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_792766__(/*! ./sitekey.js */ "./sdk/api/sitekey.js");
/* harmony import */ var _telemetry_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_792766__(/*! ./telemetry.js */ "./sdk/api/telemetry.js");
/* harmony import */ var _subscriptions_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_792766__(/*! ./subscriptions.js */ "./sdk/api/subscriptions.js");
/* harmony import */ var _debugging_js__WEBPACK_IMPORTED_MODULE_10__ = __nested_webpack_require_792766__(/*! ./debugging.js */ "./sdk/api/debugging.js");
/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_11__ = __nested_webpack_require_792766__(/*! ./filters.js */ "./sdk/api/filters.js");
/* harmony import */ var _reporting_js__WEBPACK_IMPORTED_MODULE_12__ = __nested_webpack_require_792766__(/*! ./reporting.js */ "./sdk/api/reporting.js");
/* harmony import */ var _testing_js__WEBPACK_IMPORTED_MODULE_13__ = __nested_webpack_require_792766__(/*! ./testing.js */ "./sdk/api/testing.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_14__ = __nested_webpack_require_792766__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var _content_filter_js__WEBPACK_IMPORTED_MODULE_15__ = __nested_webpack_require_792766__(/*! ./content-filter.js */ "./sdk/api/content-filter.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_16__ = __nested_webpack_require_792766__(/*! ./info.js */ "./sdk/api/info.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_17__ = __nested_webpack_require_792766__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _dnr_filters_js__WEBPACK_IMPORTED_MODULE_18__ = __nested_webpack_require_792766__(/*! ./dnr-filters.js */ "./sdk/api/dnr-filters.js");
/* harmony import */ var _browser_features_js__WEBPACK_IMPORTED_MODULE_19__ = __nested_webpack_require_792766__(/*! ./browser-features.js */ "./sdk/api/browser-features.js");
/* harmony import */ var _allowlisting_js__WEBPACK_IMPORTED_MODULE_20__ = __nested_webpack_require_792766__(/*! ./allowlisting.js */ "./sdk/api/allowlisting.js");
/* harmony import */ var _notifications_js__WEBPACK_IMPORTED_MODULE_21__ = __nested_webpack_require_792766__(/*! ./notifications.js */ "./sdk/api/notifications.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

























async function preApiCall() {
  // Service worker can be shut down and we might need
  // to initialize it before the usage.
  await _initializer_js__WEBPACK_IMPORTED_MODULE_1__["default"].start();
}

async function postApiCall() {
  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    return;
  }

  await _prefs_js__WEBPACK_IMPORTED_MODULE_14__.awaitSavingComplete();
  await _core_js__WEBPACK_IMPORTED_MODULE_17__.filterEngine.filterStorage.awaitSavingComplete();
  await _sitekey_js__WEBPACK_IMPORTED_MODULE_7__._awaitSavingComplete();
}

function isAsync(func) {
  return func.constructor && func.constructor.name === "AsyncFunction";
}

function wrapApiNamespace(target) {
  return new Proxy(target, {
    get(_target, prop, receiver) {
      // wrapping only asynchronous functions
      if (typeof _target[prop] === "function" && isAsync(_target[prop])) {
        return async function(...args) {
          await preApiCall();
          let result = await _target[prop](...args);
          await postApiCall();
          return result;
        };
      }
      return _target[prop];
    }
  });
}

/**
 * @ignore
 */
const wrappedSubscriptions = wrapApiNamespace(_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__["default"]);


/**
 * @ignore
 */
const wrappedFilters = wrapApiNamespace(_filters_js__WEBPACK_IMPORTED_MODULE_11__["default"]);


/**
 * @ignore
 */
const wrappedReporting = wrapApiNamespace(_reporting_js__WEBPACK_IMPORTED_MODULE_12__["default"]);


/**
 * @ignore
 */
const wrappedDebugging = wrapApiNamespace(_debugging_js__WEBPACK_IMPORTED_MODULE_10__["default"]);


// "Allowlisting" might be used before EWE is actually started
// and it does not require pre- and post- actions.


/**
 * @ignore
 */
const wrappedTelemetry = wrapApiNamespace(_telemetry_js__WEBPACK_IMPORTED_MODULE_8__["default"]);


/**
 * @ignore
 */
const wrappedTesting = wrapApiNamespace(_testing_js__WEBPACK_IMPORTED_MODULE_13__["default"]);


// "Notifications" namespace is already a Proxy


let snippets = {
  /**
   * Snippet callback.
   * @callback SnippetCallback
   * @param {Object} environment
   *   The environment variables
   * @param {...Array.<Array.<string>>} _
   *   The snippets names and arguments.
   */

  /**
   * Enables support for snippet filters.
   * @param {Object} [snippetInfo]
   * @param {SnippetCallback} [snippetInfo.isolatedCode]
   *   The code defining the available snippets to be executed in the isolated
   *   content script context.
   * @param {SnippetCallback} [snippetInfo.injectedCode]
   *   The code defining the available snippets to be injected and executed in
   *   the main context.
   */
  setLibrary: _content_filter_js__WEBPACK_IMPORTED_MODULE_15__.setSnippetLibrary
};

const SKIP_INIT_RULESETS_STORAGE_KEY = "ewe:skip_init_rulesets";

/**
 * @ignore
 */
async function clearSkipInitRulesets() {
  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.remove(SKIP_INIT_RULESETS_STORAGE_KEY);
}

async function onInstalled(details) {
  // Web extension update (with potential subscriptions filter
  // text changed and repacked) can happen in the same browser session.
  // So in order to not skip the next subscriptions filter text update
  // the flag is removed.
  let manifest = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.getManifest();
  if (details.reason != webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.OnInstalledReason.UPDATE ||
    !details.previousVersion || details.previousVersion == manifest.version) {
    return;
  }

  await clearSkipInitRulesets();
}

/**
* @typedef {Object} FirstRunInfo
* @property {boolean} foundStorage Whether the subscriptions storage was
*                                  initialized or not.
* @property {boolean} foundSubscriptions True when pre-existing subscriptions
*                                        were found, false otherwise.
*                                        Considers also whether custom filters
*                                        exist.
* @property {Array.<string>?} [warnings] An array of warnings.
*/

/**
 * Initializes the filter engine and starts blocking content.
 *
 * Calling this function is required for the other API calls to work, except for
 * API event listener calls, which could also be done before `start()`.
 *
 * In MV3 extensions, this must be called in the first turn of the
 * event loop.
 *
 * @param {Object?} [addonInfo] An object containing addon
 *   information belonging to sdk consumer, that can be accessed via
 *   `debugging` module. (It is usually used as an identifier in
 *   network requests, etc.). This object can be undefined for MV2. If it is,
 *   name and version will default to the extension's name and version.
 * @param {string} [addonInfo.name] Name of the addon/extension.
 * @param {string} [addonInfo.version] Version of the addon/extension.
 * @param {Array<Recommendation>?} [addonInfo.bundledSubscriptions]
 *   A list of subscriptions provided by the integrator. Cannot be undefined
 *   for MV3.
 * @param {string?} [addonInfo.bundledSubscriptionsPath]
 *   A path to subscription files provided by the integrator. Cannot be
 *   undefined for MV3.
 * @param {Object?} [addonInfo.telemetry] Settings for telemetry. The telemetry
 *   module will only be started if this is provided. This is currently an
 *   experimental feature. If used, this will send a single POST request on
 *   first start to the specified telemetry URL, using the specified bearer
 *   token for authentication, with metadata about the extension.
 * @param {string} [addonInfo.telemetry.url] The URL of the location where
 *   user active pings will be sent to.
 * @param {string} [addonInfo.telemetry.bearer] The Bearer token accompanying
 *   the telemetry URL.
 * @return {Promise<FirstRunInfo>} Promise that is resolved after starting up
 *                                 is completed.
 */
async function start(addonInfo) {
  (0,_info_js__WEBPACK_IMPORTED_MODULE_16__.setAddonInfo)(addonInfo);
  startSubmodulesWithListeners();

  let warnings = [];

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.onInstalled.addListener(onInstalled);
    warnings = await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__.validate)(
      addonInfo.bundledSubscriptions, addonInfo.bundledSubscriptionsPath);
  }

  await startSubmodules();

  let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_17__.filterEngine;
  let firstRun = {
    foundSubscriptions: filterStorage.getSubscriptionCount() != 0,
    foundStorage: !filterStorage.firstRun,
    warnings
  };

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    let migratedToMv3 = await checkAndMigrateSubscriptions();
    // If it has just migrated to MV3 there is no diff updates data,
    // so we can skip wiping it.
    await checkAndInitSubscriptions(migratedToMv3);
  }

  if (addonInfo && addonInfo.telemetry) {
    _telemetry_js__WEBPACK_IMPORTED_MODULE_8__.start(addonInfo.telemetry);
  }

  return firstRun;
}

function startSubmodulesWithListeners() {
  // for MV3, submodules that register event listeners generally need
  // to register their events in the first turn of the event loop to
  // register their event listeners.
  _message_responder_js__WEBPACK_IMPORTED_MODULE_2__.start();
  if ((0,_browser_features_js__WEBPACK_IMPORTED_MODULE_19__.isRunningInServiceWorker)()) {
    _popup_blocker_service_worker_js__WEBPACK_IMPORTED_MODULE_4__.start();
  }

  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    _dnr_request_reporter_js__WEBPACK_IMPORTED_MODULE_6__.start();
  }

  _sitekey_js__WEBPACK_IMPORTED_MODULE_7__.start();
}

async function startSubmodules() {
  await _initializer_js__WEBPACK_IMPORTED_MODULE_1__["default"].start();

  // MV2-style popup and request blocking assume that initializer is
  // started first.
  if (!(0,_browser_features_js__WEBPACK_IMPORTED_MODULE_19__.isRunningInServiceWorker)()) {
    _popup_blocker_background_page_js__WEBPACK_IMPORTED_MODULE_3__.start();
  }

  if (!webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    _request_filter_js__WEBPACK_IMPORTED_MODULE_5__.start();
  }

  _core_js__WEBPACK_IMPORTED_MODULE_17__.filterEngine.filterStorage.synchronizer.start();
}

async function checkAndMigrateSubscriptions() {
  if (_prefs_js__WEBPACK_IMPORTED_MODULE_14__.Prefs.migration_state !== _prefs_js__WEBPACK_IMPORTED_MODULE_14__.MIGRATED_TO_MV3) {
    await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__.migrate)();

    if (_prefs_js__WEBPACK_IMPORTED_MODULE_14__.Prefs.migration_state === _prefs_js__WEBPACK_IMPORTED_MODULE_14__.MIGRATED_TO_MV2) {
      await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_18__.migrateCustomFilters)();
    }

    _prefs_js__WEBPACK_IMPORTED_MODULE_14__.Prefs.migration_state = _prefs_js__WEBPACK_IMPORTED_MODULE_14__.MIGRATED_TO_MV3;
    return true;
  }
  return false;
}

/**
 * @ignore
 * @param {boolean} skipWipeOutDiffs Skip wiping diff updates data
 */
async function checkAndInitSubscriptions(skipWipeOutDiffs) {
  // Loading the subcriptions filter text wipes out diff updates,
  // so we do it in case of web extension update only.
  let skipInit = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get(
    [SKIP_INIT_RULESETS_STORAGE_KEY]
  );
  if (skipInit[SKIP_INIT_RULESETS_STORAGE_KEY]) {
    // Rulesets state is not persisted between webext updates
    await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__.ensureDNRRulesetsEnabled)();
    return;
  }

  if (!skipWipeOutDiffs) {
    // It's a webext update, so we need to wipe out all diffs
    // and start from scratch: full state provided in bundled data.
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_18__.clearRulesetUpdates)();
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_18__.removeSubscriptionsDynamicFilters)();
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_18__.enableAllDisabledStaticRules)();
  }

  await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__.updateSubscriptionInformation)();
  await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_9__.ensureDNRRulesetsEnabled)();

  await _subscriptions_js__WEBPACK_IMPORTED_MODULE_9__["default"].sync();

  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set(
    {[SKIP_INIT_RULESETS_STORAGE_KEY]: true}
  );
}


/***/ }),

/***/ "./sdk/api/info.js":
/*!*************************!*\
  !*** ./sdk/api/info.js ***!
  \*************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_808704__) => {

"use strict";
__nested_webpack_require_808704__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_808704__.d(__webpack_exports__, {
/* harmony export */   "addonBundledSubscriptions": () => (/* binding */ addonBundledSubscriptions),
/* harmony export */   "addonBundledSubscriptionsPath": () => (/* binding */ addonBundledSubscriptionsPath),
/* harmony export */   "addonName": () => (/* binding */ addonName),
/* harmony export */   "addonVersion": () => (/* binding */ addonVersion),
/* harmony export */   "application": () => (/* binding */ application),
/* harmony export */   "applicationVersion": () => (/* binding */ applicationVersion),
/* harmony export */   "getBrowserVersion": () => (/* binding */ getBrowserVersion),
/* harmony export */   "initializeDefaultAddonInfo": () => (/* binding */ initializeDefaultAddonInfo),
/* harmony export */   "isFirefox": () => (/* binding */ isFirefox),
/* harmony export */   "manifestVersion": () => (/* binding */ manifestVersion),
/* harmony export */   "platform": () => (/* binding */ platform),
/* harmony export */   "platformVersion": () => (/* binding */ platformVersion),
/* harmony export */   "setAddonInfo": () => (/* binding */ setAddonInfo)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_808704__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/* harmony import */ var adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_808704__(/*! adblockpluscore/lib/recommendations.js */ "./core/lib/recommendations.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





let addonName;
let addonVersion;
let addonBundledSubscriptions;
let addonBundledSubscriptionsPath;
let application;
let applicationVersion;
let platform;
let platformVersion;
let manifestVersion;

initializeDefaultAddonInfo();

function getBrowserVersion() {
  return applicationVersion.split(".").map(str => parseInt(str, 10));
}

function isFirefox() {
  return application.includes("firefox");
}

function initializeDefaultAddonInfo() {
  let manifest = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getManifest();

  addonName = manifest.short_name || manifest.name;
  addonVersion = manifest.version;
  application = "unknown";
  applicationVersion = "0";
  platformVersion = "0";
  manifestVersion = String(manifest.manifest_version);

  if (typeof netscape != "undefined") {
    platform = "gecko";

    let match = /\brv:([^;)]+)/.exec(navigator.userAgent);
    if (match) {
      platformVersion = match[1];
    }

    _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getBrowserInfo().then(browserInfo => {
      application = browserInfo.name.toLowerCase();
      applicationVersion = browserInfo.version;
    });
  }
  else {
    platform = "chromium";
    parseChromiumUserAgent();
  }
}

function parseChromiumUserAgent() {
  let regexp = /(\S+)\/(\S+)(?:\s*\(.*?\))?/g;
  let match;

  while (match = regexp.exec(navigator.userAgent)) {
    let [, app, version] = match;

    // For compatibility with legacy websites, Chrome's UA
    // also includes a Mozilla, AppleWebKit and Safari tokens.
    // Any further name/version pair indicates a fork.
    if (app == "Mozilla" || app == "AppleWebKit" || app == "Safari") {
      continue;
    }

    if (app == "Chrome") {
      platformVersion = version;
      if (application != "unknown") {
        continue;
      }
    }

    application = app == "OPR" ? "opera" : app.toLowerCase();
    applicationVersion = version;
  }
}

function setAddonInfo(addonInfo) {
  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
    if (!addonInfo) {
      throw new Error("No addonInfo provided to EWE.start");
    }

    if (!addonInfo.bundledSubscriptions) {
      throw new Error("No `bundledSubscriptions` provided");
    }

    if (!addonInfo.bundledSubscriptionsPath) {
      throw new Error("No `bundledSubscriptionsPath` provided");
    }
  }

  if (!addonInfo) {
    return;
  }

  if (addonInfo.name) {
    addonName = addonInfo.name;
  }
  if (addonInfo.version) {
    addonVersion = addonInfo.version;
  }
  if (addonInfo.manifestVersion) {
    manifestVersion = addonInfo.manifestVersion;
  }

  addonBundledSubscriptions = addonInfo.bundledSubscriptions;
  addonBundledSubscriptionsPath = addonInfo.bundledSubscriptionsPath;

  if (addonBundledSubscriptions &&
      addonBundledSubscriptions.length > 0) {
    (0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__.setRecommendations)(addonBundledSubscriptions);
  }
}


/***/ }),

/***/ "./sdk/api/initializer.js":
/*!********************************!*\
  !*** ./sdk/api/initializer.js ***!
  \********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_814152__) => {

"use strict";
__nested_webpack_require_814152__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_814152__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_814152__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_814152__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/* harmony import */ var _io_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_814152__(/*! ./io.js */ "./sdk/api/io.js");
/* harmony import */ var _dnr_filters_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_814152__(/*! ./dnr-filters.js */ "./sdk/api/dnr-filters.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_814152__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var _debugging_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_814152__(/*! ./debugging.js */ "./sdk/api/debugging.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */








let startupPromise;

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * Initializes stateful modules that may be used in filtering requests.
   *
   * This function is idempotent. If you call it after initialization
   * has already been launched elsewhere, then it will return the same
   * promise as the original initialization. This allows this function
   * to be called anywhere that you need to ensure that initialization
   * has completed before continuing.
   *
   * Calling this function is required for the other API calls to
   * work, except for API event listener calls, which could also be
   * done before `start()`.
   * @return {Promise} Resolves when initialization is complete
   */
  start() {
    if (!startupPromise) {
      startupPromise = (async() => {
        await _io_js__WEBPACK_IMPORTED_MODULE_2__.IO.initialize();
        await _debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].start();
        await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.init)();
        await _core_js__WEBPACK_IMPORTED_MODULE_0__.filterEngine.initialize();
        await _frame_state_js__WEBPACK_IMPORTED_MODULE_1__.start();
        await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_3__.init)();
      })();
    }
    return startupPromise;
  }
});


/***/ }),

/***/ "./sdk/api/io-bsl.js":
/*!***************************!*\
  !*** ./sdk/api/io-bsl.js ***!
  \***************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_817372__) => {

"use strict";
__nested_webpack_require_817372__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_817372__.d(__webpack_exports__, {
/* harmony export */   "IO": () => (/* binding */ IO)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_817372__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



const KEY_PREFIX = "ewe:file:";

function fileToKey(fileName) {
  return KEY_PREFIX + fileName;
}

async function loadFile(fileName) {
  let key = fileToKey(fileName);
  let items = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get(key);
  let entry = items[key];
  if (entry) {
    return entry;
  }
  throw {type: "NoSuchFile"};
}

function saveFile(fileName, data) {
  return webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({
    [fileToKey(fileName)]: {
      content: Array.from(data),
      lastModified: Date.now()
    }
  });
}

// IO implementation that is using `browser.storage.local` API
let IO = {
  /**
   * Reads text lines from a file.
   * @param {string} filename
   *    Name of the file to be read
   * @param {TextSink} listener
   *    Function that will be called for each line in the file
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async readFromFile(filename, listener) {
    let entry = await loadFile(filename);
    for (let line of entry.content) {
      listener(line);
    }
  },

  /**
   * Writes text lines to a file.
   * @param {string} filename
   *    Name of the file to be written
   * @param {Iterable.<string>} data
   *    An array-like or iterable object containing the lines (without line
   *    endings)
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  writeToFile(filename, data) {
    return saveFile(filename, data);
  },

  /**
   * Renames a file.
   * @param {string} fromFile
   *    Name of the file to be renamed
   * @param {string} newName
   *    New file name, will be overwritten if exists
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async renameFile(fromFile, newName) {
    let entry = await loadFile(fromFile);
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({[fileToKey(newName)]: entry});
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.remove(fileToKey(fromFile));
  },

  /**
   * Retrieves file metadata.
   * @param {string} filename
   *    Name of the file to be looked up
   * @return {Promise.<StatData>}
   *    Promise to be resolved with file metadata once the operation is
   *    completed
   */
  async statFile(filename) {
    try {
      let entry = await loadFile(filename);
      return {
        exists: true,
        lastModified: entry.lastModified
      };
    }
    catch (error) {
      if (error.type == "NoSuchFile") {
        return Promise.resolve({exists: false});
      }
      throw error;
    }
  },

  async fixPrefixes() {
    let data = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get();
    for (let key in data) {
      let value = data[key];

      // The order of prefixes matters:
      // the most important should be the last
      // to override the existing values jic.
      for (let eachPrefix of ["abp:file:", "file:"]) {
        if (key.startsWith(eachPrefix)) {
          let obj = {};
          obj[KEY_PREFIX + key.substring(eachPrefix.length)] = value;
          await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set(obj);
          await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.remove(key);
        }
      }
    }
  },

  /**
   * Initialize the storage
   * @return {Promise} initialization promise
   */
  async initialize() {
    // Migrating the files with 'file:' and `abp:file:` prefixes
    // to 'ewe:file:' stored in `browser.storage.local` in Firefox private mode.
    // See https://gitlab.com/eyeo/adblockplus/abc/webext-ad-filtering-solution/-/issues/369
    await this.fixPrefixes();
  }
};



/***/ }),

/***/ "./sdk/api/io-idb.js":
/*!***************************!*\
  !*** ./sdk/api/io-idb.js ***!
  \***************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_822464__) => {

"use strict";
__nested_webpack_require_822464__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_822464__.d(__webpack_exports__, {
/* harmony export */   "IO": () => (/* binding */ IO),
/* harmony export */   "getDatabase": () => (/* binding */ getDatabase)
/* harmony export */ });
/* harmony import */ var _idb_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_822464__(/*! ./idb.js */ "./sdk/api/idb.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



let database;

function clearContent(filename, entryStore, contentStore) {
  entryStore.get(filename).onsuccess = event => {
    let entry = event.target.result;
    if (entry) {
      contentStore.delete(entry.content);
    }
  };
}

function saveFile(db, filename, lines, lastModified) {
  return new Promise((resolve, reject) => {
    let data = new TextEncoder().encode(Array.from(lines).join("\n"));
    let tx = db.transaction(["file-entries", "file-contents"], "readwrite");
    let entryStore = tx.objectStore("file-entries");
    let contentStore = tx.objectStore("file-contents");

    clearContent(filename, entryStore, contentStore);
    contentStore.add(data).onsuccess = event => {
      let content = event.target.result;
      entryStore.put({lastModified, content}, filename);
    };

    tx.oncomplete = () => resolve();
    tx.onerror = tx.onabort = event => reject(event.target.error);
  });
}

async function initIO(db) {
  database = db;
}

function getDatabase() {
  if (!database) {
    throw new Error("Database hasn't been opened. Did you call start()?");
  }
  return database;
}

// IO implementation that is using `IndexedDB`
let IO = {
  /**
   * Reads text lines from a file.
   * @param {string} filename
   *    Name of the file to be read
   * @param {TextSink} listener
   *    Function that will be called for each line in the file
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async readFromFile(filename, listener) {
    let data = await new Promise((resolve, reject) => {
      let db = getDatabase();
      let tx = db.transaction(["file-entries", "file-contents"], "readonly");
      let entryStore = tx.objectStore("file-entries");
      let contentStore = tx.objectStore("file-contents");

      entryStore.get(filename).onsuccess = entryEvent => {
        let entry = entryEvent.target.result;
        if (!entry) {
          reject(new Error("File does not exist"));
          return;
        }

        contentStore.get(entry.content).onsuccess = contentEvent => {
          resolve(contentEvent.target.result);
        };
      };

      tx.onerror = tx.onabort = event => reject(event.target.error);
    });

    let decoder = new TextDecoder();
    let start = 0;

    while (true) {
      let index = data.indexOf(10 /* newline character */, start + 1000);
      let end = index != -1 ? index : data.length;
      let text = decoder.decode(data.subarray(start, end));

      for (let line of text.split("\n")) {
        listener(line);
      }

      if (index == -1) {
        break;
      }

      start = index + 1;
    }
  },

  /**
   * Writes text lines to a file.
   * @param {string} filename
   *    Name of the file to be written
   * @param {Iterable<string>} lines
   *    An array-like or iterable object containing the lines (without line
   *    endings)
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async writeToFile(filename, lines) {
    await saveFile(getDatabase(), filename, lines, Date.now());
  },

  /**
   * Renames a file.
   * @param {string} oldName
   *    Name of the file to be renamed
   * @param {string} newName
   *    New file name, will be overwritten if exists
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  renameFile(oldName, newName) {
    return new Promise((resolve, reject) => {
      let db = getDatabase();
      let tx = db.transaction(["file-entries", "file-contents"], "readwrite");
      let entryStore = tx.objectStore("file-entries");
      let contentStore = tx.objectStore("file-contents");

      entryStore.get(oldName).onsuccess = event => {
        let entry = event.target.result;
        if (!entry) {
          reject(new Error("File does not exist"));
          return;
        }

        clearContent(newName, entryStore, contentStore);
        entryStore.put(entry, newName);
        entryStore.delete(oldName);
      };

      tx.oncomplete = () => resolve();
      tx.onerror = tx.onabort = event => reject(event.target.error);
    });
  },

  /**
   * Retrieves file metadata.
   * @param {string} filename
   *    Name of the file to be looked up
   * @return {Promise<StatData>}
   *    Promise to be resolved with file metadata once the operation is
   *    completed
   */
  statFile(filename) {
    return new Promise((resolve, reject) => {
      let db = getDatabase();
      let tx = db.transaction(["file-entries"], "readonly");
      let store = tx.objectStore("file-entries");

      store.get(filename).onsuccess = event => {
        let entry = event.target.result;
        let exists = false;
        let lastModified;

        if (entry) {
          exists = true;
          lastModified = entry.lastModified;
        }

        resolve({exists, lastModified});
      };

      tx.onerror = tx.onabort = event => reject(event.target.error);
    });
  },

  /**
   * Initialize the storage
   * @return {Promise} initialization promise
   */
  async initialize() {
    let db = await (0,_idb_js__WEBPACK_IMPORTED_MODULE_0__.openDatabase)();
    await initIO(db);
  }
};


/***/ }),

/***/ "./sdk/api/io.js":
/*!***********************!*\
  !*** ./sdk/api/io.js ***!
  \***********************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_828937__) => {

"use strict";
__nested_webpack_require_828937__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_828937__.d(__webpack_exports__, {
/* harmony export */   "IO": () => (/* binding */ IO),
/* harmony export */   "readFileContent": () => (/* binding */ readFileContent)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_828937__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var _io_idb_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_828937__(/*! ./io-idb.js */ "./sdk/api/io-idb.js");
/* harmony import */ var _io_bsl_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_828937__(/*! ./io-bsl.js */ "./sdk/api/io-bsl.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */






let io;
let initializationPromise;

function readFileContent(path) {
  const url = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.getURL(path);
  return fetch(url).then(content => content.text());
}

// This is a facade implementation that forwards to the current concrete
// implementation of IO. By default IndexedDB is used but if it's unavailable
// a fallback to `browser.storage.local` is used.
let IO = {
  /**
   * Reads text lines from a file.
   * @param {string} filename
   *    Name of the file to be read
   * @param {TextSink} listener
   *    Function that will be called for each line in the file
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async readFromFile(filename, listener) {
    return io.readFromFile(filename, listener);
  },

  /**
   * Writes text lines to a file.
   * @param {string} filename
   *    Name of the file to be written
   * @param {Iterable<string>} lines
   *    An array-like or iterable object containing the lines (without line
   *    endings)
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  async writeToFile(filename, lines) {
    return io.writeToFile(filename, lines);
  },

  /**
   * Renames a file.
   * @param {string} oldName
   *    Name of the file to be renamed
   * @param {string} newName
   *    New file name, will be overwritten if exists
   * @return {Promise}
   *    Promise to be resolved or rejected once the operation is completed
   */
  renameFile(oldName, newName) {
    return io.renameFile(oldName, newName);
  },

  /**
   * Retrieves file metadata.
   * @param {string} filename
   *    Name of the file to be looked up
   * @return {Promise<StatData>}
   *    Promise to be resolved with file metadata once the operation is
   *    completed
   */
  statFile(filename) {
    return io.statFile(filename);
  },

  /**
   * Initialize the storage
   * @return {Promise} initialization promise
   */
  initialize() {
    if (!initializationPromise) {
      initializationPromise = (async() => {
        io = _io_idb_js__WEBPACK_IMPORTED_MODULE_1__.IO;
        try {
          await io.initialize();
        }
        catch (e) {
          if (e instanceof DOMException &&
              e.name == "InvalidStateError") {
            // fall back to `browser.storage.local` API if IndexedDb
            // is unavailable, eg. in Firefox in private mode. See
            // https://gitlab.com/eyeo/adblockplus/abc/webext-ad-filtering-solution/-/issues/231
            io = _io_bsl_js__WEBPACK_IMPORTED_MODULE_2__.IO;
            try {
              await io.initialize();
            }
            catch {
              initializationPromise = null;
              throw e;
            }
          }
          else {
            initializationPromise = null;
            throw e;
          }
        }
      })();
    }

    return initializationPromise;
  }
};


/***/ }),

/***/ "./sdk/api/message-responder.js":
/*!**************************************!*\
  !*** ./sdk/api/message-responder.js ***!
  \**************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_833598__) => {

"use strict";
__nested_webpack_require_833598__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_833598__.d(__webpack_exports__, {
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_833598__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_833598__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _content_filter_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_833598__(/*! ./content-filter.js */ "./sdk/api/content-filter.js");
/* harmony import */ var adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_833598__(/*! adblockpluscore/lib/elemHide.js */ "./core/lib/elemHide.js");
/* harmony import */ var _subscribe_links_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_833598__(/*! ./subscribe-links.js */ "./sdk/api/subscribe-links.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_833598__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _allowlisting_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_833598__(/*! ./allowlisting.js */ "./sdk/api/allowlisting.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */










async function handleMessage(message, sender) {
  await _initializer_js__WEBPACK_IMPORTED_MODULE_1__["default"].start();
  switch (message.type) {
    case "ewe:content-hello":
      // Firefox mistakenly runs content scripts in non-web page context,
      // it does not happen in Chrome.
      // https://gitlab.com/eyeo/adblockplus/abc/webext-ad-filtering-solution/-/issues/174.
      // Messages sent from a non-web page context do not have an
      // associated tab and can be ignored.
      if (!sender.tab) {
        return;
      }

      let filterData = await (0,_content_filter_js__WEBPACK_IMPORTED_MODULE_2__.applyContentFilters)(sender.tab.id, sender.frameId);
      return {...filterData};
    case "ewe:subscribe-link-clicked":
      (0,_subscribe_links_js__WEBPACK_IMPORTED_MODULE_4__.subscribeLinkClicked)(message.url, message.title);
      break;
    case "ewe:trace-elem-hide":
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_5__.logHiddenElements)(message.selectors, message.filters, sender);
      break;
    case "ewe:inject-css":
      let styleSheet = (0,adblockpluscore_lib_elemHide_js__WEBPACK_IMPORTED_MODULE_3__.createStyleSheet)([message.selector]);
      (0,_content_filter_js__WEBPACK_IMPORTED_MODULE_2__.injectCSS)(sender.tab.id, sender.frameId, styleSheet);
      break;
    case "ewe:allowlist-page":
      return (0,_allowlisting_js__WEBPACK_IMPORTED_MODULE_6__.allowlistPage)(
        sender.tab.id, sender.frameId, message.timestamp, message.signature
      );
  }
}

function onMessage(message, sender) {
  if (typeof message == "object" && message != null &&
      message.type && message.type.startsWith("ewe:")) {
    return handleMessage(message, sender);
  }
  return false;
}

/**
 * Start the message responder module. In MV3, this must be called in
 * the first turn of the event loop.
 */
function start() {
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.onMessage.addListener(onMessage);
}


/***/ }),

/***/ "./sdk/api/notifications.js":
/*!**********************************!*\
  !*** ./sdk/api/notifications.js ***!
  \**********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_837825__) => {

"use strict";
__nested_webpack_require_837825__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_837825__.d(__webpack_exports__, {
/* harmony export */   "notifications": () => (/* binding */ notifications)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_837825__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_837825__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_837825__(/*! adblockpluscore/lib/notifications.js */ "./core/lib/notifications.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */







const NOTIFICATION_KEY = "ewe:notifications";
class NotificationSessionStorageBackend {
  constructor() {
    this.local = new Set();
    this.loaded = this.load();
  }

  add(notification) {
    this.local.add(notification);
    this.save();
  }

  delete(notification) {
    let removed = this.local.delete(notification);
    if (removed) {
      this.save();
    }

    return removed;
  }

  [Symbol.iterator]() {
    return this.local[Symbol.iterator]();
  }

  async load() {
    let result = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.session.get([NOTIFICATION_KEY]);
    let loadedNotifications = result[NOTIFICATION_KEY] || [];
    for (let notification of loadedNotifications) {
      this.local.add(notification);
    }
  }

  async save() {
    await this.loaded;
    if (!this.debounceTimer) {
      this.debounceTimer = setTimeout(() => {
        this.debounceTimer = null;
        this.saveImmediate();
      }, 0);
    }
  }

  async saveImmediate() {
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.session.set({
      [NOTIFICATION_KEY]: [...this.local]
    });
  }
}

if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.session) {
  adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__.notifications.setLocalNotificationStorage(
    new NotificationSessionStorageBackend()
  );
}

let funcsThatRequirePrefs = [
  "start",
  "shouldIgnoreNotifications",
  "showNotification",
  "showNext",
  "markAsShown",
  "toggleIgnoreCategory",
  "getDownloadCount",
  "getIgnoredCategories"
];

/**
 * The notifications API (optional usage).
 *
 * Call `notifications.start()` to start downloading remote
 * notifications. Local notifications functions such as
 * `notifications.addNotification(notification)` and
 * `notifications.showNotification(notification)` can be used even if
 * `notifications.start()` has not been called.
 *
 *  Please also notice that notification events are **not** using the
 * {@link #eventdispatcher|EventDispatcher} interface.
 *
 * Note that, when used through EWE, the following notifications
 * functions are asynchronous and return the values specified in the
 * Core documentation wrapped in promises:
 * - start
 * - shouldIgnoreNotifications
 * - showNotification
 * - showNext
 * - markAsShown
 * - toggleIgnoreCategory
 * - getDownloadCount
 * - getIgnoredCategories
 *
 * @see {@link https://eyeo.gitlab.io/adblockplus/abc/adblockpluscore/master/docs/module-notifications.html?job=docs|Adblock Plus core notifications documentation}
 */
let notifications = new Proxy(adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__.notifications, {
  get(target, prop, receiver) {
    if (funcsThatRequirePrefs.includes(prop)) {
      return async function(...args) {
        await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_1__.init)();
        return target[prop](...args);
      };
    }
    return target[prop];
  }
});


/***/ }),

/***/ "./sdk/api/popup-blocker-background-page.js":
/*!**************************************************!*\
  !*** ./sdk/api/popup-blocker-background-page.js ***!
  \**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_842504__) => {

"use strict";
__nested_webpack_require_842504__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_842504__.d(__webpack_exports__, {
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_842504__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_842504__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_842504__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_842504__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_842504__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_842504__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */










let loadingPopups = new Map();

function forgetPopup(tabId) {
  loadingPopups.delete(tabId);

  if (loadingPopups.size == 0) {
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onBeforeRequest.removeListener(onPopupURLChanged);
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onBeforeNavigate.removeListener(onPopupURLChanged);
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCompleted.removeListener(onCompleted);
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.onRemoved.removeListener(onTabRemoved);
  }
}

function checkPotentialPopup(popupTabId, url, opener) {
  let {docDomain, sitekey, specificOnly} = opener;

  let filter = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine.defaultMatcher.match(
    url || _frame_state_js__WEBPACK_IMPORTED_MODULE_5__.BLANK_PAGE_URL, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.POPUP,
    docDomain, sitekey, specificOnly
  );

  if (filter) {
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_4__.logItem)({tabId: opener.tabId, frameId: 0, url}, filter,
            {docDomain, specificOnly, method: "popup"});

    if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.BlockingFilter) {
      webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.remove(popupTabId).catch(() => {});
    }

    forgetPopup(popupTabId);
  }
}

function onPopupURLChanged({frameId, tabId, url}) {
  if (!(0,_frame_state_js__WEBPACK_IMPORTED_MODULE_5__.isTopLevelFrameId)(frameId)) {
    return;
  }

  let opener = loadingPopups.get(tabId);
  if (opener) {
    checkPotentialPopup(tabId, url, opener);
  }
}

function onCompleted({frameId, url, tabId}) {
  if ((0,_frame_state_js__WEBPACK_IMPORTED_MODULE_5__.isTopLevelFrameId)(frameId) && url != _frame_state_js__WEBPACK_IMPORTED_MODULE_5__.BLANK_PAGE_URL) {
    forgetPopup(tabId);
  }
}

function onTabRemoved(tabId) {
  forgetPopup(tabId);
}

function onPopup({tabId, url, sourceTabId, sourceFrameId}) {
  let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_5__.getFrameInfo)(sourceTabId, sourceFrameId) || {};

  if (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) {
    return;
  }

  if (loadingPopups.size == 0) {
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onBeforeRequest.addListener(
      onPopupURLChanged,
      {
        urls: ["http://*/*", "https://*/*"],
        types: ["main_frame"]
      }
    );
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onBeforeNavigate.addListener(onPopupURLChanged);
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCompleted.addListener(onCompleted);
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.onRemoved.addListener(onTabRemoved);
  }

  let opener = {
    tabId: sourceTabId,
    specificOnly: Boolean(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK),
    docDomain: frame.hostname,
    sitekey: frame.sitekey
  };

  loadingPopups.set(tabId, opener);
  checkPotentialPopup(tabId, url, opener);
}

function onTabCreated({id, url, openerTabId}) {
  if (openerTabId) {
    onPopup({tabId: id, url, sourceTabId: openerTabId, sourceFrameId: 0});
  }
}

/**
 * Starts blocking popups. Must only be called after filter engine and
 * frame state are initialized.
 */
function start() {
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCreatedNavigationTarget.addListener(onPopup);

  // On Firefox, clicking on a <a target="_blank" rel="noopener"> link doesn't
  // emit the webNavigation.onCreatedNavigationTarget event (and Firefox >=79,
  // implies "noopener" by default). But on Chrome, opening a new empty tab
  // emits the tabs.onCreated event with openerTabId set. So this would
  // cause new tabs created by the user to be considered popups too, on Chrome.
  if (typeof netscape != "undefined") {
    webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.onCreated.addListener(onTabCreated);
  }
}


/***/ }),

/***/ "./sdk/api/popup-blocker-service-worker.js":
/*!*************************************************!*\
  !*** ./sdk/api/popup-blocker-service-worker.js ***!
  \*************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_848802__) => {

"use strict";
__nested_webpack_require_848802__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_848802__.d(__webpack_exports__, {
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_848802__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_848802__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_848802__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_848802__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_848802__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_848802__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_848802__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */











const SESSION_STORAGE_KEY = "ewe:popupBlocker:loadingPopups";

class PotentialPopupMap {
  constructor() {
    this.openerPromiseMap = {};
    this.loaded = (async() => {
      let result = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.session.get([SESSION_STORAGE_KEY]);
      this.openerMap = result[SESSION_STORAGE_KEY] || {};
    })();
  }

  async saveMap() {
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.session.set({
      [SESSION_STORAGE_KEY]: this.openerMap
    });
  }

  set(tabId, openerPromise) {
    if (this.openerPromiseMap[tabId] ||
        (this.openerMap && this.openerMap[tabId])) {
      return;
    }

    this.openerPromiseMap[tabId] = openerPromise;
    openerPromise.then(async opener => {
      await this.loaded;

      delete this.openerPromiseMap[tabId];
      if (opener) {
        this.openerMap[tabId] = opener;
        await this.saveMap();
      }
    });
  }

  async get(tabId) {
    let openerPromise = this.openerPromiseMap[tabId];
    if (openerPromise) {
      return await openerPromise;
    }

    await this.loaded;
    let opener = this.openerMap[tabId];
    return opener;
  }

  has(tabId) {
    return Object.hasOwnProperty.call(this.openerPromiseMap, tabId) ||
      (this.openerMap && Object.hasOwnProperty.call(this.openerMap, tabId));
  }

  async remove(tabId) {
    if (this.openerPromiseMap[tabId]) {
      delete this.openerPromiseMap[tabId];
    }

    await this.loaded;
    if (this.openerMap[tabId]) {
      delete this.openerMap[tabId];
      await this.saveMap();
    }
  }
}

let potentialPopups;

async function checkPotentialPopup(popupTabId, url, opener) {
  await _initializer_js__WEBPACK_IMPORTED_MODULE_4__["default"].start();
  let {docDomain, sitekey, specificOnly} = opener;

  // because of the async nature of getting to this point, it might
  // have been handled before we get here.
  if (!potentialPopups.has(popupTabId)) {
    return;
  }

  let filter = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine.defaultMatcher.match(
    url || _frame_state_js__WEBPACK_IMPORTED_MODULE_6__.BLANK_PAGE_URL, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.POPUP, docDomain, sitekey, specificOnly
  );

  if (filter) {
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_5__.logItem)({tabId: opener.tabId, frameId: 0, url}, filter,
            {docDomain, specificOnly, method: "popup"});

    if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.BlockingFilter) {
      webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.remove(popupTabId).catch(() => {});
    }

    await potentialPopups.remove(popupTabId);
  }
}

async function onPopupURLChanged({frameId, tabId, url}) {
  if (!(0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.isTopLevelFrameId)(frameId)) {
    return;
  }

  let opener = await potentialPopups.get(tabId);
  if (opener) {
    await checkPotentialPopup(tabId, url, opener);
  }
}

async function onCompleted({frameId, tabId, url}) {
  if (!(0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.isTopLevelFrameId)(frameId) || url == _frame_state_js__WEBPACK_IMPORTED_MODULE_6__.BLANK_PAGE_URL) {
    return;
  }

  let opener = await potentialPopups.get(tabId);
  if (opener) {
    await checkPotentialPopup(tabId, url, opener);
    await potentialPopups.remove(tabId);
  }
}

async function onTabRemoved(tabId) {
  await potentialPopups.remove(tabId);
}

async function onPopup({tabId, url, sourceTabId, sourceFrameId}) {
  let openerPromise = (async() => {
    await _initializer_js__WEBPACK_IMPORTED_MODULE_4__["default"].start();
    let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.getFrameInfo)(sourceTabId, sourceFrameId) || {};

    if (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) {
      return;
    }

    let opener = {
      tabId: sourceTabId,
      specificOnly: Boolean(frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK),
      docDomain: frame.hostname,
      sitekey: frame.sitekey
    };
    return opener;
  })();

  potentialPopups.set(tabId, openerPromise);

  let opener = await openerPromise;
  if (opener) {
    await checkPotentialPopup(tabId, url, opener);
  }
}

/**
 * Starts blocking popups. Must be called in the first turn of the
 * event loop.
 */
function start() {
  potentialPopups = new PotentialPopupMap();

  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCreatedNavigationTarget.addListener(onPopup);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onBeforeRequest.addListener(
    onPopupURLChanged,
    {
      urls: ["http://*/*", "https://*/*"],
      types: ["main_frame"]
    }
  );
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onBeforeNavigate.addListener(onPopupURLChanged);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCommitted.addListener(onPopupURLChanged);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onCompleted.addListener(onCompleted);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.onRemoved.addListener(onTabRemoved);
}


/***/ }),

/***/ "./sdk/api/prefs.js":
/*!**************************!*\
  !*** ./sdk/api/prefs.js ***!
  \**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_856275__) => {

"use strict";
__nested_webpack_require_856275__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_856275__.d(__webpack_exports__, {
/* harmony export */   "MIGRATED_TO_MV2": () => (/* binding */ MIGRATED_TO_MV2),
/* harmony export */   "MIGRATED_TO_MV3": () => (/* binding */ MIGRATED_TO_MV3),
/* harmony export */   "MIGRATED_TO_MV3_WITHOUT_DIFF": () => (/* binding */ MIGRATED_TO_MV3_WITHOUT_DIFF),
/* harmony export */   "Prefs": () => (/* binding */ Prefs),
/* harmony export */   "awaitSavingComplete": () => (/* binding */ awaitSavingComplete),
/* harmony export */   "defaults": () => (/* binding */ defaults),
/* harmony export */   "init": () => (/* binding */ init),
/* harmony export */   "migratePrefs": () => (/* binding */ migratePrefs)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_856275__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_events_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_856275__(/*! adblockpluscore/lib/events.js */ "./core/lib/events.js");
/* harmony import */ var adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_856275__(/*! adblockpluscore/lib/time.js */ "./core/lib/time.js");
/* harmony import */ var _io_idb_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_856275__(/*! ./io-idb.js */ "./sdk/api/io-idb.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */






// MV2
// (all the subscriptions are downloadable)
const MIGRATED_TO_MV2 = 0;

// MV3 without diff updates
// (anti-cv subscription is the only `FullUpdatableSubscription`)
const MIGRATED_TO_MV3_WITHOUT_DIFF = 1;

// MV3 with diff updates
// (all subscriptions are either
// `CountableSubscription` or `DiffUpdatableSubscriptions`)
const MIGRATED_TO_MV3 = 2;

const defaults = Object.create({
  analytics: {trustedHosts: ["adblockplus.org",
                             "notification.adblockplus.org",
                             "easylist-downloads.adblockplus.org"]},
  dynamic_filters: [],
  notificationdata: {},
  notifications_ignoredcategories: [],
  notificationurl: "https://notification.adblockplus.org/notification.json",
  notifications_initial_delay: 1000, // 1 s
  patternsbackupinterval: 24,
  patternsbackups: 0,
  ruleset_updates: [],
  savestats: false,
  show_statsinpopup: true,
  subscriptions_autoupdate: true,
  subscriptions_fallbackerrors: 5,
  subscriptions_fallbackurl: "https://adblockplus.org/getSubscription?version=%VERSION%&url=%SUBSCRIPTION%&downloadURL=%URL%&error=%ERROR%&responseStatus=%RESPONSESTATUS%",
  subscriptions_initial_delay: 1000, // 1 s
  subscriptions_check_interval: 1 * adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_2__.MILLIS_IN_HOUR,
  migration_filter_errors: [],
  migration_subscription_errors: [],
  migration_state: MIGRATED_TO_MV2
});

let Prefs = {
  on(preference, callback) {
    eventEmitter.on(preference, callback);
  },
  off(preference, callback) {
    eventEmitter.off(preference, callback);
  }
};

const KEY_PREFIX = "abp:pref:";

let eventEmitter = new adblockpluscore_lib_events_js__WEBPACK_IMPORTED_MODULE_1__.EventEmitter();
let overrides = new Map();
let initializationPromise;

function keyToPref(key) {
  return key.startsWith(KEY_PREFIX) ? key.substr(KEY_PREFIX.length) : null;
}

function prefToKey(pref) {
  return `${KEY_PREFIX}${pref}`;
}

let activeSaveActions = new Set();

function trackSaving(savePromise) {
  activeSaveActions.add(savePromise);
  savePromise.finally(() => activeSaveActions.delete(savePromise));
  return savePromise;
}

async function awaitSavingComplete() {
  if (Promise.allSettled) {
    await Promise.allSettled(activeSaveActions);
    return;
  }

  // Promise.allSettled isn't supported in oldest Firefox.
  // It was added in Firefox 71.
  for (let saveAction of activeSaveActions) {
    try {
      await saveAction;
    }
    catch (e) {
    }
  }
}

function addPreference(preference) {
  Object.defineProperty(Prefs, preference, {
    get() {
      if (overrides.has(preference)) {
        return overrides.get(preference);
      }

      let defaultValue = defaults[preference];
      // Arrays and Objects are deeply copied
      // to avoid modifications of `defaults`
      return Array.isArray(defaultValue) ||
        (typeof defaultValue === "object" && defaultValue !== null) ?
          JSON.parse(JSON.stringify(defaultValue)) :
          defaultValue;
    },
    set(value) {
      let key = prefToKey(preference);
      if (value === defaults[preference]) {
        overrides.delete(preference);
        trackSaving(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.remove(key));
        return;
      }

      overrides.set(preference, value);
      trackSaving(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({[key]: value}));
    },
    enumerable: true
  });
}

async function migratePrefs(db) {
  return new Promise((resolve, reject) => {
    let tx = db.transaction(["prefs"], "readwrite");
    tx.oncomplete = () => resolve();
    tx.onerror = tx.onabort = event => reject(event.target.error);

    let prefsStore;
    try {
      prefsStore = tx.objectStore("prefs");
    }
    catch (e) {
      // no "prefs" object store
      return;
    }
    prefsStore.getAll().onsuccess = event => {
      for (let {name, value} of event.target.result) {
        savePreference(name, value);
      }
      prefsStore.clear();
    };
  });
}

function savePreference(name, value) {
  let key = prefToKey(name);
  overrides.set(name, value);
  trackSaving(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({[key]: value}));
}

async function loadPreferences() {
  let prefs = Object.keys(Object.getPrototypeOf(defaults));
  prefs.forEach(addPreference);

  let items = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get(prefs.map(prefToKey));
  for (let key in items) {
    overrides.set(keyToPref(key), items[key]);
  }
}

async function init() {
  if (!initializationPromise) {
    initializationPromise = (async() => {
      try {
        let db = (0,_io_idb_js__WEBPACK_IMPORTED_MODULE_3__.getDatabase)();
        await migratePrefs(db);
      }
      catch (e) {
        // db might be unavailable
      }

      await loadPreferences();
    })();
  }

  return initializationPromise;
}


/***/ }),

/***/ "./sdk/api/reporting.js":
/*!******************************!*\
  !*** ./sdk/api/reporting.js ***!
  \******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_863526__) => {

"use strict";
__nested_webpack_require_863526__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_863526__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_analytics_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_863526__(/*! adblockpluscore/lib/analytics.js */ "./core/lib/analytics.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_863526__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_863526__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _request_filter_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_863526__(/*! ./request-filter.js */ "./sdk/api/request-filter.js");
/* harmony import */ var _subscribe_links_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_863526__(/*! ./subscribe-links.js */ "./sdk/api/subscribe-links.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */








let contentTypesMap = new Map();

for (let item of _request_filter_js__WEBPACK_IMPORTED_MODULE_3__.resourceTypes) {
  let contentTypeObject = Object.keys(adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_1__.contentTypes).find(key =>
    adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_1__.contentTypes[key] === item[1]
  );

  contentTypesMap.set(item[0].toLowerCase(), contentTypeObject.toLowerCase());
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * Returns the version of the first ever downloaded resource.
   * @return {string}
   * @see {@link https://gitlab.com/eyeo/adblockplus/abc/adblockpluscore/-/jobs/artifacts/0.6.0/file/build/docs/module-analytics-Analytics.html?job=docs#getFirstVersion|Adblock Plus core analytics documentation}
   * @external
   */
  getFirstVersion: adblockpluscore_lib_analytics_js__WEBPACK_IMPORTED_MODULE_0__.analytics.getFirstVersion,

  /**
  * @typedef {Object} FilterMatchInfo
  * @property {string|null} docDomain The hostname of the document that caused
  *   the request. This will be null for "main_frame" requests since those
  *   create the top-level document in the first place.
  * @property {?string} rewrittenUrl The name of the internal resource to which
  *   to rewrite the URL.
  * @property {?boolean} specificOnly Whether selectors from generic filters
  *   should be included.
  * @property {string} method The method used to match this filter. This can be
  *   the string "request", "header", "csp", "popup", "elemhide", "snippet",
  *   "allowing", or "unmatched".
  * @property {?string} allowingReason When the type in request details is
  *   undefined, this contains the reason why the request/frame got
  *   allowlisted. That is either "document", "elemhide", "genericblock",
  *   "generichide", or "extensionInitiated". "extensionInitiated" refers to any
  *   web requests initiated by a browser extension rather than a web page
  *   (those requests are not blockable).
  */

  /**
   * Emitted when any blockable item is matched.
   *
   * This includes both filters being applied on a document level and web
   * requests. Multiple events may be emitted for a document, one for each
   * filter being applied to the document. There will generally only be one
   * event emitted for each web request. The exception to this is CSP filters,
   * where multiple CSP filters may be applied to a request at the same time,
   * and an event will be emitted for each filter applied.
   * @event
   * @param {object|{frameId: number, tabId: number, url: string}} request
   *   Either
   *   the {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest#details|onBeforeRequest details}
   *   object or the {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived#details|onHeadersReceived details}
   *   object from the web extensions API, or an object with the properties
   *   `frameId`, `tabId` and `url`.
   * @param {?Filter} filter The filter that matched, if any.
   * @param {FilterMatchInfo} matchInfo Extra information that might be
   *                                    relevant depending on the context.
   * @type {BlockableEventDispatcher<{request: object,
   *                                   filter: Filter,
   *                                   matchInfo: FilterMatchInfo}>}
   */
  onBlockableItem: new _diagnostics_js__WEBPACK_IMPORTED_MODULE_2__.BlockableEventDispatcher(),

  /**
   * Returns a mapping between resourceTypes and contentTypes.
   * @return {Map<string, string>}
   */
  contentTypesMap,

  /**
   * Emitted when a subscribe link is clicked on a web page.
   *
   * A subscribe link has a URL pointing to `https://subscribe.adblockplus.org/`
   * or starting with `abp:subscribe` (deprecated), followed by a query string
   * with a `location` parameter, and optionally a `title` parameter. Subscribe
   * links can only be used on certain trusted domains (including `localhost`).
   * @example
   * <a href="https://subscribe.adblockplus.org?location=http%3A%2F%2Flocalhost%2Flist.txt&title=Example">Example</a>
   * <a href="abp:subscribe?location=location=http%3A%2F%2Flocalhost%2Flist.txt&title=Example">Example (deprecated)</a>
   * @event
   * @param {string} url The subscription URL from the subscribe link
   *                     `location`'s parameter.
   * @param {string} title The subscription title from the subscribe link
   *                       `title`'s parameter.
   * @type {EventDispatcher<{url: string, title: string}>}
   */
  onSubscribeLinkClicked: _subscribe_links_js__WEBPACK_IMPORTED_MODULE_4__.onSubscribeLinkClicked
});


/***/ }),

/***/ "./sdk/api/request-filter.js":
/*!***********************************!*\
  !*** ./sdk/api/request-filter.js ***!
  \***********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_870240__) => {

"use strict";
__nested_webpack_require_870240__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_870240__.d(__webpack_exports__, {
/* harmony export */   "getFrameInfoFromWebrequestDetails": () => (/* binding */ getFrameInfoFromWebrequestDetails),
/* harmony export */   "getParentFrameInfoFromWebrequestDetails": () => (/* binding */ getParentFrameInfoFromWebrequestDetails),
/* harmony export */   "getRequestContentType": () => (/* binding */ getRequestContentType),
/* harmony export */   "resourceTypes": () => (/* binding */ resourceTypes),
/* harmony export */   "sanitizeInitiator": () => (/* binding */ sanitizeInitiator),
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_870240__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_870240__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_870240__(/*! adblockpluscore/lib/contentTypes.js */ "./core/lib/contentTypes.js");
/* harmony import */ var adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_870240__(/*! adblockpluscore/lib/filterNotifier.js */ "./core/lib/filterNotifier.js");
/* harmony import */ var adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_870240__(/*! adblockpluscore/lib/url.js */ "./core/lib/url.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_870240__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _frame_state_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_870240__(/*! ./frame-state.js */ "./sdk/api/frame-state.js");
/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_870240__(/*! ../errors.js */ "./sdk/errors.js");
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_870240__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/* harmony import */ var _sitekey_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_870240__(/*! ./sitekey.js */ "./sdk/api/sitekey.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */














const EXTENSION_PROTOCOL = new URL(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.getURL("")).protocol;

let resourceTypes = new Map();
for (let type in adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes) {
  resourceTypes.set(type.toLowerCase(), adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes[type]);
}
resourceTypes.set("sub_frame", adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.SUBDOCUMENT);
resourceTypes.set("beacon", adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.PING);
resourceTypes.set("imageset", adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.IMAGE);
resourceTypes.set("object_subrequest", adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.OBJECT);
resourceTypes.set("main_frame", adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT);

let typeSelectors = new Map([
  [adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.IMAGE, "img,input"],
  [adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.MEDIA, "audio,video"],
  [adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.SUBDOCUMENT, "frame,iframe,object,embed"],
  [adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.OBJECT, "object,embed"]
]);

function getRequestContentType(details) {
  let contentType = resourceTypes.get(details.type) || adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.OTHER;
  if (contentType == adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) {
    return adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.OTHER;
  }
  return contentType;
}

function getFrameId(details) {
  // sub_frame requests are loading the iframe document itself, so
  // from our point of view the initiating frame is actually the
  // parent of the iframe.
  return details.type == "sub_frame" ? details.parentFrameId :
    details.frameId;
}

function getParentFrameId(details) {
  if (details.type == "sub_frame") {
    // frameAncestors is exactly what we need, but it's only
    // available in Firefox so sometimes we just don't have what we
    // need :(
    if (!details.frameAncestors) {
      return null;
    }

    return details.frameAncestors.length > 1 ?
      details.frameAncestors[1].frameId : -1;
  }
  return details.parentFrameId;
}

// Initiators have this weird thing where they sometimes use the string "null"
// instead of just giving a value of null.
function sanitizeInitiator(initiator) {
  return initiator == "null" ? null : initiator;
}

function getFrameInfoFromWebrequestDetails(details) {
  let tabId = details.tabId;
  let frameId = getFrameId(details);
  let parentFrameId = getParentFrameId(details);
  let initiator = sanitizeInitiator(details.initiator) || details.documentUrl;
  let documentUrl = details.documentUrl || sanitizeInitiator(details.initiator);

  let frame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.getFrameInfo)(tabId, frameId, {
    initiator,
    parentFrameId,
    documentUrl
  });

  if (!frame || frame.isChangingURL) {
    // `isChangingURL` indicates that `onBeforeNavigate` was already
    // triggered, but `onCommited` was not yet triggered. Thus we don't really
    // know the actual allowlisting state.
    return null;
  }

  return frame;
}

function getParentFrameInfoFromWebrequestDetails(details) {
  if (!(0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.isValidFrameId)(details.parentFrameId)) {
    return null;
  }

  let parentFrame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.getFrameInfo)(details.tabId, details.parentFrameId);
  // Due to a chrome bug, the parent frame might not exist. In this
  // case, we should fall back to the root frame. See
  // https://bugs.chromium.org/p/chromium/issues/detail?id=725917
  if (!parentFrame && (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.isValidChildFrameId)(details.parentFrameId)) {
    parentFrame = (0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.getFrameInfo)(details.tabId, 0);
  }

  return parentFrame;
}

let pendingAllowlistedRequests = new Set();
let pendingCspRequests = new Set();

class BaseFilter {
  register() {
    if (!this.listener) {
      this.listener = this.filter.bind(this);
      this.event.addListener(this.listener, ...this.eventArgs);
    }
  }

  unregister() {
    if (this.listener) {
      this.event.removeListener(this.listener);
      this.listener = null;
    }
  }

  getDocDomain(type, hostname) {
    return type == "main_frame" ? null : hostname;
  }

  getInitiator(details) {
    // Chrome calls it initiator, Firefox calls it documentUrl
    return sanitizeInitiator(details.initiator) || details.documentUrl;
  }

  getDocumentUrl(details) {
    return details.documentUrl || sanitizeInitiator(details.initiator);
  }

  collapse(details) {
    let selector = typeSelectors.get(getRequestContentType(details));
    let frameId = getFrameId(details);

    let sendCollapseMessage = () => {
      return webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.tabs.sendMessage(
        details.tabId,
        {type: "ewe:collapse", selector, url: details.url}, {frameId}
      );
    };

    if (selector && frameId != -1) {
      // Retrying to fix a connection error on Chromium 90 and on Firefox
      sendCollapseMessage()
        .catch(() => (0,_errors_js__WEBPACK_IMPORTED_MODULE_7__.ignoreNoConnectionError)(sendCollapseMessage()));
    }
  }

  block(details, filter, matchInfo) {
    let value = (() => {
      if (typeof filter.rewrite == "string") {
        let rewrittenUrl = filter.rewriteUrl(details.url);
        // If no rewrite happened (error, different origin), we'll
        // return undefined in order to avoid an "infinite" loop.
        if (rewrittenUrl != details.url) {
          matchInfo.rewrittenUrl = rewrittenUrl;
          return {redirectUrl: rewrittenUrl};
        }
      }
      else {
        this.collapse(details);
        return {cancel: true};
      }
    })();
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_8__.logItem)(details, filter, matchInfo);
    return value;
  }

  allow(details, filter, matchInfo) {
    pendingAllowlistedRequests.add(details.requestId);
    (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_8__.logItem)(details, filter, matchInfo);
  }

  match(details, frame, specificOnly, contentType, docDomain) {
    // This does nothing in BaseFilter, but should be overridden in
    // any child class that uses the default implementation of
    // BaseFilter.filter.
  }

  filter(details) {
    if (pendingAllowlistedRequests.has(details.requestId)) {
      return;
    }

    let initiator = this.getInitiator(details);
    if (initiator && initiator.startsWith(EXTENSION_PROTOCOL)) {
      // These are requests sent by an extension, so if we block these
      // we could block our own ability to update subscriptions etc.
      return this.allow(details, null, {
        method: "allowing", allowingReason: "extensionInitiated"
      });
    }

    let frame = getFrameInfoFromWebrequestDetails(details);

    if (!frame) {
      return;
    }

    let specificOnly = (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK) != 0;
    let docDomain = this.getDocDomain(details.type, frame.hostname);
    if (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT) {
      return this.allow(details, frame.allowingDocumentFilter, {
        docDomain,
        method: "allowing",
        specificOnly
      });
    }

    let contentType = getRequestContentType(details);

    return this.match(details, frame, specificOnly, contentType, docDomain);
  }
}

class RequestFilter extends BaseFilter {
  getDocumentUrl(details) {
    // We can be more idealistic here since we are doing this check
    // again later if we don't have enough info. documentUrl SHOULD
    // only ever be documentUrl (not initiator).
    return details.documentUrl;
  }

  getFrameInfo(details) {
    let frame = super.getFrameInfo(details);

    // Chromium-based browsers sometimes emit onBeforeRequest events
    // for resources on a frame before we get the onCommitted event
    // for the frame itself. This could mean that we're missing some
    // frame-level allowlisting filters, and can't actually make a
    // blocking decision yet. We only do this wait in the
    // onBeforeRequest filter because we can still do the blocking /
    // allowing when we have all the necessary info later in the
    // onHeadersReceived event.
    //
    // As an aside, if in the future we only needed to support Firefox
    // here, Firefox supports asynchronous blocking responses in the
    // webRequest API.
    if (frame) {
      // We might be missing sitekeys if we haven't received headers yet.
      if (!frame.headersReceived) {
        return null;
      }

      // A wrong URL likely means that we've navigated to a new page
      // and frame-state hasn't caught up yet.
      let {documentUrl} = details;
      let initiator = sanitizeInitiator(details.initiator);
      if ((documentUrl && frame.url != documentUrl) ||
         (initiator && frame.hostname != (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_4__.parseURL)(initiator).hostname)) {
        return null;
      }
    }

    return frame;
  }

  match(details, frame, specificOnly, contentType, docDomain) {
    let filter = _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.defaultMatcher.match(
      details.url, contentType, docDomain, frame.sitekey, specificOnly, true
    );
    if (filter) {
      let matchInfo = {docDomain, specificOnly, method: "request"};
      if (filter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.BlockingFilter) {
        return this.block(details, filter, matchInfo);
      }
      return this.allow(details, filter, matchInfo);
    }
  }
}

RequestFilter.prototype.event = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onBeforeRequest;
RequestFilter.prototype.eventArgs = [
  {
    types: Object.values(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.ResourceType)
                 .filter(type => type != "main_frame"),
    urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]
  },
  ["blocking"]
];

class HeaderFilter extends BaseFilter {
  match(details, frame, specificOnly, contentType, docDomain) {
    let matcher = _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.defaultMatcher;

    // This is a repeat of the RequestFilter check, in case it was
    // skipped due to not having enough frame information at the time.
    let requestFilter = matcher.match(
      details.url, contentType, docDomain, frame.sitekey, specificOnly, true
    );
    if (requestFilter) {
      let requestMatchInfo = {docDomain, specificOnly, method: "request"};
      if (requestFilter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.BlockingFilter) {
        return this.block(details, requestFilter, requestMatchInfo);
      }
      return this.allow(details, requestFilter, requestMatchInfo);
    }

    let matchInfo = {docDomain, specificOnly, method: "header"};
    let typeMask = adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.HEADER | contentType;
    let allowingFilter = matcher.match(details.url, typeMask, docDomain,
                                       frame.sitekey, specificOnly, true);

    if (allowingFilter && allowingFilter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.AllowingFilter) {
      return this.allow(details, allowingFilter, matchInfo);
    }

    let matches = matcher.search(details.url, typeMask, docDomain,
                                 frame.sitekey, specificOnly, "blocking");

    let filter = matches.blocking.find(blockingFilter => {
      return blockingFilter.filterHeaders(details.responseHeaders);
    });

    if (filter) {
      return this.block(details, filter, matchInfo);
    }
  }
}

HeaderFilter.prototype.event = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onHeadersReceived;
HeaderFilter.prototype.eventArgs = [
  {
    types: Object.values(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.ResourceType)
                 .filter(type => type != "main_frame"),
    urls: ["http://*/*", "https://*/*"]
  },
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest ? ["responseHeaders"] : ["blocking", "responseHeaders"]
];

class CSPFilter extends BaseFilter {
  filter(details) {
    let {requestId, tabId, frameId, responseHeaders, url, type} = details;

    if (pendingAllowlistedRequests.has(requestId)) {
      return;
    }

    let initiator = this.getInitiator(details);
    if (initiator && initiator.startsWith(EXTENSION_PROTOCOL)) {
      // These are requests sent by an extension, so if we block these
      // we could block our own ability to update subscriptions etc.
      return this.allow(details, null, {
        method: "allowing", allowingReason: "extensionInitiated"
      });
    }

    let parentFrame = getParentFrameInfoFromWebrequestDetails(details);
    let {hostname: parentHostname, sitekey: parentSitekey} = parentFrame || {};
    let matcher = _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.defaultMatcher;

    let urlInfo = (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_4__.parseURL)(url);
    let hostname = parentHostname || urlInfo.hostname;
    let sitekey = (0,_sitekey_js__WEBPACK_IMPORTED_MODULE_9__.setSitekeyFromHeaders)(
      tabId, frameId, url, responseHeaders
    ) || parentSitekey;

    let specificOnlyFilter = matcher.match(
      url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK, hostname, sitekey
    );
    let documentFilter = matcher.match(
      url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.DOCUMENT, hostname, sitekey
    );
    let specificOnly = !!specificOnlyFilter;
    let docDomain = this.getDocDomain(type, parentHostname);

    if (documentFilter) {
      return this.allow(details, documentFilter, {
        docDomain,
        method: "allowing",
        specificOnly
      });
    }

    let typeMask = adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.CSP | getRequestContentType(details);
    let matchInfo = {docDomain: docDomain || urlInfo.hostname,
                     specificOnly, method: "csp"};

    let allowingFilter = matcher.match(url, typeMask, docDomain,
                                       sitekey, specificOnly, true);
    if (allowingFilter && allowingFilter instanceof adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_1__.AllowingFilter) {
      return this.allow(details, allowingFilter, matchInfo);
    }

    let matches = matcher.search(url, typeMask, hostname,
                                 sitekey, specificOnly, "blocking");

    if (matches.blocking.length > 0) {
      pendingCspRequests.add(requestId);
      for (let filter of matches.blocking) {
        (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_8__.logItem)(details, filter, matchInfo);
        responseHeaders.push(
          {name: "Content-Security-Policy", value: filter.csp}
        );
      }
    }

    return {responseHeaders};
  }
}

CSPFilter.prototype.event = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onHeadersReceived;
CSPFilter.prototype.eventArgs = [
  {
    types: ["main_frame", "sub_frame"],
    urls: ["http://*/*", "https://*/*"]
  },
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest ? ["responseHeaders"] : ["blocking", "responseHeaders"]
];

class RequestCompletionFilter extends BaseFilter {
  filter(details) {
    let {requestId, tabId, frameId, url, type} = details;
    let wasAllowlisted = pendingAllowlistedRequests.delete(requestId);
    let wasCsp = pendingCspRequests.delete(requestId);
    if (wasAllowlisted || wasCsp) {
      return;
    }

    if (type == "main_frame" || type == "sub_frame") {
      // for these two types, it's unreliable if frame is there or not
      // yet. The request could be completed before or after the new
      // frame is committed.
      let parentFrame = getParentFrameInfoFromWebrequestDetails(details);
      let {hostname: parentHostname, sitekey: parentSitekey} =
          parentFrame || {};

      let hostname = parentHostname || (0,adblockpluscore_lib_url_js__WEBPACK_IMPORTED_MODULE_4__.parseURL)(url).hostname;
      let sitekey = (0,_sitekey_js__WEBPACK_IMPORTED_MODULE_9__.getSitekey)(tabId, frameId, url) || parentSitekey;
      let matcher = _core_js__WEBPACK_IMPORTED_MODULE_5__.filterEngine.defaultMatcher;
      let specificOnlyFilter = matcher.match(
        url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK, hostname, sitekey
      );
      let specificOnly = !!specificOnlyFilter;

      if ((0,_frame_state_js__WEBPACK_IMPORTED_MODULE_6__.isTopLevelFrameId)(frameId)) {
        let popupFilter = matcher.match(
          url, adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.POPUP, hostname, sitekey, specificOnly
        );
        if (popupFilter) {
          return;
        }
      }
      let matchInfo = {
        docDomain: this.getDocDomain(type, hostname),
        method: "unmatched",
        specificOnly
      };
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_8__.logItem)(details, null, matchInfo);
    }
    else {
      let frame = getFrameInfoFromWebrequestDetails(details);
      if (!frame) {
        return;
      }

      let specificOnly = (frame.allowlisted & adblockpluscore_lib_contentTypes_js__WEBPACK_IMPORTED_MODULE_2__.contentTypes.GENERICBLOCK) != 0;
      let matchInfo = {
        docDomain: this.getDocDomain(type, frame.hostname),
        method: "unmatched",
        specificOnly
      };
      (0,_diagnostics_js__WEBPACK_IMPORTED_MODULE_8__.logItem)(details, null, matchInfo);
    }
  }
}

RequestCompletionFilter.prototype.event = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onCompleted;
RequestCompletionFilter.prototype.eventArgs = [
  {
    types: Object.values(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.ResourceType),
    urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]
  }
];

class RequestErrorFilter extends BaseFilter {
  filter(details) {
    pendingAllowlistedRequests.delete(details.requestId);
    pendingCspRequests.delete(details.requestId);
  }
}

RequestErrorFilter.prototype.event = webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.onErrorOccurred;
RequestErrorFilter.prototype.eventArgs = [
  {
    types: Object.values(webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.ResourceType),
    urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]
  }
];

let filters = [
  new RequestFilter(),
  new HeaderFilter(),
  new CSPFilter(),
  new RequestCompletionFilter(),
  new RequestErrorFilter()
];

function onBeforeNavigate() {
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onBeforeNavigate.removeListener(onBeforeNavigate);
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webRequest.handlerBehaviorChanged();
}

function onFilterChange() {
  webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.webNavigation.onBeforeNavigate.addListener(onBeforeNavigate);
}

const FILTER_EVENTS = ["subscription.added",
                       "subscription.removed",
                       "subscription.updated",
                       "subscription.disabled",
                       "filter.added",
                       "filter.removed",
                       "filterState.enabled"];

/**
 * Starts filtering requests. Must only be called after filter engine and
 * frame state are initialized.
 */
function start() {
  if (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.declarativeNetRequest) {
    return;
  }

  for (let filter of filters) {
    filter.register();
  }

  for (let event of FILTER_EVENTS) {
    if (!adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_3__.filterNotifier.listeners(event).includes(onFilterChange)) {
      adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_3__.filterNotifier.on(event, onFilterChange);
    }
  }
}


/***/ }),

/***/ "./sdk/api/scheduler.js":
/*!******************************!*\
  !*** ./sdk/api/scheduler.js ***!
  \******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_894019__) => {

"use strict";
__nested_webpack_require_894019__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_894019__.d(__webpack_exports__, {
/* harmony export */   "Scheduler": () => (/* binding */ Scheduler)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_894019__(/*! adblockpluscore/lib/time.js */ "./core/lib/time.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



const MAX_POLL_TIMEOUT = adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_0__.MILLIS_IN_HOUR;

class Scheduler {
  constructor(config) {
    this.config = config;
    this.callListenerInProgress = false;
    this.stopped = false;

    let check = async() => {
      let nextPollTimeout;
      try {
        nextPollTimeout = await this.callListenerIfItsTime();
      }
      finally {
        if (!nextPollTimeout) {
          nextPollTimeout = this.config.errorRetryDelay;
        }

        if (nextPollTimeout > MAX_POLL_TIMEOUT) {
          nextPollTimeout = MAX_POLL_TIMEOUT;
        }

        // If stop was called while currently triggering something, don't
        // schedule the next timeout.
        if (!this.stopped) {
          this.timeout = setTimeout(check, nextPollTimeout);
        }
      }
    };
    check();
  }

  async callListenerIfItsTime() {
    let nextTimestamp = await this.config.getNextTimestamp();
    let nowTimestamp = Date.now();
    if (nextTimestamp && nowTimestamp < nextTimestamp) {
      return nextTimestamp - nowTimestamp;
    }

    let success = await this.config.listener();
    if (!success) {
      return this.config.errorRetryDelay;
    }

    return this.config.interval;
  }

  stop() {
    if (this.stopped) {
      return;
    }

    this.stopped = true;
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
  }
}


/***/ }),

/***/ "./sdk/api/sitekey.js":
/*!****************************!*\
  !*** ./sdk/api/sitekey.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_896726__) => {

"use strict";
__nested_webpack_require_896726__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_896726__.d(__webpack_exports__, {
/* harmony export */   "_awaitSavingComplete": () => (/* binding */ _awaitSavingComplete),
/* harmony export */   "_doSaveSitekeys": () => (/* binding */ _doSaveSitekeys),
/* harmony export */   "_getSitekeySignature": () => (/* binding */ _getSitekeySignature),
/* harmony export */   "_loadSitekeys": () => (/* binding */ _loadSitekeys),
/* harmony export */   "_saveSitekeys": () => (/* binding */ _saveSitekeys),
/* harmony export */   "_setSitekey": () => (/* binding */ _setSitekey),
/* harmony export */   "addListener": () => (/* binding */ addListener),
/* harmony export */   "clearAllSitekeys": () => (/* binding */ clearAllSitekeys),
/* harmony export */   "clearTabSitekeys": () => (/* binding */ clearTabSitekeys),
/* harmony export */   "getSitekey": () => (/* binding */ getSitekey),
/* harmony export */   "merge": () => (/* binding */ merge),
/* harmony export */   "setSitekeyFromHeaders": () => (/* binding */ setSitekeyFromHeaders),
/* harmony export */   "start": () => (/* binding */ start)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_rsa_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_896726__(/*! adblockpluscore/lib/rsa.js */ "./core/lib/rsa.js");
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_896726__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/* harmony import */ var _browser_features_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_896726__(/*! ./browser-features.js */ "./sdk/api/browser-features.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





/**
 * All known sitekeys, that can be looked up by
 * `tabId`, and then by `frameId`, and then by `url`
 *  (`[tabId, [frameId, [url, {sitekey, signature}]]]]`).
 *
 * @type {Object}
 */
let sitekeys = {};
let startupPromise;
let listeners = [];

function notifySitekey(tabId, frameId, url, sitekey) {
  for (let listener of listeners) {
    listener(tabId, frameId, url, sitekey);
  }
}

function notifyAllSitekeys() {
  for (let [tabId, framesMap] of Object.entries(sitekeys)) {
    for (let [frameId, sitekeysMap] of Object.entries(framesMap)) {
      for (let [url, sitekeyInfo] of Object.entries(sitekeysMap)) {
        notifySitekey(tabId, frameId, url, sitekeyInfo.sitekey);
      }
    }
  }
}

function onHeadersReceived({tabId, frameId, url, responseHeaders}) {
  let sitekey = setSitekeyFromHeaders(tabId, frameId, url, responseHeaders);
  if (sitekey) {
    notifySitekey(tabId, frameId, url, sitekey);
  }
}

function addListener(listener) {
  listeners.push(listener);
}

/**
 * Gets the stored sitekey for a given frame. Sitekeys are retrieved
 * from the headers of main_frame and sub_frame requests (the html
 * documents in tabs and iframes).
 * @param {number} tabId Id of the tab the frame is on.
 * @param {number} frameId Id of the frame on the tab.
 * @param {string} url Url for the frame.
 * @return {string|null|undefined} The sitekey if we have it, null if
 *   we've processed headers for this frame but it didn't have a
 *   sitekey, undefined if we haven't seen any headers for this frame.
 */
function getSitekey(tabId, frameId, url) {
  let sitekeysForTab = sitekeys[tabId];
  if (!sitekeysForTab) {
    return null;
  }
  let sitekeysForFrame = sitekeysForTab[frameId];
  if (!sitekeysForFrame) {
    return null;
  }
  let sitekeyInfo = sitekeysForFrame[url];
  return sitekeyInfo ? sitekeyInfo.sitekey : null;
}

function _getSitekeySignature(tabId, frameId, url) {
  return sitekeys[tabId][frameId][url].signature;
}

function _setSitekey(tabId, frameId, url, sitekey, signature) {
  let sitekeysForTab = sitekeys[tabId];
  if (!sitekeysForTab) {
    sitekeysForTab = {};
    sitekeys[tabId] = sitekeysForTab;
  }

  let sitekeysForFrame = sitekeysForTab[frameId];
  if (!sitekeysForFrame) {
    sitekeysForFrame = {};
    sitekeysForTab[frameId] = sitekeysForFrame;
  }

  sitekeysForFrame[url] = {sitekey, signature};
}

function clearAllSitekeys(save = true) {
  sitekeys = {};
  if (save) {
    _saveSitekeys();
  }
}

function clearTabSitekeys(tabId) {
  delete sitekeys[tabId];
  _saveSitekeys();
}

/**
 * Use the headers from an onHeadersReceived event for an main_frame
 * and sub_frame request to update our sitekey map. This also
 * validates the sitekey before storing.
 *
 * If there is no sitekey, this inserts a null entry in the sitekey
 * map so you can differentiate between not having a sitekey because
 * there wasn't one in the headers and because the headers haven't
 * been received yet.
 * @param {number} tabId Id of the tab the frame is on.
 * @param {number} frameId Id of the frame on the tab.
 * @param {string} url Url for the frame.
 * @param {webRequest.HttpHeaders} headers the HTTP response headers
 *   to check for a sitekey. See {@link webRequest API
 *   https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/HttpHeaders}.
 * @return {string|null} The sitekey if it was found and is
 *   valid. Null if there was no valid sitekey.
 */
function setSitekeyFromHeaders(tabId, frameId, url, headers) {
  let sitekeyHeader = getSitekeyHeader(headers);
  let newSitekey = sitekeyHeader ? sitekeyHeader.sitekey : null;

  // If this sitekey is the same as the one we already have, we can
  // just leave the existing one. No need to do signature verification
  // since we've already checked this sitekey on this site.
  let existingSitekeyInfo = getSitekey(tabId, frameId, url);
  if (existingSitekeyInfo &&
      existingSitekeyInfo.sitekey &&
      newSitekey == existingSitekeyInfo.sitekey) {
    return existingSitekeyInfo.sitekey;
  }

  if (newSitekey && verifySitekey(newSitekey, sitekeyHeader.signature, url)) {
    _setSitekey(tabId, frameId, url, newSitekey, sitekeyHeader.signature);
    _saveSitekeys();
    return newSitekey;
  }

  // Inserting null here indicates that we've received headers for a
  // URL and it didn't have sitekeys (as opposed to not receiving
  // filters yet).
  _setSitekey(tabId, frameId, url, null, null);
  _saveSitekeys();
  return null;
}

function getSitekeyHeader(headers) {
  for (let header of headers) {
    if (header.name.toLowerCase() == "x-adblock-key" && header.value) {
      let parts = header.value.split("_");
      if (parts.length < 2) {
        return null;
      }

      return {
        sitekey: parts[0].replace(/=/g, ""),
        signature: parts[1]
      };
    }
  }
  return null;
}

function verifySitekey(sitekey, signature, url) {
  let urlObj = new URL(url);
  let data = [
    urlObj.pathname + urlObj.search,
    urlObj.host,
    navigator.userAgent
  ].join("\0");
  return (0,adblockpluscore_lib_rsa_js__WEBPACK_IMPORTED_MODULE_0__.verifySignatureSync)(sitekey, signature, data);
}

const STORAGE_KEY = "ewe:sitekeys";

function verifySitekeys(_sitekeys) {
  for (let [tabId, framesMap] of Object.entries(_sitekeys)) {
    for (let [frameId, sitekeysMap] of Object.entries(framesMap)) {
      for (let [url, sitekeyInfo] of Object.entries(sitekeysMap)) {
        try {
          let verified = sitekeyInfo.sitekey === null ||
              verifySitekey(sitekeyInfo.sitekey, sitekeyInfo.signature, url);

          if (!verified) {
            delete sitekeysMap[url];
          }
        }
        catch (e) {
          delete sitekeysMap[url];
        }
      }
      if (Object.keys(sitekeysMap).length == 0) {
        delete framesMap[frameId];
      }
    }
    if (Object.keys(framesMap).length == 0) {
      delete _sitekeys[tabId];
    }
  }
}

function merge(obj1, obj2) {
  if (obj1 instanceof Array) {
    return [...obj1, ...obj2];
  }

  if (!(obj1 instanceof Object)) {
    return obj2;
  }

  let resultObj = {};

  for (let [key, obj1Values] of Object.entries(obj1)) {
    resultObj[key] = obj1Values;
  }

  for (let [key, obj2Values] of Object.entries(obj2)) {
    let map1Values = resultObj[key];
    resultObj[key] = map1Values ? merge(map1Values, obj2Values) : obj2Values;
  }

  return resultObj;
}

async function _loadSitekeys(verify = true) {
  let persistObj = await _browser_js__WEBPACK_IMPORTED_MODULE_1__["default"].storage.session.get(STORAGE_KEY);
  if (!persistObj || !persistObj[STORAGE_KEY]) {
    return;
  }

  let savedSitekeys = persistObj[STORAGE_KEY];

  if (verify) {
    verifySitekeys(savedSitekeys);
  }

  // We might have `onHeadersReceived` triggered earlier than Filter Engine
  // loading is finished. Thus we might need to merge the saved and new
  // sitekey maps.
  sitekeys = merge(savedSitekeys, sitekeys);

  notifyAllSitekeys();
}

function _doSaveSitekeys() {
  let obj = {};
  obj[STORAGE_KEY] = sitekeys;
  trackSaving(_browser_js__WEBPACK_IMPORTED_MODULE_1__["default"].storage.session.set(obj));
}

function _saveSitekeys() {
  if (!(0,_browser_features_js__WEBPACK_IMPORTED_MODULE_2__.isRunningInServiceWorker)()) {
    return;
  }

  _doSaveSitekeys();
}

let activeSaveActions = new Set();

function trackSaving(savePromise) {
  activeSaveActions.add(savePromise);
  savePromise.finally(() => activeSaveActions.delete(savePromise));
  return savePromise;
}

async function _awaitSavingComplete() {
  if (Promise.allSettled) {
    await Promise.allSettled(activeSaveActions);
    return;
  }

  // Promise.allSettled isn't supported in oldest Firefox.
  // It was added in Firefox 71.
  for (let saveAction of activeSaveActions) {
    try {
      await saveAction;
    }
    catch (e) {
    }
  }
}

async function start() {
  if (!startupPromise) {
    _browser_js__WEBPACK_IMPORTED_MODULE_1__["default"].webRequest.onHeadersReceived.addListener(
      onHeadersReceived,
      {
        urls: ["http://*/*", "https://*/*"],
        types: ["main_frame", "sub_frame"]
      },
      ["responseHeaders"]
    );

    startupPromise = ((0,_browser_features_js__WEBPACK_IMPORTED_MODULE_2__.isRunningInServiceWorker)() ?
      _loadSitekeys() : Promise.resolve(null));
  }

  await startupPromise;
}


/***/ }),

/***/ "./sdk/api/subscribe-links.js":
/*!************************************!*\
  !*** ./sdk/api/subscribe-links.js ***!
  \************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_907634__) => {

"use strict";
__nested_webpack_require_907634__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_907634__.d(__webpack_exports__, {
/* harmony export */   "onSubscribeLinkClicked": () => (/* binding */ onSubscribeLinkClicked),
/* harmony export */   "subscribeLinkClicked": () => (/* binding */ subscribeLinkClicked)
/* harmony export */ });
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_907634__(/*! ./types.js */ "./sdk/api/types.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



let dispatchFunction;

function subscribeLinkClicked(url, title) {
  if (dispatchFunction) {
    dispatchFunction({url, title});
  }
}

let onSubscribeLinkClicked = new _types_js__WEBPACK_IMPORTED_MODULE_0__.EventDispatcher(
  dispatch => {
    dispatchFunction = dispatch;
  },
  () => {
    dispatchFunction = null;
  }
);


/***/ }),

/***/ "./sdk/api/subscriptions-utils.js":
/*!****************************************!*\
  !*** ./sdk/api/subscriptions-utils.js ***!
  \****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_909384__) => {

"use strict";
__nested_webpack_require_909384__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_909384__.d(__webpack_exports__, {
/* harmony export */   "getSubscriptionRulesetMap": () => (/* binding */ getSubscriptionRulesetMap),
/* harmony export */   "rulesetExistsInManifest": () => (/* binding */ rulesetExistsInManifest),
/* harmony export */   "subscriptionFileExists": () => (/* binding */ subscriptionFileExists)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_909384__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



function getRuleset(rulesetId) {
  let manifest = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getManifest();

  if (manifest.declarative_net_request &&
    manifest.declarative_net_request.rule_resources) {
    return manifest.declarative_net_request.rule_resources.find(
      ruleset => ruleset.id == rulesetId
    );
  }

  return null;
}

function rulesetExistsInManifest(rulesetId) {
  return !!getRuleset(rulesetId);
}

async function subscriptionFileExists(subscription, path) {
  let subscriptionPath = `${path}/${subscription.id}`;
  const url = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getURL(subscriptionPath);
  try {
    const fetchResult = await fetch(url, {method: "HEAD"});
    return fetchResult.ok;
  }
  catch (error) {
    return false;
  }
}

/**
 * Get the subscription static ruleset map
 * @param {string} id The subscription id to get the map for.
 *
 * @private
 * @returns {object} The subscription map. It can be used to
 *     initialize a `Map` with key being the filter text and values
 *     being an array of ids.
 */
async function getSubscriptionRulesetMap(id) {
  let dnrSub = getRuleset(id);

  if (!dnrSub) {
    throw Error(`Subscription ${id} not found.`);
  }

  const url = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getURL(dnrSub.path + ".map");
  let response = await fetch(url);
  return await response.json();
}


/***/ }),

/***/ "./sdk/api/subscriptions-validator.js":
/*!********************************************!*\
  !*** ./sdk/api/subscriptions-validator.js ***!
  \********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_912355__) => {

"use strict";
__nested_webpack_require_912355__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_912355__.d(__webpack_exports__, {
/* harmony export */   "validate": () => (/* binding */ validate)
/* harmony export */ });
/* harmony import */ var _subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_912355__(/*! ./subscriptions-utils.js */ "./sdk/api/subscriptions-utils.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



async function validate(bundledSubscriptions,
                               bundledSubscriptionsPath) {
  let warnings = [];

  for (let subscription of bundledSubscriptions) {
    let fileExists = await (0,_subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_0__.subscriptionFileExists)(
      subscription, bundledSubscriptionsPath);
    if (!fileExists) {
      warnings.push(`No subscription content file for ID=${subscription.id}`);
    }

    if (!(0,_subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_0__.rulesetExistsInManifest)(subscription.id)) {
      warnings.push(`No ruleset with ID=${subscription.id} declared in the manifest`);
    }
  }

  return warnings;
}


/***/ }),

/***/ "./sdk/api/subscriptions.js":
/*!**********************************!*\
  !*** ./sdk/api/subscriptions.js ***!
  \**********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_914350__) => {

"use strict";
__nested_webpack_require_914350__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_914350__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "ensureDNRRulesetsEnabled": () => (/* binding */ ensureDNRRulesetsEnabled),
/* harmony export */   "getDefaultSubscriptions": () => (/* binding */ getDefaultSubscriptions),
/* harmony export */   "hasAcceptableAdsEnabled": () => (/* binding */ hasAcceptableAdsEnabled),
/* harmony export */   "isSynchronizing": () => (/* binding */ isSynchronizing),
/* harmony export */   "migrate": () => (/* binding */ migrate),
/* harmony export */   "updateSubscriptionInformation": () => (/* binding */ updateSubscriptionInformation),
/* harmony export */   "validate": () => (/* binding */ validate)
/* harmony export */ });
/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_914350__(/*! ./browser.js */ "./sdk/api/webext-browser.js");
/* harmony import */ var _subscriptions_validator_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_914350__(/*! ./subscriptions-validator.js */ "./sdk/api/subscriptions-validator.js");
/* harmony import */ var _subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_914350__(/*! ./subscriptions-utils.js */ "./sdk/api/subscriptions-utils.js");
/* harmony import */ var adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_914350__(/*! adblockpluscore/lib/subscriptionClasses.js */ "./core/lib/subscriptionClasses.js");
/* harmony import */ var adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_914350__(/*! adblockpluscore/lib/filterNotifier.js */ "./core/lib/filterNotifier.js");
/* harmony import */ var adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_914350__(/*! adblockpluscore/lib/recommendations.js */ "./core/lib/recommendations.js");
/* harmony import */ var adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_914350__(/*! adblockpluscore/lib/filterClasses.js */ "./core/lib/filterClasses.js");
/* harmony import */ var adblockpluscore_lib_filters_lists_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_914350__(/*! adblockpluscore/lib/filters/lists.js */ "./core/lib/filters/lists.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_914350__(/*! ./info.js */ "./sdk/api/info.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_914350__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_10__ = __nested_webpack_require_914350__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_11__ = __nested_webpack_require_914350__(/*! ./types.js */ "./sdk/api/types.js");
/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_12__ = __nested_webpack_require_914350__(/*! ./filters.js */ "./sdk/api/filters.js");
/* harmony import */ var _dnr_filters_js__WEBPACK_IMPORTED_MODULE_13__ = __nested_webpack_require_914350__(/*! ./dnr-filters.js */ "./sdk/api/dnr-filters.js");
/* harmony import */ var _io_js__WEBPACK_IMPORTED_MODULE_14__ = __nested_webpack_require_914350__(/*! ./io.js */ "./sdk/api/io.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_15__ = __nested_webpack_require_914350__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





















const ACCEPTABLE_ADS_ID = "0798B6A2-94A4-4ADF-89ED-BEC112FC4C7F";
const ACCEPTABLE_ADS_MV2_URL = "https://easylist-downloads.adblockplus.org/exceptionrules.txt";
const ACCEPTABLE_ADS_MV3_URL = "https://easylist-downloads.adblockplus.org/v3/full/exceptionrules.txt";

const ACCEPTABLE_ADS_PRIVACY_ID = "F12E0801-A00B-49DE-B1E3-52C9C4F90C8C";
const ACCEPTABLE_ADS_PRIVACY_MV2_URL = "https://easylist-downloads.adblockplus.org/exceptionrules-privacy-friendly.txt";
const ACCEPTABLE_ADS_PRIVACY_MV3_URL = "https://easylist-downloads.adblockplus.org/v3/full/exceptionrules-privacy-friendly.txt";

function convertSubscription(subscription) {
  const {
    id, disabled, downloadStatus, homepage, version, lastDownload, lastSuccess,
    softExpiration, expires, title, url, downloadable, downloadCount, diffURL,
    privileged} = subscription;

  let updatable = (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.FullUpdatableSubscription ||
                   subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.DiffUpdatableSubscription);

  return {
    id,
    enabled: !disabled,
    privileged,
    homepage,
    downloadable,
    updatable,
    diffURL,
    title,
    url,
    downloadCount,
    version,
    downloading: isSynchronizing(url),
    downloadStatus,
    lastSuccess,
    lastDownload,
    softExpiration,
    expires
  };
}

function convertRecommendation({id, languages, title, requires, type, url,
                                mv2URL}) {
  if (!_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
    // In MV2 we have to switch the URL to be the mv2URL
    return {id, languages, title, requires, type, url: mv2URL};
  }

  return {id, languages, title, requires, type, url, mv2URL};
}

function getSubscription(url) {
  let subscription = adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.Subscription.fromURL(url);

  if (_core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.hasSubscription(subscription) &&
      subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
    return subscription;
  }

  return null;
}

function makeListener(dispatch) {
  return subscription => {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
      dispatch(convertSubscription(subscription));
    }
  };
}

/**
 * @ignore
 */
async function hasAcceptableAdsEnabled() {
  const matches = [ACCEPTABLE_ADS_MV2_URL,
                   ACCEPTABLE_ADS_MV3_URL,
                   ACCEPTABLE_ADS_PRIVACY_MV2_URL,
                   ACCEPTABLE_ADS_PRIVACY_MV3_URL];

  for (let subscription of await getSubscriptions()) {
    if (subscription.enabled && matches.includes(subscription.url)) {
      return true;
    }
  }

  return false;
}

/**
 * @ignore
 * @param {string} uiLanguage UI language
 * @return {Array<*>}
 */
function getDefaultSubscriptions(uiLanguage) {
  let hasCurrentLang = false;
  let hasDefaultLang = false;
  let hasAA = false;
  let hasAntiCV = false;

  if (!uiLanguage) {
    // https://bugs.chromium.org/p/chromium/issues/detail?id=1159438
    if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].i18n.getUILanguage) {
      uiLanguage = _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].i18n.getUILanguage();
    }
    else {
      uiLanguage = navigator.language;
    }
  }

  let currentLang = uiLanguage.split("-")[0];
  let defaultLang = (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getManifest()
                                    .default_locale || "en").split("_")[0];

  let adSubscriptions = [];
  let adSubscriptionsDefaultLang = [];
  let aaSubscriptions = [];
  let chosenSubscriptions = [];

  for (let subscription of (0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_5__.recommendations)()) {
    switch (subscription.type) {
      case "ads":
        if (subscription.languages.includes(currentLang)){
          hasCurrentLang = true;
          adSubscriptions.push(subscription);
        }

        if (subscription.languages.includes(defaultLang)) {
          hasDefaultLang = true;
          adSubscriptionsDefaultLang.push(subscription);
        }
        break;

      case "circumvention":
        chosenSubscriptions.push(subscription);
        hasAntiCV = true;
        break;

      case "allowing":
        aaSubscriptions.push(subscription);
        hasAA = true;
        break;
    }
  }

  if (adSubscriptions.length == 0) {
    adSubscriptions = adSubscriptionsDefaultLang;
  }

  // if we have the preferred AA in the list - use it only,
  // otherwise use all listed AA subscriptions
  let preferredAASubscription = aaSubscriptions.find(
    it => it.id == ACCEPTABLE_ADS_ID);
  if (preferredAASubscription) {
    aaSubscriptions = [preferredAASubscription];
  }
  chosenSubscriptions.unshift(...aaSubscriptions);

  chosenSubscriptions.unshift(...adSubscriptions);

  return {chosenSubscriptions, hasAA, hasAntiCV,
          hasCurrentLang, hasDefaultLang};
}

function shouldAddDefaultSubscriptions() {
  let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine;
  for (let subscription of filterStorage.subscriptions()) {
    if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
      // `DiffUpdatableSubscription` is a subclass of `CountableSubscription`
      if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.CountableSubscription) {
        return false;
      }
    }

    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.FullUpdatableSubscription &&
      subscription.url != ACCEPTABLE_ADS_MV2_URL) {
      return false;
    }

    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.SpecialSubscription &&
        subscription.filterCount > 0) {
      return false;
    }
  }

  return true;
}

async function enableRuleset(rulesetId) {
  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
    if ((0,_subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_2__.rulesetExistsInManifest)(rulesetId)) {
      await _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest.updateEnabledRulesets({
        enableRulesetIds: [rulesetId]
      });

      await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_13__.restoreDynamicRules)(rulesetId);
    }
  }
}

async function disableRuleset(rulesetId) {
  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest && (0,_subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_2__.rulesetExistsInManifest)(rulesetId)) {
    await _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest.updateEnabledRulesets({
      disableRulesetIds: [rulesetId]
    });

    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_13__.disableDynamicRules)(rulesetId);
  }
}

async function getFilterText(subscription, path) {
  let subscriptionPath = `${path}/${subscription.id}`;
  let rawLines = await (0,_io_js__WEBPACK_IMPORTED_MODULE_14__.readFileContent)(subscriptionPath);
  let {lines, error} = (0,adblockpluscore_lib_filters_lists_js__WEBPACK_IMPORTED_MODULE_7__.parseFilterList)(rawLines);
  if (error) {
    throw new Error(error);
  }
  if (!lines) {
    throw new Error("invalid filter list");
  }
  lines.shift();
  return lines;
}

/**
 * @ignore
 * @param {Array<*>} bundledSubscriptions Bundled subscriptions
 * @param {String} bundledSubscriptionsPath Bundled subscriptions path
 */
async function validate(bundledSubscriptions,
                               bundledSubscriptionsPath) {
  return (0,_subscriptions_validator_js__WEBPACK_IMPORTED_MODULE_1__.validate)(
    bundledSubscriptions, bundledSubscriptionsPath);
}

async function remove(url) {
  let subscription = getSubscription(url);

  if (!subscription) {
    throw new Error(`Subscription does not exist: ${url}`);
  }

  _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.removeSubscription(subscription);

  await disableRuleset(subscription.id);
}

/**
 * @ignore
 */
async function updateSubscriptionInformation() {
  let removeUrls = [];

  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.subscriptions()) {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
      let subscriptionInfo = _info_js__WEBPACK_IMPORTED_MODULE_8__.addonBundledSubscriptions.find(
        x => x.url == subscription.url);

      if (subscriptionInfo) {
        let filterText = await getFilterText(
          subscriptionInfo, _info_js__WEBPACK_IMPORTED_MODULE_8__.addonBundledSubscriptionsPath);
        subscription.setFilterText(filterText);

        subscription.diffURL = subscriptionInfo.diff_url;
        subscription.title = subscriptionInfo.title;
        subscription.homepage = subscriptionInfo.homepage;
      }
      else {
        removeUrls.push(subscription.url);
      }
    }
  }

  for (let url of removeUrls) {
    await remove(url);
  }
}

function getSubscriptions() {
  let result = [];

  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.subscriptions()) {
    if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
      result.push(convertSubscription(subscription));
    }
  }

  return result;
}

/**
 * @ignore
 * @param {boolean} url Is synchronizing for passed URL?
 * @returns {boolean}
 */
function isSynchronizing(url) {
  return _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.synchronizer.isExecuting(url) || (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_13__.isDnrSubscriptionUpdating)(url);
}

async function add(url, properties = {}) {
  if (!adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.Subscription.isValidURL(url)) {
    throw new Error(`Invalid subscription URL provided: ${url}`);
  }

  let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine;

  let subscription = adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.Subscription.fromURL(url);

  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
    // This currently prevents us from adding user subscriptions, ie
    // those we don't know about. See EE-117.
    let subscriptionInfo = _info_js__WEBPACK_IMPORTED_MODULE_8__.addonBundledSubscriptions.find(x => x.url == url);
    if (!subscriptionInfo) {
      throw new Error(`Failed to find the subscription with URL=${url}`);
    }

    if (!subscription.downloadable) {
      let filterText;
      try {
        filterText = await getFilterText(
          subscriptionInfo, _info_js__WEBPACK_IMPORTED_MODULE_8__.addonBundledSubscriptionsPath);
      }
      catch (e) {
        // We already warn if the file doesn't exist on startup, so
        // we can ignore an error loading the bundled file here.
      }

      if (filterText) {
        subscription.setFilterText(filterText);
      }
    }
  }

  if ("title" in properties) {
    subscription.title = properties.title;
  }
  if ("homepage" in properties) {
    subscription.homepage = properties.homepage;
  }
  if ("downloadCount" in properties) {
    subscription.downloadCount = properties.downloadCount;
  }
  if ("version" in properties) {
    subscription.version = properties.version;
  }
  if ("lastDownload" in properties) {
    subscription.lastDownload = properties.lastDownload;
  }
  if ("privileged" in properties) {
    subscription.privileged = properties.privileged;
  }

  filterStorage.addSubscription(subscription);

  await enableRuleset(subscription.id);

  if (!subscription.lastDownload &&
      !isSynchronizing(subscription.url)) {
    filterStorage.synchronizer.execute(subscription);
  }
}

async function disable(url) {
  let subscription = getSubscription(url);

  if (!subscription) {
    throw new Error(`Subscription does not exist: ${url}`);
  }

  subscription.disabled = true;

  await disableRuleset(subscription.id);
}

function migrationNeeded() {
  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].runtime.getManifest().manifest_version == 2) {
    return false;
  }

  for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.subscriptions()) {
    if (subscription.downloadable) {
      return true;
    }
  }

  return false;
}

function saveMigrationError(subscription, error) {
  let errors = _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_subscription_errors;
  errors.push({subscription, error});
  _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_subscription_errors = errors;
}

/**
 * @ignore
 */
async function migrate() {
  await _initializer_js__WEBPACK_IMPORTED_MODULE_9__["default"].start();

  if (!migrationNeeded()) {
    return;
  }

  let downloadables = await getSubscriptions();
  for (let downloadable of downloadables) {
    // some subscriptions are already `CountableSubscription`,
    // that were migrated from MV2 to MV3 without diff updated.
    if (!downloadable.downloadable) {
      continue;
    }

    await remove(downloadable.url); // MV2 URL
    let subscriptionInfo = _info_js__WEBPACK_IMPORTED_MODULE_8__.addonBundledSubscriptions.find(
      it => it.mv2_url == downloadable.url);
    if (subscriptionInfo) {
      try {
        await add(subscriptionInfo.url, {
          downloadCount: downloadable.downloadCount,
          version: downloadable.version
        });
        if (!downloadable.enabled) {
          await disable(subscriptionInfo.url);
        }
      }
      catch (e) {
        saveMigrationError(downloadable, e.message);
      }
    }
    else {
      saveMigrationError(
        downloadable,
        `Failed to find the subscription with URL=${downloadable.url}`);
    }
  }
}

/**
 * @ignore
 */
async function ensureDNRRulesetsEnabled() {
  if (_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest) {
    let enabledItems = await _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest.getEnabledRulesets();

    for (let subscription of _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.subscriptions()) {
      if (!enabledItems.includes(subscription.id) && !subscription.disabled) {
        enableRuleset(subscription.id);
      }
    }
  }
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
   * The URL of the Acceptable Ads subscription.
   * @type {string}
   */
  get ACCEPTABLE_ADS_URL() {
    return _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest ?
      ACCEPTABLE_ADS_MV3_URL :
      ACCEPTABLE_ADS_MV2_URL;
  },

  /**
   * The UUID of the Acceptable Ads subscription.
   * @type {string}
   */
  ACCEPTABLE_ADS_ID,

  /**
   * The URL of the Acceptable Ads
   * without third-party tracking subscription.
   * @type {string}
   */
  get ACCEPTABLE_ADS_PRIVACY_URL() {
    return _browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest ?
      ACCEPTABLE_ADS_PRIVACY_MV3_URL :
      ACCEPTABLE_ADS_PRIVACY_MV2_URL;
  },

  /**
   * The UUID of the Acceptable Ads without third-party tracking subscription.
   * @type {string}
   */
  ACCEPTABLE_ADS_PRIVACY_ID,

  /**
   * A resource that provides a list of filters that decide what to block.
   * @typedef {Object} Subscription
   * @property {boolean} downloadable Indicates whether this subscription is
   *                                  downloaded and updated with full update
   *                                  over the network.
   * @property {boolean} updatable Indicates whether this subscription can be
   *                               updated with either full or diff update
   *                               over the network.
   * @property {?string} diffURL The URL of diff updates endpoint for
   *                             DiffUpdatableSubscriptions in MV3.
   * @property {?boolean} downloading Indicates whether the subscription is
   *                                  currently downloading (updatable
   *                                  subscriptions only).
   * @property {?string} downloadStatus The {@link https://gitlab.com/eyeo/adblockplus/abc/adblockpluscore/-/jobs/artifacts/0.6.0/file/build/docs/module-subscriptionClasses.DownloadableSubscription.html?job=docs#downloadStatus|status}
   *                                    of the most recent download attempt
   *                                    (updatable subscriptions only).
   * @property {boolean} enabled Indicates whether this subscription will
   *                             be applied.
   * @property {?number} expires Epoch time when the subscription must be
   *                             downloaded (downloadble subscriptions
   *                             only).
   * @property {?string} homepage Website of the project that manages
   *                              this filter list.
   * @property {?number} lastDownload Epoch time when the subscription
   *                                  was last downloaded to your machine
   *                                  (downloadble subscriptions only).
   * @property {?number} lastSuccess Epoch time when this subscription was last
   *                                 successfully downloaded (downloadble
   *                                 subscriptions only).
   * @property {?boolean} privileged True if this subscription can load filters
   *                                 that require privileged access, like
   *                                 snippets.
   * @property {?number} softExpiration Epoch time for the next attempt to
   *                                    download the subscription. Can be
   *                                    updated even if the subscription was
   *                                    not downloaded. If `expires` is closer,
   *                                    then `expires` prevail. (downloadble
   *                                    subscriptions only).
   * @property {string} title The display name of the subscription.
   *                          If not provided, falls back to the URL.
   * @property {string} url Where the subscription can be found in plain text.
   *                        Used a the identifier.
   * @property {string} version The version provided by the subscription's
   *                            metadata. Defaults to '0' if not provided. It
   *                            might be set if the subscription is not
   *                            downloadable.
   */

  /**
   * Creates a new subscription from a given URL. The subscription also gets
   * synchronised if it had not been previously downloaded.
   * @param {string} url The URL of the subscription to be added.
   * @param {object} [properties] An object containing properties to be
   *                              set on the new subscription.
   * @param {string} [properties.title] The display name of the subscription.
   *                                    If not provided, falls back to the URL.
   * @param {string} [properties.homepage] Website of the project that
   *                                       manages this filter list.
   * @param {boolean} [properties.privileged] Whether or not this subscription
   *                                          is allowed to run snippets.
   * @return {Promise}
   * @throws {Error} Invalid subscription URL provided.
   */
  add,

  /**
   * Adds a list of default subscriptions based on the provided bundled
   * subscriptions from the EWE.start() call.
   * Subscriptions are selected based on relevant language, type of
   * circumvention, and type of allowing.
   * @param {string} [uiLanguage] The relevant language used for
   * determining which subscriptions to add. If omitted,
   * browser.i18n.getUILanguage will be used. If
   * browser.i18n.getUILanguage is unavailable, navigator.language is
   * used.
   * @throws {Error} No default language subscription
   * @throws {Error} No current language subscription
   * @throws {Error} No anti-circumvention subscription
   * @throws {Error} No allowing subscription
   * @see {@link #start|start()}
   * @return {Promise}
   */
  async addDefaults(uiLanguage) {
    let subscriptions = [];

    if (shouldAddDefaultSubscriptions()) {
      let defaultSubscriptions = getDefaultSubscriptions(uiLanguage);
      if (!defaultSubscriptions.hasDefaultLang) {
        throw Error("No default language subscription");
      }

      if (!defaultSubscriptions.hasCurrentLang) {
        throw Error("No current language subscription");
      }

      if (!defaultSubscriptions.hasAntiCV) {
        throw Error("No anti-circumvention subscription");
      }

      if (!defaultSubscriptions.hasAA) {
        throw Error("No allowing subscription");
      }

      subscriptions.push(...defaultSubscriptions.chosenSubscriptions);
    }

    for (let subscription of subscriptions) {
      await this.add(_browser_js__WEBPACK_IMPORTED_MODULE_0__["default"].declarativeNetRequest ?
        subscription.url : subscription.mv2URL);
    }
  },

  /**
   * Returns an array of subscription objects for all subscriptions that are
   * downloaded and updated over the network.
   * @return {Promise<Array<Subscription>>}
   * @deprecated Use {@link #getSubscriptions|getSubscriptions()} instead
   */
  async getDownloadable() {
    const subscriptions = getSubscriptions();
    return subscriptions.map(each => {
      delete each.updatable; // newly introduced
      return each;
    });
  },

  /**
   * Returns an array of subscription objects for all subscriptions that are
   * downloaded and updated over the network.
   * @return {Promise<Array<Subscription>>}
   */
  async getSubscriptions() {
    const subscriptions = getSubscriptions();
    return subscriptions.map(each => {
      delete each.downloadable; // deprecated
      return each;
    });
  },

  /**
   * Returns an array of subscription objects for a given filter.
   * @param {string} text The filter rule for which to look.
   * @return {Promise<Array<Subscription>>}
   */
  async getForFilter(text) {
    return text ? Array.from(_core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine.filterStorage.subscriptions(text),
                             convertSubscription) : [];
  },

  /**
   * Returns the filter list of a given subscription URL.
   * @param {string} url The URL of the subscription.
   * @return {Promise<Array<Filter>>} Filters from the subscription.
   */
  async getFilters(url) {
    let subscription = getSubscription(url);
    if (subscription) {
      return Array.from(subscription.filterText(),
                        text => (0,_filters_js__WEBPACK_IMPORTED_MODULE_12__.convertFilter)(adblockpluscore_lib_filterClasses_js__WEBPACK_IMPORTED_MODULE_6__.Filter.fromText(text)));
    }

    return [];
  },

  /**
   * Checks if a subscription has been added.
   * @param {string} url The URL of the subscription to be checked.
   * @return {Promise<boolean>} True if a subscription has been added.
   * @throws {TypeError} Invalid URL provided.
   */
  async has(url) {
    return getSubscription(new URL(url).href) != null;
  },

  /**
   * Enables a previously disabled subscription. Has no effect otherwise.
   * @param {string} url The URL of the subscription to be enabled.
   * @return {Promise}
   * @throws {Error} Subscription does not exist.
   */
  async enable(url) {
    let subscription = getSubscription(url);

    if (!subscription) {
      throw new Error(`Subscription does not exist: ${url}`);
    }

    subscription.disabled = false;

    await enableRuleset(subscription.id);
  },

  /**
   * Disables a subscription so that it doesn't have any
   * effect until it gets enabled again.
   * @param {string} url The URL of the subscription to be disabled.
   * @return {Promise}
   * @throws {Error} Subscription does not exist.
   */
  disable,

  /**
   * Removes the subscription for the given URL.
   * It will no longer have any effect.
   * @param {string} url The URL of the subscription to be removed.
   * @return {Promise}
   * @throws {Error} Subscription does not exist.
   */
  remove,

  /**
   * Forces a new version of a subscription with the
   * given URL to be downloaded immediately.
   * @param {?string} [url] The URL of the subscription to be synchronized.
   *   If omitted, all subscriptions will be synchronized.
   * @return {Promise} Resolves when syncing has been successfully
   *   triggered. Syncing may not be completed when this promise
   *   resolves.
   * @throws {Error} Subscription does not exist.
   */
  async sync(url) {
    let subscriptions = [];
    let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_10__.filterEngine;

    if (url) {
      let subscription = getSubscription(url);

      if (!subscription) {
        throw new Error(`Subscription does not exist: ${url}`);
      }

      subscriptions.push(subscription);
    }
    else {
      for (let subscription of filterStorage.subscriptions()) {
        if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
          subscriptions.push(subscription);
        }
      }
    }
    for (let subscription of subscriptions) {
      if (!isSynchronizing(subscription.url)) {
        filterStorage.synchronizer.execute(subscription, true);
      }
    }
  },

  /**
   * Defines the recommended filter subscriptions per language.
   * @typedef {Object} Recommendation
   * @property {string} id The identifier for this subscription.
   * @property {Array<string>} languages The languages that this recommendation
   *                                      would match to.
   * @property {string} title The display name of the recommended subscription.
   * @property {Array<string>} requires A list of subscriptions that this
   *                                    one depends on.
   * @property {Array<string>} includes A list of subscriptions that this
   *                                    one also contains.
   * @property {?boolean} privileged True if this subscription can load filters
   *                                 that require privileged access, like
   *                                 snippets.
   * @property {string} type The kind of content targeted by this
   *                         recommended subscription.
   * @property {string} url Where the recommended subscription can be found
   *                        in plain text.
   * @property {?string} mv2URL Where the recommended subscription can be found
   *                            for MV2 in plain text (Manifest V3 only).
   */

  /**
   * Returns an array of all recommended subscriptions.
   * @return {Array<Recommendation>}
   */
  getRecommendations() {
    return Array.from((0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_5__.recommendations)(), convertRecommendation);
  },

  /**
   * Returns an array of MV2 to MV3 migration errors and the related
   * subscription.
   * @return {Promise<array<Subscription, string>>} The migration errors.
   */
  async getMigrationErrors() {
    return _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_subscription_errors;
  },

  /**
   * Clears the migration errors.
   * @return {Promise}
   */
  async clearMigrationErrors() {
    _prefs_js__WEBPACK_IMPORTED_MODULE_15__.Prefs.migration_subscription_errors = [];
  },

  /**
   * Emitted when a new subscription is added.
   * @event
   * @type {EventDispatcher<Subscription>}
   */
  onAdded: new _types_js__WEBPACK_IMPORTED_MODULE_11__.EventDispatcher(dispatch => {
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on("subscription.added", makeListener(dispatch));
  }),

  /**
   * Emitted when any property of the subscription has changed.
   * The name of the specific property is provided as a string, except
   * when the subscription has been updated, where it will be null.
   *
   * @event
   * @type {EventDispatcher<Subscription, string>}
   */
  onChanged: new _types_js__WEBPACK_IMPORTED_MODULE_11__.EventDispatcher(dispatch => {
    function makeChangeListener(property) {
      // This name differs between EWE and adblockpluscore.
      if (property == "disabled") {
        property = "enabled";
      }

      return subscription => {
        if (subscription instanceof adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_3__.RegularSubscription) {
          dispatch(convertSubscription(subscription), property);
        }
      };
    }

    let properties = ["disabled", "title", "homepage", "lastDownload",
                      "downloadStatus", "downloading", "privileged"];
    for (let property of properties) {
      adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on(`subscription.${property}`,
                        makeChangeListener(property));
    }

    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on("subscription.updated", makeChangeListener(null));
  }),

  /**
   * Emitted when a subscription is removed.
   * @event
   * @type {EventDispatcher<Subscription>}
   */
  onRemoved: new _types_js__WEBPACK_IMPORTED_MODULE_11__.EventDispatcher(dispatch => {
    adblockpluscore_lib_filterNotifier_js__WEBPACK_IMPORTED_MODULE_4__.filterNotifier.on("subscription.removed", makeListener(dispatch));
  })
});


/***/ }),

/***/ "./sdk/api/telemetry.js":
/*!******************************!*\
  !*** ./sdk/api/telemetry.js ***!
  \******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_948299__) => {

"use strict";
__nested_webpack_require_948299__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_948299__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   "reset": () => (/* binding */ reset),
/* harmony export */   "start": () => (/* binding */ start),
/* harmony export */   "stop": () => (/* binding */ stop)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_948299__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_948299__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");
/* harmony import */ var adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_948299__(/*! adblockpluscore/lib/time.js */ "./core/lib/time.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_948299__(/*! ./info.js */ "./sdk/api/info.js");
/* harmony import */ var _subscriptions_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_948299__(/*! ./subscriptions.js */ "./sdk/api/subscriptions.js");
/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_948299__(/*! ./types.js */ "./sdk/api/types.js");
/* harmony import */ var _scheduler_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_948299__(/*! ./scheduler.js */ "./sdk/api/scheduler.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_948299__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */











const TELEMETRY_STORAGE_KEY = "ewe:telemetry";

let scheduler = null;
let onError = new _types_js__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher(dispatch => {});

/**
 * @ignore
 * Starts the telemetry
 *
 * @param {Object} telemetry Telemetry configuration (URL, bearer)
 * @param {number} [interval]
 *        Ping interval in milliseconds (default: 12 hours)
 * @param {number} [errorRetryDelay]
 *        Error retry interval in milliseconds (default: 1 hour)
 */
function start(telemetry, interval = 12 * adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_1__.MILLIS_IN_HOUR,
                      errorRetryDelay = 1 * adblockpluscore_lib_time_js__WEBPACK_IMPORTED_MODULE_1__.MILLIS_IN_HOUR) {
  if (!telemetry.url) {
    throw new Error("No telemetry `url` provided");
  }

  if (!telemetry.bearer) {
    throw new Error("No telemetry `bearer` provided");
  }

  if (scheduler) {
    return;
  }

  scheduler = new _scheduler_js__WEBPACK_IMPORTED_MODULE_5__.Scheduler({
    interval,
    errorRetryDelay,
    listener: () => ping(telemetry),
    async getNextTimestamp() {
      let storageResult = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get(
        [TELEMETRY_STORAGE_KEY]
      );
      let storage = storageResult[TELEMETRY_STORAGE_KEY];
      let lastPing = storage && storage.lastPing;
      let lastError = storage && storage.lastError;

      if (lastError) {
        let nextRetryAfterError = new Date(lastError).getTime() +
            errorRetryDelay;
        let nowTimestamp = Date.now();
        let maxNextRetry = nowTimestamp + errorRetryDelay;
        if (nextRetryAfterError > maxNextRetry) {
          // This shouldn't happen if the clocks are working right. It implies
          // that the system clock has been set backwards since we stored that
          // timestamp. Let's correct the storage using our current clock
          // value. We shouldn't do this with lastPing because lastPing comes
          // from the server.
          nextRetryAfterError = maxNextRetry;
          await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({
            [TELEMETRY_STORAGE_KEY]: {
              ...storage,
              lastError: (new Date(nowTimestamp)).toISOString()
            }
          });
        }

        return nextRetryAfterError;
      }
      else if (lastPing) {
        return new Date(lastPing).getTime() + interval;
      }

      return null;
    }
  });
}

/**
 * @ignore
 */
async function reset() {
  stop();
  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.remove(TELEMETRY_STORAGE_KEY);
}

/**
 * @ignore
 */
function stop() {
  if (!scheduler) {
    return;
  }

  scheduler.stop();
  scheduler = null;
}

function truncateTimes(timestamp) {
  if (!timestamp) {
    return timestamp;
  }

  return timestamp.split("T")[0] + "T00:00:00Z";
}

async function ping(telemetry) {
  await _initializer_js__WEBPACK_IMPORTED_MODULE_6__["default"].start();

  const storageResult = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.get(
    [TELEMETRY_STORAGE_KEY]
  );
  const storage = storageResult[TELEMETRY_STORAGE_KEY];

  let payload = await getExtensionMetadata();
  if (storage) {
    payload.first_ping = truncateTimes(storage.firstPing);
    payload.last_ping = truncateTimes(storage.lastPing);
    payload.previous_last_ping = truncateTimes(storage.previousLastPing);
    payload.last_ping_tag = storage.lastPingTag;
  }

  let pingToken;
  try {
    pingToken = await fetchWithBearerToken(
      telemetry.url,
      telemetry.bearer,
      {payload}
    );
  }
  catch (e) {
    let lastError = (new Date()).toISOString();
    await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({
      [TELEMETRY_STORAGE_KEY]: {
        ...storage,
        lastError
      }
    });

    onError.emit({
      message: e.message,
      lastError
    });
    return false;
  }

  await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.storage.local.set({
    [TELEMETRY_STORAGE_KEY]: {
      firstPing: (storage && storage.firstPing) || pingToken,
      lastPing: pingToken,
      previousLastPing: storage && storage.lastPing,
      lastPingTag: (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])()
    }
  });
  return true;
}

async function fetchWithBearerToken(url, bearer, body) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${bearer}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(body)
  });

  if (!response.ok) {
    throw new Error(
      `Telemetry server responded with error status ${response.status}.`
    );
  }

  const data = await response.json();
  let pingToken = data.token;

  if (!pingToken) {
    throw new Error("Telemetry server response did not include a token.");
  }

  return pingToken;
}

async function getExtensionMetadata() {
  let platform;
  let platformVersion;

  if (navigator.userAgentData) {
    const platformInfo = await navigator.userAgentData.getHighEntropyValues([
      "platform",
      "platformVersion"
    ]);

    platform = platformInfo.platform;
    platformVersion = platformInfo.platformVersion;
  }
  else {
    const platformInfo = await webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__.runtime.getPlatformInfo();
    platform = platformInfo.os;
  }

  return {
    // The OS. Windows, Linux, etc.
    platform,

    // The version of the system OS.
    platform_version: platformVersion,

    // The browser. Chrome, Firefox, etc.
    application: _info_js__WEBPACK_IMPORTED_MODULE_2__.application,

    // The version of the browser.
    application_version: _info_js__WEBPACK_IMPORTED_MODULE_2__.applicationVersion,

    // Used to identify this specific project.
    addon_name: "eyeo-webext-ad-filtering-solution",

    // The Engine's current version. See the Dotenv plugin in webpack.config.js
    addon_version: "1.2.4",

    // The name of the extension using the Engine.
    extension_name: _info_js__WEBPACK_IMPORTED_MODULE_2__.addonName,

    // The extension's version.
    extension_version: _info_js__WEBPACK_IMPORTED_MODULE_2__.addonVersion,

    // Depends on having the acceptable ads subscription enabled.
    aa_active: await (0,_subscriptions_js__WEBPACK_IMPORTED_MODULE_3__.hasAcceptableAdsEnabled)()
  };
}


/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  /**
  * @typedef {Object} TelemetryPingError
  * @property {string} message The error message, describing the failure.
  * @property {string} lastError The timestamp of the error.
  */

  /**
   * Emitted when sending a telemetry ping fails.
   *
   * @event
   * @type {EventDispatcher<TelemetryPingError>}
   */
  onError
});


/***/ }),

/***/ "./sdk/api/testing.js":
/*!****************************!*\
  !*** ./sdk/api/testing.js ***!
  \****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_957545__) => {

"use strict";
__nested_webpack_require_957545__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_957545__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_957545__(/*! adblockpluscore/lib/subscriptionClasses.js */ "./core/lib/subscriptionClasses.js");
/* harmony import */ var adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_957545__(/*! adblockpluscore/lib/recommendations.js */ "./core/lib/recommendations.js");
/* harmony import */ var adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_957545__(/*! adblockpluscore/lib/notifications.js */ "./core/lib/notifications.js");
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_957545__(/*! ./core.js */ "./sdk/api/core.js");
/* harmony import */ var _prefs_js__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_957545__(/*! ./prefs.js */ "./sdk/api/prefs.js");
/* harmony import */ var _debugging_js__WEBPACK_IMPORTED_MODULE_5__ = __nested_webpack_require_957545__(/*! ./debugging.js */ "./sdk/api/debugging.js");
/* harmony import */ var _subscriptions_js__WEBPACK_IMPORTED_MODULE_6__ = __nested_webpack_require_957545__(/*! ./subscriptions.js */ "./sdk/api/subscriptions.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_7__ = __nested_webpack_require_957545__(/*! ./index.js */ "./sdk/api/index.js");
/* harmony import */ var _initializer_js__WEBPACK_IMPORTED_MODULE_8__ = __nested_webpack_require_957545__(/*! ./initializer.js */ "./sdk/api/initializer.js");
/* harmony import */ var _info_js__WEBPACK_IMPORTED_MODULE_9__ = __nested_webpack_require_957545__(/*! ./info.js */ "./sdk/api/info.js");
/* harmony import */ var _dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__ = __nested_webpack_require_957545__(/*! ./dnr-filters.js */ "./sdk/api/dnr-filters.js");
/* harmony import */ var _subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_11__ = __nested_webpack_require_957545__(/*! ./subscriptions-utils.js */ "./sdk/api/subscriptions-utils.js");
/* harmony import */ var _io_js__WEBPACK_IMPORTED_MODULE_12__ = __nested_webpack_require_957545__(/*! ./io.js */ "./sdk/api/io.js");
/* harmony import */ var adblockpluscore_lib_filterStorage_js__WEBPACK_IMPORTED_MODULE_13__ = __nested_webpack_require_957545__(/*! adblockpluscore/lib/filterStorage.js */ "./core/lib/filterStorage.js");
/* harmony import */ var _telemetry_js__WEBPACK_IMPORTED_MODULE_14__ = __nested_webpack_require_957545__(/*! ./telemetry.js */ "./sdk/api/telemetry.js");
/* harmony import */ var _sitekey_js__WEBPACK_IMPORTED_MODULE_15__ = __nested_webpack_require_957545__(/*! ./sitekey.js */ "./sdk/api/sitekey.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */





















/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  ..._sitekey_js__WEBPACK_IMPORTED_MODULE_15__, // everything exported from "sitekey.js"

  /**
   * @ignore
   * Used internally. Sets the preference value.
   * @param {string} [key] Preference key
   * @param {Object} [value] Preference value
   */
  async _setPrefs(key, value) {
    await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.init)();
    _prefs_js__WEBPACK_IMPORTED_MODULE_4__.Prefs[key] = value;
  },

  /**
   * @ignore
   * Used internally. Gets the preference value.
   * @param {string} [key] Preference key
   * @returns {Object} Preference value
   */
  async _getPrefs(key) {
    await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.init)();
    return _prefs_js__WEBPACK_IMPORTED_MODULE_4__.Prefs[key];
  },

  /**
   * @ignore
   * Used internally. Restart the Synchronizer.
   */
  _restartSynchronizer() {
    let {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine;
    filterStorage.synchronizer.stop();
    filterStorage.synchronizer.start();
  },

  /**
   * @ignore
   * Used internally. Sets the subscription property.
   * @param {string} [url] Subscription URL
   * @param {Object} [prototype] Object to set the subscription properties from.
   */
  async _setSubscriptionProperties(url, prototype) {
    let subscription = adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_0__.Subscription.fromURL(url);
    for (let property in prototype) {
      subscription[property] = prototype[property];
    }

    await _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine.filterStorage.saveToDisk();
    await _debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].ensureEverythingHasSaved();
  },

  /**
   * @ignore
   * @param {Recommendation} subscriptions
   */
  _setSubscriptions(subscriptions) {
    (0,_info_js__WEBPACK_IMPORTED_MODULE_9__.setAddonInfo)({bundledSubscriptions: subscriptions,
                  bundledSubscriptionsPath: _info_js__WEBPACK_IMPORTED_MODULE_9__.addonBundledSubscriptionsPath});
    (0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__.setRecommendations)(subscriptions);
    (0,adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_0__._clean)();
  },

  /**
   * @ignore
   * @param {Array} sources An array of sources for recommendations
   */
  _setRecommendations(sources) {
    const result = sources ?
      sources.map(recommendation => recommendation._source) : null;
    (0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__.setRecommendations)(result);
  },

  /**
   * @ignore
   * @returns {Array} An array of recommendations
   */
  _recommendations() {
    return (0,adblockpluscore_lib_recommendations_js__WEBPACK_IMPORTED_MODULE_1__.recommendations)();
  },

  /**
   * @ignore
   */
  _getDefaultSubscriptions: _subscriptions_js__WEBPACK_IMPORTED_MODULE_6__.getDefaultSubscriptions,

  /**
   * @ignore
   */
  _setAddonInfo: _info_js__WEBPACK_IMPORTED_MODULE_9__.setAddonInfo,

  /**
   * @ignore
   */
  _resetDefaultAddonInfo: _info_js__WEBPACK_IMPORTED_MODULE_9__.initializeDefaultAddonInfo,

  /**
   * @ignore
   * Clears all subscriptions and filters.
   * @return {Promise} A function that can be called to
   *                    restore the removed subscriptions and filters.
   */
  async _removeAllSubscriptions() {
    for (let subscription of await _subscriptions_js__WEBPACK_IMPORTED_MODULE_6__["default"].getSubscriptions()) {
      await _subscriptions_js__WEBPACK_IMPORTED_MODULE_6__["default"].remove(subscription.url);
    }

    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.removeAllDynamicFilters)();
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.clearRulesetUpdates)();
    (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.clearIsDnrSubscriptionUpdating)();

    const {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine;
    filterStorage._clear();
    await filterStorage.saveToDisk();

    _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine.clear();
  },

  /**
   * @ignore
   * Call dnrSubscriptionUpdate by subscription URL for testing. It
   * will get an real subscription object before calling the API.
   *
   * @param {string} url The subscription URL.
   * @param {Object} updates The updates to apply.
   */
  async _dnrSubscriptionUpdate(url, updates) {
    await this._waitForInitialization();

    const {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine;
    let subscription = filterStorage.getSubscription(url);
    // This allow testing if the subscription is not in the storage.
    if (!subscription) {
      subscription = adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_0__.Subscription.fromURL(url);
    }
    await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.dnrSubscriptionUpdate)(subscription, updates);
  },

  getSubscriptionRulesetMap: _subscriptions_utils_js__WEBPACK_IMPORTED_MODULE_11__.getSubscriptionRulesetMap,

  /*
   * @ignore
   * Serialize the result of getDynamicFilters() to an array.
   * @return {Promise} The array.
   */
  async getDynamicFilters() {
    await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.init)();

    let dynFilters = await (0,_dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.getDynamicFilters)();
    return Array.from(dynFilters.entries());
  },

  dynamicRulesAvailable: _dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.dynamicRulesAvailable,
  testSetDynamicRulesAvailable: _dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.testSetDynamicRulesAvailable,

  /**
   * @ignore
   */
  async _clearNotifications() {
    await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.init)();
    for (let notification of adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__.notifications._localNotifications) {
      adblockpluscore_lib_notifications_js__WEBPACK_IMPORTED_MODULE_2__.notifications.removeNotification(notification);
    }

    _prefs_js__WEBPACK_IMPORTED_MODULE_4__.Prefs.notificationdata = {};
    _prefs_js__WEBPACK_IMPORTED_MODULE_4__.Prefs.notifications_ignoredcategories = [];
    await (0,_prefs_js__WEBPACK_IMPORTED_MODULE_4__.awaitSavingComplete)();
  },

  enableDebugOutput(enabled) {
    if (enabled) {
      _debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].onLogEvent.addListener(_debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].CONSOLE_LOGGER);
    }
    else {
      _debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].onLogEvent.removeListener(_debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].CONSOLE_LOGGER);
    }
  },

  CONSOLE_LOGGER: _debugging_js__WEBPACK_IMPORTED_MODULE_5__["default"].logger,

  /**
   * @ignore
   * Removes "patterns.ini" to avoid state leak between the tests.
   * @return {Promise}
   */
  async _clearStorage() {
    await _io_js__WEBPACK_IMPORTED_MODULE_12__.IO.initialize();
    let oldName = adblockpluscore_lib_filterStorage_js__WEBPACK_IMPORTED_MODULE_13__.FilterStorage.sourceFile;
    let newName = "removed.tmp";
    let stat = await _io_js__WEBPACK_IMPORTED_MODULE_12__.IO.statFile(oldName);

    if (stat.exists) {
      const {filterStorage} = _core_js__WEBPACK_IMPORTED_MODULE_3__.filterEngine;
      await _io_js__WEBPACK_IMPORTED_MODULE_12__.IO.renameFile(oldName, newName);
      filterStorage.clearStats();
      await filterStorage.loadFromDisk();
    }
  },

  async _waitForInitialization() {
    await _initializer_js__WEBPACK_IMPORTED_MODULE_8__["default"].start();
  },

  clearIsDnrSubscriptionUpdating: _dnr_filters_js__WEBPACK_IMPORTED_MODULE_10__.clearIsDnrSubscriptionUpdating,
  isSynchronizing: _subscriptions_js__WEBPACK_IMPORTED_MODULE_6__.isSynchronizing,

  stopTelemetry: _telemetry_js__WEBPACK_IMPORTED_MODULE_14__.stop,
  startTelemetry: _telemetry_js__WEBPACK_IMPORTED_MODULE_14__.start,
  resetTelemetry: _telemetry_js__WEBPACK_IMPORTED_MODULE_14__.reset,

  clearSkipInitRulesets: _index_js__WEBPACK_IMPORTED_MODULE_7__.clearSkipInitRulesets,
  checkAndInitSubscriptions: _index_js__WEBPACK_IMPORTED_MODULE_7__.checkAndInitSubscriptions,
  _cleanSubscriptionClassesCache: adblockpluscore_lib_subscriptionClasses_js__WEBPACK_IMPORTED_MODULE_0__._clean
});


/***/ }),

/***/ "./sdk/api/types.js":
/*!**************************!*\
  !*** ./sdk/api/types.js ***!
  \**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_969268__) => {

"use strict";
__nested_webpack_require_969268__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_969268__.d(__webpack_exports__, {
/* harmony export */   "BlockableEventDispatcher": () => (/* reexport safe */ _diagnostics_js__WEBPACK_IMPORTED_MODULE_0__.BlockableEventDispatcher),
/* harmony export */   "EventDispatcher": () => (/* binding */ EventDispatcher),
/* harmony export */   "FilterError": () => (/* binding */ FilterError)
/* harmony export */ });
/* harmony import */ var _diagnostics_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_969268__(/*! ./diagnostics.js */ "./sdk/api/diagnostics.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */



/**
 * The EventDispatcher class allows users to listen to
 * certain events that are emitted.
 * @hideconstructor
 * @param {function} initializer
 * @param {function} [finalizer]
 */
class EventDispatcher {
  constructor(initializer, finalizer) {
    this._listeners = new Set();
    this._initialized = false;

    let dispatch = (...args) => {
      for (let listener of this._listeners) {
        listener(...args);
      }
    };

    this._initialize = initializer.bind(null, dispatch);
    this._finalize = finalizer && finalizer.bind(null, dispatch);
  }

  /**
    * Attaches a listener function to an event. This listener will be called
    * when the event is emitted. Please note that in an MV3 context this has
    * to happen in the first turn of the event loop. This should happen when
    * your service worker starts.
    * @param {function} listener The user defined function that will be called
    *                            once the specified event is emitted.
    */
  addListener(listener) {
    if (!this._initialized) {
      this._initialize();
      this._initialized = true;
    }

    this._listeners.add(listener);
  }

  /**
    * Removes the added function. The listener will no longer be called
    * by the event.
    * @param {function} listener The user defined function to be removed.
    */
  removeListener(listener) {
    this._listeners.delete(listener);

    if (this._initialized && this._finalize && this._listeners.size == 0) {
      this._finalize();
      this._initialized = false;
    }
  }

  /**
   * Call listeners with the provided arguments.
   * @param {[Object]} listener arguments
   */
  emit(...args) {
    for (let listener of this._listeners) {
      listener(...args);
    }
  }
}

/**
 * The result of parsing an invalid filter.
 * @property {string} type Either `invalid_filter` or `invalid_domain`.
 * @property {string} reason The reason why the filter is invalid.
 * @property {string?} option The filter option that made the filter invalid.
 * @param {string} type
 * @param {string} reason
 * @param {string?} option
 * @hideconstructor
 */
class FilterError extends Error {
  constructor(type, reason, option = null) {
    super(JSON.stringify({type, reason, option}));
    this.name = "FilterError";
    this.type = type;
    this.reason = reason;
    this.option = option;
  }
}


/***/ }),

/***/ "./sdk/api/webext-browser.js":
/*!***********************************!*\
  !*** ./sdk/api/webext-browser.js ***!
  \***********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_973163__) => {

"use strict";
__nested_webpack_require_973163__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_973163__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_973163__(/*! webextension-polyfill */ "./node_modules/webextension-polyfill/dist/browser-polyfill.js");
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

// reexport polyfill browser

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (webextension_polyfill__WEBPACK_IMPORTED_MODULE_0__);


/***/ }),

/***/ "./sdk/errors.js":
/*!***********************!*\
  !*** ./sdk/errors.js ***!
  \***********************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nested_webpack_require_974616__) => {

"use strict";
__nested_webpack_require_974616__.r(__webpack_exports__);
/* harmony export */ __nested_webpack_require_974616__.d(__webpack_exports__, {
/* harmony export */   "ERROR_DUPLICATE_FILTERS": () => (/* binding */ ERROR_DUPLICATE_FILTERS),
/* harmony export */   "ERROR_FILTER_NOT_FOUND": () => (/* binding */ ERROR_FILTER_NOT_FOUND),
/* harmony export */   "ERROR_TOO_MANY_FILTERS": () => (/* binding */ ERROR_TOO_MANY_FILTERS),
/* harmony export */   "ignoreNoConnectionError": () => (/* binding */ ignoreNoConnectionError)
/* harmony export */ });
/*
 * This file is part of eyeo's Web Extension Ad Blocking Toolkit (EWE),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * EWE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * EWE 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 EWE.  If not, see <http://www.gnu.org/licenses/>.
 */

const ERROR_NO_CONNECTION = "Could not establish connection. " +
      "Receiving end does not exist.";
const ERROR_CLOSED_CONNECTION = "A listener indicated an asynchronous " +
      "response by returning true, but the message channel closed before a " +
      "response was received";
// https://bugzilla.mozilla.org/show_bug.cgi?id=1578697
const ERROR_MANAGER_DISCONNECTED = "Message manager disconnected";

const ERROR_DUPLICATE_FILTERS = "storage_duplicate_filters";
const ERROR_FILTER_NOT_FOUND = "filter_not_found";
const ERROR_TOO_MANY_FILTERS = "too_many_filters";

function ignoreNoConnectionError(promise) {
  return promise.catch(error => {
    if (typeof error == "object" &&
        (error.message == ERROR_NO_CONNECTION ||
         error.message == ERROR_CLOSED_CONNECTION ||
         error.message == ERROR_MANAGER_DISCONNECTED)) {
      return;
    }

    throw error;
  });
}


/***/ }),

/***/ "./core/data/subscriptions.json":
/*!**************************************!*\
  !*** ./core/data/subscriptions.json ***!
  \**************************************/
/***/ ((module) => {

"use strict";
module.exports = JSON.parse('[{"id":"B7D76369-DD19-4602-80E8-2E32DDB490AC","type":"ads","languages":["id","ms"],"title":"ABPindo+EasyList","homepage":"http://abpindo.blogspot.com/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","A4A32212-E6BD-45F6-AD0F-E0FD18E8537B"],"url":"https://easylist-downloads.adblockplus.org/v3/full/abpindo+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abpindo+easylist.txt"},{"id":"1C571EC7-6E52-47CC-B04A-4B3008D0AEBE","type":"ads","languages":["vi"],"title":"ABPVN List+EasyList","homepage":"http://abpvn.com/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","03648752-31EE-4FD0-85C1-20B07C5551C3"],"url":"https://easylist-downloads.adblockplus.org/v3/full/abpvn+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abpvn+easylist.txt"},{"id":"E22C3B40-DC90-49D7-8BF5-E60904AB159A","type":"ads","languages":["bg"],"title":"Bulgarian list+EasyList","homepage":"https://stanev.org/abp/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","1638B159-F64A-4307-84E7-16AB08ED409E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/bulgarian_list+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/bulgarian_list+easylist.txt"},{"id":"96932CD9-6DDF-4D97-B92F-FDF747B6FAA2","type":"ads","languages":["no","nb","nn","da","is","fo","kl","sv","fi"],"title":"Dandelion Sprout\'s Nordic Filters+EasyList","homepage":"https://github.com/DandelionSprout/adfilt","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","6D489E8D-E61C-444C-BBC5-44741773ADC2"],"url":"https://easylist-downloads.adblockplus.org/v3/full/dandelion_sprouts_nordic_filters+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/dandelion_sprouts_nordic_filters+easylist.txt"},{"id":"8C13E995-8F06-4927-BEA7-6C845FB7EEBF","type":"ads","languages":["en"],"title":"EasyList","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylist.txt"},{"id":"9BD3EA2F-889D-4CC3-B680-CF484F2BD1B9","type":"ads","languages":["zh"],"title":"EasyList China+EasyList","homepage":"https://github.com/easylist/easylistchina/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","1D7F590C-B752-4BA0-9473-6A26DE1326B1"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistchina+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt"},{"id":"4B6CE485-30AB-4213-AD17-504B3F2D2825","type":"ads","languages":["cs","sk"],"title":"EasyList Czech and Slovak+EasyList","homepage":"https://adblock.sk/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","2D8C4D88-34A0-4259-9098-30D28BA674BC"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistczechslovak+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistczechslovak+easylist.txt"},{"id":"A4B88FB6-E5E5-417F-8A49-20B8244995FD","type":"ads","languages":["nl"],"title":"EasyList Dutch+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","CB94E27D-6CD1-4DB9-83D9-6B7F1A3555F6"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistdutch+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistdutch+easylist.txt"},{"id":"0CD3D105-D3B3-4652-8489-94163DE9A08F","type":"ads","languages":["de"],"title":"EasyList Germany+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","4337FB2B-A95C-44D5-B78D-11AD40F7711B"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistgermany+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistgermany+easylist.txt"},{"id":"07549D8B-F06F-4D9D-A567-929AA59E9D1D","type":"ads","languages":["he"],"title":"EasyList Hebrew+EasyList","homepage":"https://github.com/easylist/EasyListHebrew","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","AE0D9320-665E-407D-B692-1A85AE481F34"],"url":"https://easylist-downloads.adblockplus.org/v3/full/israellist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/israellist+easylist.txt"},{"id":"BBC07C05-66F1-42EC-BD4D-7AD495FAC84B","type":"ads","languages":["it"],"title":"EasyList Italy+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","2F0A4F0D-DF16-40D0-B0E0-5EB6791EC119"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistitaly+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistitaly+easylist.txt"},{"id":"CBE50FA2-DE3F-480C-B1D7-04289391C033","type":"ads","languages":["lt"],"title":"EasyList Lithuania+EasyList","homepage":"https://github.com/EasyList-Lithuania/easylist_lithuania","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","E89B3C08-2DED-40EA-8EE1-339B90D7B451"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistlithuania+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistlithuania+easylist.txt"},{"id":"3D2C09D0-DF1C-4C8E-9947-A23DCEAF8F8B","type":"ads","languages":["pl"],"title":"EasyList Polish+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","9F743FCD-801B-41D0-830F-5A4EA995216E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistpolish+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistpolish+easylist.txt"},{"id":"14DF7BE6-9675-4E07-987A-D8A1000F9FEF","type":"ads","languages":["pt"],"title":"EasyList Portuguese+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","A41441EE-BF7C-4A48-9A43-42CCEA2B2A1D"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistportuguese+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistportuguese+easylist.txt"},{"id":"C3D13A19-3E8D-41F5-AD64-0F3B36DDE128","type":"ads","languages":["es"],"title":"EasyList Spanish+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","C8C1AA76-15B4-4CA3-8A9C-AD38D6AFCAEC"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easylistspanish+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easylistspanish+easylist.txt"},{"id":"25A31255-AB36-48A4-9086-06192DE71119","type":"ads","languages":["bn","gu","hi","pa","as","mr","ml","te","kn","or","ne","si"],"title":"IndianList+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","9FAA2906-CD5C-4520-BDC4-4E098B7EA228"],"url":"https://easylist-downloads.adblockplus.org/v3/full/indianlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/indianlist+easylist.txt"},{"id":"2708BCB7-2E45-41BC-B517-1730CF532F89","type":"ads","languages":["ko"],"title":"KoreanList+EasyList","homepage":"https://easylist.to/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","BCE2062F-0D99-4861-A1F7-E3DFEA6DAB69"],"url":"https://easylist-downloads.adblockplus.org/v3/full/koreanlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/koreanlist+easylist.txt"},{"id":"950C88EA-2DD1-42E3-B2A2-2DF2ED15563A","type":"ads","languages":["lv"],"title":"Latvian List+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=99-latvian-list","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","51893C6C-F39E-43C5-A2EF-9545E388A2CE"],"url":"https://easylist-downloads.adblockplus.org/v3/full/latvianlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/latvianlist+easylist.txt"},{"id":"684A25C6-6B5D-458A-8A2B-BAC0A12B0B15","type":"ads","languages":["ar"],"title":"Liste AR+Liste FR+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=98","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","8D421590-1A68-4B68-BE50-04E17C09460E","3D60E303-1141-4775-B800-834177922876"],"url":"https://easylist-downloads.adblockplus.org/v3/full/liste_ar+liste_fr+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/liste_ar+liste_fr+easylist.txt"},{"id":"2CEA1481-C29C-44F1-A084-A2A019533797","type":"ads","languages":["fr"],"title":"Liste FR+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=98","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","8D421590-1A68-4B68-BE50-04E17C09460E"],"url":"https://easylist-downloads.adblockplus.org/v3/full/liste_fr+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/liste_fr+easylist.txt"},{"id":"EEEF75EC-B2B4-49F4-BC49-17B08266F334","type":"ads","languages":["ro"],"title":"ROList+EasyList","homepage":"https://zoso.ro/rolist/","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","99166908-5FDA-4F9E-8C4C-70BB4DEEFC08"],"url":"https://easylist-downloads.adblockplus.org/v3/full/rolist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/rolist+easylist.txt"},{"id":"1B5F78CA-8B30-4BDF-B0A3-451CB2202984","type":"ads","languages":["ru","uk"],"title":"RuAdList+EasyList","homepage":"https://forums.lanik.us/viewforum.php?f=102","includes":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF","879ECB9D-8935-4506-939E-5BBB7DD09402"],"url":"https://easylist-downloads.adblockplus.org/v3/full/ruadlist+easylist.txt","mv2_url":"https://easylist-downloads.adblockplus.org/ruadlist+easylist.txt"},{"id":"0798B6A2-94A4-4ADF-89ED-BEC112FC4C7F","type":"allowing","title":"Allow nonintrusive advertising","homepage":"https://acceptableads.com/","url":"https://easylist-downloads.adblockplus.org/v3/full/exceptionrules.txt","mv2_url":"https://easylist-downloads.adblockplus.org/exceptionrules.txt"},{"id":"D4028CDD-3D39-4624-ACC7-8140F4EC3238","type":"circumvention","title":"ABP filters","homepage":"https://github.com/abp-filters/abp-filters-anti-cv","url":"https://easylist-downloads.adblockplus.org/v3/full/abp-filters-anti-cv.txt","mv2_url":"https://easylist-downloads.adblockplus.org/abp-filters-anti-cv.txt"},{"id":"2090F374-29D9-4202-B2CE-139D6492D95E","type":"cookies","title":"I don\'t care about cookies","homepage":"https://www.i-dont-care-about-cookies.eu/","url":"https://easylist-downloads.adblockplus.org/v3/full/i_dont_care_about_cookies.txt","mv2_url":"https://easylist-downloads.adblockplus.org/i_dont_care_about_cookies.txt"},{"id":"5BD2BB73-459D-4A74-AF9D-A10157268350","type":"notifications","title":"Fanboy\'s Notifications Blocking List","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/fanboy-notifications.txt","mv2_url":"https://easylist-downloads.adblockplus.org/fanboy-notifications.txt"},{"id":"D72B6F06-52B2-4FED-96A2-1BF59CDD7AEC","type":"privacy","title":"EasyPrivacy","homepage":"https://easylist.to/","requires":["8C13E995-8F06-4927-BEA7-6C845FB7EEBF"],"url":"https://easylist-downloads.adblockplus.org/v3/full/easyprivacy.txt","mv2_url":"https://easylist-downloads.adblockplus.org/easyprivacy.txt"},{"id":"0A679439-445F-4DE7-84B9-88341F6DA520","type":"social","title":"Fanboy\'s Social Blocking List","homepage":"https://easylist.to/","url":"https://easylist-downloads.adblockplus.org/v3/full/fanboy-social.txt","mv2_url":"https://easylist-downloads.adblockplus.org/fanboy-social.txt"}]');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __nested_webpack_require_988244__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_988244__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__nested_webpack_require_988244__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__nested_webpack_require_988244__.o(definition, key) && !__nested_webpack_require_988244__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__nested_webpack_require_988244__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__nested_webpack_require_988244__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__nested_webpack_require_988244__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __nested_webpack_require_988244__("./sdk/api/index.js");
/******/ 	
/******/ 	return __webpack_exports__;
/******/ })()
;
});


/***/ }),

/***/ 16:
/***/ ((module) => {

"use strict";
module.exports = JSON.parse('{"coreLocales":["ar","de","el","en","es","fr","hu","it","ja","ko","nl","pl","pt-BR","ru","tr","zh-CN"],"nativeNames":{"af":"Afrikaans","am":"ኣማርኛ","ar":"العربية","as":"অসমীয়া","ast":"Asturianu","az":"Azərbaycan","be":"Беларуская мова","bg":"български","bn":"বাংলা (ভারত)","br":"ar brezhoneg","bs":"bosanski","ca":"català","cs":"čeština","cy":"Cymraeg","da":"dansk","de":"Deutsch","dsb":"dolnoserbski","el":"ελληνικά","en":"English","eo":"Esperanto","es":"español","et":"eesti keel","eu":"euskara","fa":"فارسى","fi":"suomi","fil":"Filipino","fo":"føroyskt","fr":"français","fy":"Frysk","gl":"Galego","gu":"ગુજરાતી (ભારત)","he":"עברית","hi":"भारतीय","hr":"Hrvatski","hsb":"hornjoserbsce","hu":"magyar","hy":"Հայերեն","id":"Bahasa Indonesia","is":"íslenska","it":"italiano","ja":"日本語","ka":"ქართული","kab":"Taqbaylit","kk":"Қазақ тілі","kl":"kalaallisut","kn":"ಕನ್ನಡ","ko":"한국어","lt":"lietuvių kalba","lv":"latviešu valoda","mg":"Malagasy","mk":"македонски","ml":"മലയാളം","mr":"मराठी","ms":"Melayu","nb":"norsk","ne":"नेपाली","nl":"Nederlands","nn":"norsk","no":"norsk","or":"ଓଡ଼ିଆ","pa":"ਪੰਜਾਬੀ (ਭਾਰਤ)","pl":"polski","pt":"português","rm":"rumantsch","ro":"română","ru":"Русский","si":"සිංහල","sk":"slovenčina","sl":"slovenščina","sq":"shqip","sr":"српски","sv":"svenska","sw":"Kiswahili","ta":"தமிழ்","te":"తెలుగు","th":"ภาษาไทย","tr":"Türkçe","uk":"українська","ur":"اردو","uz":"o’zbek","vi":"Tiếng Việt","zh":"中文"}}');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other entry modules.
(() => {
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/* eslint-env serviceworker */

if (typeof importScripts !== "undefined")
{
  importScripts("polyfill.js");
  importScripts("ext/common.js");
  importScripts("ext/background.js");
}

})();

// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";

// EXTERNAL MODULE: ./src/logger/background/index.ts + 2 modules
var background = __webpack_require__(678);
// EXTERNAL MODULE: ./node_modules/@eyeo/webext-ad-filtering-solution/dist/ewe-api.js
var ewe_api = __webpack_require__(120);
;// CONCATENATED MODULE: ./node_modules/@eyeo/snippets/webext/ml.mjs
/*!
 * This file is part of eyeo's Anti-Circumvention Snippets module (@eyeo/snippets),
 * Copyright (C) 2006-present eyeo GmbH
 * 
 * @eyeo/snippets is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 * 
 * @eyeo/snippets 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 @eyeo/snippets.  If not, see <http://www.gnu.org/licenses/>.
 */

const callback = (environment, ...filters) => {
const e=Proxy,{apply:t,bind:n,call:r}=Function,a=r.bind(t),o=r.bind(n),u=r.bind(r),i={get:(e,t)=>o(r,e[t])},c=t=>new e(t,i),l={get:(e,t)=>o(e[t],e)},s=t=>new e(t,l),{assign:p,defineProperties:f,freeze:h,getOwnPropertyDescriptor:d,getOwnPropertyDescriptors:m,getPrototypeOf:y}=s(Object),{hasOwnProperty:g}=c({}),{species:v}=Symbol,w={get(e,t){const n=e[t];class r extends n{}const a=m(n.prototype);delete a.constructor,h(f(r.prototype,a));const o=m(n);return delete o.length,delete o.prototype,o[v]={value:r},h(f(r,o))}},A=t=>new e(t,w),x="undefined"!=typeof environment?environment:{};"undefined"==typeof globalThis&&(window.globalThis=window);const{apply:B,ownKeys:b}=s(Reflect),E="world"in x,N=E&&"ISOLATED"===x.world,T=E&&"MAIN"===x.world,I="object"==typeof chrome&&!!chrome.runtime,C="object"==typeof browser&&!!browser.runtime,F=!T&&(N||I||C),O=e=>F?e:S(e,U(e)),{create:S,defineProperties:G,defineProperty:D,freeze:R,getOwnPropertyDescriptor:k,getOwnPropertyDescriptors:U}=s(Object),M=s(globalThis),H=F?globalThis:A(globalThis),{Map:P,RegExp:j,Set:X,WeakMap:L,WeakSet:Y}=H,Q=(e,t,n=null)=>{const r=b(t);for(const a of b(e)){if(r.includes(a))continue;const o=k(e,a);if(n&&"value"in o){const{value:e}=o;"function"==typeof e&&(o.value=n(e))}D(t,a,o)}},J=e=>{const t=H[e];class n extends t{}const{toString:r,valueOf:a}=t.prototype;G(n.prototype,{toString:{value:r},valueOf:{value:a}});const o=e.toLowerCase(),u=e=>function(){const t=B(e,this,arguments);return typeof t===o?new n(t):t};return Q(t,n,u),Q(t.prototype,n.prototype,u),n},K=R({frozen:new L,hidden:new Y,iframePropertiesToAbort:{read:new X,write:new X},abortedIframes:new L}),q=new j("^[A-Z]");var _=new Proxy(new P([["chrome",F&&(I&&chrome||C&&browser)||void 0],["isExtensionContext",F],["variables",K],["console",O(console)],["document",globalThis.document],["performance",O(performance)],["JSON",O(JSON)],["Map",P],["Math",O(Math)],["Number",F?Number:J("Number")],["RegExp",j],["Set",X],["String",F?String:J("String")],["WeakMap",L],["WeakSet",Y],["MouseEvent",MouseEvent]]),{get(e,t){if(e.has(t))return e.get(t);let n=globalThis[t];return"function"==typeof n&&(n=(q.test(t)?H:M)[t]),e.set(t,n),n},has:(e,t)=>e.has(t)});const V={WeakSet:WeakSet,WeakMap:WeakMap,WeakValue:class{has(){return!1}set(){}}},{apply:W}=Reflect;const{Map:Z,WeakMap:$,WeakSet:z,setTimeout:ee}=_;let te=!0,ne=e=>{e.clear(),te=!te};var re=function(e){const{WeakSet:t,WeakMap:n,WeakValue:r}=this||V,a=new t,o=new n,u=new r;return function(t){if(a.has(t))return t;if(o.has(t))return o.get(t);if(u.has(t))return u.get(t);const n=W(e,this,arguments);return a.add(n),n!==t&&("object"==typeof t&&t?o:u).set(t,n),n}}.bind({WeakMap:$,WeakSet:z,WeakValue:class extends Z{set(e,t){return te&&(te=!te,ee(ne,0,this)),super.set(e,t)}}});const{concat:ae,includes:oe,join:ue,reduce:ie,unshift:ce}=c([]),le=A(globalThis),{Map:se,WeakMap:pe}=le,fe=new se,he=t=>{const n=(e=>{const t=[];let n=e;for(;n;){if(fe.has(n))ce(t,fe.get(n));else{const e=m(n);fe.set(n,e),ce(t,e)}n=y(n)}return ce(t,{}),a(p,null,t)})("function"==typeof t?t.prototype:t),r={get(e,t){if(t in n){const{value:r,get:a}=n[t];if(a)return u(a,e);if("function"==typeof r)return o(r,e)}return e[t]},set(e,t,r){if(t in n){const{set:a}=n[t];if(a)return u(a,e,r),!0}return e[t]=r,!0}};return t=>new e(t,r)},{isExtensionContext:de,Array:me,Number:ye,String:ge,Object:ve}=_,{isArray:we}=me,{getOwnPropertyDescriptor:Ae,setPrototypeOf:xe}=ve,{toString:Be}=ve.prototype,{slice:be}=ge.prototype,{get:Ee}=Ae(Node.prototype,"nodeType"),Ne=de?{}:{Attr:he(Attr),CanvasRenderingContext2D:he(CanvasRenderingContext2D),CSSStyleDeclaration:he(CSSStyleDeclaration),Document:he(Document),Element:he(Element),HTMLCanvasElement:he(HTMLCanvasElement),HTMLElement:he(HTMLElement),HTMLImageElement:he(HTMLImageElement),HTMLScriptElement:he(HTMLScriptElement),MutationRecord:he(MutationRecord),Node:he(Node),ShadowRoot:he(ShadowRoot),get CSS2Properties(){return Ne.CSSStyleDeclaration}},Te=(e,t)=>{if("Element"!==t&&t in Ne)return Ne[t](e);if(we(e))return xe(e,me.prototype);const n=(e=>u(be,u(Be,e),8,-1))(e);if(n in Ne)return Ne[n](e);if(n in _)return xe(e,_[n].prototype);if("nodeType"in e)switch(u(Ee,e)){case 1:if(!(t in Ne))throw new Error("unknown hint "+t);return Ne[t](e);case 2:return Ne.Attr(e);case 3:return Ne.Node(e);case 9:return Ne.Document(e)}throw new Error("unknown brand "+n)};var Ie=de?e=>e===window||e===globalThis?_:e:re(((e,t="Element")=>{if(e===window||e===globalThis)return _;switch(typeof e){case"object":return e&&Te(e,t);case"string":return new ge(e);case"number":return new ye(e);default:throw new Error("unsupported value")}}));let Ce=!1;function Fe(){return Ce}let{console:Oe,document:Se,getComputedStyle:Ge,isExtensionContext:De,variables:Re,Array:ke,MutationObserver:Ue,Object:Me,XPathEvaluator:He,XPathExpression:Pe,XPathResult:je}=Ie(window);const{querySelectorAll:Xe}=Se,Le=Xe&&o(Xe,Se);function Ye(e){try{const t=navigator.userAgent.includes("Firefox")?e.openOrClosedShadowRoot:browser.dom.openOrClosedShadowRoot(e);return null===t&&Fe()&&Oe.log("Shadow root not found or not added in element yet",e),t}catch(t){return Fe()&&Oe.log("Error while accessing shadow root",e,t),null}}function Qe(e,t=!1){return qe(e,Le.bind(Se),Se,t)}function Je(e,t,n,r){const a=t.getAttribute("xlink:href")||t.getAttribute("href");if(a){const u=Le(a)[0];if(!u&&Fe())return Oe.log("No elements found matching",a),!1;if(!(o=e)||0===o.length||o.every((e=>""===e.trim()))){const e=r.length>0?r:[];return n.push({element:u,rootParents:[...e,t]}),!1}const i=u.querySelectorAll.bind(u);return{nextBoundElement:u,nestedSelectorsString:e.join("^^"),next$$:i}}var o}function Ke(e,t){const n=Ye(t);if(n){const{querySelectorAll:r}=n,a=r&&o(r,n).bind(n);return{nextBoundElement:t,nestedSelectorsString:":host "+e.join("^^"),next$$:a}}return!1}function qe(e,t,n,r,a=[]){if(e.includes("^^")){const[o,u,...i]=e.split("^^");let c,l;switch(u){case"svg":l=Je;break;case"sh":l=Ke;break;default:return Fe()&&Oe.log(u," is not supported. Supported commands are: \n^^sh^^\n^^svg^^"),[]}c=""===o.trim()?[n]:t(o);const s=[];for(const e of c){const t=l(i,e,s,a);if(!t)continue;const{next$$:n,nestedSelectorsString:o,nextBoundElement:u}=t,c=qe(o,n,u,r,[...a,e]);c&&s.push(...c)}return s}const o=t(e);return r?[...o].map((e=>({element:e,rootParents:a.length>0?a:[]}))):o}function _e(e,t,n=[]){if(t.includes("^^svg^^")&&(t=t.split("^^svg^^")[0]),t.includes("^^sh^^")){const r=t.split("^^sh^^"),a=r.length-1;if(t=`:host ${r[a]}`,a===n.length)return e.closest(t);return n[a].closest(t)}return n[0]?n[0].closest(t):e.closest(t)}const{assign:Ve,setPrototypeOf:We}=Me;class Ze extends Pe{evaluate(...e){return We(a(super.evaluate,this,e),je.prototype)}}class $e extends He{createExpression(...e){return We(a(super.createExpression,this,e),Ze.prototype)}}function ze(e){if(Re.hidden.has(e))return!1;!function(e){De&&"function"==typeof checkElement&&checkElement(e)}(e),Re.hidden.add(e);let{style:t}=Ie(e),n=Ie(t,"CSSStyleDeclaration"),r=Ie([]),{debugCSSProperties:a}=x;for(let[e,t]of a||[["display","none"]])n.setProperty(e,t,"important"),r.push([e,n.getPropertyValue(e)]);return new Ue((()=>{for(let[e,t]of r){let r=n.getPropertyValue(e),a=n.getPropertyPriority(e);r==t&&"important"==a||n.setProperty(e,t,"important")}})).observe(e,{attributes:!0,attributeFilter:["style"]}),!0}function et(e){let t=e;if(t.startsWith("xpath(")&&t.endsWith(")")){let e=t.slice(6,-1),n=(new $e).createExpression(e,null),r=je.ORDERED_NODE_SNAPSHOT_TYPE;return e=>{if(!e)return;let t=n.evaluate(Se,r,null),{snapshotLength:a}=t;for(let n=0;n<a;n++)e(t.snapshotItem(n))}}return t=>Qe(e).forEach(t)}function tt(e,t,n,r){let a;null==n&&(n=t);const o=()=>{for(const{element:o,rootParents:u}of Qe(n,!0)){const n=_e(Ie(o),t,u);n&&e(o,n,u)&&(a(),ze(n)&&"function"==typeof r&&r(n))}};return Ve(new Ue(o),{race(e){a=e,this.observe(Se,{childList:!0,characterData:!0,subtree:!0}),o()}})}function nt(e,t,n,r){let a=Ie(t,"CSSStyleDeclaration");if("none"==a.getPropertyValue("display"))return!1;let o=a.getPropertyValue("visibility");if("hidden"==o||"collapse"==o)return!1;if(!n||e==n)return!0;let u=Ie(e).parentElement;if(!u){if(!r||!r.length)return!0;u=r[r.length-1],r=r.slice(0,-1)}return nt(u,Ge(u),n,r)}function rt(e){let t=Ge(e),{cssText:n}=t;if(n)return n;for(let e of t)n+=`${e}: ${t[e]}; `;return Ie(n).trim()}let{Math:at,RegExp:ot}=Ie(window);function ut(e){let{length:t}=e;if(t>1&&"/"===e[0]){let n="/"===e[t-1];if(n||t>2&&Ie(e).endsWith("/i")){let t=[Ie(e).slice(1,n?-1:-2)];return n||t.push("i"),new ot(...t)}}return new ot(Ie(e).replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"))}const{console:it}=Ie(window),ct=()=>{};function lt(...e){Fe()&&Ie(e).unshift("%c DEBUG","font-weight: bold"),it.log(...e)}function st(e){return o(Fe()?lt:ct,null,e)}let{Array:pt,Error:ft,Map:ht,parseInt:dt}=Ie(window),mt=null,yt=null;function gt(e,t){if(null===mt)return ct;let n=mt,{participants:r}=n;return r.set(a,t),a;function a(){if(n.winners<1)return;if(st("race")(`${e} won the race`),n===mt)yt.push(a);else if(r.delete(a),--n.winners<1){for(let e of r.values())e();r.clear()}}}const vt={get(e,t){const n=e;for(;!g(e,t);)e=y(e);const{get:r,set:o}=d(e,t);return function(){return arguments.length?a(o,n,arguments):u(r,n)}}};var wt;function At(e,t,n){var r,a;n?"load"===n?(e("Waiting until window.load"),window.addEventListener("load",(()=>{e("Window.load fired."),t()}))):"loading"===n||"interactive"===n||"complete"===n?(e("Waiting document state until :",n),document.addEventListener("readystatechange",(()=>{e("Document state changed:",document.readyState),document.readyState===n&&t()}))):(e("Waiting until ",n," event is triggered on document"),(r=document,a=n,new Promise((e=>{const t=()=>{r.removeEventListener(a,t),e()};r.addEventListener(a,t)}))).then((()=>{e(n," is triggered on document, starting the snippet"),t()})).catch((t=>{e("There was an error while waiting for the event.",t)}))):t()}Ie(window),wt=window,new e(wt,vt),Ie(/^\d+$/);let{MutationObserver:xt,WeakSet:Bt,getComputedStyle:bt}=Ie(window);let{clearTimeout:Et,fetch:Nt,getComputedStyle:Tt,setTimeout:It,Map:Ct,MutationObserver:Ft,Uint8Array:Ot}=Ie(window);let St=new Ct;function Gt(e,{as:t="arrayBuffer",cleanup:n=6e4}={}){let r=t+":"+e,a=St.get(r)||{remove:()=>St.delete(r),result:null,timer:0};return Et(a.timer),a.timer=It(a.remove,n),a.result||(a.result=Nt(e).then((e=>e[t]())).catch(a.remove),St.set(r,a)),a.result}const{parseFloat:Dt,Math:Rt,MutationObserver:kt,WeakSet:Ut}=Ie(window),{min:Mt}=Rt,Ht=(e,t)=>{const n=e.length+1,r=t.length+1,a=[[0]];let o=0,u=0;for(;++o<r;)a[0][o]=o;for(o=0;++o<n;){const n=e[u];let i=0,c=0;for(a[o]=[o];++i<r;)a[o][i]=Mt(a[u][i]+1,a[o][c]+1,a[u][c]+(n!=t[c])),++c;++u}return a[n-1][r-1]};let{getComputedStyle:Pt,Map:jt,WeakSet:Xt,parseFloat:Lt}=Ie(window);const{ELEMENT_NODE:Yt,TEXT_NODE:Qt}=Node;let{MutationObserver:Jt,WeakSet:Kt,getComputedStyle:qt}=Ie(window);let{getComputedStyle:_t,MutationObserver:Vt,WeakSet:Wt}=Ie(window);Ie(window);const Zt={mark(){},end(){},toString:()=>"{mark(){},end(){}}"};function $t(e,t=10){return Zt}let{MutationObserver:zt,WeakSet:en}=Ie(window);const{ELEMENT_NODE:tn}=Node;let{MutationObserver:nn,WeakSet:rn}=Ie(window);const{ELEMENT_NODE:an}=Node;let{parseInt:on,setTimeout:un,Error:cn,MouseEvent:ln,MutationObserver:sn,WeakSet:pn}=Ie(window);const fn=["auxclick","click","dblclick","gotpointercapture","lostpointercapture","mouseenter","mousedown","mouseleave","mousemove","mouseout","mouseover","mouseup","pointerdown","pointerenter","pointermove","pointerover","pointerout","pointerup","pointercancel","pointerleave"];let{isNaN:hn,MutationObserver:dn,parseInt:mn,parseFloat:yn,setTimeout:gn}=Ie(window);const vn={log:lt,race:function(e,t="1"){switch(e){case"start":mt={winners:dt(t,10)||1,participants:new ht},yt=new pt;break;case"end":case"finish":case"stop":mt=null;for(let e of yt)e();yt=null;break;default:throw new ft(`Invalid action: ${e}`)}},debug:function(){Ce=!0},"hide-if-matches-xpath":function(e,t){const{mark:n,end:r}=$t(),a=st("hide-if-matches-xpath"),o=t=>{const o=et(`xpath(${e})`),u=new en,i=()=>{n(),o((t=>{if(u.has(t))return!1;u.add(t),l(),Ie(t).nodeType===tn?ze(t):Ie(t).textContent="",a("Matched: ",t," for selector: ",e)})),r()},c=new zt(i),l=gt("hide-if-matches-xpath",(()=>c.disconnect()));c.observe(t,{characterData:!0,childList:!0,subtree:!0}),i()};if(t){let e,n=0;const r=et(`xpath(${t})`),a=()=>{r((e=>{o(e),n++})),n>0&&e.disconnect()};e=new zt(a),e.observe(document,{characterData:!0,childList:!0,subtree:!0}),a()}else o(document)},"hide-if-matches-computed-xpath":function(e,t,n,r){const{mark:a,end:o}=$t(),u=st("hide-if-matches-computed-xpath");if(!t||!e)return void u("No query or searchQuery provided.");const i=t=>{const n=(t=>e.replace("{{}}",t))(t);u("Starting hiding elements that match query: ",n);const r=et(`xpath(${n})`),i=new rn,c=()=>{a(),r((t=>{if(i.has(t))return!1;i.add(t),s(),Ie(t).nodeType===an?ze(t):Ie(t).textContent="",u("Matched: ",t," for selector: ",e)})),o()},l=new nn(c),s=gt("hide-if-matches-computed-xpath",(()=>l.disconnect()));l.observe(document,{characterData:!0,childList:!0,subtree:!0}),c()},c=ut(n);At(u,(()=>{if(t){u("Started searching for: ",t);const e=new rn;let n;const r=et(`xpath(${t})`),a=()=>{r((t=>{if(e.has(t))return!1;if(e.add(t),u("Found node: ",t),t.innerHTML){u("Searching in: ",t.innerHTML);const e=t.innerHTML.match(c);if(e&&e.length){let t="";t=e[1]?e[1]:e[0],u("Matched search query: ",t),i(t)}}}))};n=new nn(a),n.observe(document,{characterData:!0,childList:!0,subtree:!0}),a()}}),r)},"hide-if-contains":function(e,t="*",n=null){const r=st("hide-if-contains");let a=ut(e);const o=tt((e=>a.test(Ie(e).textContent)),t,n,(e=>{r("Matched: ",e," for selector: ",t,n)}));o.race(gt("hide-if-contains",(()=>{o.disconnect()})))},"hide-if-contains-similar-text":function(e,t,n=null,r=0,a=0){const o=new Ut,u=st("hide-if-contains-similar-text"),i=Ie(e),{length:c}=i,l=c+Dt(r)||0,s=Ie([...i]).sort(),p=Dt(a)||1/0;null==n&&(n=t),u("Looking for similar text: "+i);const f=()=>{for(const{element:e,rootParents:a}of Qe(n,!0)){if(o.has(e))continue;o.add(e);const{innerText:n}=Ie(e),c=Mt(p,n.length-l+1);for(let o=0;o<c;o++){const c=Ie(n).substr(o,l);if(Ht(s,Ie([...c]).sort())-r<=0){const n=_e(Ie(e),t,a);if(u("Found similar text: "+i,n),n){d(),ze(n);break}}}}};let h=new kt(f),d=gt("hide-if-contains-similar-text",(()=>h.disconnect()));h.observe(document,{childList:!0,characterData:!0,subtree:!0}),f()},"hide-if-contains-visible-text":function(e,t,n=null,...r){let a=Ie([]);const o=new jt([["-snippet-box-margin","2"],["-disable-bg-color-check","false"],["-check-is-contained","false"]]);for(let e of r){e=Ie(e);let t=e.indexOf(":");if(t<0)continue;let n=e.slice(0,t).trim().toString(),r=e.slice(t+1).trim().toString();n&&r&&(o.has(n)?o.set(n,r):a.push([n,r]))}let u=Ie([["opacity","0"],["font-size","0px"],["color","rgba(0, 0, 0, 0)"]]),i=new jt(u.concat(a));function c(e,t,{bgColorCheck:n=!0}={}){t||(t=Pt(e)),t=Ie(t);for(const[e,n]of i){if(ut(n).test(t.getPropertyValue(e)))return!1}let r=t.getPropertyValue("color");return!n||t.getPropertyValue("background-color")!=r}function l(e,t,{bgColorCheck:n=!0}={}){let r=Pt(e,t);if(!nt(e,r)||!c(e,r,{bgColorCheck:n}))return"";let{content:a}=Ie(r);if(a&&"none"!==a){let t=Ie([]);return a=Ie(a).trim().replace(/(["'])(?:(?=(\\?))\2.)*?\1/g,(e=>""+(t.push(Ie(e).slice(1,-1))-1))),a=a.replace(/\s*attr\(\s*([^\s,)]+)[^)]*?\)\s*/g,((t,n)=>Ie(e).getAttribute(n)||"")),a.replace(/\x01(\d+)/g,((e,n)=>t[n]))}return""}function s(e,t,{boxMargin:n=2}={}){const r=Ie(e).getBoundingClientRect(),a=Ie(t).getBoundingClientRect(),o=a.left-n,u=a.right+n,i=a.top-n,c=a.bottom+n;return o<=r.left&&r.left<=u&&i<=r.top&&r.top<=c&&i<=r.bottom&&r.bottom<=c&&o<=r.right&&r.right<=u}function p(e,t,n,r,a,o,{boxMargin:u=2,bgColorCheck:i,checkIsContained:f}={}){let h=!n;if(h&&(n=Pt(e)),!nt(e,n,h&&t,o))return"";r||"hidden"!==Ie(n).getPropertyValue("overflow-x")&&"hidden"!==Ie(n).getPropertyValue("overflow-y")||(r=e);let d=l(e,":before",{bgColorCheck:i});for(let t of function(e){const t=Ye(e);return t?t.childNodes:Ie(e).childNodes}(Ie(e)))switch(Ie(t).nodeType){case Yt:d+=p(t,e,Pt(t),r,a,o,{boxMargin:u,bgColorCheck:i,checkIsContained:f});break;case Qt:if(r)s(e,r,{boxMargin:u})&&c(e,n,{bgColorCheck:i})&&(d+=Ie(t).nodeValue);else if(c(e,n,{bgColorCheck:i})){if(f&&!s(e,a,{boxMargin:u}))continue;d+=Ie(t).nodeValue}}return d+l(e,":after",{bgColorCheck:i})}const f=o.get("-snippet-box-margin"),h=Lt(f)||0,d=!("true"===o.get("-disable-bg-color-check")),m="true"===o.get("-check-is-contained");let y=ut(e),g=new Xt;const v=tt(((e,t,n)=>{if(g.has(e))return!1;g.add(e);let r=p(e,t,null,null,e,n,{boxMargin:h,bgColorCheck:d,checkIsContained:m}),a=y.test(r);return Fe()&&r.length&&lt(a,y,r),a}),t,n);v.race(gt("hide-if-contains-visible-text",(()=>{v.disconnect()})))},"hide-if-contains-and-matches-style":function(e,t="*",n=null,r=null,a=null,o,u=null,i=null){const c=st("hide-if-contains-and-matches-style"),l=new Bt,s=Fe()&&new Bt;null==n&&(n=t);const p=ut(e),f=r?ut(r):null,h=a?ut(a):null;At(c,(()=>{const e=()=>{if(!(u&&window.innerWidth<u||i&&window.innerWidth>i))for(const{element:e,rootParents:r}of Qe(n,!0))if(!l.has(e)&&p.test(Ie(e).textContent))if(!h||h.test(rt(e))){const n=_e(Ie(e),t,r);if(!n)continue;if(!f||f.test(rt(n)))a(),ze(n),l.add(e),c("Matched: ",n,"which contains: ",e," for params: ",...arguments);else{if(!s||s.has(n))continue;c("In this element the searchStyle matched but style didn't:\n",n,bt(n),...arguments),s.add(n)}}else{if(!s||s.has(e))continue;c("In this element the searchStyle didn't match:\n",e,bt(e),...arguments),s.add(e)}},r=new xt(e),a=gt("hide-if-contains-and-matches-style",(()=>r.disconnect()));r.observe(document,{childList:!0,characterData:!0,subtree:!0}),e()}),o)},"hide-if-has-and-matches-style":function(e,t="*",n=null,r=null,a=null,o=null,u=null,i=null){const c=st("hide-if-has-and-matches-style"),l=new Kt,s=Fe()&&new Kt;null==n&&(n=t);const p=r?ut(r):null,f=a?ut(a):null;At(c,(()=>{const r=()=>{if(!(u&&window.innerWidth<u||i&&window.innerWidth>i))for(const{element:r,rootParents:a}of Qe(n,!0))if(!l.has(r))if(!Ie(r).querySelector(e)||f&&!f.test(rt(r))){if(!s||s.has(r))continue;c("In this element the searchStyle didn't match:\n",r,qt(r),...arguments),s.add(r)}else{const e=_e(Ie(r),t,a);if(!e||p&&!p.test(rt(e))){if(!s||s.has(e))continue;c("In this element the searchStyle matched but style didn't:\n",e,qt(e),...arguments),s.add(e)}else o(),ze(e),l.add(r),c("Matched: ",e,"which contains: ",r," for params: ",...arguments)}},a=new Jt(r),o=gt("hide-if-has-and-matches-style",(()=>a.disconnect()));a.observe(document,{childList:!0,subtree:!0}),r()}),o)},"hide-if-labelled-by":function(e,t,n=null){let r=null==n,a=ut(e),o=new Wt,u=()=>{for(const{element:e,rootParents:u}of Qe(t,!0)){let t=r?e:_e(Ie(e),n,u);if(!t||!nt(e,_t(e),t))continue;let i=Ie(e).getAttribute("aria-labelledby"),l=()=>{o.has(t)||a.test(Ie(e).getAttribute("aria-label")||"")&&(c(),o.add(t),ze(t))};if(i)for(let e of Ie(i).split(/\s+/)){let n=Ie(document).getElementById(e);n?!o.has(n)&&a.test(n.innerText)&&(c(),o.add(n),ze(t)):l()}else l()}},i=new Vt(u),c=gt("hide-if-labelled-by",(()=>i.disconnect()));i.observe(document,{characterData:!0,childList:!0,subtree:!0}),u()},"hide-if-contains-image":function(e,t,n){null==n&&(n=t);let r=ut(e);const a=st("hide-if-contains-image");let o=()=>{for(const{element:e,rootParents:o}of Qe(n,!0)){let n=Tt(e),u=Ie(n["background-image"]).match(/^url\("(.*)"\)$/);u&&Gt(u[1]).then((n=>{if(r.test(new Ot(n).reduce(((e,t)=>e+function(e,t=2){let n=Ie(e).toString(16);n.length<t&&(n=Ie("0").repeat(t-n.length)+n);return n}(t)),""))){let n=_e(Ie(e),t,o);n&&(i(),ze(n),a("Matched: ",n," for:",...arguments))}}))}},u=new Ft(o),i=gt("hide-if-contains-image",(()=>u.disconnect()));u.observe(document,{childList:!0,subtree:!0}),o()},"simulate-mouse-event":function(...e){const t=st("simulate-mouse-event");if(e.length<1)throw new cn("[simulate-mouse-event snippet]: No selector provided.");e.length>7&&(e=e.slice(0,7));const n=Ie([]);function r(){return n.forEach((e=>{if(!e.found){(function(e){let t=e;if(t.startsWith("xpath(")&&t.endsWith(")")){let t=et(e);return()=>{let e=Ie([]);return t((t=>e.push(t))),e}}return()=>ke.from(Qe(e))})(e.selector)().length>0&&(e.found=!0)}})),n.every((e=>e.found))}function a(e,n,r){e&&n&&("click"===n&&e.click?(e.click(),t("Clicked on this node:\n",e,"\nwith a delay of",r,"ms")):(e.dispatchEvent(new ln(n,{bubbles:!0,cancelable:!0})),t("A",n,"event was dispatched with a delay of",r,"ms on this node:\n",e)))}Ie(e).forEach((e=>{const r=function(e){if(!e)return null;const n={selector:"",continue:!1,trigger:!1,event:"click",delay:"500",clicked:!1,found:!1},r=e.split("$");let a=[];r.length>=2&&(a=r[1].toLowerCase().split(",")),[n.selector]=r;for(const e of a)if("trigger"===e)n.trigger=!0;else if("continue"===e)n.continue=!0;else if(e.startsWith("event")){const t=e.toLowerCase().split("=");t[1]?n.event=t[1]:n.event="click"}else if(e.startsWith("delay")){const t=e.toLowerCase().split("=");t[1]?n.delay=t[1]:n.delay="500"}return fn.includes(n.event)||t(n.event," might be misspelled, check for typos.\n","These are the supported events:",fn),n}(e);n.push(r)}));let o=!1;const[u]=n.slice(-1);u.trigger=!0;let i=new pn;function c(){if(o||(o=r()),o)for(const e of n){const t=et(e.selector),n=on(e.delay,10);e.trigger&&t((t=>{i.has(t)||(i.add(t),e.continue?setInterval((()=>{a(t,e.event,e.delay)}),n):un((()=>{a(t,e.event,e.delay)}),n))}))}}new sn(c).observe(document,{childList:!0,subtree:!0}),c()},"skip-video":function(e,t,n=-.1,r=10,a=10){const o=yn(n||-.1),u=mn(r||10,10),i=mn(a||10,10),c=st("skip-video"),l=et(`xpath(${t})`),s=(n=0)=>{l((r=>{c("Matched: ",r," for selector: ",t),c("Running video skipping logic.");const a=Qe(e)[0];for(;hn(a.duration)&&n<u;)return void gn((()=>{const e=n+1;c("Running video skipping logic. Attempt: ",e),s(e)}),i);hn(a.duration)||(a.muted=!0,c("Muted video..."),o<=0?a.currentTime=a.duration+o:a.currentTime+=o,c("Skipped duration..."),a.paused&&a.play())}))};new dn(s).observe(document,{characterData:!0,childList:!0,subtree:!0}),s()}};let{MutationObserver:wn}=Ie(window);const{ELEMENT_NODE:An}=Node;const xn=500;async function Bn(e,t){return new Promise(((n,r)=>{if(!e||!t)return r();let a=e.config,o=a.cutoff||e.topology.graphml.nodes||xn;a=a.filter((e=>e.include));for(let e of a)e.groupName=Object.keys(e)[2];let u=(e,t,n,r)=>{"attributes"===n&&void 0!==e.attributes[r]?t.attributes[r]=e.attributes[r].value:"style"===n&&e.style[r]?t.attributes.style[r]=e.style[r]:"css"===n&&(t.cssSelectors=getComputedStyle(e).cssText||"")},i=e=>{if(o-=1,o<0)return;let t={tag:e.tagName,width:e.clientWidth,height:e.clientHeight,attributes:{style:{}},children:[]};for(let n of a)for(let r of n[n.groupName].features)for(let[a,o]of Object.entries(r))if("names"in o)for(let r of o.names)for(let a of r.split("^"))u(e,t,n.groupName,a);else u(e,t,n.groupName,a);if(e.children)for(let n of e.children){let e=i(n);e&&t.children.push(e)}return t};n(i(t))}))}const bn=5,En=7,Nn=window.self!==window.top,Tn="mldebug:";let{console:In,Map:Cn,WeakSet:Fn,MutationObserver:On}=(void 0!==Ie?Ie:e=>e)(window),Sn=new Cn;vn["hide-if-matches-xpath3"]=function(e,t){let{mark:n,end:r}=$t();const a=e=>""===e&&"http://www.w3.org/1999/xhtml";function o(e){return fontoxpath.evaluateXPathToNodes(e,document,null,null,{language:fontoxpath.evaluateXPath.XQUERY_3_1_LANGUAGE,namespaceResolver:a})}let u=st("hide-if-matches-xpath3");const i=t=>{const a=new WeakSet,i=()=>{n();const t=o(e);for(const n of Ie(t)){if(a.has(n))return!1;a.add(n),l(),Ie(n).nodeType===An?ze(n):Ie(n).textContent="",u("Matched: ",n," for selector: ",e)}r()},c=new wn(i),l=gt("hide-if-matches-xpath3",(()=>c.disconnect()));c.observe(t,{characterData:!0,childList:!0,subtree:!0}),i()};if(t){let e,n=0;const r=o(t),a=()=>{for(const e of Ie(r))i(e),n++;n>0&&e.disconnect()};e=new wn(a),e.observe(document,{characterData:!0,childList:!0,subtree:!0}),a()}else i(document)},vn["hide-if-classifies"]=function(e,t,n=""){if(!(e&&t&&"undefined"!=typeof chrome&&chrome.runtime&&chrome.runtime.sendMessage))return;let r,a=!1,o=new Cn,u=new Fn;t.startsWith(Tn)&&(a=!0,t=Ie(t).slice(8)),t=Ie(t).split("..");let i=gt("hide-if-graph-matches",(()=>f())),c=()=>{if(Sn.has(e))return Sn.get(e);s(`Preparing worker with model ${e}`);let t=new Promise(((t,n)=>{let r=setTimeout((()=>{n(`Worker preparation with ${e} failed: service worker timeout`)}),1e4);chrome.runtime.sendMessage({type:"ML:prepare",debug:a,model:e},(a=>{clearTimeout(r),a&&"config"in a?(s(`Received config for ${e}`,!1,"config:",a.config),a.config.cutoff=a.cutoff,t(a.config)):n(`Worker preparation with ${e} failed`)}))}));return t.catch((e=>{})),Sn.set(e,t),t},l=(t,n)=>{s(`Requesting inference with ${e}`,!1,"graph:",t),chrome.runtime.sendMessage({type:"ML:inference",debug:a,model:e,graph:t},(r=>{r&&"prediction"in r?(s(`Received ${r.prediction} inference results with ${e}`,!1,"graph:",t),!a&&r.prediction?(i(),ze(n)):a&&r.prediction?Ie(n).style.border="5px solid #ff0000":a&&!r.prediction&&(Ie(n).style.border="5px solid #00ff00")):(s(`Inference with ${e} failed`,!0,"graph:",t,"response:",r),!("error"in r)||r.error!==bn&&r.error!==En||f())}))},s=(e,t=!1,...n)=>{a&&In.log("%cMLDBG ♥ %c| %s%c%s%c |","color:cyan",t?"color:red":"color:inherit",e,"color:grey",Nn?" (from iframe)":"","color:inherit",...n)},p=()=>{(()=>{let e=[document];Ie(t).forEach(((t,n)=>{n&&(e=Ie(e).reduce(((e,t)=>t&&Ie(t).parentElement?e.concat(Ie(t).parentElement):e),Ie([]))),e=Ie(e).reduce(((e,n)=>{if(t)try{e=e.concat(...Ie(n).querySelectorAll(t))}catch(e){}else e.push(n);return e}),Ie([]))}));for(let t of e){let r=[t];if(n)try{r=Ie(t).querySelectorAll(n)}catch(e){}u.has(t)||o.set(t,r)}})(),!o.size&&Nn||c().then((t=>{if(!t)return Promise.reject(`Config file for ${e} corrupted`);for(let[n,r]of o.entries()){for(let a of r)s(`Preparing inference with ${e}`,!1,"target:",n),Bn({config:t},a).then((e=>{l(e,n)})).catch((e=>s(`domToGraph failed with error "${e}"`,!0,"target:",n)));u.add(n),o.delete(n)}})).catch((e=>{s(e,!0),f()}))},f=()=>{r.disconnect(),o.clear()};Nn||s(`Filter hit for ${e}: ${t.join("..")} ${n}`),r=new On((()=>p())),r.observe(document,{childList:!0,subtree:!0}),p()};
const snippets=vn;
let context;
for (const [name, ...args] of filters) {
if (snippets.hasOwnProperty(name)) {
try { context = snippets[name].apply(context, args); }
catch (error) { console.error(error); }
}
}
context = void 0;
};
const graph = new Map([["log",null],["race",null],["debug",null],["hide-if-matches-xpath",null],["hide-if-matches-computed-xpath",null],["hide-if-contains",null],["hide-if-contains-similar-text",null],["hide-if-contains-visible-text",null],["hide-if-contains-and-matches-style",null],["hide-if-has-and-matches-style",null],["hide-if-labelled-by",null],["hide-if-contains-image",null],["simulate-mouse-event",null],["skip-video",null],["hide-if-matches-xpath3",function(){var e,t,n,r,a,o;e=this,function(e){function t(e,t,n,r){const a={op:t,func:n,data:r};return e.push(a),a}function n(e,t){return e}class r{constructor(){this.program=[]}test(e,n){return t(this.program,5,e,void 0===n?null:n)}jump(e){return t(this.program,3,null,e)}record(e,r){return t(this.program,4,void 0===r?n:r,e)}bad(e=1){return t(this.program,1,null,e)}accept(){return t(this.program,0,null,null)}fail(e){return t(this.program,2,e||null,null)}}class a{constructor(e,t,n){this.programLength=e,this.maxFromByPc=t,this.maxSurvivorFromByPc=n}static fromProgram(e){const t=e.length,n=[],r=[];return e.forEach((e=>{n.push(0),r.push(0)})),e.forEach(((e,a)=>{switch(e.op){case 2:if(null===e.func)return;if(a+1>=t)throw new Error("Invalid program: program could run past end");n[a+1]+=1;break;case 1:case 4:if(a+1>=t)throw new Error("Invalid program: program could run past end");n[a+1]+=1;break;case 3:e.data.forEach((e=>{if(e<0||e>=t)throw new Error("Invalid program: program could run past end");n[e]+=1}));break;case 5:if(a+1>=t)throw new Error("Invalid program: program could run past end");r[a+1]+=1;break;case 0:r[a]+=1}})),new a(t,n,r)}static createStub(e){const t=[],n=[];for(let r=0;r<e;++r)t.push(e),n.push(e);return new a(e,t,n)}}class o{constructor(e){this.acceptingTraces=e,this.success=e.length>0}}const u=255;class i{constructor(e){this.t=0,this.i=0,this.h=new Uint16Array(e),this.l=new Uint8Array(e)}getBadness(e){return this.l[e]}add(e,t){this.l[e]=t>u?u:t;const n=function(e,t,n,r,a){let o=r,u=a;for(;o<u;){const r=o+u>>>1;n<t[e[r]]?u=r:o=r+1}return o}(this.h,this.l,t,this.i,this.t);this.h.copyWithin(n+1,n,this.t),this.h[n]=e,this.t+=1}reschedule(e,t){const n=Math.max(this.l[e],t>u?u:t);if(this.l[e]!==n){const t=this.h.indexOf(e,this.i);if(t<0||t>=this.t)return void(this.l[e]=n);this.h.copyWithin(t,t+1,this.t),this.t-=1,this.add(e,n)}}getNextPc(){return this.i>=this.t?null:this.h[this.i++]}reset(){this.t=0,this.i=0,this.l.fill(0)}}class c{constructor(e){this.o=[];let t=e.length;e.forEach((e=>{this.o.push(e>0?t:-1),t+=e})),this.u=new Uint16Array(t)}clear(){this.u.fill(0,0,this.o.length)}add(e,t){const n=this.u[t],r=this.o[t];this.u[t]+=1,this.u[r+n]=e}has(e){return this.u[e]>0}forEach(e,t){const n=this.u[e],r=this.o[e];for(let e=r;e<r+n;++e)t(this.u[e])}}function l(e,t,n=!1){return null===e?t:Array.isArray(e)?(-1===e.indexOf(t)&&(n&&(e=e.slice()),e.push(t)),e):e===t?e:[e,t]}class s{constructor(e,t){this.prefixes=e,this.record=t}}function p(e,t){let n;if(null===t){if(!Array.isArray(e))return e;n=e}else n=e===s.EMPTY?[]:Array.isArray(e)?e:[e];return new s(n,t)}s.EMPTY=new s([],null);class f{constructor(e){this.p=[],this.v=[];for(let t=0;t<e;++t)this.p.push(0),this.v.push(null)}mergeTraces(e,t,n,r,a,o){let u=!1;return n.forEach(t,(t=>{const n=this.trace(t,r,a,o);var i,c,s;c=n,s=u,e=null===(i=e)?c:null===c?i:Array.isArray(c)?c.reduce(((e,t)=>l(e,t,e===c)),i):l(i,c,s),u=e===n})),e}trace(e,t,n,r){switch(this.p[e]){case 2:return this.v[e];case 1:return null}this.p[e]=1;let a=null;const o=t[e];if(null!==o)a=o;else if(!n.has(e))throw new Error(`Trace without source at pc ${e}`);if(a=this.mergeTraces(a,e,n,t,n,r),null!==a){const t=r[e];null!==t&&(a=p(a,t))}return this.v[e]=a,this.p[e]=2,a}buildSurvivorTraces(e,t,n,r,a){for(let o=0,u=e.length;o<u;++o){if(!n.has(o)){t[o]=null;continue}this.v.fill(null),this.p.fill(0);const u=this.mergeTraces(null,o,n,e,r,a);if(null===u)throw new Error(`No non-cyclic paths found to survivor ${o}`);t[o]=p(u,null)}this.v.fill(null)}}class h{constructor(e){this.g=[],this.k=[],this.m=[],this.A=new c(e.maxFromByPc),this.T=new c(e.maxSurvivorFromByPc),this.S=new f(e.programLength);for(let t=0;t<e.programLength;++t)this.g.push(null),this.k.push(null),this.m.push(null);this.k[0]=s.EMPTY}reset(e){this.A.clear(),this.T.clear(),this.g.fill(null),e&&(this.k.fill(null),this.m.fill(null),this.k[0]=s.EMPTY)}record(e,t){this.g[e]=t}has(e){return this.A.has(e)||null!==this.k[e]}add(e,t){this.A.add(e,t)}hasSurvivor(e){return this.T.has(e)}addSurvivor(e,t){this.T.add(e,t)}buildSurvivorTraces(){const e=this.k;this.S.buildSurvivorTraces(e,this.m,this.T,this.A,this.g),this.k=this.m,this.m=e}getTraces(e){const t=e.reduce(((e,t)=>l(e,this.k[t])),null);return null===t?[]:Array.isArray(t)?t:[t]}}class d{constructor(e){this.I=[],this.M=new i(e.programLength),this.N=new i(e.programLength),this.j=new h(e)}reset(){this.M.reset(),this.M.add(0,0),this.I.length=0,this.j.reset(!0)}getNextThreadPc(){return this.M.getNextPc()}step(e,t,n){const r=this.j.has(t);this.j.add(e,t);const a=this.M.getBadness(e)+n;r?this.M.reschedule(t,a):this.M.add(t,a)}stepToNextGeneration(e,t){const n=this.j.hasSurvivor(t);this.j.addSurvivor(e,t);const r=this.M.getBadness(e);n?this.N.reschedule(t,r):this.N.add(t,r)}accept(e){this.I.push(e),this.j.addSurvivor(e,e)}fail(e){}record(e,t){this.j.record(e,t)}nextGeneration(){this.j.buildSurvivorTraces(),this.j.reset(!1);const e=this.M;e.reset(),this.M=this.N,this.N=e}getAcceptingTraces(){return this.j.getTraces(this.I)}}class m{constructor(e){this.P=[],this.U=e,this.G=a.fromProgram(e),this.P.push(new d(this.G))}execute(e,t){const n=this.P.pop()||new d(this.G);n.reset();const r=e.length;let a,u=-1;do{let o=n.getNextThreadPc();if(null===o)break;for(++u,a=u>=r?null:e[u];null!==o;){const e=this.U[o];switch(e.op){case 0:null===a?n.accept(o):n.fail(o);break;case 2:{const r=e.func;if(null===r||r(t)){n.fail(o);break}n.step(o,o+1,0);break}case 1:n.step(o,o+1,e.data);break;case 5:if(null===a){n.fail(o);break}if(!(0,e.func)(a,e.data,t)){n.fail(o);break}n.stepToNextGeneration(o,o+1);break;case 3:{const t=e.data,r=t.length;if(0===r){n.fail(o);break}for(let e=0;e<r;++e)n.step(o,t[e],0);break}case 4:{const r=(0,e.func)(e.data,u,t);null!=r&&n.record(o,r),n.step(o,o+1,0);break}}o=n.getNextThreadPc()}n.nextGeneration()}while(null!==a);const i=new o(n.getAcceptingTraces());return n.reset(),this.P.push(n),i}}function y(e){const t=new r;return e(t),new m(t.program)}var g={Assembler:r,VM:m,compileVM:y};e.Assembler=r,e.VM=m,e.compileVM=y,e.default=g,Object.defineProperty(e,"V",{value:!0})}((e="undefined"!=typeof globalThis?globalThis:e||self).whynot={}),t=this,function(e){function t(e,t){return{success:!0,offset:e,value:t}}function n(e){return t(e,void 0)}function r(e,t,n=!1){return{success:!1,offset:e,expected:t,fatal:n}}function a(e){return e>65535?2:1}function o(e,t){return(o,u)=>{const i=o.codePointAt(u);return void 0!==i&&e(i)?n(u+a(i)):r(u,t)}}function u(e,n){return(r,a)=>{const o=e(r,a);return o.success?t(o.offset,n(o.value)):o}}function i(e){return(n,r)=>{let a=[],o=r;for(;;){const t=e(n,o);if(!t.success){if(t.fatal)return t;break}if(a.push(t.value),t.offset===o)break;o=t.offset}return t(o,a)}}function c(e){return(t,r)=>{let a=r;for(;;){const n=e(t,a);if(!n.success){if(n.fatal)return n;break}if(n.offset===a)break;a=n.offset}return n(a)}}function l(e,n,r){return(a,o)=>{const u=e(a,o);if(!u.success)return u;const i=n(a,u.offset);return i.success?t(i.offset,r(u.value,i.value)):i}}function s(e,t){return e}function p(e,t){return t}function f(e,t){return l(e,t,p)}function h(e,t){return l(e,t,s)}function d(e,t){return(a,o)=>e(a,o).success?r(o,t):n(o)}function m(e){return(t,n)=>{const a=e(t,n);return a.success?a:r(a.offset,a.expected,!0)}}const y=(e,t)=>e.length===t?n(t):r(t,["end of input"]);function g(e){const t=[];let n=e.next();for(;!n.done;)t.push(n.value),n=e.next();return[t,n.value]}e.codepoint=o,e.codepoints=function(e,t){return(a,o)=>{const u=o;for(;;){const t=a.codePointAt(o);if(void 0===t)break;if(!e(t))break;o+=t>65535?2:1}return void 0!==t&&o===u?r(o,t):n(o)}},e.collect=g,e.complete=function(e){return l(e,y,s)},e.consume=function(e){return u(e,(()=>{}))},e.cut=m,e.delimited=function(e,t,n,r=!1){return f(e,r?m(h(t,n)):h(t,n))},e.dispatch=function(e,t,n=0,a=[]){return(o,u)=>{const i=o.codePointAt(u+n);if(void 0===i)return r(u,a);const c=e[i];return void 0===c?void 0===t?r(u,a):t(o,u):c(o,u)}},e.end=y,e.error=r,e.except=function(e,t,n){return f(d(t,n),e)},e.filter=function(e,t,n,a){return(o,u)=>{const i=e(o,u);return i.success?t(i.value)?i:r(u,n,a):i}},e.filterUndefined=function(e){return u(e,(e=>e.filter((e=>void 0!==e))))},e.first=s,e.followed=h,e.map=u,e.not=d,e.ok=n,e.okWithValue=t,e.optional=function(e){return(n,r)=>{const a=e(n,r);return a.success||a.fatal?a:t(r,null)}},e.or=function(e,t){return(n,a)=>{let o=null;for(const r of e){const e=r(n,a);if(e.success)return e;if(null===o||e.offset>o.offset?o=e:e.offset===o.offset&&void 0===t&&(o.expected=o.expected.concat(e.expected)),e.fatal)return e}return t=t||(null==o?void 0:o.expected)||[],o&&(o.expected=t),o||r(a,t)}},e.peek=function(e){return(n,r)=>{const a=e(n,r);return a.success?t(r,a.value):a}},e.plus=function(e){return l(e,i(e),((e,t)=>[e].concat(t)))},e.plusConsumed=function(e){return l(e,c(e),p)},e.preceded=f,e.range=function(e,t,n){return o((n=>e<=n&&n<=t),n||[`${String.fromCodePoint(e)}-${String.fromCodePoint(t)}`])},e.recognize=function(e){return(n,r)=>{const a=e(n,r);return a.success?t(a.offset,n.slice(r,a.offset)):a}},e.second=p,e.sequence=function(...e){return(n,r)=>{const a=[];for(const t of e){const e=t(n,r);if(!e.success)return e;r=e.offset,a.push(e.value)}return t(r,a)}},e.sequenceConsumed=function(...e){return(t,r)=>{for(const n of e){const e=n(t,r);if(!e.success)return e;r=e.offset}return n(r)}},e.skipChars=function(e){return(t,o)=>{let u=e;for(;u>0;){const e=t.codePointAt(o);if(void 0===e)return r(o,["any character"]);o+=a(e),u-=1}return n(o)}},e.star=i,e.starConsumed=c,e.start=(e,t)=>0===t?n(t):r(t,["start of input"]),e.streaming=function(e){return function*(t,n){const r=e(t,n);return r.success&&(yield r.value),r}},e.streamingComplete=function(e){return function*(t,n){const r=yield*e(t,n);return r.success?y(t,r.offset):r}},e.streamingFilterUndefined=function(e){return function*(t,n){const r=e(t,n);let a=r.next();for(;!a.done;){const e=a.value;void 0!==e&&(yield e),a=r.next()}return a.value}},e.streamingOptional=function(e){return function*(t,r){const[a,o]=g(e(t,r));return o.success?(yield*a,o):o.fatal?o:n(r)}},e.streamingStar=function(e){return function*(t,r){for(;;){const[a,o]=g(e(t,r));if(!o.success)return o.fatal?o:n(r);if(yield*a,r===o.offset)return n(r);r=o.offset}}},e.streamingThen=function(e,t){return function*(n,r){const a=yield*e(n,r);return a.success?yield*t(n,a.offset):a}},e.then=l,e.token=function(e){return(n,a)=>{const o=a+e.length;return n.slice(a,o)===e?t(o,e):r(a,[e])}},Object.defineProperty(e,"__esModule",{value:!0})}((t="undefined"!=typeof globalThis?globalThis:t||self).prsc={}),n=this,function(e,t){function n(e){return t=>t===e}function r(e,t){if(null===e||null===t)throw new Error("unescaped hyphen may not be used as a range endpoint");if(t<e)throw new Error("character range is in the wrong order");return n=>e<=n&&n<=t}function a(e){return!0}function o(){return!1}function u(e,t){return n=>e(n)||t(n)}const i=-1,c=-2;function l(e,t){switch(t.kind){case"predicate":return void e.test(t.value);case"regexp":return void p(e,t.value,!1)}}function s(e,t){t.forEach((t=>{!function(e,t){const[n,{min:r,max:a}]=t;if(null!==a){for(let t=0;t<r;++t)l(e,n);for(let t=r;t<a;++t){const t=e.jump([]);t.data.push(e.program.length),l(e,n),t.data.push(e.program.length)}}else if(r>0){for(let t=0;t<r-1;++t)l(e,n);const t=e.program.length;l(e,n),e.jump([t]).data.push(e.program.length)}else{const t=e.program.length,r=e.jump([]);r.data.push(e.program.length),l(e,n),e.jump([t]),r.data.push(e.program.length)}}(e,t)}))}function p(e,t,n){const r=e.program.length,a=e.jump([]);n&&(a.data.push(e.program.length),e.test((()=>!0)),e.jump([r]));const o=[];if(t.forEach((t=>{a.data.push(e.program.length),s(e,t),o.push(e.jump([]))})),o.forEach((t=>{t.data.push(e.program.length)})),n){const t=e.program.length,n=e.jump([]);n.data.push(e.program.length),e.test((()=>!0)),e.jump([t]),n.data.push(e.program.length)}}function f(e,t){return{success:!0,offset:e,value:t}}function h(e){return f(e,void 0)}function d(e,t,n=!1){return{success:!1,offset:e,expected:t,fatal:n}}function m(e){return(t,n)=>{const r=n+e.length;return t.slice(n,r)===e?f(r,e):d(n,[e])}}function y(e,t){return(n,r)=>{const a=e(n,r);return a.success?f(a.offset,t(a.value)):a}}function g(e,t,n,r){return(a,o)=>{const u=e(a,o);return u.success?t(u.value)?u:d(o,n,r):u}}function v(e,t){return(n,r)=>{let a=null;for(const o of e){const e=o(n,r);if(e.success)return e;if(null===a||e.offset>a.offset?a=e:e.offset===a.offset&&void 0===t&&(a.expected=a.expected.concat(e.expected)),e.fatal)return e}return t=t||(null==a?void 0:a.expected)||[],a&&(a.expected=t),a||d(r,t)}}function w(e){return(t,n)=>{const r=e(t,n);return r.success||r.fatal?r:f(n,null)}}function A(e){return(t,n)=>{let r=[],a=n;for(;;){const n=e(t,a);if(!n.success){if(n.fatal)return n;break}if(r.push(n.value),n.offset===a)break;a=n.offset}return f(a,r)}}function x(e,t,n){return(r,a)=>{const o=e(r,a);if(!o.success)return o;const u=t(r,o.offset);return u.success?f(u.offset,n(o.value,u.value)):u}}function B(e){return x(e,A(e),((e,t)=>[e].concat(t)))}function b(e,t){return e}function E(e,t){return t}function N(e,t){return x(e,t,E)}function T(e,t){return x(e,t,b)}function I(e,t,n,r=!1){return N(e,r?F(T(t,n)):T(t,n))}function C(e,t){return(n,r)=>e(n,r).success?d(r,t):h(r)}function F(e){return(t,n)=>{const r=e(t,n);return r.success?r:d(r.offset,r.expected,!0)}}const O=(e,t)=>e.length===t?h(t):d(t,["end of input"]),S=["Lu","Ll","Lt","Lm","Lo","Mn","Mc","Me","Nd","Nl","No","Pc","Pd","Ps","Pe","Pi","Pf","Po","Zs","Zl","Zp","Sm","Sc","Sk","So","Cc","Cf","Co","Cn"],G={};function D(e){return e.codePointAt(0)}"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(((e,t)=>{G[e]=t}));const R=e=>e===i||e===c;function k(e){return t=>!R(t)&&!e(t)}function U(e,t){return null===t?e:n=>e(n)&&!t(n)}const M=function(e,t){const n=new Map;let a=0;return e.forEach(((e,o)=>{const i=t[o];null!==e&&e.split("|").forEach((e=>{const t=n.get(e),o=r(a,a+i-1);n.set(e,t?u(t,o):o)})),a+=i})),n}(["BasicLatin","Latin-1Supplement","LatinExtended-A","LatinExtended-B","IPAExtensions","SpacingModifierLetters","CombiningDiacriticalMarks","GreekandCoptic|Greek","Cyrillic","CyrillicSupplement","Armenian","Hebrew","Arabic","Syriac","ArabicSupplement","Thaana","NKo","Samaritan","Mandaic","SyriacSupplement","ArabicExtended-B","ArabicExtended-A","Devanagari","Bengali","Gurmukhi","Gujarati","Oriya","Tamil","Telugu","Kannada","Malayalam","Sinhala","Thai","Lao","Tibetan","Myanmar","Georgian","HangulJamo","Ethiopic","EthiopicSupplement","Cherokee","UnifiedCanadianAboriginalSyllabics","Ogham","Runic","Tagalog","Hanunoo","Buhid","Tagbanwa","Khmer","Mongolian","UnifiedCanadianAboriginalSyllabicsExtended","Limbu","TaiLe","NewTaiLue","KhmerSymbols","Buginese","TaiTham","CombiningDiacriticalMarksExtended","Balinese","Sundanese","Batak","Lepcha","OlChiki","CyrillicExtended-C","GeorgianExtended","SundaneseSupplement","VedicExtensions","PhoneticExtensions","PhoneticExtensionsSupplement","CombiningDiacriticalMarksSupplement","LatinExtendedAdditional","GreekExtended","GeneralPunctuation","SuperscriptsandSubscripts","CurrencySymbols","CombiningDiacriticalMarksforSymbols|CombiningMarksforSymbols","LetterlikeSymbols","NumberForms","Arrows","MathematicalOperators","MiscellaneousTechnical","ControlPictures","OpticalCharacterRecognition","EnclosedAlphanumerics","BoxDrawing","BlockElements","GeometricShapes","MiscellaneousSymbols","Dingbats","MiscellaneousMathematicalSymbols-A","SupplementalArrows-A","BraillePatterns","SupplementalArrows-B","MiscellaneousMathematicalSymbols-B","SupplementalMathematicalOperators","MiscellaneousSymbolsandArrows","Glagolitic","LatinExtended-C","Coptic","GeorgianSupplement","Tifinagh","EthiopicExtended","CyrillicExtended-A","SupplementalPunctuation","CJKRadicalsSupplement","KangxiRadicals",null,"IdeographicDescriptionCharacters","CJKSymbolsandPunctuation","Hiragana","Katakana","Bopomofo","HangulCompatibilityJamo","Kanbun","BopomofoExtended","CJKStrokes","KatakanaPhoneticExtensions","EnclosedCJKLettersandMonths","CJKCompatibility","CJKUnifiedIdeographsExtensionA","YijingHexagramSymbols","CJKUnifiedIdeographs","YiSyllables","YiRadicals","Lisu","Vai","CyrillicExtended-B","Bamum","ModifierToneLetters","LatinExtended-D","SylotiNagri","CommonIndicNumberForms","Phags-pa","Saurashtra","DevanagariExtended","KayahLi","Rejang","HangulJamoExtended-A","Javanese","MyanmarExtended-B","Cham","MyanmarExtended-A","TaiViet","MeeteiMayekExtensions","EthiopicExtended-A","LatinExtended-E","CherokeeSupplement","MeeteiMayek","HangulSyllables","HangulJamoExtended-B","HighSurrogates","HighPrivateUseSurrogates","LowSurrogates","PrivateUseArea|PrivateUse","CJKCompatibilityIdeographs","AlphabeticPresentationForms","ArabicPresentationForms-A","VariationSelectors","VerticalForms","CombiningHalfMarks","CJKCompatibilityForms","SmallFormVariants","ArabicPresentationForms-B","HalfwidthandFullwidthForms","Specials","LinearBSyllabary","LinearBIdeograms","AegeanNumbers","AncientGreekNumbers","AncientSymbols","PhaistosDisc",null,"Lycian","Carian","CopticEpactNumbers","OldItalic","Gothic","OldPermic","Ugaritic","OldPersian",null,"Deseret","Shavian","Osmanya","Osage","Elbasan","CaucasianAlbanian","Vithkuqi",null,"LinearA","LatinExtended-F",null,"CypriotSyllabary","ImperialAramaic","Palmyrene","Nabataean",null,"Hatran","Phoenician","Lydian",null,"MeroiticHieroglyphs","MeroiticCursive","Kharoshthi","OldSouthArabian","OldNorthArabian",null,"Manichaean","Avestan","InscriptionalParthian","InscriptionalPahlavi","PsalterPahlavi",null,"OldTurkic",null,"OldHungarian","HanifiRohingya",null,"RumiNumeralSymbols","Yezidi","ArabicExtended-C","OldSogdian","Sogdian","OldUyghur","Chorasmian","Elymaic","Brahmi","Kaithi","SoraSompeng","Chakma","Mahajani","Sharada","SinhalaArchaicNumbers","Khojki",null,"Multani","Khudawadi","Grantha",null,"Newa","Tirhuta",null,"Siddham","Modi","MongolianSupplement","Takri",null,"Ahom",null,"Dogra",null,"WarangCiti","DivesAkuru",null,"Nandinagari","ZanabazarSquare","Soyombo","UnifiedCanadianAboriginalSyllabicsExtended-A","PauCinHau","DevanagariExtended-A",null,"Bhaiksuki","Marchen",null,"MasaramGondi","GunjalaGondi",null,"Makasar","Kawi",null,"LisuSupplement","TamilSupplement","Cuneiform","CuneiformNumbersandPunctuation","EarlyDynasticCuneiform",null,"Cypro-Minoan","EgyptianHieroglyphs","EgyptianHieroglyphFormatControls",null,"AnatolianHieroglyphs",null,"BamumSupplement","Mro","Tangsa","BassaVah","PahawhHmong",null,"Medefaidrin",null,"Miao",null,"IdeographicSymbolsandPunctuation","Tangut","TangutComponents","KhitanSmallScript","TangutSupplement",null,"KanaExtended-B","KanaSupplement","KanaExtended-A","SmallKanaExtension","Nushu",null,"Duployan","ShorthandFormatControls",null,"ZnamennyMusicalNotation",null,"ByzantineMusicalSymbols","MusicalSymbols","AncientGreekMusicalNotation",null,"KaktovikNumerals","MayanNumerals","TaiXuanJingSymbols","CountingRodNumerals",null,"MathematicalAlphanumericSymbols","SuttonSignWriting",null,"LatinExtended-G","GlagoliticSupplement","CyrillicExtended-D",null,"NyiakengPuachueHmong",null,"Toto","Wancho",null,"NagMundari",null,"EthiopicExtended-B","MendeKikakui",null,"Adlam",null,"IndicSiyaqNumbers",null,"OttomanSiyaqNumbers",null,"ArabicMathematicalAlphabeticSymbols",null,"MahjongTiles","DominoTiles","PlayingCards","EnclosedAlphanumericSupplement","EnclosedIdeographicSupplement","MiscellaneousSymbolsandPictographs","Emoticons","OrnamentalDingbats","TransportandMapSymbols","AlchemicalSymbols","GeometricShapesExtended","SupplementalArrows-C","SupplementalSymbolsandPictographs","ChessSymbols","SymbolsandPictographsExtended-A","SymbolsforLegacyComputing",null,"CJKUnifiedIdeographsExtensionB",null,"CJKUnifiedIdeographsExtensionC","CJKUnifiedIdeographsExtensionD","CJKUnifiedIdeographsExtensionE","CJKUnifiedIdeographsExtensionF",null,"CJKCompatibilityIdeographsSupplement",null,"CJKUnifiedIdeographsExtensionG","CJKUnifiedIdeographsExtensionH",null,"Tags",null,"VariationSelectorsSupplement",null,"SupplementaryPrivateUseArea-A|PrivateUse","SupplementaryPrivateUseArea-B|PrivateUse"],[128,128,128,208,96,80,112,144,256,48,96,112,256,80,48,64,64,64,32,16,48,96,128,128,128,128,128,128,128,128,128,128,128,128,256,160,96,256,384,32,96,640,32,96,32,32,32,32,128,176,80,80,48,96,32,32,144,80,128,64,64,80,48,16,48,16,48,128,64,64,256,256,112,48,48,48,80,64,112,256,256,64,32,160,128,32,96,256,192,48,16,256,128,128,256,256,96,32,128,48,80,96,32,128,128,224,16,16,64,96,96,48,96,16,32,48,16,256,256,6592,64,20992,1168,64,48,320,96,96,32,224,48,16,64,96,32,48,48,32,96,32,96,32,96,32,48,64,80,64,11184,80,896,128,1024,6400,512,80,688,16,16,16,32,32,144,240,16,128,128,64,80,64,48,128,32,64,32,48,32,48,32,64,32,80,48,48,80,48,64,80,64,384,64,64,64,32,32,48,48,32,32,32,64,32,96,96,32,32,32,64,64,32,32,48,80,80,48,128,64,288,32,64,64,48,64,64,48,32,128,80,48,80,48,96,32,80,48,48,80,128,128,128,96,160,128,96,32,80,48,80,176,80,80,96,96,64,96,80,96,16,64,96,160,112,80,64,96,80,304,32,96,80,16,64,1024,128,208,2624,112,1072,48,4e3,640,8576,576,48,96,48,144,688,96,96,160,64,32,6144,768,512,128,8816,16,256,48,64,400,2304,160,16,4688,208,48,256,256,80,112,32,32,96,32,128,1024,688,1104,256,48,96,112,80,320,48,64,464,48,736,32,224,32,96,784,80,64,80,176,256,256,48,112,96,256,256,768,80,48,128,128,128,256,256,112,144,256,1024,42720,32,4160,224,5776,7488,3088,544,1504,4944,4192,711760,128,128,240,65040,65536,65536]),H=function(e){const t=new Map,a=e.split(""),i=S.map((()=>[]));let c=0,l=0;for(;l<a.length;){const e=G[a[l]],t=(31&e)-2;let o=1+G[a[l+1]];switch(32&e?(o+=G[a[l+2]]<<6,o+=G[a[l+3]]<<12,o+=G[a[l+4]]<<18,l+=5):l+=2,t){case-2:{let e=0;for(let t=c;t<c+o;++t)i[e].push(n(t)),e=(e+1)%2;break}case-1:break;default:{const e=i[t];1===o?e.push(n(c)):e.push(r(c,c+o-1));break}}c+=o}const s=new Map;return S.forEach(((e,n)=>{const r=i[n].reduce(u,o);t.set(e,r);const a=e.charAt(0),c=s.get(a)||[];s.set(a,c),c.push(r)})),s.forEach(((e,n)=>{t.set(n,e.reduce(u,o))})),t}(" ");function P(e){return 32===e||9===e||10===e||13===e}const j=[n(D(":")),r(D("A"),D("Z")),n(D("_")),r(D("a"),D("z")),r(192,214),r(216,246),r(192,214),r(216,246),r(248,767),r(880,893),r(895,8191),r(8204,8205),r(8304,8591),r(11264,12271),r(12289,55295),r(63744,64975),r(65008,65533),r(65536,983039)].reduce(u),X=[j,n(D("-")),n(D(".")),r(D("0"),D("9")),n(183),r(768,879),r(8255,8256)].reduce(u),L=H.get("Nd"),Y=k(L),Q=U(r(0,1114111),[H.get("P"),H.get("Z"),H.get("C")].reduce(u)),J=k(Q);function K(e){return 10!==e&&13!==e&&!R(e)}const q={s:P,S:k(P),i:j,I:k(j),c:X,C:k(X),d:L,D:Y,w:Q,W:J},_=m("*"),V=m("\\"),W=m("{"),Z=m("}"),$=m("["),z=m("]"),ee=m("^"),te=m("$"),ne=m(","),re=m("-"),ae=m("("),oe=m(")"),ue=m("."),ie=m("|"),ce=m("+"),le=m("?"),se=m("-["),pe=D("0");function fe(e){function t(e){return new Set(e.split("").map((e=>D(e))))}function o(e,t){const n=e.codePointAt(t);return void 0===n?d(t,["any character"]):f(t+String.fromCodePoint(n).length,n)}const l="xpath"===e.language?N(V,v([y(m("n"),(()=>10)),y(m("r"),(()=>13)),y(m("t"),(()=>9)),y(v([V,ie,ue,re,ee,le,_,ce,W,Z,te,ae,oe,$,z]),(e=>D(e)))])):N(V,v([y(m("n"),(()=>10)),y(m("r"),(()=>13)),y(m("t"),(()=>9)),y(v([V,ie,ue,re,ee,le,_,ce,W,Z,ae,oe,$,z]),(e=>D(e)))]));function s(e,n){const r=t(n);return x(m(e),w(g(o,(e=>r.has(e)),n.split(""))),((e,t)=>function(e){const t=H.get(e);if(null==t)throw new Error(`${e} is not a valid unicode category`);return t}(null===t?e:e+String.fromCodePoint(t))))}const p=v([s("L","ultmo"),s("M","nce"),s("N","dlo"),s("P","cdseifo"),s("Z","slp"),s("S","mcko"),s("C","cfon")]),h=[r(D("a"),D("z")),r(D("A"),D("Z")),r(D("0"),D("9")),n(45)].reduce(u),E=y(N(m("Is"),function(e){return(t,n)=>{const r=e(t,n);return r.success?f(r.offset,t.slice(n,r.offset)):r}}(B(g(o,h,["block identifier"])))),(t=>function(e,t){const n=M.get(e);if(void 0===n){if(t)return a;throw new Error(`The unicode block identifier "${e}" is not known.`)}return n}(t,"xpath"!==e.language))),S=v([p,E]),G=I(m("\\p{"),S,Z,!0),R=y(I(m("\\P{"),S,Z,!0),k),P=N(V,y(v("sSiIcCdDwW".split("").map((e=>m(e)))),(e=>q[e]))),j=y(ue,(()=>K)),X=v([P,G,R]),L=t("\\[]"),Y=g(o,(e=>!L.has(e)),["unescaped character"]),Q=v([l,Y]),J=v([y(re,(()=>null)),Q]),fe=x(J,N(re,J),r);function he(e,t){return[e].concat(t||[])}const de=y(function(e){return(t,n)=>{const r=e(t,n);return r.success?f(n,r.value):r}}(v([z,se])),(()=>null)),me=D("-"),ye=v([y(T(T(re,C($,["not ["])),de),(()=>me)),N(C(re,["not -"]),Q)]),ge=v([x(y(ye,n),v([function(e,t){return ge(e,t)},de]),he),x(v([fe,X]),v([we,de]),he)]),ve=v([x(y(Q,n),v([ge,de]),he),x(v([fe,X]),v([we,de]),he)]);function we(e,t){return ve(e,t)}const Ae=y(ve,(e=>e.reduce(u))),xe=y(N(ee,Ae),k),Be=x(v([N(C(ee,["not ^"]),Ae),xe]),w(N(re,(function(e,t){return be(e,t)}))),U),be=I($,Be,z,!0),Ee="xpath"===e.language?v([y(l,n),X,be,j,y(ee,(()=>e=>e===i)),y(te,(()=>e=>e===c))]):v([y(l,n),X,be,j]),Ne="xpath"===e.language?t(".\\?*+{}()|^$[]"):t(".\\?*+{}()|[]"),Te=g(o,(e=>!Ne.has(e)),["NormalChar"]),Ie=y(N(V,x(y(g(o,r(D("1"),D("9")),["digit"]),(e=>e-pe)),A(y(g(o,r(pe,D("9")),["digit"]),(e=>e-pe))),((e,t)=>{t.reduce(((e,t)=>10*e+t),e)}))),(e=>{throw new Error("Backreferences in XPath patterns are not yet implemented.")})),Ce="xpath"===e.language?v([y(Te,(e=>({kind:"predicate",value:n(e)}))),y(Ee,(e=>({kind:"predicate",value:e}))),y(I(ae,N(w(m("?:")),ke),oe,!0),(e=>({kind:"regexp",value:e}))),Ie]):v([y(Te,(e=>({kind:"predicate",value:n(e)}))),y(Ee,(e=>({kind:"predicate",value:e}))),y(I(ae,ke,oe,!0),(e=>({kind:"regexp",value:e})))]),Fe=y(B(y(g(o,r(pe,D("9")),["digit"]),(e=>e-pe))),(e=>e.reduce(((e,t)=>10*e+t)))),Oe=v([x(Fe,N(ne,Fe),((e,t)=>{if(t<e)throw new Error("quantifier range is in the wrong order");return{min:e,max:t}})),x(Fe,ne,(e=>({min:e,max:null}))),y(Fe,(e=>({min:e,max:e})))]),Se="xpath"===e.language?x(v([y(le,(()=>({min:0,max:1}))),y(_,(()=>({min:0,max:null}))),y(ce,(()=>({min:1,max:null}))),I(W,Oe,Z,!0)]),w(le),((e,t)=>e)):v([y(le,(()=>({min:0,max:1}))),y(_,(()=>({min:0,max:null}))),y(ce,(()=>({min:1,max:null}))),I(W,Oe,Z,!0)]),Ge=x(Ce,y(w(Se),(e=>null===e?{min:1,max:1}:e)),((e,t)=>[e,t])),De=A(Ge),Re=x(De,A(N(ie,F(De))),((e,t)=>[e].concat(t)));function ke(e,t){return Re(e,t)}const Ue=function(e){return x(e,O,b)}(Re);return function(e){let t;try{t=Ue(e,0)}catch(t){throw new Error(`Error parsing pattern "${e}": ${t instanceof Error?t.message:t}`)}return t.success?t.value:function(e,t,n){const r=n.map((e=>`"${e}"`));throw new Error(`Error parsing pattern "${e}" at offset ${t}: expected ${r.length>1?"one of "+r.join(", "):r[0]} but found "${e.slice(t,t+1)}"`)}(e,t.offset,t.expected)}}function he(e){return[...e].map((e=>e.codePointAt(0)))}e.compile=function(e,n={language:"xsd"}){const r=fe(n)(e),a=t.compileVM((e=>{p(e,r,"xpath"===n.language),e.accept()}));return function(e){const t="xpath"===n.language?[i,...he(e),c]:he(e);return a.execute(t).success}},Object.defineProperty(e,"__esModule",{value:!0})}((n="undefined"!=typeof globalThis?globalThis:n||self).xspattern={},n.whynot),(r=this).fontoxpath=(a=r.xspattern,o=r.prsc,function(e,t){const n="3.29.0",r={};var a;function o(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var u="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};function i(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var t=0;t<e.length;++t){var n=e[t];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}var c=i(this);function l(e,t){if(t)e:{var n=c;e=e.split(".");for(var r=0;r<e.length-1;r++){var a=e[r];if(!(a in n))break e;n=n[a]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&u(n,e,{configurable:!0,writable:!0,value:t})}}function s(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function p(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:o(e)}}function f(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function h(e){return e instanceof Array?e:f(p(e))}l("Symbol",(function(e){function t(e){if(this instanceof t)throw new TypeError("Symbol is not a constructor");return new n(r+(e||"")+"_"+a++,e)}function n(e,t){this.h=e,u(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;n.prototype.toString=function(){return this.h};var r="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",a=0;return t})),l("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),n=0;n<t.length;n++){var r=c[t[n]];"function"==typeof r&&"function"!=typeof r.prototype[e]&&u(r.prototype,e,{configurable:!0,writable:!0,value:function(){return s(o(this))}})}return e})),l("Symbol.asyncIterator",(function(e){return e||Symbol("Symbol.asyncIterator")}));var d,m="function"==typeof Object.create?Object.create:function(e){function t(){}return t.prototype=e,new t};if("function"==typeof Object.setPrototypeOf)d=Object.setPrototypeOf;else{var y;e:{var g={a:!0},v={};try{v.__proto__=g,y=v.a;break e}catch(e){}y=!1}d=y?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var w=d;function A(e,t){if(e.prototype=m(t.prototype),e.prototype.constructor=e,w)w(e,t);else for(var n in t)if("prototype"!=n)if(Object.defineProperties){var r=Object.getOwnPropertyDescriptor(t,n);r&&Object.defineProperty(e,n,r)}else e[n]=t[n];e.zc=t.prototype}function x(){this.B=!1,this.o=null,this.l=void 0,this.h=1,this.da=0,this.v=null}function B(e){if(e.B)throw new TypeError("Generator is already running");e.B=!0}function b(e,t){e.v={kc:t,mc:!0},e.h=e.da}function E(e){this.h=new x,this.o=e}function N(e,t){B(e.h);var n=e.h.o;return n?T(e,"return"in n?n.return:function(e){return{value:e,done:!0}},t,e.h.return):(e.h.return(t),I(e))}function T(e,t,n,r){try{var a=t.call(e.h.o,n);if(!(a instanceof Object))throw new TypeError("Iterator result "+a+" is not an object");if(!a.done)return e.h.B=!1,a;var o=a.value}catch(t){return e.h.o=null,b(e.h,t),I(e)}return e.h.o=null,r.call(e.h,o),I(e)}function I(e){for(;e.h.h;)try{var t=e.o(e.h);if(t)return e.h.B=!1,{value:t.value,done:!1}}catch(t){e.h.l=void 0,b(e.h,t)}if(e.h.B=!1,e.h.v){if(t=e.h.v,e.h.v=null,t.mc)throw t.kc;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function C(e){this.next=function(t){return B(e.h),e.h.o?t=T(e,e.h.o.next,t,e.h.s):(e.h.s(t),t=I(e)),t},this.throw=function(t){return B(e.h),e.h.o?t=T(e,e.h.o.throw,t,e.h.s):(b(e.h,t),t=I(e)),t},this.return=function(t){return N(e,t)},this[Symbol.iterator]=function(){return this}}function F(e){function t(t){return e.next(t)}function n(t){return e.throw(t)}return new Promise((function(r,a){function o(e){e.done?r(e.value):Promise.resolve(e.value).then(t,n).then(o,a)}o(e.next())}))}function O(){for(var e=Number(this),t=[],n=e;n<arguments.length;n++)t[n-e]=arguments[n];return t}function S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}x.prototype.s=function(e){this.l=e},x.prototype.return=function(e){this.v={return:e},this.h=this.da},l("Promise",(function(e){function t(e){this.o=0,this.v=void 0,this.h=[],this.da=!1;var t=this.B();try{e(t.resolve,t.reject)}catch(e){t.reject(e)}}function n(){this.h=null}function r(e){return e instanceof t?e:new t((function(t){t(e)}))}if(e)return e;n.prototype.o=function(e){if(null==this.h){this.h=[];var t=this;this.v((function(){t.l()}))}this.h.push(e)};var a=c.setTimeout;n.prototype.v=function(e){a(e,0)},n.prototype.l=function(){for(;this.h&&this.h.length;){var e=this.h;this.h=[];for(var t=0;t<e.length;++t){var n=e[t];e[t]=null;try{n()}catch(e){this.B(e)}}}this.h=null},n.prototype.B=function(e){this.v((function(){throw e}))},t.prototype.B=function(){function e(e){return function(r){n||(n=!0,e.call(t,r))}}var t=this,n=!1;return{resolve:e(this.la),reject:e(this.l)}},t.prototype.la=function(e){if(e===this)this.l(new TypeError("A Promise cannot resolve to itself"));else if(e instanceof t)this.ab(e);else{e:switch(typeof e){case"object":var n=null!=e;break e;case"function":n=!0;break e;default:n=!1}n?this.S(e):this.s(e)}},t.prototype.S=function(e){var t=void 0;try{t=e.then}catch(e){return void this.l(e)}"function"==typeof t?this.Ba(t,e):this.s(e)},t.prototype.l=function(e){this.ta(2,e)},t.prototype.s=function(e){this.ta(1,e)},t.prototype.ta=function(e,t){if(0!=this.o)throw Error("Cannot settle("+e+", "+t+"): Promise already settled in state"+this.o);this.o=e,this.v=t,2===this.o&&this.pa(),this.A()},t.prototype.pa=function(){var e=this;a((function(){if(e.K()){var t=c.console;void 0!==t&&t.error(e.v)}}),1)},t.prototype.K=function(){if(this.da)return!1;var e=c.CustomEvent,t=c.Event,n=c.dispatchEvent;return void 0===n||("function"==typeof e?e=new e("unhandledrejection",{cancelable:!0}):"function"==typeof t?e=new t("unhandledrejection",{cancelable:!0}):(e=c.document.createEvent("CustomEvent")).initCustomEvent("unhandledrejection",!1,!0,e),e.promise=this,e.reason=this.v,n(e))},t.prototype.A=function(){if(null!=this.h){for(var e=0;e<this.h.length;++e)o.o(this.h[e]);this.h=null}};var o=new n;return t.prototype.ab=function(e){var t=this.B();e.rb(t.resolve,t.reject)},t.prototype.Ba=function(e,t){var n=this.B();try{e.call(t,n.resolve,n.reject)}catch(e){n.reject(e)}},t.prototype.then=function(e,n){function r(e,t){return"function"==typeof e?function(t){try{a(e(t))}catch(e){o(e)}}:t}var a,o,u=new t((function(e,t){a=e,o=t}));return this.rb(r(e,a),r(n,o)),u},t.prototype.catch=function(e){return this.then(void 0,e)},t.prototype.rb=function(e,t){function n(){switch(r.o){case 1:e(r.v);break;case 2:t(r.v);break;default:throw Error("Unexpected state: "+r.o)}}var r=this;null==this.h?o.o(n):this.h.push(n),this.da=!0},t.resolve=r,t.reject=function(e){return new t((function(t,n){n(e)}))},t.race=function(e){return new t((function(t,n){for(var a=p(e),o=a.next();!o.done;o=a.next())r(o.value).rb(t,n)}))},t.all=function(e){var n=p(e),a=n.next();return a.done?r([]):new t((function(e,t){function o(t){return function(n){u[t]=n,0==--i&&e(u)}}var u=[],i=0;do{u.push(void 0),i++,r(a.value).rb(o(u.length-1),t),a=n.next()}while(!a.done)}))},t}));var G="function"==typeof Object.assign?Object.assign:function(e,t){for(var n=1;n<arguments.length;n++){var r=arguments[n];if(r)for(var a in r)S(r,a)&&(e[a]=r[a])}return e};function D(e,t,n){if(null==e)throw new TypeError("The 'this' value for String.prototype."+n+" must not be null or undefined");if(t instanceof RegExp)throw new TypeError("First argument to String.prototype."+n+" must not be a regular expression");return e+""}function R(e,t){return e=void 0!==e?String(e):" ",0<t&&e?e.repeat(Math.ceil(t/e.length)).substring(0,t):""}function k(e,t,n){e instanceof String&&(e=String(e));for(var r=e.length,a=0;a<r;a++){var o=e[a];if(t.call(n,o,a,e))return{Jb:a,Qb:o}}return{Jb:-1,Qb:void 0}}function U(e){return e||Array.prototype.fill}function M(e,t){e instanceof String&&(e+="");var n=0,r=!1,a={next:function(){if(!r&&n<e.length){var a=n++;return{value:t(a,e[a]),done:!1}}return r=!0,{done:!0,value:void 0}}};return a[Symbol.iterator]=function(){return a},a}function H(e,t){if(!("0"!==e&&"-0"!==e||"0"!==t&&"-0"!==t))return 0;var n=/(?:\+|(-))?(\d+)?(?:\.(\d+))?/;e=n.exec(e+"");var r=n.exec(t+""),a=!e[1],o=!r[1];return t=(e[2]||"").replace(/^0*/,""),n=(r[2]||"").replace(/^0*/,""),e=e[3]||"",r=r[3]||"",a&&!o?1:!a&&o?-1:(a=a&&o,t.length>n.length?a?1:-1:t.length<n.length?a?-1:1:t>n?a?1:-1:t<n?a?-1:1:(t=Math.max(e.length,r.length),(n=e.padEnd(t,"0"))>(t=r.padEnd(t,"0"))?a?1:-1:n<t?a?-1:1:0))}function P(e,t){return!(-1<(e=e.toString()).indexOf(".")&&0===t)&&(!(e=/^[-+]?0*([1-9]\d*)?(?:\.((?:\d*[1-9])*)0*)?$/.exec(e))[2]||e[2].length<=t)}function j(){return function(e,t){return 1>H(e,t)}}function X(){return function(e,t){return 0>H(e,t)}}function L(){return function(e,t){return-1<H(e,t)}}function Y(){return function(e,t){return 0<H(e,t)}}function Q(e,t){switch(t){case"required":return/(Z)|([+-])([01]\d):([0-5]\d)$/.test(e.toString());case"prohibited":return!/(Z)|([+-])([01]\d):([0-5]\d)$/.test(e.toString());case"optional":return!0}}function J(e){switch(e){case 1:case 0:case 6:case 3:case 18:case 22:case 21:case 20:case 23:case 44:return{};case 4:return{na:P,ya:j(),xc:X(),za:L(),yc:Y()};case 9:case 8:case 7:case 11:case 12:case 13:case 15:case 14:return{Ea:Q};default:return null}}l("Object.assign",(function(e){return e||G})),l("String.prototype.repeat",(function(e){return e||function(e){var t=D(this,null,"repeat");if(0>e||1342177279<e)throw new RangeError("Invalid count value");e|=0;for(var n="";e;)1&e&&(n+=t),(e>>>=1)&&(t+=t);return n}})),l("String.prototype.padEnd",(function(e){return e||function(e,t){var n=D(this,null,"padStart");return n+R(t,e-n.length)}})),l("WeakMap",(function(e){function t(e){if(this.h=(c+=Math.random()+1).toString(),e){e=p(e);for(var t;!(t=e.next()).done;)t=t.value,this.set(t[0],t[1])}}function n(){}function r(e){var t=typeof e;return"object"===t&&null!==e||"function"===t}function a(e){if(!S(e,i)){var t=new n;u(e,i,{value:t})}}function o(e){var t=Object[e];t&&(Object[e]=function(e){return e instanceof n?e:(Object.isExtensible(e)&&a(e),t(e))})}if(function(){if(!e||!Object.seal)return!1;try{var t=Object.seal({}),n=Object.seal({}),r=new e([[t,2],[n,3]]);return 2==r.get(t)&&3==r.get(n)&&(r.delete(t),r.set(n,4),!r.has(t)&&4==r.get(n))}catch(e){return!1}}())return e;var i="$jscomp_hidden_"+Math.random();o("freeze"),o("preventExtensions"),o("seal");var c=0;return t.prototype.set=function(e,t){if(!r(e))throw Error("Invalid WeakMap key");if(a(e),!S(e,i))throw Error("WeakMap key fail: "+e);return e[i][this.h]=t,this},t.prototype.get=function(e){return r(e)&&S(e,i)?e[i][this.h]:void 0},t.prototype.has=function(e){return r(e)&&S(e,i)&&S(e[i],this.h)},t.prototype.delete=function(e){return!!(r(e)&&S(e,i)&&S(e[i],this.h))&&delete e[i][this.h]},t})),l("Map",(function(e){function t(){var e={};return e.Ga=e.next=e.head=e}function n(e,t){var n=e.h;return s((function(){if(n){for(;n.head!=e.h;)n=n.Ga;for(;n.next!=n.head;)return n=n.next,{done:!1,value:t(n)};n=null}return{done:!0,value:void 0}}))}function r(e,t){var n=t&&typeof t;"object"==n||"function"==n?o.has(t)?n=o.get(t):(n=""+ ++u,o.set(t,n)):n="p_"+t;var r=e.o[n];if(r&&S(e.o,n))for(e=0;e<r.length;e++){var a=r[e];if(t!=t&&a.key!=a.key||t===a.key)return{id:n,list:r,index:e,ka:a}}return{id:n,list:r,index:-1,ka:void 0}}function a(e){if(this.o={},this.h=t(),this.size=0,e){e=p(e);for(var n;!(n=e.next()).done;)n=n.value,this.set(n[0],n[1])}}if(function(){if(!e||"function"!=typeof e||!e.prototype.entries||"function"!=typeof Object.seal)return!1;try{var t=Object.seal({x:4}),n=new e(p([[t,"s"]]));if("s"!=n.get(t)||1!=n.size||n.get({x:4})||n.set({x:4},"t")!=n||2!=n.size)return!1;var r=n.entries(),a=r.next();return!a.done&&a.value[0]==t&&"s"==a.value[1]&&!((a=r.next()).done||4!=a.value[0].x||"t"!=a.value[1]||!r.next().done)}catch(e){return!1}}())return e;var o=new WeakMap;a.prototype.set=function(e,t){var n=r(this,e=0===e?0:e);return n.list||(n.list=this.o[n.id]=[]),n.ka?n.ka.value=t:(n.ka={next:this.h,Ga:this.h.Ga,head:this.h,key:e,value:t},n.list.push(n.ka),this.h.Ga.next=n.ka,this.h.Ga=n.ka,this.size++),this},a.prototype.delete=function(e){return!(!(e=r(this,e)).ka||!e.list||(e.list.splice(e.index,1),e.list.length||delete this.o[e.id],e.ka.Ga.next=e.ka.next,e.ka.next.Ga=e.ka.Ga,e.ka.head=null,this.size--,0))},a.prototype.clear=function(){this.o={},this.h=this.h.Ga=t(),this.size=0},a.prototype.has=function(e){return!!r(this,e).ka},a.prototype.get=function(e){return(e=r(this,e).ka)&&e.value},a.prototype.entries=function(){return n(this,(function(e){return[e.key,e.value]}))},a.prototype.keys=function(){return n(this,(function(e){return e.key}))},a.prototype.values=function(){return n(this,(function(e){return e.value}))},a.prototype.forEach=function(e,t){for(var n,r=this.entries();!(n=r.next()).done;)n=n.value,e.call(t,n[1],n[0],this)},a.prototype[Symbol.iterator]=a.prototype.entries;var u=0;return a})),l("Array.prototype.find",(function(e){return e||function(e,t){return k(this,e,t).Qb}})),l("String.prototype.startsWith",(function(e){return e||function(e,t){var n=D(this,e,"startsWith"),r=n.length,a=e.length;t=Math.max(0,Math.min(0|t,n.length));for(var o=0;o<a&&t<r;)if(n[t++]!=e[o++])return!1;return o>=a}})),l("Array.prototype.fill",(function(e){return e||function(e,t,n){var r=this.length||0;for(0>t&&(t=Math.max(0,r+t)),(null==n||n>r)&&(n=r),0>(n=Number(n))&&(n=Math.max(0,r+n)),t=Number(t||0);t<n;t++)this[t]=e;return this}})),l("Int8Array.prototype.fill",U),l("Uint8Array.prototype.fill",U),l("Uint8ClampedArray.prototype.fill",U),l("Int16Array.prototype.fill",U),l("Uint16Array.prototype.fill",U),l("Int32Array.prototype.fill",U),l("Uint32Array.prototype.fill",U),l("Float32Array.prototype.fill",U),l("Float64Array.prototype.fill",U),l("Array.from",(function(e){return e||function(e,t,n){t=null!=t?t:function(e){return e};var r=[],a="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];if("function"==typeof a){e=a.call(e);for(var o=0;!(a=e.next()).done;)r.push(t.call(n,a.value,o++))}else for(a=e.length,o=0;o<a;o++)r.push(t.call(n,e[o],o));return r}})),l("Object.is",(function(e){return e||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}})),l("Array.prototype.includes",(function(e){return e||function(e,t){var n=this;n instanceof String&&(n=String(n));var r=n.length;for(0>(t=t||0)&&(t=Math.max(t+r,0));t<r;t++){var a=n[t];if(a===e||Object.is(a,e))return!0}return!1}})),l("String.prototype.includes",(function(e){return e||function(e,t){return-1!==D(this,e,"includes").indexOf(e,t||0)}})),l("Number.MAX_SAFE_INTEGER",(function(){return 9007199254740991})),l("Number.MIN_SAFE_INTEGER",(function(){return-9007199254740991})),l("Math.trunc",(function(e){return e||function(e){if(e=Number(e),isNaN(e)||1/0===e||-1/0===e||0===e)return e;var t=Math.floor(Math.abs(e));return 0>e?-t:t}})),l("Number.isFinite",(function(e){return e||function(e){return"number"==typeof e&&!isNaN(e)&&1/0!==e&&-1/0!==e}})),l("String.prototype.padStart",(function(e){return e||function(e,t){var n=D(this,null,"padStart");return R(t,e-n.length)+n}})),l("Array.prototype.keys",(function(e){return e||function(){return M(this,(function(e){return e}))}})),l("Number.isInteger",(function(e){return e||function(e){return!!Number.isFinite(e)&&e===Math.floor(e)}})),l("Number.isSafeInteger",(function(e){return e||function(e){return Number.isInteger(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER}})),l("Array.prototype.findIndex",(function(e){return e||function(e,t){return k(this,e,t).Jb}})),l("String.prototype.endsWith",(function(e){return e||function(e,t){var n=D(this,e,"endsWith");void 0===t&&(t=n.length),t=Math.max(0,Math.min(0|t,n.length));for(var r=e.length;0<r&&0<t;)if(n[--t]!=e[--r])return!1;return 0>=r}})),l("String.fromCodePoint",(function(e){return e||function(e){for(var t="",n=0;n<arguments.length;n++){var r=Number(arguments[n]);if(0>r||1114111<r||r!==Math.floor(r))throw new RangeError("invalid_code_point "+r);65535>=r?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(r>>>10&1023|55296),t+=String.fromCharCode(1023&r|56320))}return t}})),l("String.prototype.codePointAt",(function(e){return e||function(e){var t=D(this,null,"codePointAt"),n=t.length;if(0<=(e=Number(e)||0)&&e<n){e|=0;var r=t.charCodeAt(e);return 55296>r||56319<r||e+1===n||56320>(e=t.charCodeAt(e+1))||57343<e?r:1024*(r-55296)+e+9216}}})),l("Set",(function(e){function t(e){if(this.h=new Map,e){e=p(e);for(var t;!(t=e.next()).done;)this.add(t.value)}this.size=this.h.size}return function(){if(!e||"function"!=typeof e||!e.prototype.entries||"function"!=typeof Object.seal)return!1;try{var t=Object.seal({x:4}),n=new e(p([t]));if(!n.has(t)||1!=n.size||n.add(t)!=n||1!=n.size||n.add({x:4})!=n||2!=n.size)return!1;var r=n.entries(),a=r.next();return!a.done&&a.value[0]==t&&a.value[1]==t&&!(a=r.next()).done&&a.value[0]!=t&&4==a.value[0].x&&a.value[1]==a.value[0]&&r.next().done}catch(e){return!1}}()?e:(t.prototype.add=function(e){return e=0===e?0:e,this.h.set(e,e),this.size=this.h.size,this},t.prototype.delete=function(e){return e=this.h.delete(e),this.size=this.h.size,e},t.prototype.clear=function(){this.h.clear(),this.size=0},t.prototype.has=function(e){return this.h.has(e)},t.prototype.entries=function(){return this.h.entries()},t.prototype.values=function(){return this.h.values()},t.prototype.keys=t.prototype.values,t.prototype[Symbol.iterator]=t.prototype.values,t.prototype.forEach=function(e,t){var n=this;this.h.forEach((function(r){return e.call(t,r,r,n)}))},t)})),l("Math.log10",(function(e){return e||function(e){return Math.log(e)/Math.LN10}})),l("Object.values",(function(e){return e||function(e){var t,n=[];for(t in e)S(e,t)&&n.push(e[t]);return n}})),l("Number.isNaN",(function(e){return e||function(e){return"number"==typeof e&&isNaN(e)}})),l("Array.prototype.values",(function(e){return e||function(){return M(this,(function(e,t){return t}))}})),l("Object.getOwnPropertySymbols",(function(e){return e||function(){return[]}}));var K={},q={};function _(e){return/^([+-]?(\d*(\.\d*)?([eE][+-]?\d*)?|INF)|NaN)$/.test(e)}function V(e){return/^[_:A-Za-z][-._:A-Za-z0-9]*$/.test(e)}function W(e){return V(e)&&/^[_A-Za-z]([-._A-Za-z0-9])*$/.test(e)}function Z(e){return 1===(e=e.split(":")).length?W(e[0]):2===e.length&&W(e[0])&&W(e[1])}function $(e){return!/[\u0009\u000A\u000D]/.test(e)}function z(e){return W(e)}var ee=new Map([[45,function(){return!0}],[46,function(){return!0}],[1,function(){return!0}],[0,function(e){return/^(0|1|true|false)$/.test(e)}],[6,function(e){return _(e)}],[3,_],[4,function(e){return/^[+-]?\d*(\.\d*)?$/.test(e)}],[18,function(e){return/^(-)?P(\d+Y)?(\d+M)?(\d+D)?(T(\d+H)?(\d+M)?(\d+(\.\d*)?S)?)?$/.test(e)}],[9,function(e){return/^-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[8,function(e){return/^(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[7,function(e){return/^-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[11,function(e){return/^-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[12,function(e){return/^-?([1-9][0-9]{3,}|0[0-9]{3})(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[13,function(e){return/^--(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[15,function(e){return/^---(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[14,function(e){return/^--(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?$/.test(e)}],[22,function(e){return/^([0-9A-Fa-f]{2})*$/.test(e)}],[21,function(e){return new RegExp(/^((([A-Za-z0-9+/] ?){4})*((([A-Za-z0-9+/] ?){3}[A-Za-z0-9+/])|(([A-Za-z0-9+/] ?){2}[AEIMQUYcgkosw048] ?=)|(([A-Za-z0-9+/] ?)[AQgw] ?= ?=)))?$/).test(e)}],[20,function(){return!0}],[44,Z],[48,$],[52,function(e){return $(e)&&!/^ | {2,}| $/.test(e)}],[51,function(e){return/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/.test(e)}],[50,function(e){return/^[-._:A-Za-z0-9]+$/.test(e)}],[25,V],[23,Z],[24,W],[42,z],[41,z],[26,function(e){return W(e)}],[5,function(e){return/^[+-]?\d+$/.test(e)}],[16,function(e){return/^-?P[0-9]+(Y([0-9]+M)?|M)$/.test(e)}],[17,function(e){return/^-?P([0-9]+D)?(T([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]+)?S)?)?$/.test(e)}]]),te=Object.create(null);function ne(e,t){if(!te[t])throw Error("Unknown type");return{type:t,value:e}}[{D:0,name:59},{D:0,name:46,parent:59,L:{whiteSpace:"preserve"}},{D:0,name:19,parent:46},{D:0,name:1,parent:46},{D:0,name:0,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:4,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:6,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:3,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:18,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:9,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:8,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:7,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:11,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:12,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:13,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:15,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:14,parent:46,L:{Ea:"optional",whiteSpace:"collapse"}},{D:0,name:22,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:21,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:20,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:23,parent:46,L:{whiteSpace:"collapse"}},{D:0,name:44,parent:46,L:{whiteSpace:"collapse"}},{D:1,name:10,T:9,L:{whiteSpace:"collapse",Ea:"required"}},{D:1,name:48,T:1,L:{whiteSpace:"replace"}},{D:1,name:52,T:48,L:{whiteSpace:"collapse"}},{D:1,name:51,T:52,L:{whiteSpace:"collapse"}},{D:1,name:50,T:52,L:{whiteSpace:"collapse"}},{D:2,name:49,type:50,L:{minLength:1,whiteSpace:"collapse"}},{D:1,name:25,T:52,L:{whiteSpace:"collapse"}},{D:1,name:24,T:25,L:{whiteSpace:"collapse"}},{D:1,name:42,T:24,L:{whiteSpace:"collapse"}},{D:1,name:41,T:24,L:{whiteSpace:"collapse"}},{D:2,name:43,type:41,L:{minLength:1,whiteSpace:"collapse"}},{D:1,name:26,T:24,L:{whiteSpace:"collapse"}},{D:2,name:40,type:26,L:{minLength:1,whiteSpace:"collapse"}},{D:0,name:5,parent:4,L:{na:0,whiteSpace:"collapse"}},{D:1,name:27,T:5,L:{na:0,ya:"0",whiteSpace:"collapse"}},{D:1,name:28,T:27,L:{na:0,ya:"-1",whiteSpace:"collapse"}},{D:1,name:31,T:5,L:{na:0,ya:"9223372036854775807",za:"-9223372036854775808",whiteSpace:"collapse"}},{D:1,name:32,T:31,L:{na:0,ya:"2147483647",za:"-2147483648",whiteSpace:"collapse"}},{D:1,name:33,T:32,L:{na:0,ya:"32767",za:"-32768",whiteSpace:"collapse"}},{D:1,name:34,T:33,L:{na:0,ya:"127",za:"-128",whiteSpace:"collapse"}},{D:1,name:30,T:5,L:{na:0,za:"0",whiteSpace:"collapse"}},{D:1,name:36,T:30,L:{na:0,ya:"18446744073709551615",za:"0",whiteSpace:"collapse"}},{D:1,name:35,T:36,L:{na:0,ya:"4294967295",za:"0",whiteSpace:"collapse"}},{D:1,name:38,T:35,L:{na:0,ya:"65535",za:"0",whiteSpace:"collapse"}},{D:1,name:37,T:38,L:{na:0,ya:"255",za:"0",whiteSpace:"collapse"}},{D:1,name:29,T:30,L:{na:0,za:"1",whiteSpace:"collapse"}},{D:1,name:16,T:18,L:{whiteSpace:"collapse"}},{D:1,name:17,T:18,L:{whiteSpace:"collapse"}},{D:1,name:60,T:59},{D:3,name:39,Fa:[]},{D:1,name:61,T:60},{D:1,name:62,T:60},{D:0,name:53,parent:59},{D:1,name:54,T:53},{D:1,name:58,T:53},{D:1,name:47,T:53},{D:1,name:56,T:53},{D:1,name:57,T:53},{D:1,name:55,T:53},{D:3,name:2,Fa:[4,5,6,3]},{D:3,name:63,Fa:[]}].forEach((function(e){var t=e.name,n=e.L||{};switch(e.D){case 0:e=e.parent?te[e.parent]:null;var r=ee.get(t)||null;te[t]={D:0,type:t,Na:n,parent:e,kb:r,Pa:J(t),Fa:[]};break;case 1:e=te[e.T],r=ee.get(t)||null,te[t]={D:1,type:t,Na:n,parent:e,kb:r,Pa:e.Pa,Fa:[]};break;case 2:te[t]={D:2,type:t,Na:n,parent:te[e.type],kb:null,Pa:K,Fa:[]};break;case 3:e=e.Fa.map((function(e){return te[e]})),te[t]={D:3,type:t,Na:n,parent:null,kb:null,Pa:q,Fa:e}}}));var re=ne(!0,0),ae=ne(!1,0);function oe(e){return Error("FORG0006: "+(void 0===e?"A wrong argument type was specified in a function call.":e))}function ue(e,t){this.done=e,this.value=t}var ie=new ue(!0,void 0);function ce(e){return new ue(!1,e)}function le(e,t){if(3===t.D)return!!t.Fa.find((function(t){return le(e,t)}));for(;e;){if(e.type===t.type)return!0;if(3===e.D)return!!e.Fa.find((function(e){return se(e.type,t.type)}));e=e.parent}return!1}function se(e,t){return e===t||le(te[e],te[t])}function pe(e){this.o=Ie,this.h=e;var t=-1;this.value={next:function(){return++t>=e.length?ie:ce(e[t])}}}function fe(){this.value={next:function(){return ie}}}function he(e,t){this.type=e,this.value=t}(a=pe.prototype).sb=function(){return this},a.filter=function(e){var t=this,n=-1;return this.o.create({next:function(){for(n++;n<t.h.length&&!e(t.h[n],n,t);)n++;return n>=t.h.length?ie:ce(t.h[n])}})},a.first=function(){return this.h[0]},a.O=function(){return this.h},a.ha=function(){if(se(this.h[0].type,53))return!0;throw oe("Cannot determine the effective boolean value of a sequence with a length higher than one.")},a.Qa=function(){return this.h.length},a.G=function(){return!1},a.wa=function(){return!1},a.map=function(e){var t=this,n=-1;return this.o.create({next:function(){return++n>=t.h.length?ie:ce(e(t.h[n],n,t))}},this.h.length)},a.M=function(e){return e(this.h)},a.Z=function(e){return e.multiple?e.multiple(this):e.default(this)},(a=fe.prototype).sb=function(){return this},a.filter=function(){return this},a.first=function(){return null},a.O=function(){return[]},a.ha=function(){return!1},a.Qa=function(){return 0},a.G=function(){return!0},a.wa=function(){return!1},a.map=function(){return this},a.M=function(e){return e([])},a.Z=function(e){return e.empty?e.empty(this):e.default(this)};var de={},me=(de[0]="xs:boolean",de[1]="xs:string",de[2]="xs:numeric",de[3]="xs:double",de[4]="xs:decimal",de[5]="xs:integer",de[6]="xs:float",de[7]="xs:date",de[8]="xs:time",de[9]="xs:dateTime",de[10]="xs:dateTimeStamp",de[11]="xs:gYearMonth",de[12]="xs:gYear",de[13]="xs:gMonthDay",de[14]="xs:gMonth",de[15]="xs:gDay",de[16]="xs:yearMonthDuration",de[17]="xs:dayTimeDuration",de[18]="xs:duration",de[19]="xs:untypedAtomic",de[20]="xs:anyURI",de[21]="xs:base64Binary",de[22]="xs:hexBinary",de[23]="xs:QName",de[24]="xs:NCName",de[25]="xs:Name",de[26]="xs:ENTITY",de[27]="xs:nonPositiveInteger",de[28]="xs:negativeInteger",de[29]="xs:positiveInteger",de[30]="xs:nonNegativeInteger",de[31]="xs:long",de[32]="xs:int",de[33]="xs:short",de[34]="xs:byte",de[35]="xs:unsignedInt",de[36]="xs:unsignedLong",de[37]="xs:unsignedByte",de[38]="xs:unsignedShort",de[39]="xs:error",de[40]="xs:ENTITIES",de[41]="xs:IDREF",de[42]="xs:ID",de[43]="xs:IDREFS",de[44]="xs:NOTATION",de[45]="xs:anySimpleType",de[46]="xs:anyAtomicType",de[47]="attribute()",de[48]="xs:normalizedString",de[49]="xs:NMTOKENS",de[50]="xs:NMTOKEN",de[51]="xs:language",de[52]="xs:token",de[53]="node()",de[54]="element()",de[55]="document-node()",de[56]="text()",de[57]="processing-instruction()",de[58]="comment()",de[59]="item()",de[60]="function(*)",de[61]="map(*)",de[62]="array(*)",de[63]="none",de),ye={"xs:boolean":0,"xs:string":1,"xs:numeric":2,"xs:double":3,"xs:decimal":4,"xs:integer":5,"xs:float":6,"xs:date":7,"xs:time":8,"xs:dateTime":9,"xs:dateTimeStamp":10,"xs:gYearMonth":11,"xs:gYear":12,"xs:gMonthDay":13,"xs:gMonth":14,"xs:gDay":15,"xs:yearMonthDuration":16,"xs:dayTimeDuration":17,"xs:duration":18,"xs:untypedAtomic":19,"xs:anyURI":20,"xs:base64Binary":21,"xs:hexBinary":22,"xs:QName":23,"xs:NCName":24,"xs:Name":25,"xs:ENTITY":26,"xs:nonPositiveInteger":27,"xs:negativeInteger":28,"xs:positiveInteger":29,"xs:nonNegativeInteger":30,"xs:long":31,"xs:int":32,"xs:short":33,"xs:byte":34,"xs:unsignedInt":35,"xs:unsignedLong":36,"xs:unsignedByte":37,"xs:unsignedShort":38,"xs:error":39,"xs:ENTITIES":40,"xs:IDREF":41,"xs:ID":42,"xs:IDREFS":43,"xs:NOTATION":44,"xs:anySimpleType":45,"xs:anyAtomicType":46,"attribute()":47,"xs:normalizedString":48,"xs:NMTOKENS":49,"xs:NMTOKEN":50,"xs:language":51,"xs:token":52,"node()":53,"element()":54,"document-node()":55,"text()":56,"processing-instruction()":57,"comment()":58,"item()":59,"function(*)":60,"map(*)":61,"array(*)":62};function ge(e){return 2===e.g?me[e.type]+"*":1===e.g?me[e.type]+"+":0===e.g?me[e.type]+"?":me[e.type]}function ve(e){if("none"===e)throw Error('XPST0051: The type "none" could not be found');if(!e.startsWith("xs:")&&0<=e.indexOf(":"))throw Error("XPST0081: Invalid prefix for input "+e);var t=ye[e];if(void 0===t)throw Error('XPST0051: The type "'+e+'" could not be found');return t}function we(e){switch(e[e.length-1]){case"*":return{type:ve(e.substr(0,e.length-1)),g:2};case"?":return{type:ve(e.substr(0,e.length-1)),g:0};case"+":return{type:ve(e.substr(0,e.length-1)),g:1};default:return{type:ve(e),g:3}}}function Ae(e){switch(e){case"*":return 2;case"?":return 0;case"+":return 1;default:return 3}}function xe(e){var t=e.value;if(se(e.type,53))return!0;if(se(e.type,0))return t;if(se(e.type,1)||se(e.type,20)||se(e.type,19))return 0!==t.length;if(se(e.type,2))return!isNaN(t)&&0!==t;throw oe("Cannot determine the effective boolean value of a value with the type "+me[e.type])}function Be(e,t){var n=this;this.B=Ie,this.value={next:function(t){return null!==n.o&&n.h>=n.o?ie:void 0!==n.v[n.h]?ce(n.v[n.h++]):(t=e.next(t)).done?(n.o=n.h,t):((n.l||2>n.h)&&(n.v[n.h]=t.value),n.h++,t)}},this.l=!1,this.v=[],this.h=0,this.o=void 0===t?null:t}function be(e,t){e.h=void 0===t?0:t}function Ee(e){this.v=Ie,this.h=e;var t=!1;this.value={next:function(){return t?ie:(t=!0,ce(e))}},this.o=null}(a=Be.prototype).sb=function(){return this.B.create(this.O())},a.filter=function(e){var t=this,n=-1,r=this.value;return this.B.create({next:function(a){for(n++,a=r.next(a);!a.done&&!e(a.value,n,t);)n++,a=r.next(0);return a}})},a.first=function(){if(void 0!==this.v[0])return this.v[0];var e=this.value.next(0);return be(this),e.done?null:e.value},a.O=function(){if(this.h>this.v.length&&this.o!==this.v.length)throw Error("Implementation error: Sequence Iterator has progressed.");var e=this.value;this.l=!0;for(var t=e.next(0);!t.done;)t=e.next(0);return this.v},a.ha=function(){var e=this.value,t=this.h;be(this);var n=e.next(0);if(n.done)return be(this,t),!1;if(se((n=n.value).type,53))return be(this,t),!0;if(!e.next(0).done)throw oe("Cannot determine the effective boolean value of a sequence with a length higher than one.");return be(this,t),xe(n)},a.Qa=function(e){if(null!==this.o)return this.o;if(void 0!==e&&e)return-1;e=this.h;var t=this.O().length;return be(this,e),t},a.G=function(){return 0===this.o||null===this.first()},a.wa=function(){if(null!==this.o)return 1===this.o;var e=this.value,t=this.h;return be(this),e.next(0).done?(be(this,t),!1):(e=e.next(0),be(this,t),e.done)},a.map=function(e){var t=this,n=0,r=this.value;return this.B.create({next:function(a){return(a=r.next(a)).done?ie:ce(e(a.value,n++,t))}},this.o)},a.M=function(e,t){var n,r=this.value,a=[],o=!0;return function(){for(var u=r.next(o?0:t);!u.done;u=r.next(t))o=!1,a.push(u.value);n=e(a).value}(),this.B.create({next:function(){return n.next(0)}})},a.Z=function(e){function t(e){r=e.value,-1!==(e=e.Qa(!0))&&(n.o=e)}var n=this,r=null;return this.B.create({next:function(a){return r?r.next(a):n.G()?(t(e.empty?e.empty(n):e.default(n)),r.next(a)):n.wa()?(t(e.m?e.m(n):e.default(n)),r.next(a)):(t(e.multiple?e.multiple(n):e.default(n)),r.next(a))}})},(a=Ee.prototype).sb=function(){return this},a.filter=function(e){return e(this.h,0,this)?this:this.v.create()},a.first=function(){return this.h},a.O=function(){return[this.h]},a.ha=function(){return null===this.o&&(this.o=xe(this.h)),this.o},a.Qa=function(){return 1},a.G=function(){return!1},a.wa=function(){return!0},a.map=function(e){return this.v.create(e(this.h,0,this))},a.M=function(e){return e([this.h])},a.Z=function(e){return e.m?e.m(this):e.default(this)};var Ne=new fe;function Te(e,t){if(null===(e=void 0===e?null:e))return Ne;if(Array.isArray(e))switch(e.length){case 0:return Ne;case 1:return new Ee(e[0]);default:return new pe(e)}return e.next?new Be(e,void 0===t?null:t):new Ee(e)}var Ie={create:Te,m:function(e){return new Ee(e)},empty:function(){return Te()},ba:function(){return Te(re)},W:function(){return Te(ae)}};function Ce(e){var t=[],n=e.value;return function(){var e=0;return Ie.create({next:function(){if(void 0!==t[e])return t[e++];var r=n.next(0);return r.done?r:t[e++]=r}})}}function Fe(e,t,n){this.namespaceURI=t||null,this.prefix=e||"",this.localName=n}function Oe(e){var t=e.j,n=e.arity,r=void 0!==e.Sa&&e.Sa,a=void 0!==e.I&&e.I,o=e.localName,u=e.namespaceURI,i=e.i;for(e=e.value,he.call(this,60,null),this.value=e,this.I=a,a=-1,e=0;e<t.length;e++)4===t[e]&&(a=e);-1<a&&(e=Array(n-(t.length-1)).fill(t[a-1]),t=t.slice(0,a).concat(e)),this.o=t,this.v=n,this.da=r,this.B=o,this.l=u,this.s=i}function Se(e,t){var n=e.value,r=t.map((function(e){return null===e?null:Ce(e)}));return t=new Oe({j:t=t.reduce((function(t,n,r){return null===n&&t.push(e.o[r]),t}),[]),arity:t.length,Sa:!0,I:e.I,localName:"boundFunction",namespaceURI:e.l,i:e.s,value:function(e,t,a){var o=Array.from(arguments).slice(3),u=r.map((function(e){return null===e?o.shift():e()}));return n.apply(void 0,[e,t,a].concat(u))}}),Ie.m(t)}function Ge(e,t){var n=[];return 2!==e&&1!==e||n.push("type-1-or-type-2"),n.push("type-"+e),t&&n.push("name-"+t),n}function De(e){var t=e.node.nodeType;if(2===t||1===t)var n=e.node.localName;return Ge(t,n)}function Re(e){var t=e.nodeType;if(2===t||1===t)var n=e.localName;return Ge(t,n)}function ke(){}function Ue(){}Fe.prototype.Ca=function(){return this.prefix?this.prefix+":"+this.localName:this.localName},A(Oe,he),Oe.prototype.Sa=function(){return this.da},ke.prototype.getAllAttributes=function(e,t){return t=void 0===t?null:t,1!==e.nodeType?[]:(e=Array.from(e.attributes),null===t?e:e.filter((function(e){return Re(e).includes(t)})))},ke.prototype.getAttribute=function(e,t){return 1!==e.nodeType?null:e.getAttribute(t)},ke.prototype.getChildNodes=function(e,t){return t=void 0===t?null:t,e=Array.from(e.childNodes),null===t?e:e.filter((function(e){return Re(e).includes(t)}))},ke.prototype.getData=function(e){return 2===e.nodeType?e.value:e.data},ke.prototype.getFirstChild=function(e,t){for(t=void 0===t?null:t,e=e.firstChild;e;e=e.nextSibling)if(null===t||Re(e).includes(t))return e;return null},ke.prototype.getLastChild=function(e,t){for(t=void 0===t?null:t,e=e.lastChild;e;e=e.previousSibling)if(null===t||Re(e).includes(t))return e;return null},ke.prototype.getNextSibling=function(e,t){for(t=void 0===t?null:t,e=e.nextSibling;e;e=e.nextSibling)if(null===t||Re(e).includes(t))return e;return null},ke.prototype.getParentNode=function(e,t){return t=void 0===t?null:t,(e=2===e.nodeType?e.ownerElement:e.parentNode)&&(null===t||Re(e).includes(t))?e:null},ke.prototype.getPreviousSibling=function(e,t){for(t=void 0===t?null:t,e=e.previousSibling;e;e=e.previousSibling)if(null===t||Re(e).includes(t))return e;return null},(a=Ue.prototype).insertBefore=function(e,t,n){return e.insertBefore(t,n)},a.removeAttributeNS=function(e,t,n){return e.removeAttributeNS(t,n)},a.removeChild=function(e,t){return e.removeChild(t)},a.setAttributeNS=function(e,t,n,r){e.setAttributeNS(t,n,r)},a.setData=function(e,t){e.data=t};var Me=new Ue;function He(e){this.h=e}function Pe(e){return void 0!==e.Ta}function je(e,t,n){var r=null;return t&&(Pe(t.node)?r={F:t.F,offset:n,parent:t.node}:t.F&&(r=t.F)),{node:e,F:r}}function Xe(e){this.h=e,this.o=[]}function Le(e,t,n){return e.getAllAttributes(t.node,void 0===n?null:n).map((function(e){return je(e,t,e.nodeName)}))}function Ye(e,t,n){return Pe(t=t.node)?(e=t.attributes.find((function(e){return n===e.name})))?e.value:null:(e=e.h.getAttribute(t,n))?e:null}function Qe(e,t,n){return e.getChildNodes(t.node,void 0===n?null:n).map((function(e,n){return je(e,t,n)}))}function Je(e,t){return e.getData(t.node)}function Ke(e,t,n){var r=t.node;return Pe(r)?e=r.childNodes[0]:((n=e.h.getFirstChild(r,void 0===n?null:n))&&10===n.nodeType&&(n=e.h.getNextSibling(n)),e=n),e?je(e,t,0):null}function qe(e,t,n){n=void 0===n?null:n;var r=t.node;return Pe(r)?(e=r.childNodes.length-1,r=r.childNodes[e]):((r=e.h.getLastChild(r,n))&&10===r.nodeType&&(r=e.h.getPreviousSibling(r)),e=e.getChildNodes(t.node,n).length-1),r?je(r,t,e):null}function _e(e,t,n){n=void 0===n?null:n;var r=t.node,a=t.F;if(Pe(r)){if(a)var o=a.offset+1,u=a.parent.childNodes[o]}else{if(!a){for(u=r;u&&(!(u=e.h.getNextSibling(u,n))||10===u.nodeType););return u?{node:u,F:null}:null}o=a.offset+1;var i=Ve(e,t,null);u=e.getChildNodes(i.node,n)[o]}return u?je(u,i||Ve(e,t,n),o):null}function Ve(e,t,n){n=void 0===n?null:n;var r=t.node,a=t.F;if(a)"number"==typeof a.offset&&r===a.parent.childNodes[a.offset]||"string"==typeof a.offset&&r===a.parent.attributes.find((function(e){return a.offset===e.nodeName}))?(e=a.parent,t=a.F):(e=e.getParentNode(r,n),t=a);else{if(Pe(r))return null;e=e.getParentNode(r,n),t=null}return e?{node:e,F:t}:null}function We(e,t,n){n=void 0===n?null:n;var r=t.node,a=t.F;if(Pe(r)){if(a)var o=a.offset-1,u=a.parent.childNodes[o]}else{if(!a){for(u=r;u&&(!(u=e.h.getPreviousSibling(u,n))||10===u.nodeType););return u?{node:u,F:null}:null}o=a.offset-1;var i=Ve(e,t,null);u=e.getChildNodes(i.node,n)[o]}return u?je(u,i||Ve(e,t,n),o):null}function Ze(e,t,n,r,a){return a.M((function(e){var t=p(e).next().value;return r.M((function(e){e=p(e).next().value;var n=t.value;if(0>=n||n>e.P.length)throw Error("FOAY0001: array position out of bounds.");return e.P[n-1]()}))}))}function $e(e){Oe.call(this,{value:function(e,n,r,a){return Ze(e,n,r,Ie.m(t),a)},localName:"get",namespaceURI:"http://www.w3.org/2005/xpath-functions/array",j:[{type:5,g:3}],arity:1,i:{type:59,g:2}});var t=this;this.type=62,this.P=e}function ze(e){switch(e.node.nodeType){case 2:return 47;case 1:return 54;case 3:case 4:return 56;case 7:return 57;case 8:return 58;case 9:return 55;default:return 53}}function et(e){return{type:ze(e),value:e}}function tt(e,t){return e=e.map((function(e){return e.first()})),t(e)}function nt(e,t){var n=se(e.type,1)||se(e.type,20)||se(e.type,19),r=se(t.type,1)||se(t.type,20)||se(t.type,19);return n&&r?e.value===t.value:(n=se(e.type,4)||se(e.type,3)||se(e.type,6),r=se(t.type,4)||se(t.type,3)||se(t.type,6),n&&r?!(!isNaN(e.value)||!isNaN(t.value))||e.value===t.value:(n=se(e.type,0)||se(e.type,22)||se(e.type,18)||se(e.type,23)||se(e.type,44),r=se(t.type,0)||se(t.type,22)||se(t.type,18)||se(t.type,23)||se(t.type,44),!(!n||!r)&&e.value===t.value))}function rt(e,t,n,r,a){return tt([r,a],(function(e){var t=(e=p(e)).next().value,n=e.next().value;return(e=t.h.find((function(e){return nt(e.key,n)})))?e.value():Ie.empty()}))}function at(e){Oe.call(this,{j:[{type:59,g:3}],arity:1,localName:"get",namespaceURI:"http://www.w3.org/2005/xpath-functions/map",value:function(e,n,r,a){return rt(e,n,r,Ie.m(t),a)},i:{type:59,g:2}});var t=this;this.type=61,this.h=e}function ot(){}function ut(e,t){return e.eb()===t.eb()&&e.fb()===t.fb()}function it(e){if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw Error("FODT0002: Number of seconds given to construct DayTimeDuration overflows MAX_SAFE_INTEGER or MIN_SAFE_INTEGER");this.ea=e}function ct(e){var t=Math.abs(e.bb()),n=Math.abs(e.getHours()),r=Math.abs(e.getMinutes());return n=(n?n+"H":"")+(r?r+"M":"")+((e=Math.abs(e.getSeconds()))?e+"S":""),(t=t?t+"D":"")&&n?t+"T"+n:t||(n?"T"+n:"T0S")}function lt(e,t,n,r,a,o){return e=86400*e+3600*t+60*n+r+a,new it(o||0===e?e:-e)}function st(e){return(e=/^(-)?P(\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+(\.\d*)?S)?)?$/.exec(e))?lt(e[4]?parseInt(e[4],10):0,e[5]?parseInt(e[5],10):0,e[6]?parseInt(e[6],10):0,e[7]?parseInt(e[7],10):0,e[8]?parseFloat(e[8]):0,!e[1]):null}function pt(e){return"Z"===(e=/^(Z)|([+-])([01]\d):([0-5]\d)$/.exec(e))[1]?lt(0,0,0,0,0,!0):lt(0,e[3]?parseInt(e[3],10):0,e[4]?parseInt(e[4],10):0,0,0,"+"===e[2])}function ft(e,t){if(isNaN(t))throw Error("FOCA0005: Cannot multiply xs:dayTimeDuration by NaN");if((e=e.ea*t)>Number.MAX_SAFE_INTEGER||!Number.isFinite(e))throw Error("FODT0002: Value overflow while multiplying xs:dayTimeDuration");return new it(e<Number.MIN_SAFE_INTEGER||Object.is(-0,e)?0:e)}function ht(e){return e?parseInt(e,10):null}function dt(e){var t=(e+="").startsWith("-");return t&&(e=e.substring(1)),(t?"-":"")+e.padStart(4,"0")}function mt(e){return(e+"").padStart(2,"0")}function yt(e){return 1===(e+="").split(".")[0].length&&(e=e.padStart(e.length+1,"0")),e}function gt(e){return 0===e.getHours()&&0===e.getMinutes()?"Z":(e.qa()?"+":"-")+mt(Math.abs(e.getHours()))+":"+mt(Math.abs(e.getMinutes()))}function vt(e,t,n,r,a,o,u,i,c){this.v=e,this.h=t,this.o=n+(24===r?1:0),this.l=24===r?0:r,this.s=a,this.B=o,this.sa=u,this.Y=i,this.type=void 0===c?9:c}function wt(e){var t=/^(?:(-?\d{4,}))?(?:--?(\d\d))?(?:-{1,3}(\d\d))?(T)?(?:(\d\d):(\d\d):(\d\d))?(\.\d+)?(Z|(?:[+-]\d\d:\d\d))?$/.exec(e);e=t[1]?parseInt(t[1],10):null;var n=ht(t[2]),r=ht(t[3]),a=t[4],o=ht(t[5]),u=ht(t[6]),i=ht(t[7]),c=t[8]?parseFloat(t[8]):0;if(t=t[9]?pt(t[9]):null,e&&(-271821>e||273860<e))throw Error("FODT0001: Datetime year is out of bounds");return a?new vt(e,n,r,o,u,i,c,t,9):null!==o&&null!==u&&null!==i?new vt(1972,12,31,o,u,i,c,t,8):null!==e&&null!==n&&null!==r?new vt(e,n,r,0,0,0,0,t,7):null!==e&&null!==n?new vt(e,n,1,0,0,0,0,t,11):null!==n&&null!==r?new vt(1972,n,r,0,0,0,0,t,13):null!==e?new vt(e,1,1,0,0,0,0,t,12):null!==n?new vt(1972,n,1,0,0,0,0,t,14):new vt(1972,12,r,0,0,0,0,t,15)}function At(e,t){switch(t){case 15:return new vt(1972,12,e.o,0,0,0,0,e.Y,15);case 14:return new vt(1972,e.h,1,0,0,0,0,e.Y,14);case 12:return new vt(e.v,1,1,0,0,0,0,e.Y,12);case 13:return new vt(1972,e.h,e.o,0,0,0,0,e.Y,13);case 11:return new vt(e.v,e.h,1,0,0,0,0,e.Y,11);case 8:return new vt(1972,12,31,e.l,e.s,e.B,e.sa,e.Y,8);case 7:return new vt(e.v,e.h,e.o,0,0,0,0,e.Y,7);default:return new vt(e.v,e.h,e.o,e.l,e.s,e.B,e.sa,e.Y,9)}}function xt(e,t){return t=e.Y||t||pt("Z"),new Date(Date.UTC(e.v,e.h-1,e.o,e.l-t.getHours(),e.s-t.getMinutes(),e.B,1e3*e.sa))}function Bt(e,t,n){var r=xt(e,n).getTime();return r===(n=xt(t,n).getTime())?e.sa===t.sa?0:e.sa>t.sa?1:-1:r>n?1:-1}function bt(e,t,n){return 0===Bt(e,t,n)}function Et(e,t,n){return new it(e=(xt(e,n).getTime()-xt(t,n).getTime())/1e3)}function Nt(e){throw Error("Not implemented: adding durations to "+me[e.type])}function Tt(e){throw Error("Not implemented: subtracting durations from "+me[e.type])}function It(e,t){if(null===e)return null;switch(typeof e){case"boolean":return e?re:ae;case"number":return ne(e,3);case"string":return ne(e,1);case"object":if("nodeType"in e)return et({node:e,F:null});if(Array.isArray(e))return new $e(e.map((function(e){return void 0===e?function(){return Ie.empty()}:Ce(e=null===(e=It(e))?Ie.empty():Ie.m(e))})));if(e instanceof Date){var n=wt(e.toISOString());return ne(n,n.type)}return new at(Object.keys(e).filter((function(t){return void 0!==e[t]})).map((function(t){var n=It(e[t]);return n=null===n?Ie.empty():Ie.m(n),{key:ne(t,1),value:Ce(n)}})))}throw Error("Value "+String(e)+' of type "'+typeof e+'" is not adaptable to an XPath value.')}function Ct(e,t){if("number"!=typeof e&&("string"!=typeof e||!ee.get(t)(e)))throw Error("Cannot convert JavaScript value '"+e+"' to the XPath type "+me[t]+" since it is not valid.")}function Ft(e,t,n){if(null===t)return null;switch(e){case 0:return t?re:ae;case 1:return ne(t+"",1);case 3:case 2:return Ct(t,3),ne(+t,3);case 4:return Ct(t,e),ne(+t,4);case 5:return Ct(t,e),ne(0|t,5);case 6:return Ct(t,e),ne(+t,6);case 7:case 8:case 9:case 11:case 12:case 13:case 14:case 15:if(!(t instanceof Date))throw Error("The JavaScript value "+t+" with type "+typeof t+" is not a valid type to be converted to an XPath "+me[e]+".");return ne(At(wt(t.toISOString()),e),e);case 53:case 47:case 55:case 54:case 56:case 57:case 58:if("object"!=typeof t||!("nodeType"in t))throw Error("The JavaScript value "+t+" with type "+typeof t+" is not a valid type to be converted to an XPath "+me[e]+".");return et({node:t,F:null});case 59:case 61:return It(t);default:throw Error('Values of the type "'+me[e]+'" can not be adapted from JavaScript to equivalent XPath values.')}}function Ot(e,t,n){if(0===n.g)return null===(t=Ft(n.type,t))?[]:[t];if(2===n.g||1===n.g){if(!Array.isArray(t))throw Error("The JavaScript value "+t+" should be an array if it is to be converted to "+ge(n)+".");return t.map((function(e){return Ft(n.type,e)})).filter((function(e){return null!==e}))}var r=Ft(n.type,t);if(null===r)throw Error("The JavaScript value "+t+" should be a single entry if it is to be converted to "+ge(n)+".");return[r]}function St(e,t,n){return n=void 0===n?{type:59,g:0}:n,Ie.create(Ot(e,t,n))}function Gt(){var e=void 0===e?Math.floor(Math.random()*Dt):e;this.h=Math.abs(e%Dt)}(a=He.prototype).insertBefore=function(e,t,n){return this.h.insertBefore(e,t,n)},a.removeAttributeNS=function(e,t,n){return this.h.removeAttributeNS(e,t,n)},a.removeChild=function(e,t){return this.h.removeChild(e,t)},a.setAttributeNS=function(e,t,n,r){this.h.setAttributeNS(e,t,n,r)},a.setData=function(e,t){this.h.setData(e,t)},Xe.prototype.getAllAttributes=function(e,t){return Pe(e)?e.attributes:this.h.getAllAttributes(e,void 0===t?null:t)},Xe.prototype.getChildNodes=function(e,t){return t=Pe(e)?e.childNodes:this.h.getChildNodes(e,void 0===t?null:t),9===e.nodeType?t.filter((function(e){return 10!==e.nodeType})):t},Xe.prototype.getData=function(e){return Pe(e)?2===e.nodeType?e.value:e.data:this.h.getData(e)||""},Xe.prototype.getParentNode=function(e,t){return this.h.getParentNode(e,void 0===t?null:t)},A($e,Oe),A(at,Oe),(a=ot.prototype).bb=function(){return 0},a.getHours=function(){return 0},a.getMinutes=function(){return 0},a.cb=function(){return 0},a.eb=function(){return 0},a.fb=function(){return 0},a.getSeconds=function(){return 0},a.gb=function(){return 0},a.qa=function(){return!0},A(it,ot),(a=it.prototype).bb=function(){return Math.trunc(this.ea/86400)},a.getHours=function(){return Math.trunc(this.ea%86400/3600)},a.getMinutes=function(){return Math.trunc(this.ea%3600/60)},a.fb=function(){return this.ea},a.getSeconds=function(){var e=this.ea%60;return Object.is(-0,e)?0:e},a.qa=function(){return!Object.is(-0,this.ea)&&0<=this.ea},a.toString=function(){return(this.qa()?"P":"-P")+ct(this)},(a=vt.prototype).getDay=function(){return this.o},a.getHours=function(){return this.l},a.getMinutes=function(){return this.s},a.getMonth=function(){return this.h},a.getSeconds=function(){return this.B},a.getYear=function(){return this.v},a.toString=function(){switch(this.type){case 9:return dt(this.v)+"-"+mt(this.h)+"-"+mt(this.o)+"T"+mt(this.l)+":"+mt(this.s)+":"+yt(this.B+this.sa)+(this.Y?gt(this.Y):"");case 7:return dt(this.v)+"-"+mt(this.h)+"-"+mt(this.o)+(this.Y?gt(this.Y):"");case 8:return mt(this.l)+":"+mt(this.s)+":"+yt(this.B+this.sa)+(this.Y?gt(this.Y):"");case 15:return"---"+mt(this.o)+(this.Y?gt(this.Y):"");case 14:return"--"+mt(this.h)+(this.Y?gt(this.Y):"");case 13:return"--"+mt(this.h)+"-"+mt(this.o)+(this.Y?gt(this.Y):"");case 12:return dt(this.v)+(this.Y?gt(this.Y):"");case 11:return dt(this.v)+"-"+mt(this.h)+(this.Y?gt(this.Y):"")}throw Error("Unexpected subType")};var Dt=Math.pow(2,32);function Rt(e,t,n){t=void 0===t?{yb:null,Db:null,tb:!1}:t,n=void 0===n?new Gt:n,this.h=t,this.Ka=e.Ka,this.Da=e.Da,this.N=e.N,this.Aa=e.Aa||Object.create(null),this.o=n}function kt(e,t){var n=0,r=t.value;return{next:function(a){return(a=r.next(a)).done?ie:ce(Pt(e,n++,a.value,t))}}}function Ut(e){return e.h.tb||(e.h.tb=!0,e.h.yb=wt((new Date).toISOString()),e.h.Db=st("PT0S")),e.h.yb}function Mt(e){return e.h.tb||(e.h.tb=!0,e.h.yb=wt((new Date).toISOString()),e.h.Db=st("PT0S")),e.h.Db}function Ht(e,t){return e=29421*(null!=(t=void 0===t?null:t)?t:e.o.h)%Dt,{zb:Math.floor(e),jc:e/Dt}}function Pt(e,t,n,r){return new Rt({N:n,Ka:t,Da:r||e.Da,Aa:e.Aa},e.h,e.o)}function jt(e,t){return new Rt({N:e.N,Ka:e.Ka,Da:e.Da,Aa:Object.assign(Object.create(null),e.Aa,t)},e.h,e.o)}function Xt(e,t,n,r,a,o,u,i,c){this.debug=e,this.La=t,this.h=n,this.o=r,this.B=a,this.l=o,this.da=u,this.s=i,this.v=c}function Lt(e){var t=0,n=null,r=!0;return Ie.create({next:function(a){for(;t<e.length;){n||(n=e[t].value,r=!0);var o=n.next(r?0:a);if(r=!1,!o.done)return o;t++,n=null}return ie}})}function Yt(e,t,n){return Error("FORG0001: Cannot cast "+e+" to "+me[t]+(n?", "+n:""))}function Qt(e){return Error("XPDY0002: "+e)}function Jt(e){return Error("XPTY0004: "+e)}function Kt(e){return Error("FOTY0013: Atomization is not supported for "+me[e]+".")}function qt(e){return Error("XPST0081: The prefix "+e+" could not be resolved.")}function _t(e,t){if(se(e.type,46)||se(e.type,19)||se(e.type,0)||se(e.type,4)||se(e.type,3)||se(e.type,6)||se(e.type,5)||se(e.type,2)||se(e.type,23)||se(e.type,1))return Ie.create(e);var n=t.h;if(se(e.type,53)){var r=e.value;if(2===r.node.nodeType||3===r.node.nodeType)return Ie.create(ne(Je(n,r),19));if(8===r.node.nodeType||7===r.node.nodeType)return Ie.create(ne(Je(n,r),1));var a=[];return function e(t){if(8!==r.node.nodeType&&7!==r.node.nodeType){var o=t.nodeType;3===o||4===o?a.push(n.getData(t)):1!==o&&9!==o||n.getChildNodes(t).forEach((function(t){e(t)}))}}(r.node),Ie.create(ne(a.join(""),19))}if(se(e.type,60)&&!se(e.type,62))throw Kt(e.type);if(se(e.type,62))return Lt(e.P.map((function(e){return Vt(e(),t)})));throw Error("Atomizing "+e.type+" is not implemented.")}function Vt(e,t){var n=!1,r=e.value,a=null;return Ie.create({next:function(){for(;!n;){if(!a){var e=r.next(0);if(e.done){n=!0;break}a=_t(e.value,t).value}if(!(e=a.next(0)).done)return e;a=null}return ie}})}function Wt(e){for(e=te[e];e&&0!==e.D;)e=e.parent;return e?e.type:null}function Zt(e,t){var n=(t=te[t]).Na;if(!n||!n.whiteSpace)return t.parent?Zt(e,t.parent.type):e;switch(t.Na.whiteSpace){case"replace":return e.replace(/[\u0009\u000A\u000D]/g," ");case"collapse":return e.replace(/[\u0009\u000A\u000D]/g," ").replace(/ {2,}/g," ").replace(/^ | $/g,"")}return e}function $t(e,t){for(t=te[t];t&&null===t.kb;){if(2===t.D||3===t.D)return!0;t=t.parent}return!t||t.kb(e)}function zt(e,t){for(;e;){if(e.Pa&&e.Pa[t])return e.Pa[t];e=e.parent}return function(){return!0}}function en(e,t){for(var n=te[t];n;){if(n.Na&&!Object.keys(n.Na).every((function(t){if("whiteSpace"===t)return!0;var r=zt(n,t);return!r||r(e,n.Na[t])})))return!1;n=n.parent}return!0}function tn(e){return!e||2===e.g||0===e.g}function nn(e){return e(1)||e(19)?function(e){return{u:!0,value:ne(e,20)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:anyURI or any of its derived types.")}}}function rn(e){return e(22)?function(e){for(var t="",n=0;n<e.length;n+=2)t+=String.fromCharCode(parseInt(e.substr(n,2),16));return{u:!0,value:ne(btoa(t),21)}}:e(1)||e(19)?function(e){return{u:!0,value:ne(e,21)}}:function(){return{error:Error("XPTY0004: Casting not supported from given type to xs:base64Binary or any of its derived types."),u:!1}}}function an(e){return e(2)?function(e){return{u:!0,value:0===e||isNaN(e)?ae:re}}:e(1)||e(19)?function(e){switch(e){case"true":case"1":return{u:!0,value:re};case"false":case"0":return{u:!0,value:ae};default:return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:boolean or any of its derived types.")}}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:boolean or any of its derived types.")}}}function on(e){return e(9)?function(e){return{u:!0,value:ne(At(e,7),7)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),7)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:date or any of its derived types.")}}}function un(e){return e(7)?function(e){return{u:!0,value:ne(At(e,9),9)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),9)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:dateTime or any of its derived types.")}}}function cn(e){return e(18)&&!e(16)?function(e){return{u:!0,value:ne(e.Ja,17)}}:e(16)?function(){return{u:!0,value:ne(st("PT0.0S"),17)}}:e(19)||e(1)?function(e){var t=st(e);return t?{u:!0,value:ne(t,17)}:{u:!1,error:Error("FORG0001: Can not cast "+e+" to xs:dayTimeDuration")}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:dayTimeDuration or any of its derived types.")}}}function ln(e){return e(5)?function(e){return{u:!0,value:ne(e,4)}}:e(6)||e(3)?function(e){return isNaN(e)||!isFinite(e)?{u:!1,error:Error("FOCA0002: Can not cast "+e+" to xs:decimal")}:Math.abs(e)>Number.MAX_VALUE?{u:!1,error:Error("FOAR0002: Can not cast "+e+" to xs:decimal, it is out of bounds for JavaScript numbers")}:{u:!0,value:ne(e,4)}}:e(0)?function(e){return{u:!0,value:ne(e?1:0,4)}}:e(1)||e(19)?function(e){var t=parseFloat(e);return!isNaN(t)||isFinite(t)?{u:!0,value:ne(t,4)}:{u:!1,error:Error("FORG0001: Can not cast "+e+" to xs:decimal")}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:decimal or any of its derived types.")}}}function sn(e,t){return e(2)?function(e){return{u:!0,value:e}}:e(0)?function(e){return{u:!0,value:e?1:0}}:e(1)||e(19)?function(e){switch(e){case"NaN":return{u:!0,value:NaN};case"INF":case"+INF":return{u:!0,value:1/0};case"-INF":return{u:!0,value:-1/0};case"0":case"+0":return{u:!0,value:0};case"-0":return{u:!0,value:-0}}var n=parseFloat(e);return isNaN(n)?{u:!1,error:Yt(e,t)}:{u:!0,value:n}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to "+t+" or any of its derived types.")}}}function pn(e){var t=sn(e,3);return function(e){return(e=t(e)).u?{u:!0,value:ne(e.value,3)}:e}}function fn(e){if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw Error("FODT0002: Number of months given to construct YearMonthDuration overflows MAX_SAFE_INTEGER or MIN_SAFE_INTEGER");this.ga=e}function hn(e){var t=Math.abs(e.gb());return(t?t+"Y":"")+((e=Math.abs(e.cb()))?e+"M":"")||"0M"}function dn(e){var t=/^(-)?P(\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+(\.\d*)?S)?)?$/.exec(e);if(t){if(e=!t[1],(t=12*(t[2]?parseInt(t[2],10):0)+(t[3]?parseInt(t[3],10):0))>Number.MAX_SAFE_INTEGER||!Number.isFinite(t))throw Error("FODT0002: Value overflow while constructing xs:yearMonthDuration");e=new fn(e||0===t?t:-t)}else e=null;return e}function mn(e,t){if(isNaN(t))throw Error("FOCA0005: Cannot multiply xs:yearMonthDuration by NaN");if((e=Math.round(e.ga*t))>Number.MAX_SAFE_INTEGER||!Number.isFinite(e))throw Error("FODT0002: Value overflow while constructing xs:yearMonthDuration");return new fn(e<Number.MIN_SAFE_INTEGER||0===e?0:e)}function yn(e,t){this.Wa=e,this.Ja=t}function gn(e){return e(16)?function(e){return{u:!0,value:ne(new yn(e,new it(e.qa()?0:-0)),18)}}:e(17)?function(e){return{u:!0,value:ne(e=new yn(new fn(e.qa()?0:-0),e),18)}}:e(18)?function(e){return{u:!0,value:ne(e,18)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(new yn(dn(e),st(e)),18)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:duration or any of its derived types.")}}}function vn(e){var t=sn(e,6);return function(e){return(e=t(e)).u?{u:!0,value:ne(e.value,6)}:e}}function wn(e){return e(7)||e(9)?function(e){return{u:!0,value:ne(At(e,15),15)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),15)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:gDay or any of its derived types.")}}}function An(e){return e(7)||e(9)?function(e){return{u:!0,value:ne(At(e,14),14)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),14)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:gMonth or any of its derived types.")}}}function xn(e){return e(7)||e(9)?function(e){return{u:!0,value:ne(At(e,13),13)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),13)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:gMonthDay or any of its derived types.")}}}function Bn(e){return e(7)||e(9)?function(e){return{u:!0,value:ne(At(e,12),12)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),12)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:gYear or any of its derived types.")}}}function bn(e){return e(7)||e(9)?function(e){return{u:!0,value:ne(At(e,11),11)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),11)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:gYearMonth or any of its derived types.")}}}function En(e){return e(21)?function(e){for(var t="",n=0,r=(e=atob(e)).length;n<r;n++)t+=Number(e.charCodeAt(n)).toString(16);return{u:!0,value:ne(t.toUpperCase(),22)}}:e(1)||e(19)?function(e){return{u:!0,value:ne(e,22)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:hexBinary or any of its derived types.")}}}function Nn(e){return e(0)?function(e){return{u:!0,value:ne(e?1:0,5)}}:e(2)?function(e){var t=Math.trunc(e);return!isFinite(t)||isNaN(t)?{u:!1,error:Error("FOCA0002: can not cast "+e+" to xs:integer")}:Number.isSafeInteger(t)?{u:!0,value:ne(t,5)}:{u:!1,error:Error("FOAR0002: can not cast "+e+" to xs:integer, it is out of bounds for JavaScript numbers.")}}:e(1)||e(19)?function(e){var t=parseInt(e,10);return isNaN(t)?{u:!1,error:Yt(e,5)}:Number.isSafeInteger(t)?{u:!0,value:ne(t,5)}:{u:!1,error:Error("FOCA0003: can not cast "+e+" to xs:integer, it is out of bounds for JavaScript numbers.")}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:integer or any of its derived types.")}}}A(fn,ot),(a=fn.prototype).cb=function(){var e=this.ga%12;return 0===e?0:e},a.eb=function(){return this.ga},a.gb=function(){return Math.trunc(this.ga/12)},a.qa=function(){return!Object.is(-0,this.ga)&&0<=this.ga},a.toString=function(){return(this.qa()?"P":"-P")+hn(this)},A(yn,ot),(a=yn.prototype).bb=function(){return this.Ja.bb()},a.getHours=function(){return this.Ja.getHours()},a.getMinutes=function(){return this.Ja.getMinutes()},a.cb=function(){return this.Wa.cb()},a.eb=function(){return this.Wa.eb()},a.fb=function(){return this.Ja.fb()},a.getSeconds=function(){return this.Ja.getSeconds()},a.gb=function(){return this.Wa.gb()},a.qa=function(){return this.Wa.qa()&&this.Ja.qa()},a.toString=function(){var e=this.qa()?"P":"-P",t=hn(this.Wa),n=ct(this.Ja);return"0M"===t?e+n:"T0S"===n?e+t:e+t+n};var Tn=[3,6,4,5];function In(e){var t=Rn;return function(n){for(var r=p(Tn),a=r.next();!a.done;a=r.next())if((a=t(e,a.value)(n)).u)return a;return{u:!1,error:Error('XPTY0004: Casting not supported from "'+n+'" given type to xs:numeric or any of its derived types.')}}}function Cn(e){if(e(1)||e(19))return function(e){return{u:!0,value:e+""}};if(e(20))return function(e){return{u:!0,value:e}};if(e(23))return function(e){return{u:!0,value:e.prefix?e.prefix+":"+e.localName:e.localName}};if(e(44))return function(e){return{u:!0,value:e.toString()}};if(e(2)){if(e(5)||e(4))return function(e){return{u:!0,value:(e+"").replace("e","E")}};if(e(6)||e(3))return function(e){return isNaN(e)?{u:!0,value:"NaN"}:isFinite(e)?Object.is(e,-0)?{u:!0,value:"-0"}:{u:!0,value:(e+"").replace("e","E").replace("E+","E")}:{u:!0,value:(0>e?"-":"")+"INF"}}}return e(9)||e(7)||e(8)||e(15)||e(14)||e(13)||e(12)||e(11)||e(16)||e(17)||e(18)?function(e){return{u:!0,value:e.toString()}}:e(22)?function(e){return{u:!0,value:e.toUpperCase()}}:function(e){return{u:!0,value:e+""}}}function Fn(e){var t=Cn(e);return function(e){return(e=t(e)).u?{u:!0,value:ne(e.value,1)}:e}}function On(e){return e(9)?function(e){return{u:!0,value:ne(At(e,8),8)}}:e(19)||e(1)?function(e){return{u:!0,value:ne(wt(e),8)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:time or any of its derived types.")}}}function Sn(e){var t=Cn(e);return function(e){return(e=t(e)).u?{u:!0,value:ne(e.value,19)}:e}}function Gn(e){return e(18)&&!e(17)?function(e){return{u:!0,value:ne(e.Wa,16)}}:e(17)?function(){return{u:!0,value:ne(dn("P0M"),16)}}:e(19)||e(1)?function(e){var t=dn(e);return t?{u:!0,value:ne(t,16)}:{u:!1,error:Yt(e,16)}}:function(){return{u:!1,error:Error("XPTY0004: Casting not supported from given type to xs:yearMonthDuration or any of its derived types.")}}}var Dn=[2,5,17,16];function Rn(e,t){function n(t){return se(e,t)}if(39===t)return function(){return{u:!1,error:Error("FORG0001: Casting to xs:error is always invalid.")}};switch(t){case 19:return Sn(n);case 1:return Fn(n);case 6:return vn(n);case 3:return pn(n);case 4:return ln(n);case 5:return Nn(n);case 2:return In(e);case 18:return gn(n);case 16:return Gn(n);case 17:return cn(n);case 9:return un(n);case 8:return On(n);case 7:return on(n);case 11:return bn(n);case 12:return Bn(n);case 13:return xn(n);case 15:return wn(n);case 14:return An(n);case 0:return an(n);case 21:return rn(n);case 22:return En(n);case 20:return nn(n);case 23:throw Error("Casting to xs:QName is not implemented.")}return function(){return{u:!1,error:Error("XPTY0004: Casting not supported from "+e+" to "+t+".")}}}var kn=Object.create(null);function Un(e,t){if(19===e&&1===t)return function(e){return{u:!0,value:ne(e,1)}};if(44===t)return function(){return{u:!1,error:Error("XPST0080: Casting to xs:NOTATION is not permitted.")}};if(39===t)return function(){return{u:!1,error:Error("FORG0001: Casting to xs:error is not permitted.")}};if(45===e||45===t)return function(){return{u:!1,error:Error("XPST0080: Casting from or to xs:anySimpleType is not permitted.")}};if(46===e||46===t)return function(){return{u:!1,error:Error("XPST0080: Casting from or to xs:anyAtomicType is not permitted.")}};if(se(e,60)&&1===t)return function(){return{u:!1,error:Error("FOTY0014: Casting from function item to xs:string is not permitted.")}};if(e===t)return function(e){return{u:!0,value:{type:t,value:e}}};var n=Dn.includes(e)?e:Wt(e),r=Dn.includes(t)?t:Wt(t);if(null===r||null===n)return function(){return{u:!1,error:Error("XPST0081: Can not cast: type "+(r?me[e]:me[t])+" is unknown.")}};var a=[];return 1!==n&&19!==n||a.push((function(e){var n=Zt(e,t);return $t(n,t)?{u:!0,value:n}:{u:!1,error:Yt(e,t,"pattern validation failed.")}})),n!==r&&(a.push(Rn(n,r)),a.push((function(e){return{u:!0,value:e.value}}))),19!==r&&1!==r||a.push((function(e){return $t(e,t)?{u:!0,value:e}:{u:!1,error:Yt(e,t,"pattern validation failed.")}})),a.push((function(e){return en(e,t)?{u:!0,value:e}:{u:!1,error:Yt(e,t,"pattern validation failed.")}})),a.push((function(e){return{u:!0,value:{type:t,value:e}}})),function(e){e={u:!0,value:e};for(var t=0,n=a.length;t<n&&!1!==(e=a[t](e.value)).u;++t);return e}}function Mn(e,t){var n=e.type+1e4*t,r=kn[n];return r||(r=kn[n]=Un(e.type,t)),r.call(void 0,e.value,t)}function Hn(e,t){if(!0===(e=Mn(e,t)).u)return e.value;throw e.error}function Pn(e){var t=!1;return{next:function(){return t?ie:(t=!0,ce(e))}}}function jn(e,t){return e===t||!(!e||!t||e.offset!==t.offset||e.parent!==t.parent)&&jn(e.F,t.F)}function Xn(e,t){return!!(e===t||e.node===t.node&&jn(e.F,t.F))}function Ln(e,t,n){var r=Ve(e,t,null);e=Qe(e,r,null),r=0;for(var a=e.length;r<a;++r){var o=e[r];if(Xn(o,t))return-1;if(Xn(o,n))return 1}}function Yn(e,t){for(var n=[];t;t=Ve(e,t,null))n.unshift(t);return n}function Qn(e,t){for(var n=[];t;t=e.getParentNode(t,null))n.unshift(t);return n}function Jn(e,t,n,r){if(n.F||r.F||Pe(n.node)||Pe(r.node)){if(Xn(n,r))return 0;n=Yn(t,n),r=Yn(t,r);var a=n[0],o=r[0];if(!Xn(a,o))return t=e.findIndex((function(e){return Xn(e,a)})),n=e.findIndex((function(e){return Xn(e,o)})),-1===t&&(t=e.push(a)),-1===n&&(n=e.push(o)),t-n;e=1;for(var u=Math.min(n.length,r.length);e<u&&Xn(n[e],r[e]);++e);return n[e]?r[e]?Ln(t,n[e],r[e]):1:-1}if((n=n.node)===(r=r.node))return 0;if(n=Qn(t,n),r=Qn(t,r),n[0]!==r[0]){var i={node:n[0],F:null},c={node:r[0],F:null};return t=e.findIndex((function(e){return Xn(e,i)})),n=e.findIndex((function(e){return Xn(e,c)})),-1===t&&(t=e.push(i)),-1===n&&(n=e.push(c)),t-n}for(u=1,e=Math.min(n.length,r.length);u<e&&n[u]===r[u];++u);if(e=n[u],n=r[u],!e)return-1;if(!n)return 1;for(t=t.getChildNodes(r[u-1],null),r=0,u=t.length;r<u;++r){var l=t[r];if(l===e)return-1;if(l===n)return 1}}function Kn(e,t,n,r){var a=se(n.type,47),o=se(r.type,47);if(a&&!o){if(Xn(n=Ve(t,n.value),r=r.value))return 1}else if(o&&!a){if(Xn(n=n.value,r=Ve(t,r.value)))return-1}else if(a&&o){if(Xn(Ve(t,r.value),Ve(t,n.value)))return n.value.node.localName>r.value.node.localName?1:-1;n=Ve(t,n.value),r=Ve(t,r.value)}else n=n.value,r=r.value;return Jn(e,t,n,r)}function qn(e,t,n){return Kn(e.o,e,t,n)}function _n(e,t){return Wn(t,(function(t,n){return Kn(e.o,e,t,n)})).filter((function(e,t,n){return 0===t||!Xn(e.value,n[t-1].value)}))}function Vn(e,t){return e<t?-1:0}function Wn(e,t){if(t=void 0===t?Vn:t,1>=e.length)return e;var n=Math.floor(e.length/2),r=Wn(e.slice(0,n),t);for(e=Wn(e.slice(n),t),n=[];r.length&&e.length;)0>t(r[0],e[0])?n.push(r.shift()):n.push(e.shift());return n.concat(r.concat(e))}var Zn=e;function $n(e,t){if(se(e.type,2)){if(se(e.type,6))return 3===t?ne(e.value,3):null;if(se(e.type,4)){if(6===t)return ne(e.value,6);if(3===t)return ne(e.value,3)}return null}return se(e.type,20)&&1===t?ne(e.value,1):null}function zn(e,t,n,r,a){if(se(e.type,t.type))return e;if(se(t.type,46)&&se(e.type,53)&&(e=_t(e,n).first()),se(e.type,t.type)||46===t.type)return e;if(se(e.type,19)){if(!(n=Hn(e,t.type)))throw Error("XPTY0004 Unable to convert "+(a?"return":"argument")+" of type "+me[e.type]+" to type "+ge(t)+" while calling "+r);return n}if(!(n=$n(e,t.type)))throw Error("XPTY0004 Unable to cast "+(a?"return":"argument")+" of type "+me[e.type]+" to type "+ge(t)+" while calling "+r);return n}function er(e){switch(e){case 2:return"*";case 1:return"+";case 0:return"?";case 3:return""}}function tr(e,t,n,r,a){return 0===e.g?t.Z({default:function(){return t.map((function(t){return zn(t,e,n,r,a)}))},multiple:function(){throw Error("XPTY0004: Multiplicity of "+(a?"function return value":"function argument")+" of type "+me[e.type]+er(e.g)+" for "+r+' is incorrect. Expected "?", but got "+".')}}):1===e.g?t.Z({empty:function(){throw Error("XPTY0004: Multiplicity of "+(a?"function return value":"function argument")+" of type "+me[e.type]+er(e.g)+" for "+r+' is incorrect. Expected "+", but got "empty-sequence()"')},default:function(){return t.map((function(t){return zn(t,e,n,r,a)}))}}):2===e.g?t.map((function(t){return zn(t,e,n,r,a)})):t.Z({m:function(){return t.map((function(t){return zn(t,e,n,r,a)}))},default:function(){throw Error("XPTY0004: Multiplicity of "+(a?"function return value":"function argument")+" of type "+me[e.type]+er(e.g)+" for "+r+" is incorrect. Expected exactly one")}})}function nr(e,t){return se(e,5)?ne(t,5):se(e,6)?ne(t,6):se(e,3)?ne(t,3):ne(t,4)}var rr=[{oa:"M",ma:1e3},{oa:"CM",ma:900},{oa:"D",ma:500},{oa:"CD",ma:400},{oa:"C",ma:100},{oa:"XC",ma:90},{oa:"L",ma:50},{oa:"XL",ma:40},{oa:"X",ma:10},{oa:"IX",ma:9},{oa:"V",ma:5},{oa:"IV",ma:4},{oa:"I",ma:1}];function ar(e,t){var n=parseInt(e,10);if(e=0>n,!(n=Math.abs(n)))return"-";var r=rr.reduce((function(e,t){var r=Math.floor(n/t.ma);return n-=r*t.ma,e+t.oa.repeat(r)}),"");return t&&(r=r.toLowerCase()),e&&(r="-"+r),r}var or="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");function ur(e,t){var n=0>(e=parseInt(e,10));if(!(e=Math.abs(e)))return"-";for(var r,a="";0<e;)r=(e-1)%or.length,a=or[r]+a,e=(e-r)/or.length|0;return t&&(a=a.toLowerCase()),n&&(a="-"+a),a}function ir(e){if(Math.floor(e)===e||isNaN(e))return 0;var t=(e=/\d+(?:\.(\d*))?(?:[Ee](-)?(\d+))*/.exec(""+e))[1]?e[1].length:0;return e[3]?e[2]?t+parseInt(e[3],10):0>(e=t-parseInt(e[3],10))?0:e:t}function cr(e,t,n){return t&&0==e*n%1%.5?0==Math.floor(e*n)%2?Math.floor(e*n)/n:Math.ceil(e*n)/n:Math.round(e*n)/n}function lr(e,t,n,r,a,o){var u=!1;return Ie.create({next:function(){if(u)return ie;var t,n=a.first();if(!n)return u=!0,ie;if((se(n.type,6)||se(n.type,3))&&(0===n.value||isNaN(n.value)||1/0===n.value||-1/0===n.value))return u=!0,ce(n);if(t=o?o.first().value:0,u=!0,ir(n.value)<t)return ce(n);var r=[5,4,3,6].find((function(e){return se(n.type,e)}));switch(t=cr(Hn(n,4).value,e,Math.pow(10,t)),r){case 4:return ce(ne(t,4));case 3:return ce(ne(t,3));case 6:return ce(ne(t,6));case 5:return ce(ne(t,5))}}})}function sr(e,t,n,r){return Vt(r,t).Z({empty:function(){return Ie.m(ne(NaN,3))},m:function(){var e=Mn(r.first(),3);return e.u?Ie.m(e.value):Ie.m(ne(NaN,3))},multiple:function(){throw Error("fn:number may only be called with zero or one values")}})}function pr(e){for(var t=5381,n=0;n<e.length;++n)t=33*t+e.charCodeAt(n),t%=Number.MAX_SAFE_INTEGER;return t}function fr(e,t,n,r){function a(t){function n(n,r,a,o){if(o.G()||o.wa())return o;for(n=o.O(),r=t,a=n.length-1;1<a;a--){var u=n[o=(r=Ht(e,r).zb)%a];n[o]=n[a],n[a]=u}return Ie.create(n)}return Ie.m(new at([{key:ne("number",1),value:function(){return Ie.m(ne(Ht(e,t).jc,3))}},{key:ne("next",1),value:function(){return Ie.m(new Oe({value:function(){return a(Ht(e,t).zb)},Sa:!0,localName:"",namespaceURI:"",j:[],arity:0,i:{type:61,g:3}}))}},{key:ne("permute",1),value:function(){return Ie.m(new Oe({value:n,Sa:!0,localName:"",namespaceURI:"",j:[{type:59,g:2}],arity:1,i:{type:59,g:2}}))}}]))}return a(((r=void 0===r?Ie.empty():r).G()?Ht(e):Ht(e,pr(Hn(r.first(),1).value))).zb)}var hr=[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"abs",j:[{type:2,g:0}],i:{type:2,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return nr(e.type,Math.abs(e.value))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"format-integer",j:[{type:5,g:0},{type:1,g:3}],i:{type:1,g:3},callFunction:function(e,t,n,r,a){if(e=r.first(),a=a.first(),r.G())return Ie.m(ne("",1));switch(a.value){case"I":return r=ar(e.value),Ie.m(ne(r,1));case"i":return r=ar(e.value,!0),Ie.m(ne(r,1));case"A":return Ie.m(ne(ur(e.value),1));case"a":return Ie.m(ne(ur(e.value,!0),1));default:throw Error("Picture: "+a.value+' is not implemented yet. The supported picture strings are "A", "a", "I", and "i"')}}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"ceiling",j:[{type:2,g:0}],i:{type:2,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return nr(e.type,Math.ceil(e.value))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"floor",j:[{type:2,g:0}],i:{type:2,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return nr(e.type,Math.floor(e.value))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"round",j:[{type:2,g:0}],i:{type:2,g:0},callFunction:lr.bind(null,!1)},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"round",j:[{type:2,g:0},{type:5,g:3}],i:{type:2,g:0},callFunction:lr.bind(null,!1)},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"round-half-to-even",j:[{type:2,g:0}],i:{type:2,g:0},callFunction:lr.bind(null,!0)},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"round-half-to-even",j:[{type:2,g:0},{type:5,g:3}],i:{type:2,g:0},callFunction:lr.bind(null,!0)},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"number",j:[{type:46,g:0}],i:{type:3,g:3},callFunction:sr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"number",j:[],i:{type:3,g:3},callFunction:function(e,t,n){var r=e.N&&tr({type:46,g:0},Ie.m(e.N),t,"fn:number",!1);if(!r)throw Qt("fn:number needs an atomizable context item.");return sr(e,t,n,r)}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"random-number-generator",j:[],i:{type:61,g:3},callFunction:fr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"random-number-generator",j:[{type:46,g:0}],i:{type:61,g:3},callFunction:fr}];function dr(){throw Error("FOCH0002: No collations are supported")}function mr(e,t,n,r){if(null===t.N)throw Qt("The function which was called depends on dynamic context, which is absent.");return e(t,n,r,Ie.m(t.N))}function yr(e,t,n,r){return r.Z({empty:function(){return Ie.m(ne("",1))},default:function(){return r.map((function(e){if(se(e.type,53)){var n=_t(e,t).first();return se(e.type,47)?Hn(n,1):n}return Hn(e,1)}))}})}function gr(e,t,n,r,a){return tt([a],(function(e){var n=p(e).next().value;return Vt(r,t).M((function(e){return e=e.map((function(e){return Hn(e,1).value})).join(n.value),Ie.m(ne(e,1))}))}))}function vr(e,t,n,r){return r.G()?Ie.m(ne(0,5)):(e=r.first().value,Ie.m(ne(Array.from(e).length,5)))}function wr(e,t,n,r,a,o){var u=lr(!1,e,t,n,a,null),i=null!==o?lr(!1,e,t,n,o,null):null,c=!1,l=null,s=null,p=null;return Ie.create({next:function(){return c?ie:l||null!==(l=r.first())?(s||(s=u.first()),!p&&o&&(p=null,p=i.first()),c=!0,ce(ne(Array.from(l.value).slice(Math.max(s.value-1,0),o?s.value+p.value-1:void 0).join(""),1))):(c=!0,ce(ne("",1)))}})}function Ar(e,t,n,r,a){return r.G()||0===r.first().value.length?Ie.empty():(e=r.first().value,a=Er(a=a.first().value),Ie.create(e.split(a).map((function(e){return ne(e,1)}))))}function xr(e,t,n,r){return r.G()?Ie.m(ne("",1)):(e=r.first().value.trim(),Ie.m(ne(e.replace(/\s+/g," "),1)))}var Br=new Map,br=new Map;function Er(e){if(br.has(e))return br.get(e);try{var t=new RegExp(e,"g")}catch(e){throw Error("FORX0002: "+e)}if(t.test(""))throw Error("FORX0003: the pattern "+e+" matches the zero length string");return br.set(e,t),t}var Nr=[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"compare",j:[{type:1,g:0},{type:1,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r,a){return r.G()||a.G()?Ie.empty():(e=r.first().value)>(a=a.first().value)?Ie.m(ne(1,5)):e<a?Ie.m(ne(-1,5)):Ie.m(ne(0,5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"compare",j:[{type:1,g:0},{type:1,g:0},{type:1,g:3}],i:{type:5,g:0},callFunction:dr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"concat",j:[{type:46,g:0},{type:46,g:0},4],i:{type:1,g:3},callFunction:function(e,t,n){var r=O.apply(3,arguments);return tt(r=r.map((function(e){return Vt(e,t).M((function(e){return Ie.m(ne(e.map((function(e){return null===e?"":Hn(e,1).value})).join(""),1))}))})),(function(e){return Ie.m(ne(e.map((function(e){return e.value})).join(""),1))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"contains",j:[{type:1,g:0},{type:1,g:0},{type:1,g:0}],i:{type:0,g:3},callFunction:dr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"contains",j:[{type:1,g:0},{type:1,g:0}],i:{type:0,g:3},callFunction:function(e,t,n,r,a){return e=r.G()?"":r.first().value,0===(a=a.G()?"":a.first().value).length?Ie.ba():0===e.length?Ie.W():e.includes(a)?Ie.ba():Ie.W()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"ends-with",j:[{type:1,g:0},{type:1,g:0}],i:{type:0,g:3},callFunction:function(e,t,n,r,a){return 0===(e=a.G()?"":a.first().value).length?Ie.ba():0===(r=r.G()?"":r.first().value).length?Ie.W():r.endsWith(e)?Ie.ba():Ie.W()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"ends-with",j:[{type:1,g:0},{type:1,g:0},{type:1,g:3}],i:{type:0,g:3},callFunction:dr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"normalize-space",j:[{type:1,g:0}],i:{type:1,g:3},callFunction:xr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"normalize-space",j:[],i:{type:1,g:3},callFunction:mr.bind(null,(function(e,t,n,r){return xr(e,t,n,yr(e,t,n,r))}))},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"starts-with",j:[{type:1,g:0},{type:1,g:0}],i:{type:0,g:3},callFunction:function(e,t,n,r,a){return 0===(e=a.G()?"":a.first().value).length?Ie.ba():0===(r=r.G()?"":r.first().value).length?Ie.W():r.startsWith(e)?Ie.ba():Ie.W()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"starts-with",j:[{type:1,g:0},{type:1,g:0},{type:1,g:3}],i:{type:0,g:3},callFunction:dr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string",j:[{type:59,g:0}],i:{type:1,g:3},callFunction:yr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string",j:[],i:{type:1,g:3},callFunction:mr.bind(null,yr)},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"substring-before",j:[{type:1,g:0},{type:1,g:0}],i:{type:1,g:3},callFunction:function(e,t,n,r,a){return e=r.G()?"":r.first().value,""===(a=a.G()?"":a.first().value)||-1===(a=e.indexOf(a))?Ie.m(ne("",1)):Ie.m(ne(e.substring(0,a),1))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"substring-after",j:[{type:1,g:0},{type:1,g:0}],i:{type:1,g:3},callFunction:function(e,t,n,r,a){return e=r.G()?"":r.first().value,""===(a=a.G()?"":a.first().value)?Ie.m(ne(e,1)):-1===(t=e.indexOf(a))?Ie.m(ne("",1)):Ie.m(ne(e.substring(t+a.length),1))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"substring",j:[{type:1,g:0},{type:3,g:3}],i:{type:1,g:3},callFunction:wr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"substring",j:[{type:1,g:0},{type:3,g:3},{type:3,g:3}],i:{type:1,g:3},callFunction:wr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"upper-case",j:[{type:1,g:0}],i:{type:1,g:3},callFunction:function(e,t,n,r){return r.G()?Ie.m(ne("",1)):r.map((function(e){return ne(e.value.toUpperCase(),1)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"lower-case",j:[{type:1,g:0}],i:{type:1,g:3},callFunction:function(e,t,n,r){return r.G()?Ie.m(ne("",1)):r.map((function(e){return ne(e.value.toLowerCase(),1)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string-join",j:[{type:46,g:2},{type:1,g:3}],i:{type:1,g:3},callFunction:gr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string-join",j:[{type:46,g:2}],i:{type:1,g:3},callFunction:function(e,t,n,r){return gr(e,t,n,r,Ie.m(ne("",1)))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string-length",j:[{type:1,g:0}],i:{type:5,g:3},callFunction:vr},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"string-length",j:[],i:{type:5,g:3},callFunction:mr.bind(null,(function(e,t,n,r){return vr(e,t,n,yr(e,t,n,r))}))},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"tokenize",j:[{type:1,g:0},{type:1,g:3},{type:1,g:3}],i:{type:1,g:2},callFunction:function(){throw Error("Not implemented: Using flags in tokenize is not supported")}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"tokenize",j:[{type:1,g:0},{type:1,g:3}],i:{type:1,g:2},callFunction:Ar},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"tokenize",j:[{type:1,g:0}],i:{type:1,g:2},callFunction:function(e,t,n,r){return Ar(e,t,n,xr(e,t,n,r),Ie.m(ne(" ",1)))}},{j:[{type:1,g:0},{type:1,g:3},{type:1,g:3}],callFunction:function(e,t,n,r,a,o){return tt([r,a,o],(function(e){var t=p(e),n=t.next().value;e=t.next().value,t=t.next().value,n=Array.from(n?n.value:"");var r=Array.from(e.value),a=Array.from(t.value);return e=n.map((function(e){return r.includes(e)?(e=r.indexOf(e))<=a.length?a[e]:void 0:e})),Ie.m(ne(e.join(""),1))}))},localName:"translate",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:5,g:2}],callFunction:function(e,t,n,r){return r.M((function(e){return e=e.map((function(e){if(9===(e=e.value)||10===e||13===e||32<=e&&55295>=e||57344<=e&&65533>=e||65536<=e&&1114111>=e)return String.fromCodePoint(e);throw Error("FOCH0001")})).join(""),Ie.m(ne(e,1))}))},localName:"codepoints-to-string",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:1,g:0}],callFunction:function(e,t,n,r){return tt([r],(function(e){return 0===(e=(e=p(e).next().value)?e.value.split(""):[]).length?Ie.empty():Ie.create(e.map((function(e){return ne(e.codePointAt(0),5)})))}))},localName:"string-to-codepoints",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:5,g:2}},{j:[{type:1,g:0}],callFunction:function(e,t,n,r){return tt([r],(function(e){return null===(e=p(e).next().value)||0===e.value.length?Ie.create(ne("",1)):Ie.create(ne(encodeURIComponent(e.value).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})),1))}))},localName:"encode-for-uri",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:1,g:0}],callFunction:function(e,t,n,r){return tt([r],(function(e){return null===(e=p(e).next().value)||0===e.value.length?Ie.create(ne("",1)):Ie.create(ne(e.value.replace(/([\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFEF "<>{}|\\^`/\n\u007f\u0080-\u009f]|[\uD800-\uDBFF][\uDC00-\uDFFF])/g,(function(e){return encodeURI(e)})),1))}))},localName:"iri-to-uri",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:1,g:0},{type:1,g:0}],callFunction:function(e,t,n,r,a){return tt([r,a],(function(e){var t=p(e);if(e=t.next().value,t=t.next().value,null===e||null===t)return Ie.empty();if(e=e.value,t=t.value,e.length!==t.length)return Ie.W();e=e.split(""),t=t.split("");for(var n=0;n<e.length;n++)if(e[n].codePointAt(0)!==t[n].codePointAt(0))return Ie.W();return Ie.ba()}))},localName:"codepoint-equal",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:0}},{j:[{type:1,g:0},{type:1,g:3}],callFunction:function(e,t,n,r,a){return tt([r,a],(function(e){var t=p(e);e=t.next().value,t=t.next().value,e=e?e.value:"",t=t.value;var n=Br.get(t);if(!n){try{n=Zn.compile(t,{language:"xpath"})}catch(e){throw Error("FORX0002: "+e)}Br.set(t,n)}return n(e)?Ie.ba():Ie.W()}))},localName:"matches",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:1,g:0},{type:1,g:3},{type:1,g:3}],callFunction:function(e,t,n,r,a,o){return tt([r,a,o],(function(e){var t=p(e);e=t.next().value;var n=t.next().value;if(t=t.next().value,e=e?e.value:"",n=n.value,(t=t.value).includes("$0"))throw Error("Using $0 in fn:replace to replace substrings with full matches is not supported.");return t=t.split(/((?:\$\$)|(?:\\\$)|(?:\\\\))/).map((function(e){switch(e){case"\\$":return"$$";case"\\\\":return"\\";case"$$":throw Error('FORX0004: invalid replacement: "$$"');default:return e}})).join(""),n=Er(n),e=e.replace(n,t),Ie.m(ne(e,1))}))},localName:"replace",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:1,g:0},{type:1,g:3},{type:1,g:3},{type:1,g:3}],localName:"replace",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3},callFunction:function(){throw Error("Not implemented: Using flags in replace is not supported")}}];function Tr(e,t,n,r,a){if(null===n.N)throw Qt("The function "+e+" depends on dynamic context, which is absent.");return t(n,r,a,Ie.m(n.N))}function Ir(e,t,n,r){return tt([r],(function(e){if(null===(e=p(e).next().value))return Ie.empty();switch((e=e.value).node.nodeType){case 1:case 2:return Ie.m(ne(new Fe(e.node.prefix,e.node.namespaceURI,e.node.localName),23));case 7:return Ie.m(ne(new Fe("","",e.node.target),23));default:return Ie.empty()}}))}function Cr(e,t,n,r){return r.Z({default:function(){return yr(e,t,n,Ir(e,t,n,r))},empty:function(){return Ie.m(ne("",1))}})}function Fr(e,t,n,r){return Vt(r,t)}function Or(e,t,n,r){return tt([r],(function(e){return null!==(e=(e=p(e).next().value)?e.value:null)&&Ke(t.h,e,null)?Ie.ba():Ie.W()}))}function Sr(e,t,n,r){return tt([r],(function(e){function n(e){for(var t=0,n=e;null!==n;)(e.node.nodeType!==n.node.nodeType?0:1===n.node.nodeType?n.node.localName===e.node.localName&&n.node.namespaceURI===e.node.namespaceURI:7===n.node.nodeType?n.node.target===e.node.target:1)&&t++,n=We(a,n,null);return t}var r=p(e).next().value;if(null===r)return Ie.empty();var a=t.h;for(e="",r=r.value;null!==Ve(t.h,r,null);r=Ve(t.h,r,null))switch(r.node.nodeType){case 1:var o=r;e="/Q{"+(o.node.namespaceURI||"")+"}"+o.node.localName+"["+n(o)+"]"+e;break;case 2:e="/@"+((o=r).node.namespaceURI?"Q{"+o.node.namespaceURI+"}":"")+o.node.localName+e;break;case 3:e="/text()["+n(r)+"]"+e;break;case 7:e="/processing-instruction("+(o=r).node.target+")["+n(o)+"]"+e;break;case 8:e="/comment()["+n(r)+"]"+e}return 9===r.node.nodeType?Ie.create(ne(e||"/",1)):Ie.create(ne("Q{http://www.w3.org/2005/xpath-functions}root()"+e,1))}))}function Gr(e,t,n,r){return r.map((function(e){return ne(e.value.node.namespaceURI||"",20)}))}function Dr(e,t,n,r){return r.Z({default:function(){return r.map((function(e){return 7===e.value.node.nodeType?ne(e.value.node.target,1):ne(e.value.node.localName||"",1)}))},empty:function(){return Ie.m(ne("",1))}})}function Rr(e,t,n){if(2===t.node.nodeType)return Xn(t,n);for(;n;){if(Xn(t,n))return!0;if(9===n.node.nodeType)break;n=Ve(e,n,null)}return!1}function kr(e,t,n,r){return r.map((function(e){if(!se(e.type,53))throw Error("XPTY0004 Argument passed to fn:root() should be of the type node()");for(e=e.value;e;){var n=e;e=Ve(t.h,n,null)}return et(n)}))}var Ur=[{j:[{type:53,g:0}],callFunction:Cr,localName:"name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[],callFunction:Tr.bind(null,"name",Cr),localName:"name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:53,g:3}],callFunction:Gr,localName:"namespace-uri",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:20,g:3}},{j:[],callFunction:Tr.bind(null,"namespace-uri",Gr),localName:"namespace-uri",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:20,g:3}},{j:[{type:53,g:2}],callFunction:function(e,t,n,r){return r.M((function(e){return e.length?(e=_n(t.h,e).reduceRight((function(e,n,r,a){return r===a.length-1?(e.push(n),e):(Rr(t.h,n.value,e[0].value)||e.unshift(n),e)}),[]),Ie.create(e)):Ie.empty()}))},localName:"innermost",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:53,g:2}},{j:[{type:53,g:2}],callFunction:function(e,t,n,r){return r.M((function(e){return e.length?(e=_n(t.h,e).reduce((function(e,n,r){return 0===r?(e.push(n),e):(Rr(t.h,e[e.length-1].value,n.value)||e.push(n),e)}),[]),Ie.create(e)):Ie.empty()}),1)},localName:"outermost",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:53,g:2}},{j:[{type:53,g:0}],callFunction:Or,localName:"has-children",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[],callFunction:Tr.bind(null,"has-children",Or),localName:"has-children",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:53,g:0}],callFunction:Sr,localName:"path",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:0}},{j:[],callFunction:Tr.bind(null,"path",Sr),localName:"path",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:0}},{j:[{type:53,g:0}],callFunction:Ir,localName:"node-name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:23,g:0}},{j:[],callFunction:Tr.bind(null,"node-name",Ir),localName:"node-name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:23,g:0}},{j:[{type:53,g:0}],callFunction:Dr,localName:"local-name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[],callFunction:Tr.bind(null,"local-name",Dr),localName:"local-name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}},{j:[{type:53,g:0}],callFunction:kr,localName:"root",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:53,g:0}},{j:[],callFunction:Tr.bind(null,"root",kr),localName:"root",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:53,g:0}},{j:[],callFunction:Tr.bind(null,"data",Fr),localName:"data",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:2}},{j:[{type:59,g:2}],callFunction:Fr,localName:"data",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:2}}];function Mr(e,t){var n=0,r=e.length,a=!1,o=null;return{next:function(){if(!a){for(;n<r;){o||(o=t(e[n],n,e));var u=o.next(0);if(o=null,!u.value)return ce(!1);n++}return a=!0,ce(!0)}return ie}}}function Hr(e){return 1===(e=e.node.nodeType)||3===e}function Pr(e,t){if((se(e.type,4)||se(e.type,6))&&(se(t.type,4)||se(t.type,6))){var n=Hn(e,6),r=Hn(t,6);return n.value===r.value||isNaN(e.value)&&isNaN(t.value)}return(se(e.type,4)||se(e.type,6)||se(e.type,3))&&(se(t.type,4)||se(t.type,6)||se(t.type,3))?(n=Hn(e,3),r=Hn(t,3),n.value===r.value||isNaN(e.value)&&isNaN(t.value)):se(e.type,23)&&se(t.type,23)?e.value.namespaceURI===t.value.namespaceURI&&e.value.localName===t.value.localName:(se(e.type,9)||se(e.type,7)||se(e.type,8)||se(e.type,11)||se(e.type,12)||se(e.type,13)||se(e.type,14)||se(e.type,15))&&(se(t.type,9)||se(t.type,7)||se(t.type,8)||se(t.type,11)||se(t.type,12)||se(t.type,13)||se(t.type,14)||se(t.type,15))?bt(e.value,t.value):(se(e.type,16)||se(e.type,17)||se(e.type,18))&&(se(t.type,16)||se(t.type,17)||se(t.type,17))?ut(e.value,t.value):e.value===t.value}function jr(e,t,n){return n=p([t,n].map((function(t){return{type:1,value:t.reduce((function(t,n){return t+_t(n,e).first().value}),"")}}))),ce(Pr(t=n.next().value,n=n.next().value))}function Xr(e,t,n,r){for(;e.value&&se(e.value.type,56);){t.push(e.value);var a=_e(r,e.value.value);if(e=n.next(0),a&&3!==a.node.nodeType)break}return e}function Lr(e,t,n,r,a){var o,u=t.h,i=r.value,c=a.value,l=null,s=null,p=null,f=[],h=[];return{next:function(){for(;!o;)if(l||(l=i.next(0)),l=Xr(l,f,i,u),s||(s=c.next(0)),s=Xr(s,h,c,u),f.length||h.length){var r=jr(t,f,h);if(f.length=0,h.length=0,!1===r.value)return o=!0,r}else{if(l.done||s.done)return o=!0,ce(l.done===s.done);if(p||(p=_r(e,t,n,l.value,s.value)),r=p.next(0),p=null,!1===r.value)return o=!0,r;s=l=null}return ie}}}function Yr(e,t,n,r,a){return r.h.length!==a.h.length?Pn(!1):Mr(r.h,(function(r){var o=a.h.find((function(e){return Pr(e.key,r.key)}));return o?Lr(e,t,n,r.value(),o.value()):Pn(!1)}))}function Qr(e,t,n,r,a){return r.P.length!==a.P.length?Pn(!1):Mr(r.P,(function(r,o){return o=a.P[o],Lr(e,t,n,r(),o())}))}function Jr(e,t,n,r,a){return r=Qe(t.h,r.value),a=Qe(t.h,a.value),r=r.filter((function(e){return Hr(e)})),a=a.filter((function(e){return Hr(e)})),Lr(e,t,n,r=Ie.create(r.map((function(e){return et(e)}))),a=Ie.create(a.map((function(e){return et(e)}))))}function Kr(e,t,n,r,a){var o=Lr(e,t,n,Ir(e,t,n,Ie.m(r)),Ir(e,t,n,Ie.m(a))),u=Jr(e,t,n,r,a);r=Le(t.h,r.value).filter((function(e){return"http://www.w3.org/2000/xmlns/"!==e.node.namespaceURI})).sort((function(e,t){return e.node.nodeName>t.node.nodeName?1:-1})).map((function(e){return et(e)})),a=Le(t.h,a.value).filter((function(e){return"http://www.w3.org/2000/xmlns/"!==e.node.namespaceURI})).sort((function(e,t){return e.node.nodeName>t.node.nodeName?1:-1})).map((function(e){return et(e)}));var i=Lr(e,t,n,Ie.create(r),Ie.create(a)),c=!1;return{next:function(){if(c)return ie;var e=o.next(0);return!e.done&&!1===e.value||!(e=i.next(0)).done&&!1===e.value?(c=!0,e):(e=u.next(0),c=!0,e)}}}function qr(e,t,n,r,a){var o=Lr(e,t,n,Ir(e,t,n,Ie.m(r)),Ir(e,t,n,Ie.m(a))),u=!1;return{next:function(){if(u)return ie;var e=o.next(0);return e.done||!1!==e.value?ce(Pr(_t(r,t).first(),_t(a,t).first())):(u=!0,e)}}}function _r(e,t,n,r,a){if(se(r.type,46)&&se(a.type,46))return Pn(Pr(r,a));if(se(r.type,61)&&se(a.type,61))return Yr(e,t,n,r,a);if(se(r.type,62)&&se(a.type,62))return Qr(e,t,n,r,a);if(se(r.type,53)&&se(a.type,53)){if(se(r.type,55)&&se(a.type,55))return Jr(e,t,n,r,a);if(se(r.type,54)&&se(a.type,54))return Kr(e,t,n,r,a);if(se(r.type,47)&&se(a.type,47)||se(r.type,57)&&se(a.type,57)||se(r.type,58)&&se(a.type,58))return qr(e,t,n,r,a)}return Pn(!1)}function Vr(e){return Error("XUST0001: "+(void 0===e?"Can not execute an updating expression in a non-updating context.":e))}function Wr(e){return Error("XUTY0004: The attribute "+e.name+'="'+e.value+'" follows a node that is not an attribute node.')}function Zr(){return Error("XUTY0005: The target of a insert expression with into must be a single element or document node.")}function $r(){return Error("XUTY0006: The target of a insert expression with before or after must be a single element, text, comment, or processing instruction node.")}function zr(){return Error("XUTY0008: The target of a replace expression must be a single element, attribute, text, comment, or processing instruction node.")}function ea(){return Error("XUTY0012: The target of a rename expression must be a single element, attribute, or processing instruction node.")}function ta(e){return Error("XUDY0017: The target "+e.outerHTML+" is used in more than one replace value of expression.")}function na(e){return Error("XUDY0021: Applying the updates will result in the XDM instance violating constraint: '"+e+"'")}function ra(e){return Error("XUDY0023: The namespace binding "+e+" is conflicting.")}function aa(e){return Error("XUDY0024: The namespace binding "+e+" is conflicting.")}function oa(){return Error("XUDY0027: The target for an insert, replace, or rename expression expression should not be empty.")}function ua(e,t,n,r,a){n=void 0===n?{C:!1,X:!1,R:"unsorted",subtree:!1}:n,this.o=e,this.da=n.R||"unsorted",this.subtree=!!n.subtree,this.X=!!n.X,this.C=!!n.C,this.ta=t,this.I=!1,this.ab=null,this.Yb=void 0!==r&&r,this.type=a}function ia(e,t,n){return t&&null!==t.N&&e.C?(null===e.ab&&(e.ab=Ce(e.h(null,n).sb())),e=e.ab()):e=e.h(t,n),e}function ca(e,t){this.J=e,this.fa=t}function la(e){e&&"object"==typeof e&&"nodeType"in e&&"function"==typeof(e=e.ownerDocument||e).createElementNS&&"function"==typeof e.createProcessingInstruction&&"function"==typeof e.createTextNode&&"function"==typeof e.createComment&&(this.h=e),this.h||(this.h=null)}function sa(e,t,n,r){var a=Ve(n,e).node,o=(e=_e(n,e))?e.node:null;t.forEach((function(e){r.insertBefore(a,e.node,o)}))}function pa(e,t,n,r){var a=Ve(n,e).node;t.forEach((function(t){r.insertBefore(a,t.node,e.node)}))}function fa(e,t,n,r){var a=(n=Ke(n,e))?n.node:null;t.forEach((function(t){r.insertBefore(e.node,t.node,a)}))}function ha(e,t,n){t.forEach((function(t){n.insertBefore(e.node,t.node,null)}))}function da(e,t,n,r){t.forEach((function(t){var a=t.node.nodeName;if(Ye(n,e,a))throw na("An attribute "+a+" already exists.");r.setAttributeNS(e.node,t.node.namespaceURI,a,Je(n,t))}))}function ma(e,t,n,r,a){switch(r||(r=new la(e?e.node:null)),e.node.nodeType){case 1:var o=n.getAllAttributes(e.node),u=n.getChildNodes(e.node),i=r.createElementNS(t.namespaceURI,t.Ca()),c={node:i,F:null};o.forEach((function(e){a.setAttributeNS(i,e.namespaceURI,e.nodeName,e.value)})),u.forEach((function(e){a.insertBefore(i,e,null)}));break;case 2:(t=r.createAttributeNS(t.namespaceURI,t.Ca())).value=Je(n,e),c={node:t,F:null};break;case 7:c={node:r.createProcessingInstruction(t.Ca(),Je(n,e)),F:null}}if(!Ve(n,e))throw Error("Not supported: renaming detached nodes.");ga(e,[c],n,a)}function ya(e,t,n,r){n.getChildNodes(e.node).forEach((function(t){return r.removeChild(e.node,t)})),t&&r.insertBefore(e.node,t.node,null)}function ga(e,t,n,r){var a=Ve(n,e),o=e.node.nodeType;if(2===o){if(t.some((function(e){return 2!==e.node.nodeType})))throw Error('Constraint "If $target is an attribute node, $replacement must consist of zero or more attribute nodes." failed.');var u=a?a.node:null;r.removeAttributeNS(u,e.node.namespaceURI,e.node.nodeName),t.forEach((function(e){var t=e.node.nodeName;if(Ye(n,a,t))throw na("An attribute "+t+" already exists.");r.setAttributeNS(u,e.node.namespaceURI,t,Je(n,e))}))}if(1===o||3===o||8===o||7===o){var i=(o=_e(n,e))?o.node:null;r.removeChild(a.node,e.node),t.forEach((function(e){r.insertBefore(a.node,e.node,i)}))}}function va(e,t,n,r){if(wa(e,t),e.filter((function(e){return-1!==["insertInto","insertAttributes","replaceValue","rename"].indexOf(e.type)})).forEach((function(e){switch(e.type){case"insertInto":ha(e.target,e.content,r);break;case"insertAttributes":da(e.target,e.content,t,r);break;case"rename":ma(e.target,e.o,t,n,r);break;case"replaceValue":var a=e.target;if(e=e.o,2===a.node.nodeType){var o=Ve(t,a);o?r.setAttributeNS(o.node,a.node.namespaceURI,a.node.nodeName,e):a.node.value=e}else r.setData(a.node,e)}})),e.filter((function(e){return-1!==["insertBefore","insertAfter","insertIntoAsFirst","insertIntoAsLast"].indexOf(e.type)})).forEach((function(e){switch(e.type){case"insertAfter":sa(e.target,e.content,t,r);break;case"insertBefore":pa(e.target,e.content,t,r);break;case"insertIntoAsFirst":fa(e.target,e.content,t,r);break;case"insertIntoAsLast":ha(e.target,e.content,r)}})),e.filter((function(e){return"replaceNode"===e.type})).forEach((function(e){ga(e.target,e.o,t,r)})),e.filter((function(e){return"replaceElementContent"===e.type})).forEach((function(e){ya(e.target,e.text,t,r)})),e.filter((function(e){return"delete"===e.type})).forEach((function(e){e=e.target;var n=Ve(t,e);(n=n?n.node:null)&&(2===e.node.nodeType?r.removeAttributeNS(n,e.node.namespaceURI,e.node.nodeName):r.removeChild(n,e.node))})),e.some((function(e){return"put"===e.type})))throw Error('Not implemented: the execution for pendingUpdate "put" is not yet implemented.')}function wa(e,t){function n(e){return new Fe(e.node.prefix,e.node.namespaceURI,e.node.localName)}function r(t,n){var r=new Set;e.filter((function(e){return e.type===t})).map((function(e){return e.target})).forEach((function(e){e=e?e.node:null,r.has(e)&&n(e),r.add(e)}))}r("rename",(function(e){throw Error("XUDY0015: The target "+e.outerHTML+" is used in more than one rename expression.")})),r("replaceNode",(function(e){throw Error("XUDY0016: The target "+e.outerHTML+" is used in more than one replace expression.")})),r("replaceValue",(function(e){throw ta(e)})),r("replaceElementContent",(function(e){throw ta(e)}));var a=new Map;e.filter((function(e){return"replaceNode"===e.type&&2===e.target.node.nodeType})).forEach((function(e){var r=Ve(t,e.target);r=r?r.node:null;var o=a.get(r);o?o.push.apply(o,h(e.o.map(n))):a.set(r,e.o.map(n))})),e.filter((function(e){return"rename"===e.type&&2===e.target.node.nodeType})).forEach((function(e){var n=Ve(t,e.target);if(n){n=n.node;var r=a.get(n);r?r.push(e.o):a.set(n,[e.o])}})),a.forEach((function(e){var t={};e.forEach((function(e){if(t[e.prefix]||(t[e.prefix]=e.namespaceURI),t[e.prefix]!==e.namespaceURI)throw aa(e.namespaceURI)}))}))}function Aa(e){return e.concat.apply(e,h(O.apply(1,arguments).filter(Boolean)))}function xa(e,t,n,r){ua.call(this,e,t,n,!0,r),this.I=!0}function Ba(e){return e.I?function(t,n){return e.s(t,n)}:function(t,n){var r=e.h(t,n);return{next:function(){return ce({fa:[],J:r.O()})}}}}function ba(e,t){return t((e=e.next(0)).value.fa),Ie.create(e.value.J)}function Ea(e,t,n,r){xa.call(this,e,t,n,r),this.I=this.ta.some((function(e){return e.I}))}function Na(e){e.ta.some((function(e){return e.I}))&&(e.I=!0)}ua.prototype.B=function(){return null},ua.prototype.v=function(e){if(this.ta.forEach((function(t){return t.v(e)})),!this.Yb&&this.ta.some((function(e){return e.I})))throw Vr()},(a=la.prototype).createAttributeNS=function(e,t){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createAttributeNS(e,t)},a.createCDATASection=function(e){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createCDATASection(e)},a.createComment=function(e){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createComment(e)},a.createDocument=function(){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.implementation.createDocument(null,null,null)},a.createElementNS=function(e,t){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createElementNS(e,t)},a.createProcessingInstruction=function(e,t){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createProcessingInstruction(e,t)},a.createTextNode=function(e){if(!this.h)throw Error("Please pass a node factory if an XQuery script uses node constructors");return this.h.createTextNode(e)},A(xa,ua),xa.prototype.h=function(){throw Vr()},A(Ea,xa),Ea.prototype.h=function(e,t){return this.A(e,t,this.ta.map((function(e){return function(n){return e.h(n,t)}})))},Ea.prototype.s=function(e,t){var n=[],r=this.A(e,t,this.ta.map((function(e){return e.I?function(r){return ba(r=e.s(r,t),(function(e){return n=Aa(n,e)}))}:function(n){return e.h(n,t)}}))),a=!1;return{next:function(){if(a)return ie;var e=r.O();return a=!0,ce(new ca(e,n))}}},Ea.prototype.v=function(e){xa.prototype.v.call(this,e),Na(this)};var Ta=["external","attribute","nodeName","nodeType","universal"],Ia=Ta.length;function Ca(e){if(this.h=Ta.map((function(t){return e[t]||0})),Object.keys(e).some((function(e){return!Ta.includes(e)})))throw Error("Invalid specificity kind passed")}function Fa(e,t){for(var n=0;n<Ia;++n){if(t.h[n]<e.h[n])return 1;if(t.h[n]>e.h[n])return-1}return 0}function Oa(){return Jt("Expected base expression of a function call to evaluate to a sequence of single function item")}function Sa(e,t,n,r){for(var a=[],o=0;o<t.length;++o)if(null===t[o])a.push(null);else{var u=tr(e[o],t[o],n,r,!1);a.push(u)}return a}function Ga(e,t){if(!se(e.type,60))throw Jt("Expected base expression to evaluate to a function item");if(e.v!==t)throw Oa();return e}function Da(e,t,n,r,a,o,u){var i=0;return a=a.map((function(e){return e?null:o[i++](n)})),0<=(a=Sa(e.o,a,r,e.B)).indexOf(null)?Se(e,a):(t=t.apply(void 0,[n,r,u].concat(h(a))),tr(e.s,t,r,e.B,!0))}function Ra(e,t,n){var r={};Ea.call(this,new Ca((r.external=1,r)),[e].concat(t.filter((function(e){return!!e}))),{R:"unsorted",X:!1,subtree:!1,C:!1},n),this.la=t.length,this.S=t.map((function(e){return null===e})),this.K=null,this.pa=e,this.Ba=t}function ka(e,t,n,r,a,o){return tt([r,a,o],(function(e){var t=p(e);e=t.next().value;var n=t.next().value;if(t=t.next().value,n=n.value,t=t.value,n>e.P.length||0>=n)throw Error("FOAY0001: subarray start out of bounds.");if(0>t)throw Error("FOAY0002: subarray length out of bounds.");if(n+t>e.P.length+1)throw Error("FOAY0001: subarray start + length out of bounds.");return Ie.m(new $e(e.P.slice(n-1,t+n-1)))}))}function Ua(e,t,n,r,a){return tt([r],(function(e){var t=p(e).next().value;return a.M((function(e){e=e.map((function(e){return e.value})).sort((function(e,t){return t-e})).filter((function(e,t,n){return n[t-1]!==e}));for(var n=t.P.concat(),r=0,a=e.length;r<a;++r){var o=e[r];if(o>t.P.length||0>=o)throw Error("FOAY0001: subarray position out of bounds.");n.splice(o-1,1)}return Ie.m(new $e(n))}))}))}function Ma(e){return se(e,1)||se(e,20)||se(e,19)}function Ha(e,t,n,r,a){return 0===r.length?0!==a.length:0!==a.length&&_r(e,t,n,r[0],a[0]).next(0).value?Ha(e,t,n,r.slice(1),a.slice(1)):r[0].value!=r[0].value||(Ma(r[0].type)&&0!==a.length&&Ma(a[0].type)||0!==a.length)&&r[0].value<a[0].value}function Pa(e,t,n,r){return r.sort((function(r,a){return Lr(e,t,n,Ie.create(r),Ie.create(a)).next(0).value?0:Ha(e,t,n,r,a)?-1:1})),Ie.m(new $e(r.map((function(e){return function(){return Ie.create(e)}}))))}function ja(e,t){return se(t.type,62)?t.P.reduce((function(e,t){return t().M((function(t){return t.reduce(ja,e)}))}),e):Lt([e,Ie.m(t)])}Ca.prototype.add=function(e){var t=this;return new Ca(Ta.reduce((function(n,r,a){return n[r]=t.h[a]+e.h[a],n}),Object.create(null)))},A(Ra,Ea),Ra.prototype.s=function(e,t){var n=this;if(!this.l||!this.l.I)return Ea.prototype.s.call(this,e,t);var r=[],a=Da(this.l,(function(e,t,a){return ba(n.l.value.apply(n.l,[e,t,a].concat(h(O.apply(3,arguments)))),(function(e){r=Aa(r,e)}))}),e,t,this.S,this.Ba.map((function(n){return function(){return n.I?ba(n.s(e,t),(function(e){r=Aa(r,e)})):ia(n,e,t)}})),this.K),o=!1;return{next:function(){if(o)return ie;var e=a.O();return o=!0,ce({fa:r,J:e})}}},Ra.prototype.A=function(e,t,n){var r=this,a=(n=p(n)).next().value,o=f(n);if(this.l)return Da(this.l,(function(e,t,n){return r.l.value.apply(r.l,[e,t,n].concat(h(O.apply(3,arguments))))}),e,t,this.S,o,this.K);var u=a(e);return u.Z({default:function(){throw Oa()},m:function(){return u.M((function(n){if((n=Ga(n=p(n).next().value,r.la)).I)throw Error("XUDY0038: The function returned by the PrimaryExpr of a dynamic function invocation can not be an updating function");return Da(n,n.value,e,t,r.S,o,r.K)}))}})},Ra.prototype.v=function(e){if(this.K=So(e),Ea.prototype.v.call(this,e),this.pa.C){if(!(e=ia(this.pa,null,null)).wa())throw Oa();this.l=Ga(e.first(),this.la),this.l.I&&(this.I=!0)}};var Xa=[{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"size",j:[{type:62,g:3}],i:{type:5,g:3},callFunction:function(e,t,n,r){return tt([r],(function(e){return e=p(e).next().value,Ie.m(ne(e.P.length,5))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"get",j:[{type:62,g:3},{type:5,g:3}],i:{type:59,g:2},callFunction:Ze},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"put",j:[{type:62,g:3},{type:5,g:3},{type:59,g:2}],i:{type:62,g:3},callFunction:function(e,t,n,r,a,o){return tt([a,r],(function(e){var t=p(e);if(e=t.next().value,t=t.next().value,0>=(e=e.value)||e>t.P.length)throw Error("FOAY0001: array position out of bounds.");return(t=t.P.concat()).splice(e-1,1,Ce(o)),Ie.m(new $e(t))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"append",j:[{type:62,g:3},{type:59,g:2}],i:{type:62,g:3},callFunction:function(e,t,n,r,a){return tt([r],(function(e){return e=p(e).next().value.P.concat([Ce(a)]),Ie.m(new $e(e))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"subarray",j:[{type:62,g:3},{type:5,g:3},{type:5,g:3}],i:{type:62,g:3},callFunction:ka},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"subarray",j:[{type:62,g:3},{type:5,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r,a){var o=Ie.m(ne(r.first().value.length-a.first().value+1,5));return ka(e,t,n,r,a,o)}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"remove",j:[{type:62,g:3},{type:5,g:2}],i:{type:62,g:3},callFunction:Ua},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"insert-before",j:[{type:62,g:3},{type:5,g:3},{type:59,g:2}],i:{type:62,g:3},callFunction:function(e,t,n,r,a,o){return tt([r,a],(function(e){var t=p(e);if(e=t.next().value,(t=t.next().value.value)>e.P.length+1||0>=t)throw Error("FOAY0001: subarray position out of bounds.");return(e=e.P.concat()).splice(t-1,0,Ce(o)),Ie.m(new $e(e))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"head",j:[{type:62,g:3}],i:{type:59,g:2},callFunction:function(e,t,n,r){return Ze(e,t,n,r,Ie.m(ne(1,5)))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"tail",j:[{type:62,g:3}],i:{type:59,g:2},callFunction:function(e,t,n,r){return Ua(e,t,n,r,Ie.m(ne(1,5)))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"reverse",j:[{type:62,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r){return tt([r],(function(e){return e=p(e).next().value,Ie.m(new $e(e.P.concat().reverse()))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"join",j:[{type:62,g:2}],i:{type:62,g:3},callFunction:function(e,t,n,r){return r.M((function(e){return e=e.reduce((function(e,t){return e.concat(t.P)}),[]),Ie.m(new $e(e))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"for-each",j:[{type:62,g:3},{type:60,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r,a){return tt([r,a],(function(r){var a=(r=p(r)).next().value,o=r.next().value;if(1!==o.v)throw Jt("The callback passed into array:for-each has a wrong arity.");return r=a.P.map((function(r){return Ce(o.value.call(void 0,e,t,n,Sa(o.o,[r()],t,"array:for-each")[0]))})),Ie.m(new $e(r))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"filter",j:[{type:62,g:3},{type:60,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r,a){return tt([r,a],(function(r){var a=(r=p(r)).next().value,o=r.next().value;if(1!==o.v)throw Jt("The callback passed into array:filter has a wrong arity.");var u=a.P.map((function(r){return r=Sa(o.o,[r()],t,"array:filter")[0],(0,o.value)(e,t,n,r)})),i=[],c=!1;return Ie.create({next:function(){if(c)return ie;for(var e=0,t=a.P.length;e<t;++e){var n=u[e].ha();i[e]=n}return e=a.P.filter((function(e,t){return i[t]})),c=!0,ce(new $e(e))}})}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"fold-left",j:[{type:62,g:3},{type:59,g:2},{type:60,g:3}],i:{type:59,g:2},callFunction:function(e,t,n,r,a,o){return tt([r,o],(function(r){var o=(r=p(r)).next().value,u=r.next().value;if(2!==u.v)throw Jt("The callback passed into array:fold-left has a wrong arity.");return o.P.reduce((function(r,a){return a=Sa(u.o,[a()],t,"array:fold-left")[0],u.value.call(void 0,e,t,n,r,a)}),a)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"fold-right",j:[{type:62,g:3},{type:59,g:2},{type:60,g:3}],i:{type:59,g:2},callFunction:function(e,t,n,r,a,o){return tt([r,o],(function(r){var o=(r=p(r)).next().value,u=r.next().value;if(2!==u.v)throw Jt("The callback passed into array:fold-right has a wrong arity.");return o.P.reduceRight((function(r,a){return a=Sa(u.o,[a()],t,"array:fold-right")[0],u.value.call(void 0,e,t,n,r,a)}),a)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"for-each-pair",j:[{type:62,g:3},{type:62,g:3},{type:60,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r,a,o){return tt([r,a,o],(function(r){var a=p(r);r=a.next().value;var o=a.next().value;if(2!==(a=a.next().value).v)throw Jt("The callback passed into array:for-each-pair has a wrong arity.");for(var u=[],i=0,c=Math.min(r.P.length,o.P.length);i<c;++i){var l=p(Sa(a.o,[r.P[i](),o.P[i]()],t,"array:for-each-pair")),s=l.next().value;l=l.next().value,u[i]=Ce(a.value.call(void 0,e,t,n,s,l))}return Ie.m(new $e(u))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"sort",j:[{type:62,g:3}],i:{type:62,g:3},callFunction:function(e,t,n,r){return tt([r],(function(r){return r=p(r).next().value.P.map((function(e){return e().O()})),Pa(e,t,n,r)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/array",localName:"flatten",j:[{type:59,g:2}],i:{type:59,g:2},callFunction:function(e,t,n,r){return r.M((function(e){return e.reduce(ja,Ie.empty())}))}}];function La(e,t,n,r,a){return a.G()?a:Ie.m(Hn(a.first(),e))}var Ya=[{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"untypedAtomic",j:[{type:46,g:0}],i:{type:19,g:0},callFunction:La.bind(null,19)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"error",j:[{type:46,g:0}],i:{type:39,g:0},callFunction:La.bind(null,39)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"string",j:[{type:46,g:0}],i:{type:1,g:0},callFunction:La.bind(null,1)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"boolean",j:[{type:46,g:0}],i:{type:0,g:0},callFunction:La.bind(null,0)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"decimal",j:[{type:46,g:0}],i:{type:4,g:0},callFunction:La.bind(null,4)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"float",j:[{type:46,g:0}],i:{type:6,g:0},callFunction:La.bind(null,6)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"double",j:[{type:46,g:0}],i:{type:3,g:0},callFunction:La.bind(null,3)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"duration",j:[{type:46,g:0}],i:{type:18,g:0},callFunction:La.bind(null,18)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"dateTime",j:[{type:46,g:0}],i:{type:9,g:0},callFunction:La.bind(null,9)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"dateTimeStamp",j:[{type:46,g:0}],i:{type:10,g:0},callFunction:La.bind(null,10)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"time",j:[{type:46,g:0}],i:{type:8,g:0},callFunction:La.bind(null,8)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"date",j:[{type:46,g:0}],i:{type:7,g:0},callFunction:La.bind(null,7)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"gYearMonth",j:[{type:46,g:0}],i:{type:11,g:0},callFunction:La.bind(null,11)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"gYear",j:[{type:46,g:0}],i:{type:12,g:0},callFunction:La.bind(null,12)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"gMonthDay",j:[{type:46,g:0}],i:{type:13,g:0},callFunction:La.bind(null,13)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"gDay",j:[{type:46,g:0}],i:{type:15,g:0},callFunction:La.bind(null,15)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"gMonth",j:[{type:46,g:0}],i:{type:14,g:0},callFunction:La.bind(null,14)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"hexBinary",j:[{type:46,g:0}],i:{type:22,g:0},callFunction:La.bind(null,22)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"base64Binary",j:[{type:46,g:0}],i:{type:21,g:0},callFunction:La.bind(null,21)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"QName",j:[{type:46,g:0}],i:{type:23,g:0},callFunction:function(e,t,n,r){if(r.G())return r;if(se((e=r.first()).type,2))throw Error("XPTY0004: The provided QName is not a string-like value.");if(!$t(e=Zt(e=Hn(e,1).value,23),23))throw Error("FORG0001: The provided QName is invalid.");if(!e.includes(":"))return n=n.aa(""),Ie.m(ne(new Fe("",n,e),23));if(t=(r=p(e.split(":"))).next().value,r=r.next().value,!(n=n.aa(t)))throw Error("FONS0004: The value "+e+" can not be cast to a QName. Did you mean to use fn:QName?");return Ie.m(ne(new Fe(t,n,r),23))}},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"anyURI",j:[{type:46,g:0}],i:{type:20,g:0},callFunction:La.bind(null,20)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"normalizedString",j:[{type:46,g:0}],i:{type:48,g:0},callFunction:La.bind(null,48)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"token",j:[{type:46,g:0}],i:{type:52,g:0},callFunction:La.bind(null,52)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"language",j:[{type:46,g:0}],i:{type:51,g:0},callFunction:La.bind(null,51)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"NMTOKEN",j:[{type:46,g:0}],i:{type:50,g:0},callFunction:La.bind(null,50)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"NMTOKENS",j:[{type:46,g:0}],i:{type:49,g:2},callFunction:La.bind(null,49)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"Name",j:[{type:46,g:0}],i:{type:25,g:0},callFunction:La.bind(null,25)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"NCName",j:[{type:46,g:0}],i:{type:24,g:0},callFunction:La.bind(null,24)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"ID",j:[{type:46,g:0}],i:{type:42,g:0},callFunction:La.bind(null,42)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"IDREF",j:[{type:46,g:0}],i:{type:41,g:0},callFunction:La.bind(null,41)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"IDREFS",j:[{type:46,g:0}],i:{type:43,g:2},callFunction:La.bind(null,43)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"ENTITY",j:[{type:46,g:0}],i:{type:26,g:0},callFunction:La.bind(null,26)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"ENTITIES",j:[{type:46,g:0}],i:{type:40,g:2},callFunction:La.bind(null,40)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"integer",j:[{type:46,g:0}],i:{type:5,g:0},callFunction:La.bind(null,5)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"nonPositiveInteger",j:[{type:46,g:0}],i:{type:27,g:0},callFunction:La.bind(null,27)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"negativeInteger",j:[{type:46,g:0}],i:{type:28,g:0},callFunction:La.bind(null,28)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"long",j:[{type:46,g:0}],i:{type:31,g:0},callFunction:La.bind(null,31)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"int",j:[{type:46,g:0}],i:{type:32,g:0},callFunction:La.bind(null,32)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"short",j:[{type:46,g:0}],i:{type:33,g:0},callFunction:La.bind(null,33)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"byte",j:[{type:46,g:0}],i:{type:34,g:0},callFunction:La.bind(null,34)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"nonNegativeInteger",j:[{type:46,g:0}],i:{type:30,g:0},callFunction:La.bind(null,30)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"unsignedLong",j:[{type:46,g:0}],i:{type:36,g:0},callFunction:La.bind(null,36)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"unsignedInt",j:[{type:46,g:0}],i:{type:35,g:0},callFunction:La.bind(null,35)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"unsignedShort",j:[{type:46,g:0}],i:{type:38,g:0},callFunction:La.bind(null,38)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"unsignedByte",j:[{type:46,g:0}],i:{type:37,g:0},callFunction:La.bind(null,37)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"positiveInteger",j:[{type:46,g:0}],i:{type:29,g:0},callFunction:La.bind(null,29)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"yearMonthDuration",j:[{type:46,g:0}],i:{type:16,g:0},callFunction:La.bind(null,16)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"dayTimeDuration",j:[{type:46,g:0}],i:{type:17,g:0},callFunction:La.bind(null,17)},{namespaceURI:"http://www.w3.org/2001/XMLSchema",localName:"dateTimeStamp",j:[{type:46,g:0}],i:{type:10,g:0},callFunction:La.bind(null,10)}];function Qa(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getYear(),5))}function Ja(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getMonth(),5))}function Ka(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getDay(),5))}function qa(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getHours(),5))}function _a(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getMinutes(),5))}function Va(e,t,n,r){return r.G()||(t=(e=Ie).m,r=r.first().value,r=t.call(e,ne(r.B+r.sa,4))),r}function Wa(e,t,n,r){return r.G()?r:(e=r.first().value.Y)?Ie.m(ne(e,17)):Ie.empty()}var Za=[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"dateTime",j:[{type:7,g:0},{type:8,g:0}],i:{type:9,g:0},callFunction:function(e,t,n,r,a){if(r.G())return r;if(a.G())return a;if(e=r.first().value,a=a.first().value,t=e.Y,n=a.Y,t||n){if(!t||n)if(!t&&n)t=n;else if(!ut(t,n))throw Error("FORG0008: fn:dateTime: got a date and time value with different timezones.")}else t=null;return Ie.m(ne(new vt(e.getYear(),e.getMonth(),e.getDay(),a.getHours(),a.getMinutes(),a.getSeconds(),a.sa,t),9))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"year-from-dateTime",j:[{type:9,g:0}],i:{type:5,g:0},callFunction:Qa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"month-from-dateTime",j:[{type:9,g:0}],i:{type:5,g:0},callFunction:Ja},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"day-from-dateTime",j:[{type:9,g:0}],i:{type:5,g:0},callFunction:Ka},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"hours-from-dateTime",j:[{type:9,g:0}],i:{type:5,g:0},callFunction:qa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"minutes-from-dateTime",j:[{type:9,g:0}],i:{type:5,g:0},callFunction:_a},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"seconds-from-dateTime",j:[{type:9,g:0}],i:{type:4,g:0},callFunction:Va},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"timezone-from-dateTime",j:[{type:9,g:0}],i:{type:17,g:0},callFunction:Wa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"year-from-date",j:[{type:7,g:0}],i:{type:5,g:0},callFunction:Qa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"month-from-date",j:[{type:7,g:0}],i:{type:5,g:0},callFunction:Ja},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"day-from-date",j:[{type:7,g:0}],i:{type:5,g:0},callFunction:Ka},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"timezone-from-date",j:[{type:7,g:0}],i:{type:17,g:0},callFunction:Wa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"hours-from-time",j:[{type:8,g:0}],i:{type:5,g:0},callFunction:qa},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"minutes-from-time",j:[{type:8,g:0}],i:{type:5,g:0},callFunction:_a},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"seconds-from-time",j:[{type:8,g:0}],i:{type:4,g:0},callFunction:Va},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"timezone-from-time",j:[{type:8,g:0}],i:{type:17,g:0},callFunction:Wa}];function $a(e,t){var n=t.h,r=t.o,a=t.B;switch(e.node.nodeType){case 1:var o=r.createElementNS(e.node.namespaceURI,e.node.nodeName);for(n.getAllAttributes(e.node).forEach((function(e){return a.setAttributeNS(o,e.namespaceURI,e.nodeName,e.value)})),e=(r=p(Qe(n,e))).next();!e.done;e=r.next())e=$a(e.value,t),a.insertBefore(o,e.node,null);return{node:o,F:null};case 2:return(t=r.createAttributeNS(e.node.namespaceURI,e.node.nodeName)).value=Je(n,e),{node:t,F:null};case 4:return{node:r.createCDATASection(Je(n,e)),F:null};case 8:return{node:r.createComment(Je(n,e)),F:null};case 9:for(r=r.createDocument(),e=(n=p(Qe(n,e))).next();!e.done;e=n.next())e=$a(e.value,t),a.insertBefore(r,e.node,null);return{node:r,F:null};case 7:return{node:r.createProcessingInstruction(e.node.target,Je(n,e)),F:null};case 3:return{node:r.createTextNode(Je(n,e)),F:null}}}function za(e,t){var n=t.B,r=t.o,a=t.h;if(!Pe(e.node))return $a(e,t).node;switch(e.node.nodeType){case 2:return(r=r.createAttributeNS(e.node.namespaceURI,e.node.nodeName)).value=Je(a,e),r;case 8:return r.createComment(Je(a,e));case 1:var o=e.node.prefix,u=e.node.localName,i=r.createElementNS(e.node.namespaceURI,o?o+":"+u:u);return Qe(a,e).forEach((function(e){e=za(e,t),n.insertBefore(i,e,null)})),Le(a,e).forEach((function(e){n.setAttributeNS(i,e.node.namespaceURI,e.node.nodeName,Je(a,e))})),i.normalize(),i;case 7:return r.createProcessingInstruction(e.node.target,Je(a,e));case 3:return r.createTextNode(Je(a,e))}}function eo(e,t,n){var r=e;for(e=Ve(n,r);null!==e;){if(2===r.node.nodeType)t.push(r.node.nodeName);else{var a=Qe(n,e);t.push(a.findIndex((function(e){return Xn(e,r)})))}e=Ve(n,r=e)}return r}function to(e,t,n){for(var r={};0<t.length;)r.$a=t.pop(),e="string"==typeof r.$a?Le(n,e).find(function(e){return function(t){return t.node.nodeName===e.$a}}(r)):Qe(n,e)[r.$a],r={$a:r.$a};return e.node}function no(e,t,n){var r=e.node;if(!(Pe(r)||n||e.F))return r;r=t.da;var a=[];return n?za(e,t):(e=eo(e,a,t.h),(n=r.get(e.node))||(n={node:za(e,t),F:null},r.set(e.node,n)),to(n,a,t.h))}function ro(e,t,n,r,a){return r.M((function(e){for(var n="",r=0;r<e.length;r++){var o=e[r],u=t.v&&se(o.type,53)?t.v.serializeToString(no(o.value,t,!1)):Vt(Ie.m(o),t).map((function(e){return Hn(e,1)})).first().value;n+="{type: "+me[o.type]+", value: "+u+"}\n"}return void 0!==a&&(n+=a.first().value),t.s.trace(n),Ie.create(e)}))}var ao=[{j:[{type:59,g:2}],callFunction:ro,localName:"trace",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:1,g:3}],callFunction:ro,localName:"trace",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}}];function oo(e,t,n,r,a){throw e=void 0===r||r.G()?new Fe("err","http://www.w3.org/2005/xqt-errors","FOER0000"):r.first().value,t="",void 0===a||a.G()||(t=": "+a.first().value),Error(""+e.localName+t)}var uo=[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"error",j:[],i:{type:63,g:3},callFunction:oo},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"error",j:[{type:23,g:0}],i:{type:63,g:3},callFunction:oo},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"error",j:[{type:23,g:0},{type:1,g:3}],i:{type:63,g:3},callFunction:oo},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"error",j:[{type:23,g:0},{type:1,g:3},{type:59,g:2}],i:{type:63,g:3},callFunction:function(){throw Error("Not implemented: Using an error object in error is not supported")}}];function io(e){return"string"==typeof e?e:(e=(new ke).getChildNodes(e).find((function(e){return 8===e.nodeType})))?e.data:"some expression"}function co(e,t){e=Error.call(this,e),this.message=e.message,"stack"in e&&(this.stack=e.stack),this.position={end:{ja:t.end.ja,line:t.end.line,offset:t.end.offset},start:{ja:t.start.ja,line:t.start.line,offset:t.start.offset}}}function lo(e,t){if(t instanceof Error)throw t;"string"!=typeof e&&(e=io(e));var n=ni(t);e=e.replace("\r","").split("\n");var r=Math.floor(Math.log10(Math.min(n.end.line+2,e.length)))+1;throw e=e.reduce((function(e,t,a){var o=a+1;if(2<n.start.line-o||2<o-n.end.line)return e;if(a=Array(r).fill(" ",0,Math.floor(Math.log10(o))+1-r).join("")+o+": ",e.push(a+t),o>=n.start.line&&o<=n.end.line){var u=o<n.end.line?t.length+a.length:n.end.ja-1+a.length;o=o>n.start.line?a.length:n.start.ja-1+a.length,t=" ".repeat(a.length)+Array.from(t.substring(0,o-a.length),(function(e){return"\t"===e?"\t":" "})).join("")+"^".repeat(u-o),e.push(t)}return e}),[]),t=ri(t).join("\n"),new co(e.join("\n")+"\n\n"+t,n)}A(co,Error);var so=Object.create(null);function po(e,t){for(var n=[],r=0;r<e.length+1;++r)n[r]=[];return function r(a,o){if(0===a)return o;if(0===o)return a;if(void 0!==n[a][o])return n[a][o];var u=0;return e[a-1]!==t[o-1]&&(u=1),u=Math.min(r(a-1,o)+1,r(a,o-1)+1,r(a-1,o-1)+u),n[a][o]=u}(e.length,t.length)}function fo(e){var t=so[e]?so[e]:Object.keys(so).map((function(t){return{name:t,Ab:po(e,t.slice(t.lastIndexOf(":")+1))}})).sort((function(e,t){return e.Ab-t.Ab})).slice(0,5).filter((function(t){return t.Ab<e.length/2})).reduce((function(e,t){return e.concat(so[t.name])}),[]).slice(0,5);return t.length?t.map((function(e){return'"Q{'+e.namespaceURI+"}"+e.localName+" ("+e.j.map((function(e){return 4===e?"...":ge(e)})).join(", ")+')"'})).reduce((function(e,t,n,r){return 0===n?e+t:e+(n!==r.length-1?", ":" or ")+t}),"Did you mean ")+"?":"No similar functions found."}function ho(e,t,n){var r=so[e+":"+t];return r&&(r=r.find((function(e){return e.j.some((function(e){return 4===e}))?e.j.length-1<=n:e.j.length===n})))?{j:r.j,arity:n,callFunction:r.callFunction,I:r.I,localName:t,namespaceURI:e,i:r.i}:null}function mo(e,t,n,r,a){so[e+":"+t]||(so[e+":"+t]=[]),so[e+":"+t].push({j:n,arity:n.length,callFunction:a,I:!1,localName:t,namespaceURI:e,i:r})}var yo={},go=(yo.xml="http://www.w3.org/XML/1998/namespace",yo.xs="http://www.w3.org/2001/XMLSchema",yo.fn="http://www.w3.org/2005/xpath-functions",yo.map="http://www.w3.org/2005/xpath-functions/map",yo.array="http://www.w3.org/2005/xpath-functions/array",yo.math="http://www.w3.org/2005/xpath-functions/math",yo.fontoxpath="http://fontoxml.com/fontoxpath",yo.local="http://www.w3.org/2005/xquery-local-functions",yo);function vo(e,t,n,r){this.Ha=[Object.create(null)],this.Ia=Object.create(null),this.s=e,this.da=Object.keys(t).reduce((function(e,n){return void 0===t[n]||(e[n]="Q{}"+n+"[0]"),e}),Object.create(null)),this.o=Object.create(null),this.h=Object.create(null),this.v=n,this.l=r,this.B=[]}function wo(e){return Error("XPTY0004: "+e)}function Ao(e,t){return e=2===e.node.nodeType?e.node.nodeName+'="'+Je(t,e)+'"':e.node.outerHTML,Error("XQTY0024: The node "+e+" follows a node that is not an attribute node or a namespace node.")}function xo(e){return Error('XQDY0044: The node name "'+e.Ca()+'" is invalid for a computed attribute constructor.')}function Bo(){return Error("XQST0045: Functions and variables may not be declared in one of the reserved namespace URIs.")}function bo(){return Error("XQST0060: Functions declared in a module or as an external function must reside in a namespace.")}function Eo(){return Error("XQST0066: A Prolog may contain at most one default function namespace declaration.")}function No(){return Error("XQST0070: The prefixes xml and xmlns may not be used in a namespace declaration or be bound to another namespaceURI.")}function To(e){return Error('XQDY0074: The value "'+e+'" of a name expressions cannot be converted to an expanded QName.')}function Io(e){return Error('XPST0081: The prefix "'+e+'" could not be resolved')}function Co(e,t){return"Q{"+(e||"")+"}"+t}function Fo(e,t){for(var n=e.length-1;0<=n;--n)if(t in e[n])return e[n][t]}function Oo(e){this.o=e,this.s=this.h=0,this.B=[Object.create(null)],this.l=Object.create(null),this.v=null,this.Ia=e&&e.Ia,this.Ha=e&&e.Ha}function So(e){for(var t=new Oo(e.o),n=0;n<e.h+1;++n)t.B=[Object.assign(Object.create(null),t.B[0],e.B[n])],t.Ha=[Object.assign(Object.create(null),t.Ha[0],e.Ha[n])],t.l=Object.assign(Object.create(null),e.l),t.Ia=e.Ia,t.v=e.v;return t}function Go(e){e.s++,e.h++,e.B[e.h]=Object.create(null),e.Ha[e.h]=Object.create(null)}function Do(e,t,n){return(e=e.Ia[Co(t,n)])?e:null}function Ro(e,t,n,r,a){if(r=Co(t,n)+"~"+r,e.l[r])throw Error('XQST0049: The function or variable "Q{'+t+"}"+n+'" is declared more than once.');e.l[r]=a}function ko(e,t,n){e.B[e.h][t]=n}function Uo(e,t,n){return t=Co(t||"",n),e.Ha[e.h][t]=t+"["+e.s+"]"}function Mo(e,t,n,r){e.Ia[Co(t||"",n)+"["+e.s+"]"]=r}function Ho(e){e.B.length=e.h,e.Ha.length=e.h,e.h--}function Po(e,t){"*"===t||Array.isArray(t)||(t=[t]);for(var n=1;n<e.length;++n)if(Array.isArray(e[n])){var r=e[n];if("*"===t||t.includes(r[0]))return r}return null}function jo(e){return 2>e.length?"":"object"==typeof e[1]?e[2]||"":e[1]||""}function Xo(e,t){return Array.isArray(e)?"object"!=typeof(e=e[1])||Array.isArray(e)?null:t in e?e[t]:null:null}function Lo(e,t){return t.reduce(Po,e)}function Yo(e,t){for(var n=[],r=1;r<e.length;++r)if(Array.isArray(e[r])){var a=e[r];"*"!==t&&a[0]!==t||n.push(a)}return n}function Qo(e){return{localName:jo(e),namespaceURI:Xo(e,"URI"),prefix:Xo(e,"prefix")}}function Jo(e){function t(e){switch(e[0]){case"documentTest":return 55;case"elementTest":return 54;case"attributeTest":return 47;case"piTest":return 57;case"commentTest":return 58;case"textTest":return 56;case"anyKindTest":return 53;case"anyItemType":return 59;case"anyFunctionTest":case"functionTest":case"typedFunctionTest":return 60;case"anyMapTest":case"typedMapTest":return 61;case"anyArrayTest":case"typedArrayTest":return 62;case"atomicType":return ve([Xo(e,"prefix"),jo(e)].join(":"));case"parenthesizedItemType":return t(Po(e,"*"));default:throw Error('Type declaration "'+Po(n,"*")[0]+'" is not supported.')}}var n=Po(e,"typeDeclaration");if(!n||Po(n,"voidSequenceType"))return{type:59,g:2};e={type:t(Po(n,"*")),g:3};var r=null,a=Po(n,"occurrenceIndicator");switch(a&&(r=jo(a)),r){case"*":return e.g=2,e;case"?":return e.g=0,e;case"+":return e.g=1,e;case"":case null:return e}}function Ko(e,t,n){if("object"!=typeof e[1]||Array.isArray(e[1])){var r={};r[t]=n,e.splice(1,0,r)}else e[1][t]=n}function qo(e){var t={type:62,g:3};return Ko(e,"type",t),t}function _o(e,t){if(!t||!t.ia)return{type:59,g:2};var n=Po(e,"EQName");if(!n)return{type:59,g:2};var r=Qo(n);n=r.localName;var a=r.prefix;return r=Yo(Po(e,"arguments"),"*"),(n=t.ia.Ua({localName:n,prefix:a},r.length))&&(t=t.ia.xa(n.namespaceURI,n.localName,r.length+1))?(59!==t.i.type&&Ko(e,"type",t.i),t.i):{type:59,g:2}}function Vo(e,t,n){return(e<<20)+(t<<12)+(n.charCodeAt(0)<<8)+n.charCodeAt(1)}vo.prototype.xa=function(e,t,n){return ho(e,t,n)},vo.prototype.ib=function(e,t){return e?null:(e=this.da[t],this.o[t]||(this.o[t]={name:t}),e)},vo.prototype.Ua=function(e,t){var n=this.l(e,t);if(n)this.B.push({nc:e,arity:t,Lb:n});else if(""===e.prefix){if(this.v)return{namespaceURI:this.v,localName:e.localName}}else if(t=this.aa(e.prefix,!0))return{namespaceURI:t,localName:e.localName};return n},vo.prototype.aa=function(e,t){return void 0===t||t?go[e]?go[e]:(t=this.s(e),this.h[e]||(this.h[e]={namespaceURI:t,prefix:e}),void 0!==t||e?t:null):null},Oo.prototype.xa=function(e,t,n,r){r=void 0!==r&&r;var a=this.l[Co(e,t)+"~"+n];return!a||r&&a.Eb?null===this.o?null:this.o.xa(e,t,n,r):a},Oo.prototype.ib=function(e,t){var n=Fo(this.Ha,Co(e,t));return n||(null===this.o?null:this.o.ib(e,t))},Oo.prototype.Ua=function(e,t){var n=e.prefix,r=e.localName;return""===n&&this.v?{localName:r,namespaceURI:this.v}:n&&(n=this.aa(n,!1))?{localName:r,namespaceURI:n}:null===this.o?null:this.o.Ua(e,t)},Oo.prototype.aa=function(e,t){var n=Fo(this.B,e||"");return void 0===n?null===this.o?void 0:this.o.aa(e||"",void 0===t||t):n};var Wo={},Zo=(Wo[Vo(2,2,"idivOp")]=5,Wo[Vo(16,16,"addOp")]=16,Wo[Vo(16,16,"subtractOp")]=16,Wo[Vo(16,16,"divOp")]=4,Wo[Vo(16,2,"multiplyOp")]=16,Wo[Vo(16,2,"divOp")]=16,Wo[Vo(2,16,"multiplyOp")]=16,Wo[Vo(17,17,"addOp")]=17,Wo[Vo(17,17,"subtractOp")]=17,Wo[Vo(17,17,"divOp")]=4,Wo[Vo(17,2,"multiplyOp")]=17,Wo[Vo(17,2,"divOp")]=17,Wo[Vo(2,17,"multiplyOp")]=17,Wo[Vo(9,9,"subtractOp")]=17,Wo[Vo(7,7,"subtractOp")]=17,Wo[Vo(8,8,"subtractOp")]=17,Wo[Vo(9,16,"addOp")]=9,Wo[Vo(9,16,"subtractOp")]=9,Wo[Vo(9,17,"addOp")]=9,Wo[Vo(9,17,"subtractOp")]=9,Wo[Vo(7,16,"addOp")]=7,Wo[Vo(7,16,"subtractOp")]=7,Wo[Vo(7,17,"addOp")]=7,Wo[Vo(7,17,"subtractOp")]=7,Wo[Vo(8,17,"addOp")]=8,Wo[Vo(8,17,"subtractOp")]=8,Wo[Vo(9,16,"addOp")]=9,Wo[Vo(9,16,"subtractOp")]=9,Wo[Vo(9,17,"addOp")]=9,Wo[Vo(9,17,"subtractOp")]=9,Wo[Vo(7,17,"addOp")]=7,Wo[Vo(7,17,"subtractOp")]=7,Wo[Vo(7,16,"addOp")]=7,Wo[Vo(7,16,"subtractOp")]=7,Wo[Vo(8,17,"addOp")]=8,Wo[Vo(8,17,"subtractOp")]=8,Wo),$o={},zo=($o[Vo(2,2,"addOp")]=function(e,t){return e+t},$o[Vo(2,2,"subtractOp")]=function(e,t){return e-t},$o[Vo(2,2,"multiplyOp")]=function(e,t){return e*t},$o[Vo(2,2,"divOp")]=function(e,t){return e/t},$o[Vo(2,2,"modOp")]=function(e,t){return e%t},$o[Vo(2,2,"idivOp")]=function(e,t){return Math.trunc(e/t)},$o[Vo(16,16,"addOp")]=function(e,t){return new fn(e.ga+t.ga)},$o[Vo(16,16,"subtractOp")]=function(e,t){return new fn(e.ga-t.ga)},$o[Vo(16,16,"divOp")]=function(e,t){return e.ga/t.ga},$o[Vo(16,2,"multiplyOp")]=mn,$o[Vo(16,2,"divOp")]=function(e,t){if(isNaN(t))throw Error("FOCA0005: Cannot divide xs:yearMonthDuration by NaN");if((e=Math.round(e.ga/t))>Number.MAX_SAFE_INTEGER||!Number.isFinite(e))throw Error("FODT0002: Value overflow while dividing xs:yearMonthDuration");return new fn(e<Number.MIN_SAFE_INTEGER||0===e?0:e)},$o[Vo(2,16,"multiplyOp")]=function(e,t){return mn(t,e)},$o[Vo(17,17,"addOp")]=function(e,t){return new it(e.ea+t.ea)},$o[Vo(17,17,"subtractOp")]=function(e,t){return new it(e.ea-t.ea)},$o[Vo(17,17,"divOp")]=function(e,t){if(0===t.ea)throw Error("FOAR0001: Division by 0");return e.ea/t.ea},$o[Vo(17,2,"multiplyOp")]=ft,$o[Vo(17,2,"divOp")]=function(e,t){if(isNaN(t))throw Error("FOCA0005: Cannot divide xs:dayTimeDuration by NaN");if((e=e.ea/t)>Number.MAX_SAFE_INTEGER||!Number.isFinite(e))throw Error("FODT0002: Value overflow while dividing xs:dayTimeDuration");return new it(e<Number.MIN_SAFE_INTEGER||Object.is(-0,e)?0:e)},$o[Vo(2,17,"multiplyOp")]=function(e,t){return ft(t,e)},$o[Vo(9,9,"subtractOp")]=Et,$o[Vo(7,7,"subtractOp")]=Et,$o[Vo(8,8,"subtractOp")]=Et,$o[Vo(9,16,"addOp")]=Nt,$o[Vo(9,16,"subtractOp")]=Tt,$o[Vo(9,17,"addOp")]=Nt,$o[Vo(9,17,"subtractOp")]=Tt,$o[Vo(7,16,"addOp")]=Nt,$o[Vo(7,16,"subtractOp")]=Tt,$o[Vo(7,17,"addOp")]=Nt,$o[Vo(7,17,"subtractOp")]=Tt,$o[Vo(8,17,"addOp")]=Nt,$o[Vo(8,17,"subtractOp")]=Tt,$o[Vo(9,16,"addOp")]=Nt,$o[Vo(9,16,"subtractOp")]=Tt,$o[Vo(9,17,"addOp")]=Nt,$o[Vo(9,17,"subtractOp")]=Tt,$o[Vo(7,17,"addOp")]=Nt,$o[Vo(7,17,"subtractOp")]=Tt,$o[Vo(7,16,"addOp")]=Nt,$o[Vo(7,16,"subtractOp")]=Tt,$o[Vo(8,17,"addOp")]=Nt,$o[Vo(8,17,"subtractOp")]=Tt,$o);function eu(e,t){return se(e,5)&&se(t,5)?5:se(e,4)&&se(t,4)?4:se(e,6)&&se(t,6)?6:3}var tu=[2,16,17,9,7,8];function nu(e,t,n){function r(e,t){return{U:a?a(e):e,V:o?o(t):t}}var a=null,o=null;se(t,19)&&(a=function(e){return Hn(e,3)},t=3),se(n,19)&&(o=function(e){return Hn(e,3)},n=3);var u=tu.filter((function(e){return se(t,e)})),i=tu.filter((function(e){return se(n,e)}));if(u.includes(2)&&i.includes(2)){var c=zo[Vo(2,2,e)],l=Zo[Vo(2,2,e)];return l||(l=eu(t,n)),"divOp"===e&&5===l&&(l=4),"idivOp"===e?au(r,c)[0]:function(e,t){return e=r(e,t),ne(c(e.U.value,e.V.value),l)}}for(var s=(u=p(u)).next();!s.done;s=u.next()){s=s.value;for(var f={},h=p(i),d=h.next();!d.done;f={nb:f.nb,qb:f.qb},d=h.next())if(d=d.value,f.nb=zo[Vo(s,d,e)],f.qb=Zo[Vo(s,d,e)],f.nb&&void 0!==f.qb)return function(e){return function(t,n){return t=r(t,n),ne(e.nb(t.U.value,t.V.value),e.qb)}}(f)}}function ru(e,t,n){function r(e,t){return{U:o?o(e):e,V:u?u(t):t}}var a=[2,53,59,46,47];if(a.includes(t)||a.includes(n))return 2;var o=null,u=null;se(t,19)&&(o=function(e){return Hn(e,3)},t=3),se(n,19)&&(u=function(e){return Hn(e,3)},n=3);var i=tu.filter((function(e){return se(t,e)}));if(a=tu.filter((function(e){return se(n,e)})),i.includes(2)&&a.includes(2))return void 0===(a=Zo[Vo(2,2,e)])&&(a=eu(t,n)),"divOp"===e&&5===a&&(a=4),"idivOp"===e?au(r,(function(e,t){return Math.trunc(e/t)}))[1]:a;for(var c=(i=p(i)).next();!c.done;c=i.next()){c=c.value;for(var l=p(a),s=l.next();!s.done;s=l.next())if(void 0!==(s=Zo[Vo(c,s.value,e)]))return s}}function au(e,t){return[function(n,r){if(n=(r=e(n,r)).U,0===(r=r.V).value)throw Error("FOAR0001: Divisor of idiv operator cannot be (-)0");if(Number.isNaN(n.value)||Number.isNaN(r.value)||!Number.isFinite(n.value))throw Error("FOAR0002: One of the operands of idiv is NaN or the first operand is (-)INF");return Number.isFinite(n.value)&&!Number.isFinite(r.value)?ne(0,5):ne(t(n.value,r.value),5)},5]}var ou=Object.create(null);function uu(e,t,n,r,a){ua.call(this,t.o.add(n.o),[t,n],{C:!1},!1,r),this.A=t,this.K=n,this.l=e,this.s=a}function iu(e,t){for(var n=wu,r=!1,a=1;a<e.length;a++)switch(e[a][0]){case"letClause":Fu(t);var o=e[a],u=t,i=n,c=Lo(o,["letClauseItem","typedVariableBinding","varName"]);c=Qo(c),i=i((o=Lo(o,["letClauseItem","letExpr"]))[1],u),Cu(u,c.localName,i);break;case"forClause":r=!0,Fu(t),cu(e[a],t,n);break;case"whereClause":Fu(t),n(u=e[a],t),Ko(u,"type",{type:0,g:3});break;case"orderByClause":Fu(t);break;case"returnClause":return u=n,Ko(n=Lo(a=e[a],["*"]),"type",t=u(n,t)),Ko(a,"type",t),(n=t)?(r&&(n={type:n.type,g:2}),59!==n.type&&Ko(e,"type",n),n):{type:59,g:2};default:return(n=n(e[a],t))?(r&&(n={type:n.type,g:2}),59!==n.type&&Ko(e,"type",n),n):{type:59,g:2}}if(!(0<t.h))throw Error("Variable scope out of bound");t.h--,t.o.pop(),t.v.pop()}function cu(e,t,n){var r=Qo(Lo(e,["forClauseItem","typedVariableBinding","varName"]));(e=Lo(e,["forClauseItem","forExpr","sequenceExpr"]))&&((e=Yo(e,"*").map((function(e){return n(e,t)}))).includes(void 0)||e.includes(null)||1===(e=lu(e)).length&&Cu(t,r.localName,e[0]))}function lu(e){return e.filter((function(e,t,n){return n.findIndex((function(t){return t.type===e.type&&t.g===e.g}))===t}))}function su(e,t){if(!t||!t.ia)return{type:59,g:2};var n=Po(e,"functionName"),r=Qo(n),a=r.localName,o=r.prefix,u=r.namespaceURI;if(r=Yo(Po(e,"arguments"),"*"),null===u){if(!(o=t.ia.Ua({localName:a,prefix:o},r.length)))return{type:59,g:2};a=o.localName,Ko(n,"URI",u=o.namespaceURI),n[2]=a}return(t=t.ia.xa(u,a,r.length))&&63!==t.i.type?(59!==t.i.type&&Ko(e,"type",t.i),t.i):{type:59,g:2}}function pu(e){var t={type:61,g:3};return Ko(e,"type",t),t}function fu(e,t){if(!t||!t.ia)return{type:59,g:2};var n=Po(e,"functionName"),r=Qo(n),a=r.localName,o=r.namespaceURI,u=r.prefix;if(r=Number(Lo(e,["integerConstantExpr","value"])[1]),!o){if(!(o=t.ia.Ua({localName:a,prefix:u},r)))return{type:59,g:2};a=o.localName,Ko(n,"URI",o=o.namespaceURI)}return(t=t.ia.xa(o,a,r)||null)?(59!==t.i.type&&63!==t.i.type&&Ko(e,"type",t.i),t.i):{type:59,g:2}}function hu(e,t){var n=Yo(e,"stepExpr");if(!n)return{type:59,g:2};for(var r=(n=p(n)).next();!r.done;r=n.next()){var a=r.value;r=t;var o=null;if(a){for(var u=Yo(a,"*"),i="",c=(u=p(u)).next();!c.done;c=u.next())switch(c=c.value,c[0]){case"filterExpr":o=Xo(Lo(c,["*"]),"type");break;case"xpathAxis":e:{switch(i=c[1]){case"attribute":o={type:47,g:2};break e;case"child":case"decendant":case"self":case"descendant-or-self":case"following-sibling":case"following":case"namespace":case"parent":case"ancestor":case"preceding-sibling":case"preceding":case"ancestor-or-self":o={type:53,g:2};break e}o=void 0}break;case"nameTest":var l=Qo(c);if(null!==l.namespaceURI)break;if("attribute"===i&&!l.prefix)break;void 0!==(l=r.aa(l.prefix||""))&&Ko(c,"URI",l);break;case"lookup":o={type:59,g:2}}o&&59!==o.type&&Ko(a,"type",o)}a=Xo(a,"type")}return a&&59!==a.type&&Ko(e,"type",a),a}function du(e){var t={type:0,g:3};return Ko(e,"type",t),t}function mu(e,t,n){return(t=0===t?{type:53,g:2}:1===t?n[0]:n.includes(void 0)||n.includes(null)||1<(t=lu(n)).length?{type:59,g:2}:{type:t[0].type,g:2})&&59!==t.type&&Ko(e,"type",t),t}function yu(e,t,n,r){if(!t||n.includes(void 0))return{type:59,g:2};for(var a=Yo(e,"typeswitchExprCaseClause"),o=0;o<n.length;o++){var u=Po(a[o],"*");switch(u[0]){case"sequenceType":if(u=gu(u,t,n[o]))return 59!==u.type&&Ko(e,"type",u),u;continue;case"sequenceTypeUnion":for(r=Yo(u,"*"),a=0;2>a;a++)if(u=gu(r[a],t,n[o]))return 59!==u.type&&Ko(e,"type",u),u;default:return{type:59,g:2}}}return 59!==r.type&&Ko(e,"type",r),r}function gu(e,t,n){var r=Yo(e,"*"),a=Po(e,"atomicType");if(!a)return{type:59,g:2};if(ve(Xo(a,"prefix")+":"+a[2])===t.type)if(1===r.length){if(3===t.g)return n}else if(e=Po(e,"occurrenceIndicator")[1],t.g===Ae(e))return n}function vu(e,t){wu(e,t)}function wu(e,t){var n=Tu.get(e[0]);if(n)return n(e,t);for(n=1;n<e.length;n++)e[n]&&wu(e[n],t)}function Au(e,t){var n=wu(Po(e,"firstOperand")[1],t),r=wu(Po(e,"secondOperand")[1],t),a=e[0];if(n&&r){if(!(t=ru(a,n.type,r.type)))throw Error("XPTY0004: "+a+" not available for types "+ge(n)+" and "+ge(r));n={type:t,g:n.g},2!==t&&59!==t&&Ko(e,"type",n),e=n}else e={type:2,g:3};return e}function xu(e,t){wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t);e:{switch(e[0]){case"orOp":case"andOp":Ko(e,"type",t={type:0,g:3}),e=t;break e}e=void 0}return e}function Bu(e,t){wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t);e:{switch(e[0]){case"unionOp":case"intersectOp":case"exceptOp":Ko(e,"type",t={type:53,g:2}),e=t;break e}e=void 0}return e}function bu(e,t){return wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t),Ko(e,"type",t={type:0,g:3}),t}function Eu(e,t){wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t),t=Xo(Lo(e,["firstOperand","*"]),"type");var n=Xo(Lo(e,["secondOperand","*"]),"type");return Ko(e,"type",t={type:0,g:tn(t)||tn(n)?0:3}),t}function Nu(e,t){wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t),t=Xo(Lo(e,["firstOperand","*"]),"type");var n=Xo(Lo(e,["secondOperand","*"]),"type");return Ko(e,"type",t={type:0,g:tn(t)||tn(n)?0:3}),t}A(uu,ua),uu.prototype.h=function(e,t){var n=this;return Vt(ia(this.A,e,t),t).M((function(r){return 0===r.length?Ie.empty():Vt(ia(n.K,e,t),t).M((function(e){if(0===e.length)return Ie.empty();if(1<r.length||1<e.length)throw Error('XPTY0004: the operands of the "'+n.l+'" operator should be empty or singleton.');var t=r[0];if(e=e[0],n.s&&n.type)return Ie.m(n.s(t,e));var a=t.type,o=e.type,u=n.l,i=a+"~"+o+"~"+u,c=ou[i];if(c||(c=ou[i]=nu(u,a,o)),!(a=c))throw Error("XPTY0004: "+n.l+" not available for types "+me[t.type]+" and "+me[e.type]);return Ie.m(a(t,e))}))}))};var Tu=new Map([["unaryMinusOp",function(e,t){return(t=wu(Po(e,"operand")[1],t))?se(t.type,2)?(Ko(e,"type",t={type:t.type,g:t.g}),e=t):(Ko(e,"type",t={type:3,g:3}),e=t):(Ko(e,"type",t={type:2,g:2}),e=t),e}],["unaryPlusOp",function(e,t){return(t=wu(Po(e,"operand")[1],t))?se(t.type,2)?(Ko(e,"type",t={type:t.type,g:t.g}),e=t):(Ko(e,"type",t={type:3,g:3}),e=t):(Ko(e,"type",t={type:2,g:2}),e=t),e}],["addOp",Au],["subtractOp",Au],["divOp",Au],["idivOp",Au],["modOp",Au],["multiplyOp",Au],["andOp",xu],["orOp",xu],["sequenceExpr",function(e,t){var n=Yo(e,"*"),r=n.map((function(e){return wu(e,t)}));return mu(e,n.length,r)}],["unionOp",Bu],["intersectOp",Bu],["exceptOp",Bu],["stringConcatenateOp",function(e,t){return wu(Po(e,"firstOperand")[1],t),wu(Po(e,"secondOperand")[1],t),Ko(e,"type",t={type:1,g:3}),t}],["rangeSequenceExpr",function(e,t){return wu(Po(e,"startExpr")[1],t),wu(Po(e,"endExpr")[1],t),Ko(e,"type",t={type:5,g:1}),t}],["equalOp",bu],["notEqualOp",bu],["lessThanOrEqualOp",bu],["lessThanOp",bu],["greaterThanOrEqualOp",bu],["greaterThanOp",bu],["eqOp",Eu],["neOp",Eu],["ltOp",Eu],["leOp",Eu],["gtOp",Eu],["geOp",Eu],["isOp",Nu],["nodeBeforeOp",Nu],["nodeAfterOp",Nu],["pathExpr",function(e,t){var n=Po(e,"rootExpr");return n&&n[1]&&wu(n[1],t),Yo(e,"stepExpr").map((function(e){return wu(e,t)})),hu(e,t)}],["contextItemExpr",function(){return{type:59,g:2}}],["ifThenElseExpr",function(e,t){wu(Po(Po(e,"ifClause"),"*"),t);var n=wu(Po(Po(e,"thenClause"),"*"),t);return t=wu(Po(Po(e,"elseClause"),"*"),t),n&&t&&n.type===t.type&&n.g===t.g?(59!==n.type&&Ko(e,"type",n),e=n):e={type:59,g:2},e}],["instanceOfExpr",function(e,t){return wu(Po(e,"argExpr"),t),wu(Po(e,"sequenceType"),t),Ko(e,"type",t={type:0,g:3}),t}],["integerConstantExpr",function(e){var t={type:5,g:3};return Ko(e,"type",t),t}],["doubleConstantExpr",function(e){var t={type:3,g:3};return Ko(e,"type",t),t}],["decimalConstantExpr",function(e){var t={type:4,g:3};return Ko(e,"type",t),t}],["stringConstantExpr",function(e){var t={type:1,g:3};return Ko(e,"type",t),t}],["functionCallExpr",function(e,t){return Yo(Po(e,"arguments"),"*").map((function(e){return wu(e,t)})),su(e,t)}],["arrowExpr",function(e,t){return wu(Po(e,"argExpr")[1],t),_o(e,t)}],["dynamicFunctionInvocationExpr",function(e,t){return wu(Lo(e,["functionItem","*"]),t),(e=Po(e,"arguments"))&&wu(e,t),{type:59,g:2}}],["namedFunctionRef",function(e,t){return fu(e,t)}],["inlineFunctionExpr",function(e,t){return wu(Po(e,"functionBody")[1],t),Ko(e,"type",t={type:60,g:3}),t}],["castExpr",function(e){var t=Lo(e,["singleType","atomicType"]);return 59!==(t={type:ve(Xo(t,"prefix")+":"+t[2]),g:3}).type&&Ko(e,"type",t),t}],["castableExpr",function(e){var t={type:0,g:3};return Ko(e,"type",t),t}],["simpleMapExpr",function(e,t){for(var n,r=Yo(e,"pathExpr"),a=0;a<r.length;a++)n=wu(r[a],t);return null!=n?(59!==(t={type:n.type,g:2}).type&&Ko(e,"type",t),e=t):e={type:59,g:2},e}],["mapConstructor",function(e,t){return Yo(e,"mapConstructorEntry").map((function(e){return{key:wu(Lo(e,["mapKeyExpr","*"]),t),value:wu(Lo(e,["mapValueExpr","*"]),t)}})),pu(e)}],["arrayConstructor",function(e,t){return Yo(Po(e,"*"),"arrayElem").map((function(e){return wu(e,t)})),qo(e)}],["unaryLookup",function(e){return Po(e,"NCName"),{type:59,g:2}}],["typeswitchExpr",function(e,t){return yu(e,wu(Po(e,"argExpr")[1],t),Yo(e,"typeswitchExprCaseClause").map((function(e){return wu(Lo(e,["resultExpr"])[1],t)})),wu(Lo(e,["typeswitchExprDefaultClause","resultExpr"])[1],t))}],["quantifiedExpr",function(e,t){return Yo(e,"*").map((function(e){return wu(e,t)})),du(e)}],["x:stackTrace",function(e,t){return wu((e=Yo(e,"*"))[0],t)}],["queryBody",function(e,t){return wu(e[1],t)}],["flworExpr",function(e,t){return iu(e,t)}],["varRef",function(e,t){var n,r=Qo(Po(e,"name"));e:{for(n=t.h;0<=n;n--){var a=t.o[n][r.localName];if(a){n=a;break e}}n=void 0}return n&&59!==n.type&&Ko(e,"type",n),null===r.namespaceURI&&void 0!==(t=t.aa(r.prefix))&&Ko(e,"URI",t),n}]]);function Iu(e){this.h=0,this.ia=e,this.o=[{}],this.v=[{}]}function Cu(e,t,n){if(e.o[e.h][t])throw Error("Another variable of in the scope "+e.h+" with the same name "+t+" already exists");e.o[e.h][t]=n}function Fu(e){e.h++,e.o.push({}),e.v.push({})}function Ou(e,t){var n={};ua.call(this,new Ca((n.external=1,n)),e,{C:e.every((function(e){return e.C}))},!1,t),this.l=e}function Su(e,t){var n={};ua.call(this,new Ca((n.external=1,n)),e,{C:e.every((function(e){return e.C}))},!1,t),this.l=e}function Gu(e){if(null===e)throw Qt("context is absent, it needs to be present to use axes.");if(!se(e.type,53))throw Error("XPTY0020: Axes can only be applied to nodes.");return e.value}function Du(e,t,n){var r=t;return{next:function(){if(!r)return ie;var t=r;return r=Ve(e,t,n),ce(et(t))}}}function Ru(e,t){t=t||{Ra:!1},ua.call(this,e.o,[e],{R:"reverse-sorted",X:!1,subtree:!1,C:!1}),this.l=e,this.s=!!t.Ra}Iu.prototype.aa=function(e){for(var t=this.h;0<=t;t--){var n=this.v[t][e];if(void 0!==n)return n}return this.ia?this.ia.aa(e):void 0},A(Ou,ua),Ou.prototype.h=function(e,t){return 0===this.l.length?Ie.m(new $e([])):ia(this.l[0],e,t).M((function(e){return Ie.m(new $e(e.map((function(e){return Ce(Ie.m(e))}))))}))},A(Su,ua),Su.prototype.h=function(e,t){return Ie.m(new $e(this.l.map((function(n){return Ce(ia(n,e,t))}))))},A(Ru,ua),Ru.prototype.h=function(e,t){var n=this;t=t.h,e=Gu(e.N);var r=this.l.B();return r=r&&(r.startsWith("name-")||"type-1"===r)?"type-1":null,Ie.create(Du(t,this.s?e:Ve(t,e,r),r)).filter((function(e){return n.l.l(e)}))};var ku=new Map([["type-1-or-type-2",["name","type-1","type-2"]],["type-1",["name"]],["type-2",["name"]]]);function Uu(e,t){if(null===e)return t;if(null===t||e===t)return e;var n=e.startsWith("name-")?"name":e,r=t.startsWith("name-")?"name":t,a=ku.get(n);return void 0!==a&&a.includes(r)?t:void 0!==(t=ku.get(r))&&t.includes(n)?e:"empty"}function Mu(e,t){var n={};ua.call(this,new Ca((n.attribute=1,n)),[e],{R:"unsorted",subtree:!0,X:!0,C:!1}),this.l=e,this.s=Uu(this.l.B(),t)}function Hu(e,t){ua.call(this,e.o,[e],{R:"sorted",subtree:!0,X:!0,C:!1}),this.s=e,this.l=Uu(t,e.B())}function Pu(e,t,n){var r=t.node.nodeType;if(1!==r&&9!==r)return{next:function(){return ie}};var a=Ke(e,t,n);return{next:function(){if(!a)return ie;var t=a;return a=_e(e,a,n),ce(t)}}}function ju(e,t,n){var r=[Pn(t)];return{next:function(t){if(0<r.length&&0!=(1&t)&&r.shift(),!r.length)return ie;for(t=r[0].next(0);t.done;){if(r.shift(),!r.length)return ie;t=r[0].next(0)}return r.unshift(Pu(e,t.value,n)),ce(et(t.value))}}}function Xu(e,t){t=t||{Ra:!1},ua.call(this,e.o,[e],{C:!1,X:!1,R:"sorted",subtree:!0}),this.l=e,this.s=!!t.Ra,this.A=(e=this.l.B())&&(e.startsWith("name-")||"type-1"===e)||"type-1-or-type-2"===e?"type-1":null}function Lu(e,t,n){var r=e.node.nodeType;if(1!==r&&9!==r)return e;for(r=qe(t,e,n);null!==r;){if(1!==r.node.nodeType)return r;r=qe(t,e=r,n)}return e}function Yu(e,t,n,r){if(void 0!==n&&n){var a=t,o=!1;return{next:function(){if(o)return ie;if(Xn(a,t))return Xn(a=Lu(t,e,r),t)?(o=!0,ie):ce(et(a));var n=a.node.nodeType,u=9===n||2===n?null:We(e,a,r);return null!==u?ce(et(a=Lu(u,e,r))):Xn(a=9===n?null:Ve(e,a,r),t)?(o=!0,ie):ce(et(a))}}}var u=[Pu(e,t,r)];return{next:function(){if(!u.length)return ie;for(var t=u[0].next(0);t.done;){if(u.shift(),!u.length)return ie;t=u[0].next(0)}return u.unshift(Pu(e,t.value,r)),ce(et(t.value))}}}function Qu(e,t,n){for(var r=[];t&&9!==t.node.nodeType;t=Ve(e,t,null)){var a=_e(e,t,n);a&&r.push(a)}var o=null;return{next:function(){for(;o||r.length;){if(!o){o=Yu(e,r[0],!1,n);var t=ce(et(r[0])),a=_e(e,r[0],n);return a?r[0]=a:r.shift(),t}if(!(t=o.next(0)).done)return t;o=null}return ie}}}function Ju(e){ua.call(this,e.o,[e],{R:"sorted",X:!0,subtree:!1,C:!1}),this.l=e,this.s=(e=this.l.B())&&(e.startsWith("name-")||"type-1"===e)?"type-1":null}function Ku(e,t,n){return{next:function(){return(t=t&&_e(e,t,n))?ce(et(t)):ie}}}function qu(e,t){ua.call(this,e.o,[e],{R:"sorted",X:!0,subtree:!1,C:!1}),this.l=e,this.s=Uu(this.l.B(),t)}function _u(e,t){ua.call(this,e.o,[e],{R:"reverse-sorted",X:!0,subtree:!0,C:!1}),this.l=e,this.s=Uu(t,this.l.B())}function Vu(e,t,n){for(var r=[];t&&9!==t.node.nodeType;t=Ve(e,t,null)){var a=We(e,t,n);null!==a&&r.push(a)}var o=null;return{next:function(){for(;o||r.length;){o||(o=Yu(e,r[0],!0,n));var t=o.next(0);if(t.done){o=null,t=We(e,r[0],n);var a=ce(et(r[0]));return null===t?r.shift():r[0]=t,a}return t}return ie}}}function Wu(e){ua.call(this,e.o,[e],{C:!1,X:!0,R:"reverse-sorted",subtree:!1}),this.l=e,this.s=(e=this.l.B())&&(e.startsWith("name-")||"type-1"===e)?"type-1":null}function Zu(e,t,n){return{next:function(){return(t=t&&We(e,t,n))?ce(et(t)):ie}}}function $u(e,t){ua.call(this,e.o,[e],{C:!1,X:!0,R:"reverse-sorted",subtree:!1}),this.l=e,this.s=Uu(this.l.B(),t)}function zu(e,t){ua.call(this,e.o,[e],{R:"sorted",subtree:!0,X:!0,C:!1}),this.l=e,this.s=Uu(this.l.B(),t)}function ei(e,t,n,r){var a=e.o.add(t.o).add(n.o);Ea.call(this,a,[e,t,n],{C:e.C&&t.C&&n.C,X:t.X===n.X&&t.X,R:t.da===n.da?t.da:"unsorted",subtree:t.subtree===n.subtree&&t.subtree},r),this.l=e}function ti(e,t,n){this.location=e,this.o=t,this.h=n}function ni(e){return e.h instanceof Error?e.location:ni(e.h)}function ri(e){var t=e.h instanceof co?["Inner error:",e.h.message]:e.h instanceof Error?[e.h.toString()]:ri(e.h);return t.push("  at <"+e.o+">:"+e.location.start.line+":"+e.location.start.ja+" - "+e.location.end.line+":"+e.location.end.ja),t}function ai(e,t,n){Ea.call(this,n.o,[n],{C:n.C,X:n.X,R:n.da,subtree:n.subtree}),this.l=t,this.K={end:{ja:e.end.ja,line:e.end.line,offset:e.end.offset},start:{ja:e.start.ja,line:e.start.line,offset:e.start.offset}}}function oi(e,t,n,r){ua.call(this,e,t,n,!0),this.l=r,this.I=this.l.I}function ui(e,t,n,r){var a=[],o=e.K(t,n,r,(function(n){if(e.l instanceof oi)return ba(ui(e.l,t,n,r),(function(e){return a=e}));var o=null;return Ie.create({next:function(){for(;;){if(!o){var t=n.next(0);if(t.done)return ie;t=e.l.s(t.value,r),o=ba(t,(function(e){return a=Aa(a,e)})).value}if(!(t=o.next(0)).done)return t;o=null}}})})),u=!1;return{next:function(){if(u)return ie;var e=o.O();return u=!0,ce(new ca(e,a))}}}function ii(e,t,n,r){return e.K(t,n,r,(function(n){if(e.l instanceof oi)return ii(e.l,t,n,r);var a=null;return Ie.create({next:function(){for(;;){if(!a){var t=n.next(0);if(t.done)return ie;a=ia(e.l,t.value,r).value}if(!(t=a.next(0)).done)return t;a=null}}})}))}function ci(e,t,n,r){oi.call(this,t.o.add(r.o),[t,r],{C:!1},r),this.S=e.prefix,this.la=e.namespaceURI,this.Xb=e.localName,this.Gb=null,this.A=n,this.Ba=null,this.pa=t}function li(e,t,n){var r={};ua.call(this,new Ca((r.external=1,r)),[n],{C:!1,R:"unsorted"}),this.S=e.map((function(e){return e.name})),this.A=e.map((function(e){return e.type})),this.s=null,this.K=t,this.l=n}function si(e,t,n){if(oi.call(this,t.o.add(n.o),[t,n],{C:!1,X:n.X,R:n.da,subtree:n.subtree},n),e.prefix||e.namespaceURI)throw Error("Not implemented: let expressions with namespace usage.");this.A=e.prefix,this.S=e.namespaceURI,this.Ba=e.localName,this.la=t,this.pa=null}function pi(e,t){switch(ua.call(this,new Ca({}),[],{C:!0,R:"sorted"},!1,t),t.type){case 5:var n=ne(parseInt(e,10),t.type);break;case 1:n=ne(e,t.type);break;case 4:case 3:n=ne(parseFloat(e),t.type);break;default:throw new TypeError("Type "+t+" not expected in a literal")}this.l=function(){return Ie.m(n)}}function fi(e,t){var n={};ua.call(this,new Ca((n.external=1,n)),e.reduce((function(e,t){return e.concat(t.key,t.value)}),[]),{C:!1},!1,t),this.l=e}function hi(e,t,n){var r={};ua.call(this,new Ca((r.external=1,r)),[],{C:!0},!1,n),this.s=t,this.A=e,this.l=null}A(Mu,ua),Mu.prototype.h=function(e,t){var n=this;return t=t.h,1!==(e=Gu(e.N)).node.nodeType?Ie.empty():(e=Le(t,e,this.s).filter((function(e){return"http://www.w3.org/2000/xmlns/"!==e.node.namespaceURI})).map((function(e){return et(e)})).filter((function(e){return n.l.l(e)})),Ie.create(e))},Mu.prototype.B=function(){return"type-1"},A(Hu,ua),Hu.prototype.h=function(e,t){var n=this,r=t.h,a=Gu(e.N);if(1!==(e=a.node.nodeType)&&9!==e)return Ie.empty();var o=null,u=!1;return Ie.create({next:function(){for(;!u;){if(!o){if(!(o=Ke(r,a,n.l))){u=!0;continue}return ce(et(o))}if(o=_e(r,o,n.l))return ce(et(o));u=!0}return ie}}).filter((function(e){return n.s.l(e)}))},A(Xu,ua),Xu.prototype.h=function(e,t){var n=this;return e=ju(t=t.h,e=Gu(e.N),this.A),this.s||e.next(0),Ie.create(e).filter((function(e){return n.l.l(e)}))},A(Ju,ua),Ju.prototype.h=function(e,t){var n=this;return t=t.h,e=Gu(e.N),Ie.create(Qu(t,e,this.s)).filter((function(e){return n.l.l(e)}))},A(qu,ua),qu.prototype.h=function(e,t){var n=this;return t=t.h,e=Gu(e.N),Ie.create(Ku(t,e,this.s)).filter((function(e){return n.l.l(e)}))},A(_u,ua),_u.prototype.h=function(e,t){return(e=Ve(t=t.h,e=Gu(e.N),this.s))?(e=et(e),this.l.l(e)?Ie.m(e):Ie.empty()):Ie.empty()},A(Wu,ua),Wu.prototype.h=function(e,t){var n=this;return t=t.h,e=Gu(e.N),Ie.create(Vu(t,e,this.s)).filter((function(e){return n.l.l(e)}))},A($u,ua),$u.prototype.h=function(e,t){var n=this;return t=t.h,e=Gu(e.N),Ie.create(Zu(t,e,this.s)).filter((function(e){return n.l.l(e)}))},A(zu,ua),zu.prototype.h=function(e){return Gu(e.N),this.l.l(e.N)?Ie.m(e.N):Ie.empty()},zu.prototype.B=function(){return this.s},A(ei,Ea),ei.prototype.A=function(e,t,n){var r=null,a=n[0](e);return Ie.create({next:function(t){return r||(r=(a.ha()?n[1](e):n[2](e)).value),r.next(t)}})},ei.prototype.v=function(e){if(Ea.prototype.v.call(this,e),this.l.I)throw Vr()},A(ai,Ea),ai.prototype.A=function(e,t,n){var r=this;t=p(n).next().value;try{var a=t(e)}catch(e){throw new ti(this.K,this.l,e)}return Ie.create({next:function(e){try{return a.value.next(e)}catch(e){throw new ti(r.K,r.l,e)}}})},ai.prototype.v=function(e){try{Ea.prototype.v.call(this,e)}catch(e){throw new ti(this.K,this.l,e)}},A(oi,ua),oi.prototype.h=function(e,t){var n=this;return this.K(e,Pn(e),t,(function(r){if(n.l instanceof oi)return ii(n.l,e,r,t);var a=null;return Ie.create({next:function(e){for(;;){if(!a){var o=r.next(0);if(o.done)return ie;a=ia(n.l,o.value,t).value}if(!(o=a.next(e)).done)return o;a=null}}})}))},oi.prototype.s=function(e,t){return ui(this,e,Pn(e),t)},oi.prototype.v=function(e){ua.prototype.v.call(this,e),this.I=this.l.I;for(var t=(e=p(this.ta)).next();!t.done;t=e.next())if((t=t.value)!==this.l&&t.I)throw Vr()},A(ci,oi),ci.prototype.K=function(e,t,n,r){var a=this,o=null,u=null,i=0;return r({next:function(){for(var e={};;){if(!o){var r=t.next(0);if(r.done)return ie;u=r.value,i=0,o=ia(a.pa,u,n).value}if(e.mb=o.next(0),!e.mb.done)return i++,(r={})[a.Gb]=function(e){return function(){return Ie.m(e.mb.value)}}(e),e=r,a.Ba&&(e[a.Ba]=function(){return Ie.m(new he(5,i))}),ce(jt(u,e));o=null,e={mb:e.mb}}}})},ci.prototype.v=function(e){if(this.S&&(this.la=e.aa(this.S),!this.la&&this.S))throw Error("XPST0081: Could not resolve namespace for prefix "+this.S+" in a for expression");if(this.pa.v(e),Go(e),this.Gb=Uo(e,this.la,this.Xb),this.A){if(this.A.prefix&&(this.A.namespaceURI=e.aa(this.A.prefix),!this.A.namespaceURI&&this.A.prefix))throw Error("XPST0081: Could not resolve namespace for prefix "+this.S+" in the positionalVariableBinding in a for expression");this.Ba=Uo(e,this.A.namespaceURI,this.A.localName)}if(this.l.v(e),Ho(e),this.pa.I)throw Vr();this.l.I&&(this.I=!0)},A(li,ua),li.prototype.h=function(e,t){var n=this,r=new Oe({j:this.A,arity:this.A.length,Sa:!0,I:this.l.I,localName:"dynamic-function",namespaceURI:"",i:this.K,value:function(r,a,o){var u=O.apply(3,arguments),i=jt(Pt(e,-1,null,Ie.empty()),n.s.reduce((function(e,t,n){return e[t]=Ce(u[n]),e}),Object.create(null)));return ia(n.l,i,t)}});return Ie.m(r)},li.prototype.v=function(e){if(Go(e),this.s=this.S.map((function(t){return Uo(e,t.namespaceURI,t.localName)})),this.l.v(e),Ho(e),this.l.I)throw Error("Not implemented: inline functions can not yet be updating.")},A(si,oi),si.prototype.K=function(e,t,n,r){var a=this;return r({next:function(){var e=t.next(0);if(e.done)return ie;var r={};return ce(e=jt(e=e.value,(r[a.pa]=Ce(ia(a.la,e,n)),r)))}})},si.prototype.v=function(e){if(this.A&&(this.S=e.aa(this.A),!this.S&&this.A))throw Error("XPST0081: Could not resolve namespace for prefix "+this.A+" using in a for expression");if(this.la.v(e),Go(e),this.pa=Uo(e,this.S,this.Ba),this.l.v(e),Ho(e),this.I=this.l.I,this.la.I)throw Vr()},A(pi,ua),pi.prototype.h=function(){return this.l()},A(fi,ua),fi.prototype.h=function(e,t){var n=this;return tt(this.l.map((function(n){return Vt(ia(n.key,e,t),t).Z({default:function(){throw Error("XPTY0004: A key of a map should be a single atomizable value.")},m:function(e){return e}})})),(function(r){return Ie.m(new at(r.map((function(r,a){return{key:r,value:Ce(ia(n.l[a].value,e,t))}}))))}))},A(hi,ua),hi.prototype.h=function(){var e=new Oe({j:this.l.j,I:this.l.I,arity:this.s,localName:this.l.localName,namespaceURI:this.l.namespaceURI,i:this.l.i,value:this.l.callFunction});return Ie.m(e)},hi.prototype.v=function(e){var t=this.A.namespaceURI,n=this.A.localName,r=this.A.prefix;if(null===t){var a=e.Ua({localName:n,prefix:r},this.s);if(!a)throw Error("XPST0017: The function "+(r?r+":":"")+n+" with arity "+this.s+" could not be resolved. "+fo(n));t=a.namespaceURI,n=a.localName}if(this.l=e.xa(t,n,this.s)||null,!this.l)throw e=this.A,Error("XPST0017: Function "+(e.namespaceURI?"Q{"+e.namespaceURI+"}":e.prefix?e.prefix+":":"")+e.localName+" with arity of "+this.s+" not registered. "+fo(n));ua.prototype.v.call(this,e)};var di={},mi=(di[5]=5,di[27]=5,di[28]=5,di[31]=5,di[32]=5,di[33]=5,di[34]=5,di[30]=5,di[36]=5,di[35]=5,di[38]=5,di[37]=5,di[29]=5,di[4]=4,di[6]=6,di[3]=3,di);function yi(e,t,n){ua.call(this,t.o,[t],{C:!1},!1,n),this.s=t,this.l=e}function gi(e,t){ua.call(this,e.reduce((function(e,t){return e.add(t.o)}),new Ca({})),e,{C:e.every((function(e){return e.C}))},!1,t),this.l=e,this.s=e.reduce((function(e,t){return Uu(e,t.B())}),null)}function vi(e,t){var n,r=e.reduce((function(e,t){return 0<Fa(e,t.o)?e:t.o}),new Ca({}));for(ua.call(this,r,e,{C:e.every((function(e){return e.C}))},!1,t),t=0;t<e.length&&(void 0===n&&(n=e[t].B()),null!==n);++t)if(n!==e[t].B()){n=null;break}this.s=n,this.l=e}function wi(e,t){var n;return Ie.create({next:function(r){for(;;){if(!n){var a=e.value.next(r);if(a.done)return ie;n=_t(a.value,t)}if(!(a=n.value.next(r)).done)return a;n=null}}})}function Ai(e,t){if("eqOp"===e)return function(e,n){return e=(n=t(e,n)).U,n=n.V,e.value.namespaceURI===n.value.namespaceURI&&e.value.localName===n.value.localName};if("neOp"===e)return function(e,n){return e=(n=t(e,n)).U,n=n.V,e.value.namespaceURI!==n.value.namespaceURI||e.value.localName!==n.value.localName};throw Error('XPTY0004: Only the "eq" and "ne" comparison is defined for xs:QName')}function xi(e,t){switch(e){case"eqOp":return function(e,n){return(e=t(e,n)).U.value===e.V.value};case"neOp":return function(e,n){return(e=t(e,n)).U.value!==e.V.value};case"ltOp":return function(e,n){return(e=t(e,n)).U.value<e.V.value};case"leOp":return function(e,n){return(e=t(e,n)).U.value<=e.V.value};case"gtOp":return function(e,n){return(e=t(e,n)).U.value>e.V.value};case"geOp":return function(e,n){return(e=t(e,n)).U.value>=e.V.value}}}function Bi(e,t){switch(e){case"ltOp":return function(e,n){return(e=t(e,n)).U.value.ga<e.V.value.ga};case"leOp":return function(e,n){return e=(n=t(e,n)).U,n=n.V,ut(e.value,n.value)||e.value.ga<n.value.ga};case"gtOp":return function(e,n){return(e=t(e,n)).U.value.ga>e.V.value.ga};case"geOp":return function(e,n){return e=(n=t(e,n)).U,n=n.V,ut(e.value,n.value)||e.value.ga>n.value.ga}}}function bi(e,t){switch(e){case"eqOp":return function(e,n){return ut((e=t(e,n)).U.value,e.V.value)};case"ltOp":return function(e,n){return(e=t(e,n)).U.value.ea<e.V.value.ea};case"leOp":return function(e,n){return e=(n=t(e,n)).U,n=n.V,ut(e.value,n.value)||e.value.ea<n.value.ea};case"gtOp":return function(e,n){return(e=t(e,n)).U.value.ea>e.V.value.ea};case"geOp":return function(e,n){return e=(n=t(e,n)).U,n=n.V,ut(e.value,n.value)||e.value.ea>n.value.ea}}}function Ei(e,t){switch(e){case"eqOp":return function(e,n){return ut((e=t(e,n)).U.value,e.V.value)};case"neOp":return function(e,n){return!ut((e=t(e,n)).U.value,e.V.value)}}}function Ni(e,t){switch(e){case"eqOp":return function(e,n,r){return bt((e=t(e,n)).U.value,e.V.value,Mt(r))};case"neOp":return function(e,n,r){return!bt((e=t(e,n)).U.value,e.V.value,Mt(r))};case"ltOp":return function(e,n,r){return e=t(e,n),r=Mt(r),0>Bt(e.U.value,e.V.value,r)};case"leOp":return function(e,n,r){var a;return e=(n=t(e,n)).U,n=n.V,(a=bt(e.value,n.value,Mt(r)))||(r=Mt(r),a=0>Bt(e.value,n.value,r)),a};case"gtOp":return function(e,n,r){return e=t(e,n),r=Mt(r),0<Bt(e.U.value,e.V.value,r)};case"geOp":return function(e,n,r){var a;return e=(n=t(e,n)).U,n=n.V,(a=bt(e.value,n.value,Mt(r)))||(r=Mt(r),a=0<Bt(e.value,n.value,r)),a}}}function Ti(e,t){switch(e){case"eqOp":return function(e,n,r){return bt((e=t(e,n)).U.value,e.V.value,Mt(r))};case"neOp":return function(e,n,r){return!bt((e=t(e,n)).U.value,e.V.value,Mt(r))}}}function Ii(e,t,n){function r(e,t){return{U:u?u(e):e,V:i?i(t):t}}function a(e){return se(t,e)&&se(n,e)}function o(e){return 0<e.filter((function(e){return se(t,e)})).length&&0<e.filter((function(e){return se(n,e)})).length}var u=null,i=null;if(se(t,19)&&se(n,19)?t=n=1:se(t,19)?(u=function(e){return Hn(e,n)},t=n):se(n,19)&&(i=function(e){return Hn(e,t)},n=t),se(t,23)&&se(n,23))return Ai(e,r);if(a(0)||o([1,47,61])||o([2,47,61])||a(20)||a(22)||a(21)||o([1,20])){var c=xi(e,r);if(void 0!==c)return c}if(a(16)&&void 0!==(c=Bi(e,r))||a(17)&&void 0!==(c=bi(e,r))||a(18)&&void 0!==(c=Ei(e,r)))return c;if((a(9)||a(7)||a(8))&&void 0!==(c=Ni(e,r)))return c;if((a(11)||a(12)||a(13)||a(14)||a(15))&&void 0!==(c=Ti(e,r)))return c;throw Error("XPTY0004: "+e+" not available for "+me[t]+" and "+me[n])}A(yi,ua),yi.prototype.h=function(e,t){var n=this;return Vt(ia(this.s,e,t),t).M((function(e){if(0===e.length)return Ie.empty();var t=e[0];if(n.type)return e="+"===n.l?+t.value:-t.value,0===t.type&&(e=Number.NaN),Ie.m(ne(e,n.type.type));if(1<e.length)throw Error("XPTY0004: The operand to a unary operator must be a sequence with a length less than one");return se(t.type,19)?(t=Hn(t,3).value,Ie.m(ne("+"===n.l?t:-t,3))):se(t.type,2)?"+"===n.l?Ie.m(t):Ie.m(ne(-1*t.value,mi[t.type])):Ie.m(ne(Number.NaN,3))}))},A(gi,ua),gi.prototype.h=function(e,t){var n=this,r=0,a=null,o=!1,u=null;if(null!==e){var i=e.N;null!==i&&se(i.type,53)&&(u=De(i.value))}return Ie.create({next:function(){if(!o){for(;r<n.l.length;){if(!a){var i=n.l[r];if(null!==u&&null!==i.B()&&!u.includes(i.B()))return r++,o=!0,ce(ae);a=ia(i,e,t)}if(!1===a.ha())return o=!0,ce(ae);a=null,r++}return o=!0,ce(re)}return ie}})},gi.prototype.B=function(){return this.s},A(vi,ua),vi.prototype.h=function(e,t){var n=this,r=0,a=null,o=!1,u=null;if(null!==e){var i=e.N;null!==i&&se(i.type,53)&&(u=De(i.value))}return Ie.create({next:function(){if(!o){for(;r<n.l.length;){if(!a){var i=n.l[r];if(null!==u&&null!==i.B()&&!u.includes(i.B())){r++;continue}a=ia(i,e,t)}if(!0===a.ha())return o=!0,ce(re);a=null,r++}return o=!0,ce(ae)}return ie}})},vi.prototype.B=function(){return this.s};var Ci=Object.create(null);function Fi(e,t,n){var r=t+"~"+n+"~"+e,a=Ci[r];return a||(a=Ci[r]=Ii(e,t,n)),a}function Oi(e,t,n){ua.call(this,t.o.add(n.o),[t,n],{C:!1}),this.l=t,this.A=n,this.s=e}A(Oi,ua),Oi.prototype.h=function(e,t){var n=this,r=ia(this.l,e,t),a=ia(this.A,e,t),o=wi(r,t),u=wi(a,t);return o.Z({empty:function(){return Ie.empty()},m:function(){return u.Z({empty:function(){return Ie.empty()},m:function(){var t=o.first(),r=u.first();return Fi(n.s,t.type,r.type)(t,r,e)?Ie.ba():Ie.W()},multiple:function(){throw Error("XPTY0004: Sequences to compare are not singleton.")}})},multiple:function(){throw Error("XPTY0004: Sequences to compare are not singleton.")}})};var Si={},Gi=(Si.equalOp="eqOp",Si.notEqualOp="neOp",Si.lessThanOrEqualOp="leOp",Si.lessThanOp="ltOp",Si.greaterThanOrEqualOp="geOp",Si.greaterThanOp="gtOp",Si);function Di(e,t,n,r){return e=Gi[e],n.M((function(n){return t.filter((function(t){for(var a=0,o=n.length;a<o;++a){var u=n[a],i=void 0,c=void 0,l=t.type,s=u.type;if((se(l,19)||se(s,19))&&(se(l,2)?i=3:se(s,2)?c=3:se(l,17)?i=17:se(s,17)?c=17:se(l,16)?i=16:se(s,16)?c=16:se(l,19)?c=s:se(s,19)&&(i=l)),i=(c=p([c,i])).next().value,c=c.next().value,i?t=Hn(t,i):c&&(u=Hn(u,c)),Fi(e,t.type,u.type)(t,u,r))return!0}return!1})).Z({default:function(){return Ie.ba()},empty:function(){return Ie.W()}})}))}function Ri(e,t,n){ua.call(this,t.o.add(n.o),[t,n],{C:!1}),this.l=t,this.A=n,this.s=e}function ki(e,t,n,r){if(!se(n,53)||!se(r,53))throw Error("XPTY0004: Sequences to compare are not nodes");switch(e){case"isOp":return Ui(n,r);case"nodeBeforeOp":return t?function(e,n){return 0>qn(t,e.first(),n.first())}:void 0;case"nodeAfterOp":return t?function(e,n){return 0<qn(t,e.first(),n.first())}:void 0;default:throw Error("Unexpected operator")}}function Ui(e,t){return e!==t||47!==e&&53!==e&&54!==e&&55!==e&&56!==e&&57!==e&&58!==e?function(){return!1}:function(e,t){return Xn(e.first().value,t.first().value)}}function Mi(e,t,n){ua.call(this,t.o.add(n.o),[t,n],{C:!1}),this.l=t,this.A=n,this.s=e}function Hi(e,t,n,r){return n.M((function(n){if(n.some((function(e){return!se(e.type,53)})))throw Error("XPTY0004: Sequences given to "+e+" should only contain nodes.");return"sorted"===r?Ie.create(n):"reverse-sorted"===r?Ie.create(n.reverse()):Ie.create(_n(t,n))}))}function Pi(e,t,n,r){ua.call(this,0<Fa(t.o,n.o)?t.o:n.o,[t,n],{C:t.C&&n.C},!1,r),this.l=e,this.s=t,this.A=n}function ji(e,t){Ea.call(this,e.reduce((function(e,t){return e.add(t.o)}),new Ca({})),e,{R:"unsorted",C:e.every((function(e){return e.C}))},t)}function Xi(e,t,n){ua.call(this,new Ca({}).add(e.o),[e,t],{C:e.C&&t.C},!1,n),this.l=e,this.s=t}function Li(e,t,n){if(ua.call(this,e.o,[e],{C:!1}),this.l=ve(t.prefix?t.prefix+":"+t.localName:t.localName),46===this.l||45===this.l||44===this.l)throw Error("XPST0080: Casting to xs:anyAtomicType, xs:anySimpleType or xs:NOTATION is not permitted.");if(t.namespaceURI)throw Error("Not implemented: castable as expressions with a namespace URI.");this.A=e,this.s=n}function Yi(e,t,n){if(ua.call(this,e.o,[e],{C:!1}),this.l=ve(t.prefix?t.prefix+":"+t.localName:t.localName),46===this.l||45===this.l||44===this.l)throw Error("XPST0080: Casting to xs:anyAtomicType, xs:anySimpleType or xs:NOTATION is not permitted.");if(t.namespaceURI)throw Error("Not implemented: casting expressions with a namespace URI.");this.A=e,this.s=n}function Qi(e,t){var n=e.value,r=null,a=!1;return Ie.create({next:function(){for(;!a;){if(!r){var e=n.next(0);if(e.done)return a=!0,ce(re);r=t(e.value)}if(e=r.ha(),r=null,!1===e)return a=!0,ce(ae)}return ie}})}function Ji(e,t,n,r){ua.call(this,e.o,[e],{C:!1},!1,r),this.A=e,this.s=t,this.l=n}function Ki(e,t){return!(null===e||null===t||!se(e.type,53)||!se(t.type,53))&&Xn(e.value,t.value)}function qi(e){var t=e.next(0);if(t.done)return Ie.empty();var n=null,r=null;return Ie.create({next:function(a){if(t.done)return ie;n||(n=t.value.value);do{var o=n.next(a);if(o.done){if((t=e.next(0)).done)return o;n=t.value.value}}while(o.done||Ki(o.value,r));return r=o.value,o}})}function _i(e,t){var n=[];!function(){for(var e=t.next(0),r={};!e.done;)r.ob=e.value.value,(e={current:r.ob.next(0),next:function(e){return function(t){return e.ob.next(t)}}(r)}).current.done||n.push(e),e=t.next(0),r={ob:r.ob}}();var r=null,a=!1,o={};return Ie.create((o[Symbol.iterator]=function(){return this},o.next=function(){a||(a=!0,n.every((function(e){return se(e.current.value.type,53)}))&&n.sort((function(t,n){return qn(e,t.current.value,n.current.value)})));do{if(!n.length)return ie;var t=n.shift(),o=t.current;if(t.current=t.next(0),!se(o.value.type,53))return o;if(!t.current.done){for(var u=0,i=n.length-1,c=0;u<=i;){c=Math.floor((u+i)/2);var l=qn(e,t.current.value,n[c].current.value);if(0===l){u=c;break}0<l?u=c+1:i=c-1}n.splice(u,0,t)}}while(Ki(o.value,r));return r=o.value,o},o))}function Vi(e,t){var n=e.reduce((function(e,t){return 0<Fa(e,t.o)?e:t.o}),new Ca({}));ua.call(this,n,e,{C:e.every((function(e){return e.C}))},!1,t),this.l=e}function Wi(e){return e.every((function(e){return null===e||se(e.type,5)||se(e.type,4)}))||null!==e.map((function(e){return e?Wt(e.type):null})).reduce((function(e,t){return null===t||t===e?e:null}))?e:e.every((function(e){return null===e||se(e.type,1)||se(e.type,20)}))?e.map((function(e){return e?Hn(e,1):null})):e.every((function(e){return null===e||se(e.type,4)||se(e.type,6)}))?e.map((function(e){return e?Hn(e,6):e})):e.every((function(e){return null===e||se(e.type,4)||se(e.type,6)||se(e.type,3)}))?e.map((function(e){return e?Hn(e,3):e})):null}function Zi(e){return(e=e.find((function(e){return!!e})))?Wt(e.type):null}function $i(e,t){var n=new Ca({});oi.call(this,n,[t].concat(h(e.map((function(e){return e.ca})))),{C:!1,X:!1,R:"unsorted",subtree:!1},t),this.A=e}function zi(e){ua.call(this,e?e.o:new Ca({}),e?[e]:[],{R:"sorted",subtree:!1,X:!1,C:!1}),this.l=e}function ec(e){ua.call(this,new Ca({}),[],{R:"sorted"},!1,e)}function tc(e,t){var n=!1,r=!1;if(t.forEach((function(e){se(e.type,53)?n=!0:r=!0})),r&&n)throw Error("XPTY0018: The path operator should either return nodes or non-nodes. Mixed sequences are not allowed.");return n?_n(e,t):t}function nc(e,t){var n=e.every((function(e){return e.X})),r=e.every((function(e){return e.subtree}));ua.call(this,e.reduce((function(e,t){return e.add(t.o)}),new Ca({})),e,{C:!1,X:n,R:t?"sorted":"unsorted",subtree:r}),this.l=e,this.s=t}function rc(e,t){ua.call(this,e.o.add(t.o),[e,t],{C:e.C&&t.C,X:e.X,R:e.da,subtree:e.subtree}),this.s=e,this.l=t}function ac(e,t,n){if(n=[n],se(e.type,62))if("*"===t)n.push.apply(n,h(e.P.map((function(e){return e()}))));else{if(!se(t.type,5))throw wo("The key specifier is not an integer.");var r=t.value;if(e.P.length<r||0>=r)throw Error("FOAY0001: Array index out of bounds");n.push(e.P[r-1]())}else{if(!se(e.type,61))throw wo("The provided context item is not a map or an array.");"*"===t?n.push.apply(n,h(e.h.map((function(e){return e.value()})))):(e=e.h.find((function(e){return nt(e.key,t)})))&&n.push(e.value())}return Lt(n)}function oc(e,t,n,r,a){return"*"===t?ac(e,t,n):Lt([n,t=Ce(t=ia(t,r,a))().M((function(t){return t.reduce((function(t,n){return ac(e,n,t)}),new fe)}))])}function uc(e,t){ua.call(this,e.o,[e].concat("*"===t?[]:[t]),{C:e.C,R:e.da,subtree:e.subtree}),this.l=e,this.s=t}function ic(e,t){var n={};ua.call(this,new Ca((n.external=1,n)),"*"===e?[]:[e],{C:!1},!1,t),this.l=e}function cc(e,t,n,r){var a=t.map((function(e){return e.jb}));t=t.map((function(e){return e.name}));var o=a.reduce((function(e,t){return e.add(t.o)}),n.o);ua.call(this,o,a.concat(n),{C:!1},!1,r),this.s=e,this.A=t,this.K=a,this.S=n,this.l=null}function lc(e){ua.call(this,e,[],{C:!1})}function sc(e){var t={};lc.call(this,new Ca((t.nodeType=1,t))),this.s=e}function pc(e,t){t=void 0===t?{kind:null}:t;var n=e.prefix,r=e.namespaceURI,a={};"*"!==(e=e.localName)&&(a.nodeName=1),a.nodeType=1,lc.call(this,new Ca(a)),this.s=e,this.K=r,this.A=n,this.S=t.kind}function fc(e){var t={};lc.call(this,new Ca((t.nodeName=1,t))),this.s=e}function hc(e){lc.call(this,new Ca({})),this.s=e}function dc(e,t,n){ua.call(this,new Ca({}),[],{C:!1,R:"unsorted"}),this.A=n,this.s=t,this.K=e,this.l=null}function mc(e,t){var n=new Ca({});oi.call(this,n,[e,t],{C:!1,X:!1,R:"unsorted",subtree:!1},t),this.A=e}function yc(e){this.type=e}function gc(e){this.type="delete",this.target=e}function vc(e,t,n){this.type=n,this.target=e,this.content=t}function wc(e,t){vc.call(this,e,t,"insertAfter")}function Ac(e,t){this.type="insertAttributes",this.target=e,this.content=t}function xc(e,t){vc.call(this,e,t,"insertBefore")}function Bc(e,t){vc.call(this,e,t,"insertIntoAsFirst")}function bc(e,t){vc.call(this,e,t,"insertIntoAsLast")}function Ec(e,t){vc.call(this,e,t,"insertInto")}function Nc(e,t){this.type="rename",this.target=e,this.o=t.Ca?t:new Fe(t.prefix,t.namespaceURI,t.localName)}function Tc(e,t){this.type="replaceElementContent",this.target=e,this.text=t}function Ic(e,t){this.type="replaceNode",this.target=e,this.o=t}function Cc(e,t){this.type="replaceValue",this.target=e,this.o=t}function Fc(e,t){return new Ic(e,t)}function Oc(e){xa.call(this,new Ca({}),[e],{C:!1,R:"unsorted"}),this.l=e}function Sc(e,t,n,r,a,o){var u=t.h;return e.reduce((function e(t,n){return se(n.type,62)?(n.P.forEach((function(n){return n().O().forEach((function(n){return e(t,n)}))})),t):(t.push(n),t)}),[]).forEach((function(e,i,c){if(se(e.type,47)){if(a)throw o(e.value,u);n.push(e.value.node)}else if(se(e.type,46)||se(e.type,53)&&3===e.value.node.nodeType){var l=se(e.type,46)?Hn(_t(e,t).first(),1).value:Je(u,e.value);0!==i&&se(c[i-1].type,46)&&se(e.type,46)?(r.push({data:" "+l,Ta:!0,nodeType:3}),a=!0):l&&(r.push({data:""+l,Ta:!0,nodeType:3}),a=!0)}else if(se(e.type,55)){var s=[];Qe(u,e.value).forEach((function(e){return s.push(et(e))})),a=Sc(s,t,n,r,a,o)}else{if(!se(e.type,53)){if(se(e.type,60))throw Kt(e.type);throw Error("Atomizing "+e.type+" is not implemented.")}r.push(e.value.node),a=!0}})),a}function Gc(e,t,n){var r=[],a=[],o=!1;return e.forEach((function(e){o=Sc(e,t,r,a,o,n)})),{attributes:r,Xa:a}}function Dc(e,t,n,r,a){var o=[];switch(e){case 4:r.length&&o.push(new Ac(t,r)),a.length&&o.push(new Bc(t,a));break;case 5:r.length&&o.push(new Ac(t,r)),a.length&&o.push(new bc(t,a));break;case 3:r.length&&o.push(new Ac(t,r)),a.length&&o.push(new Ec(t,a));break;case 2:r.length&&o.push(new Ac(n,r)),a.length&&o.push(new xc(t,a));break;case 1:r.length&&o.push(new Ac(n,r)),a.length&&o.push(new wc(t,a))}return o}function Rc(e,t,n){xa.call(this,new Ca({}),[e,n],{C:!1,R:"unsorted"}),this.K=e,this.l=t,this.A=n}function kc(){return Jt("Casting not supported from given type to a single xs:string or xs:untypedAtomic or any of its derived types.")}A(Ri,ua),Ri.prototype.h=function(e,t){var n=this,r=ia(this.l,e,t),a=ia(this.A,e,t);return r.Z({empty:function(){return Ie.W()},default:function(){return a.Z({empty:function(){return Ie.W()},default:function(){var o=wi(r,t),u=wi(a,t);return Di(n.s,o,u,e)}})}})},A(Mi,ua),Mi.prototype.h=function(e,t){var n=this,r=ia(this.l,e,t),a=ia(this.A,e,t);return r.Z({empty:function(){return Ie.empty()},multiple:function(){throw Error("XPTY0004: Sequences to compare are not singleton")},m:function(){return a.Z({empty:function(){return Ie.empty()},multiple:function(){throw Error("XPTY0004: Sequences to compare are not singleton")},m:function(){var o=r.first(),u=a.first();return ki(n.s,t.h,o.type,u.type)(r,a,e)?Ie.ba():Ie.W()}})}})},A(Pi,ua),Pi.prototype.h=function(e,t){var n=this,r=Hi(this.l,t.h,ia(this.s,e,t),this.s.da);e=Hi(this.l,t.h,ia(this.A,e,t),this.A.da);var a=r.value,o=e.value,u=null,i=null,c=!1,l=!1;return Ie.create({next:function(){if(c)return ie;for(;!l;){if(!u){var e=a.next(0);if(e.done)return c=!0,ie;u=e.value}if(!i){if((e=o.next(0)).done){l=!0;break}i=e.value}if(Xn(u.value,i.value)){if(e=ce(u),i=u=null,"intersectOp"===n.l)return e}else if(0>qn(t.h,u,i)){if(e=ce(u),u=null,"exceptOp"===n.l)return e}else i=null}return"exceptOp"===n.l?null!==u?(e=ce(u),u=null,e):a.next(0):(c=!0,ie)}})},A(ji,Ea),ji.prototype.A=function(e,t,n){return n.length?Lt(n.map((function(t){return t(e)}))):Ie.empty()},A(Xi,ua),Xi.prototype.h=function(e,t){var n=this,r=kt(e,ia(this.l,e,t)),a=null,o=null,u=!1;return Ie.create({next:function(e){for(;!u;){if(!a&&(a=r.next(e)).done)return u=!0,ie;o||(o=ia(n.s,a.value,t));var i=o.value.next(e);if(!i.done)return i;a=o=null}}})},A(Li,ua),Li.prototype.h=function(e,t){var n=this,r=Vt(ia(this.A,e,t),t);return r.Z({empty:function(){return n.s?Ie.ba():Ie.W()},m:function(){return r.map((function(e){return Mn(e,n.l).u?re:ae}))},multiple:function(){return Ie.W()}})},A(Yi,ua),Yi.prototype.h=function(e,t){var n=this,r=Vt(ia(this.A,e,t),t);return r.Z({empty:function(){if(!n.s)throw Error("XPTY0004: Sequence to cast is empty while target type is singleton.");return Ie.empty()},m:function(){return r.map((function(e){return Hn(e,n.l)}))},multiple:function(){throw Error("XPTY0004: Sequence to cast is not singleton or empty.")}})},A(Ji,ua),Ji.prototype.h=function(e,t){var n=this,r=ia(this.A,e,t);return r.Z({empty:function(){return"?"===n.l||"*"===n.l?Ie.ba():Ie.W()},multiple:function(){return"+"===n.l||"*"===n.l?Qi(r,(function(r){var a=Ie.m(r);return r=Pt(e,0,r,a),ia(n.s,r,t)})):Ie.W()},m:function(){return Qi(r,(function(r){var a=Ie.m(r);return r=Pt(e,0,r,a),ia(n.s,r,t)}))}})},A(Vi,ua),Vi.prototype.h=function(e,t){var n=this;if(this.l.every((function(e){return"sorted"===e.da}))){var r=0;return _i(t.h,{next:function(){return r>=n.l.length?ie:ce(ia(n.l[r++],e,t))}}).map((function(e){if(!se(e.type,53))throw Error("XPTY0004: The sequences to union are not of type node()*");return e}))}return Lt(this.l.map((function(n){return ia(n,e,t)}))).M((function(e){if(e.some((function(e){return!se(e.type,53)})))throw Error("XPTY0004: The sequences to union are not of type node()*");return e=_n(t.h,e),Ie.create(e)}))},A($i,oi),$i.prototype.K=function(e,t,n,r){if(this.A[1])throw Error("More than one order spec is not supported for the order by clause.");var a,o,u=[],i=!1,c=null,l=this.A[0];return Ie.create({next:function(){if(!i){for(var s=t.next(0);!s.done;)u.push(s.value),s=t.next(0);if((s=u.map((function(e){return l.ca.h(e,n)})).map((function(e){return Vt(e,n)}))).find((function(e){return!e.G()&&!e.wa()})))throw wo("Order by only accepts empty or singleton sequences");if(Zi(a=(a=s.map((function(e){return e.first()}))).map((function(e){return null===e?e:se(19,e.type)?Hn(e,1):e})))&&!(a=Wi(a)))throw wo("Could not cast values");s=a.length,o=a.map((function(e,t){return t}));for(var f=0;f<s;f++)if(f+1!==s)for(var h=f;0<=h;h--){var d=h,m=h+1;if(m!==s){var y=a[o[d]],g=a[o[m]];if(null!==g||null!==y){if(l.lc){if(null===y)continue;if(null===g&&null!==y){y=p([o[m],o[d]]),o[d]=y.next().value,o[m]=y.next().value;continue}if(isNaN(g.value)&&null!==y&&!isNaN(y.value)){y=p([o[m],o[d]]),o[d]=y.next().value,o[m]=y.next().value;continue}}else{if(null===g)continue;if(null===y&&null!==g){y=p([o[m],o[d]]),o[d]=y.next().value,o[m]=y.next().value;continue}if(isNaN(y.value)&&null!==g&&!isNaN(g.value)){y=p([o[m],o[d]]),o[d]=y.next().value,o[m]=y.next().value;continue}}Fi("gtOp",y.type,g.type)(y,g,e)&&(y=p([o[m],o[d]]),o[d]=y.next().value,o[m]=y.next().value)}}}var v=l.Kb?0:a.length-1;c=r({next:function(){return l.Kb?v>=a.length?ie:ce(u[o[v++]]):0>v?ie:ce(u[o[v--]])}}).value,i=!0}return c.next(0)}})},A(zi,ua),zi.prototype.h=function(e,t){if(null===e.N)throw Qt("context is absent, it needs to be present to use paths.");for(var n=t.h,r=e.N.value;9!==r.node.nodeType;)if(null===(r=Ve(n,r)))throw Error("XPDY0050: the root node of the context node is not a document node.");return n=Ie.m(et(r)),this.l?ia(this.l,Pt(e,0,n.first(),n),t):n},A(ec,ua),ec.prototype.h=function(e){if(null===e.N)throw Qt('context is absent, it needs to be present to use the "." operator');return Ie.m(e.N)},A(nc,ua),nc.prototype.h=function(e,t){var n=this,r=!0;return this.l.reduce((function(a,o,u){var i=null===a?Pn(e):kt(e,a);if(a={next:function(e){if((e=i.next(e)).done)return ie;if(null!==e.value.N&&!se(e.value.N.type,53)&&0<u)throw Error("XPTY0019: The result of E1 in a path expression E1/E2 should not evaluate to a sequence of nodes.");return ce(ia(o,e.value,t))}},n.s)switch(o.da){case"reverse-sorted":var c=a;a={next:function(e){return(e=c.next(e)).done?e:ce(e.value.M((function(e){return Ie.create(e.reverse())})))}};case"sorted":if(o.subtree&&r){var l=qi(a);break}l=_i(t.h,a);break;case"unsorted":return qi(a).M((function(e){return Ie.create(tc(t.h,e))}))}else l=qi(a);return r=r&&o.X,l}),null)},nc.prototype.B=function(){return this.l[0].B()},A(rc,ua),rc.prototype.h=function(e,t){var n=this,r=ia(this.s,e,t);if(this.l.C){var a=ia(this.l,e,t);if(a.G())return a;var o=a.first();if(se(o.type,2)){var u=o.value;if(!Number.isInteger(u))return Ie.empty();var i=r.value,c=!1;return Ie.create({next:function(){if(!c){for(var e=i.next(0);!e.done;e=i.next(0))if(1==u--)return c=!0,e;c=!0}return ie}})}return a.ha()?r:Ie.empty()}var l=r.value,s=null,p=0,f=null;return Ie.create({next:function(a){for(var o=!1;!(s&&s.done||(s||(s=l.next(o?0:a),o=!0),s.done));){f||(f=ia(n.l,Pt(e,p,s.value,r),t));var u=f.first();u=null!==u&&(se(u.type,2)?u.value===p+1:f.ha()),f=null;var i=s.value;if(s=null,p++,u)return ce(i)}return s}})},rc.prototype.B=function(){return this.s.B()},A(uc,ua),uc.prototype.h=function(e,t){var n=this;return ia(this.l,e,t).M((function(r){return r.reduce((function(r,a){return oc(a,n.s,r,e,t)}),new fe)}))},uc.prototype.B=function(){return this.l.B()},A(ic,ua),ic.prototype.h=function(e,t){return oc(e.N,this.l,new fe,e,t)},A(cc,ua),cc.prototype.h=function(e,t){var n=this,r=e,a=this.l.map((function(a,o){var u=ia(n.K[o],r,t).O();return r=jt(e,((o={})[a]=function(){return Ie.create(u)},o)),u}));if(a.some((function(e){return 0===e.length})))return"every"===this.s?Ie.ba():Ie.W();var o=Array(a.length).fill(0);o[0]=-1;for(var u=!0;u;){u=!1;for(var i=0,c=o.length;i<c;++i){var l=a[i];if(!(++o[i]>l.length-1)){for(u=Object.create(null),i={},c=0;c<o.length;i={xb:i.xb},c++)i.xb=a[c][o[c]],u[this.l[c]]=function(e){return function(){return Ie.m(e.xb)}}(i);if(u=jt(e,u),(u=ia(this.S,u,t)).ha()&&"some"===this.s)return Ie.ba();if(!u.ha()&&"every"===this.s)return Ie.W();u=!0;break}o[i]=0}}return"every"===this.s?Ie.ba():Ie.W()},cc.prototype.v=function(e){this.l=[];for(var t=0,n=this.A.length;t<n;++t){this.K[t].v(e),Go(e);var r=this.A[t],a=r.prefix?e.aa(r.prefix):null;r=Uo(e,a,r.localName),this.l[t]=r}for(this.S.v(e),t=0,n=this.A.length;t<n;++t)Ho(e)},A(lc,ua),lc.prototype.h=function(e){return this.l(e.N)?Ie.ba():Ie.W()},A(sc,lc),sc.prototype.l=function(e){return!!se(e.type,53)&&(e=e.value.node.nodeType,3===this.s&&4===e||this.s===e)},sc.prototype.B=function(){return"type-"+this.s},A(pc,lc),pc.prototype.l=function(e){var t=se(e.type,54),n=se(e.type,47);return!(!t&&!n||(e=e.value,null!==this.S&&(1===this.S&&!t||2===this.S&&!n)||(null!==this.A||""===this.K||"*"!==this.s)&&("*"===this.A?"*"!==this.s&&this.s!==e.node.localName:"*"!==this.s&&this.s!==e.node.localName||(e.node.namespaceURI||null)!==((""===this.A?t?this.K:null:this.K)||null))))},pc.prototype.B=function(){return"*"===this.s?null===this.S?"type-1-or-type-2":"type-"+this.S:"name-"+this.s},pc.prototype.v=function(e){if(null===this.K&&"*"!==this.A&&(this.K=e.aa(this.A||"")||null,!this.K&&this.A))throw Error("XPST0081: The prefix "+this.A+" could not be resolved.")},A(fc,lc),fc.prototype.l=function(e){return se(e.type,57)&&e.value.node.target===this.s},fc.prototype.B=function(){return"type-7"},A(hc,lc),hc.prototype.l=function(e){return se(e.type,ve(this.s.prefix?this.s.prefix+":"+this.s.localName:this.s.localName))},A(dc,ua),dc.prototype.h=function(e,t){if(!e.Aa[this.l]){if(this.S)return this.S(e,t);throw Error("XQDY0054: The variable "+this.A+" is declared but not in scope.")}return e.Aa[this.l]()},dc.prototype.v=function(e){if(null===this.s&&this.K&&(this.s=e.aa(this.K)),this.l=e.ib(this.s||"",this.A),!this.l)throw Error("XPST0008, The variable "+this.A+" is not in scope.");(e=e.Ia[this.l])&&(this.S=e)},A(mc,oi),mc.prototype.K=function(e,t,n,r){var a=this,o=null,u=null;return r({next:function(){for(;;){if(!u){var e=t.next(0);if(e.done)return ie;o=e.value,u=ia(a.A,o,n)}e=u.ha();var r=o;if(u=o=null,e)return ce(r)}}})},A(gc,yc),gc.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t},A(vc,yc),vc.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t.content=this.content.map((function(t){return no(t,e,!0)})),t},A(wc,vc),A(Ac,yc),Ac.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t.content=this.content.map((function(t){return no(t,e,!0)})),t},A(xc,vc),A(Bc,vc),A(bc,vc),A(Ec,vc),A(Nc,yc),Nc.prototype.h=function(e){var t={},n={};return n.type=this.type,n.target=no(this.target,e,!1),n.newName=(t.prefix=this.o.prefix,t.namespaceURI=this.o.namespaceURI,t.localName=this.o.localName,t),n},A(Tc,yc),Tc.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t.text=this.text?no(this.text,e,!0):null,t},A(Ic,yc),Ic.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t.replacement=this.o.map((function(t){return no(t,e,!0)})),t},A(Cc,yc),Cc.prototype.h=function(e){var t={};return t.type=this.type,t.target=no(this.target,e,!1),t["string-value"]=this.o,t},A(Oc,xa),Oc.prototype.s=function(e,t){var n,r,a=Ba(this.l)(e,t),o=t.h;return{next:function(){if(!n){var e=a.next(0);if(e.value.J.some((function(e){return!se(e.type,53)})))throw Error("XUTY0007: The target of a delete expression must be a sequence of zero or more nodes.");n=e.value.J,r=e.value.fa}return ce({fa:Aa((n=n.filter((function(e){return Ve(o,e.value)}))).map((function(e){return new gc(e.value)})),r),J:[]})}}},A(Rc,xa),Rc.prototype.s=function(e,t){var n,r,a,o,u,i,c=this,l=Ba(this.K)(e,t),s=Ba(this.A)(e,t),p=t.h;return{next:function(){if(!n){var e=l.next(0),f=Gc([e.value.J],t,Wr);n=f.attributes.map((function(e){return{node:e,F:null}})),r=f.Xa.map((function(e){return{node:e,F:null}})),a=e.value.fa}if(!o){if(0===(e=s.next(0)).value.J.length)throw oa();if(3<=c.l){if(1!==e.value.J.length)throw Zr();if(!se(e.value.J[0].type,54)&&!se(e.value.J[0].type,55))throw Zr()}else{if(1!==e.value.J.length)throw $r();if(!(se(e.value.J[0].type,54)||se(e.value.J[0].type,56)||se(e.value.J[0].type,58)||se(e.value.J[0].type,57)))throw $r();if(null===(i=Ve(p,e.value.J[0].value,null)))throw Error("XUDY0029: The target "+e.value.J[0].value.outerHTML+" for inserting a node before or after must have a parent.")}o=e.value.J[0],u=e.value.fa}if(n.length){if(3<=c.l){if(!se(o.type,54))throw Error("XUTY0022: An insert expression specifies the insertion of an attribute node into a document node.")}else if(1!==i.node.nodeType)throw Error("XUDY0030: An insert expression specifies the insertion of an attribute node before or after a child of a document node.");n.reduce((function(e,t){var n=t.node.prefix||"",r=t.node.prefix||"",a=t.node.namespaceURI,u=r?o.value.node.lookupNamespaceURI(r):null;if(u&&u!==a)throw ra(a);if((r=e[r])&&a!==r)throw aa(a);return e[n]=t.node.namespaceURI,e}),{})}return ce({J:[],fa:Aa(Dc(c.l,o.value,i||null,n,r),a,u)})}}};var Uc=/([A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])/,Mc=new RegExp(Uc.source+new RegExp("("+Uc.source+"|[-.0-9·̀-ͯ‿⁀])").source+"*","g");function Hc(e){return!!(e=e.match(Mc))&&1===e.length}function Pc(e,t){return Vt(t,e).Z({m:function(e){if(se((e=e.first()).type,1)||se(e.type,19)){if(!Hc(e.value))throw Error('XQDY0041: The value "'+e.value+'" of a name expressions cannot be converted to a NCName.');return Ie.m(e)}throw kc()},default:function(){throw kc()}}).value}function jc(e,t,n){return Vt(n,t).Z({m:function(t){if(se((t=t.first()).type,23))return Ie.m(t);if(se(t.type,1)||se(t.type,19)){if(1===(t=t.value.split(":")).length)t=t[0];else{var n=t[0],r=e.aa(n);t=t[1]}if(!Hc(t)||n&&!Hc(n))throw To(n?n+":"+t:t);if(n&&!r)throw To(n+":"+t);return Ie.m({type:23,value:new Fe(n,r,t)})}throw kc()},default:function(){throw kc()}}).value}function Xc(e,t){xa.call(this,new Ca({}),[e,t],{C:!1,R:"unsorted"}),this.A=e,this.K=t,this.l=void 0}function Lc(e,t,n){var r,a,o;return{next:function(){if(!r){var u=n.next(0),i=Gc([u.value.J],e,aa);r={attributes:i.attributes.map((function(e){return{node:e,F:null}})),Xa:i.Xa.map((function(e){return{node:e,F:null}}))},a=u.value.fa}if(0===(i=t.next(0)).value.J.length)throw oa();if(1!==i.value.J.length)throw zr();if(!(se(i.value.J[0].type,54)||se(i.value.J[0].type,47)||se(i.value.J[0].type,56)||se(i.value.J[0].type,58)||se(i.value.J[0].type,57)))throw zr();if(null===(o=Ve(e.h,i.value.J[0].value,null)))throw Error("XUDY0009: The target "+i.value.J[0].value.outerHTML+" for replacing a node must have a parent.");if(u=i.value.J[0],i=i.value.fa,se(u.type,47)){if(r.Xa.length)throw Error("XUTY0011: When replacing an attribute the new value must be zero or more attribute nodes.");r.attributes.reduce((function(e,t){var n=t.node.prefix||"";t=t.node.namespaceURI;var r=o.node.lookupNamespaceURI(n);if(r&&r!==t)throw ra(t);if((r=e[n])&&t!==r)throw aa(t);return e[n]=t,e}),{})}else if(r.attributes.length)throw Error("XUTY0010: When replacing an an element, text, comment, or processing instruction node the new value must be a single node.");return ce({J:[],fa:Aa([Fc(u.value,[].concat(r.attributes,r.Xa))],a,i)})}}}function Yc(e,t,n){var r,a,o,u,i=!1;return{next:function(){if(i)return ie;if(!o){var c=n.next(0),l=Vt(Ie.create(c.value.J),e).map((function(e){return Hn(e,1)})).O().map((function(e){return e.value})).join(" ");o=0===l.length?null:{node:e.o.createTextNode(l),F:null},u=c.value.fa}if(!r){if(0===(c=t.next(0)).value.J.length)throw oa();if(1!==c.value.J.length)throw zr();if(!(se(c.value.J[0].type,54)||se(c.value.J[0].type,47)||se(c.value.J[0].type,56)||se(c.value.J[0].type,58)||se(c.value.J[0].type,57)))throw zr();r=c.value.J[0],a=c.value.fa}if(se(r.type,54))return i=!0,ce({J:[],fa:Aa([new Tc(r.value,o)],u,a)});if(se(r.type,47)||se(r.type,56)||se(r.type,58)||se(r.type,57)){if(c=o?Je(e.h,o):"",se(r.type,58)&&(c.includes("--")||c.endsWith("-")))throw Error('XQDY0072: The content "'+c+'" for a comment node contains two adjacent hyphens or ends with a hyphen.');if(se(r.type,57)&&c.includes("?>"))throw Error('XQDY0026: The content "'+c+'" for a processing instruction node contains "?>".');return i=!0,ce({J:[],fa:Aa([new Cc(r.value,c)],u,a)})}}}}function Qc(e,t,n){xa.call(this,new Ca({}),[t,n],{C:!1,R:"unsorted"}),this.K=e,this.l=t,this.A=n}function Jc(e){switch(e.type){case"delete":return new gc({node:e.target,F:null});case"insertAfter":return new wc({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"insertBefore":return new xc({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"insertInto":return new Ec({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"insertIntoAsFirst":return new Bc({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"insertIntoAsLast":return new bc({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"insertAttributes":return new Ac({node:e.target,F:null},e.content.map((function(e){return{node:e,F:null}})));case"rename":return new Nc({node:e.target,F:null},e.newName);case"replaceNode":return new Ic({node:e.target,F:null},e.replacement.map((function(e){return{node:e,F:null}})));case"replaceValue":return new Cc({node:e.target,F:null},e["string-value"]);case"replaceElementContent":return new Tc({node:e.target,F:null},e.text?{node:e.text,F:null}:null);default:throw Error('Unexpected type "'+e.type+'" when parsing a transferable pending update.')}}function Kc(e,t,n){if(t.find((function(t){return Xn(t,e)})))return!0;var r=Ve(n,e);return!!r&&Kc(r,t,n)}function qc(e,t,n){xa.call(this,new Ca({}),e.reduce((function(e,t){return e.push(t.jb),e}),[t,n]),{C:!1,R:"unsorted"}),this.l=e,this.K=t,this.A=n,this.I=null}function _c(e,t){return{node:{nodeType:2,Ta:!0,nodeName:e.Ca(),namespaceURI:e.namespaceURI,prefix:e.prefix,localName:e.localName,name:e.Ca(),value:t},F:null}}function Vc(e,t){var n=t.wb||[];n=n.concat(e.Oa||[]),ua.call(this,new Ca({}),n,{C:!1,R:"unsorted"}),e.Oa?this.s=e.Oa:this.name=new Fe(e.prefix,e.namespaceURI,e.localName),this.l=t,this.A=void 0}function Wc(e){ua.call(this,e?e.o:new Ca({}),e?[e]:[],{C:!1,R:"unsorted"}),this.l=e}function Zc(e,t,n,r){ua.call(this,new Ca({}),r.concat(t).concat(e.Oa||[]),{C:!1,R:"unsorted"}),e.Oa?this.s=e.Oa:this.l=new Fe(e.prefix,e.namespaceURI,e.localName),this.S=n.reduce((function(e,t){if(t.prefix in e)throw Error("XQST0071: The namespace declaration with the prefix "+t.prefix+" has already been declared on the constructed element.");return e[t.prefix||""]=t.uri,e}),{}),this.K=t,this.la=r,this.A=void 0}function $c(e){if(/^xml$/i.test(e))throw Error('XQDY0064: The target of a created PI may not be "'+e+'"')}function zc(e,t){return{node:{data:t,Ta:!0,nodeName:e,nodeType:7,target:e},F:null}}function el(e,t){var n=e.Fb?[e.Fb].concat(t):[t];ua.call(this,n.reduce((function(e,t){return e.add(t.o)}),new Ca({})),n,{C:!1,R:"unsorted"}),this.l=e,this.s=t}function tl(e){ua.call(this,e?e.o:new Ca({}),e?[e]:[],{C:!1,R:"unsorted"}),this.l=e}function nl(e,t,n,r){var a,o=new Ca({});Ea.call(this,o,(a=[e].concat(h(t.map((function(e){return e.ic}))),[n])).concat.apply(a,h(t.map((function(e){return e.Pb.map((function(e){return e.Ob}))})))),{C:!1,X:!1,R:"unsorted",subtree:!1},r),this.K=e,this.l=t.length,this.S=t.map((function(e){return e.Pb}))}A(Xc,xa),Xc.prototype.s=function(e,t){var n=this,r=Ba(this.A)(e,t),a=Ba(this.K)(e,t);return{next:function(){var e=r.next(0),o=e.value.J;if(0===o.length)throw oa();if(1!==o.length)throw ea();if(!se(o[0].type,54)&&!se(o[0].type,47)&&!se(o[0].type,57))throw ea();o=o[0];var u=a.next(0);e:{var i=n.l,c=Ie.create(u.value.J);switch(o.type){case 54:if(i=jc(i,t,c).next(0).value.value,(c=o.value.node.lookupNamespaceURI(i.prefix))&&c!==i.namespaceURI)throw ra(i.namespaceURI);break e;case 47:if((i=jc(i,t,c).next(0).value.value).namespaceURI&&(c=o.value.node.lookupNamespaceURI(i.prefix))&&c!==i.namespaceURI)throw ra(i.namespaceURI);break e;case 57:i=new Fe("",null,i=Pc(t,c).next(0).value.value);break e}i=void 0}return ce({J:[],fa:Aa([new Nc(o.value,i)],e.value.fa,u.value.fa)})}}},Xc.prototype.v=function(e){this.l=So(e),xa.prototype.v.call(this,e)},A(Qc,xa),Qc.prototype.s=function(e,t){var n=Ba(this.l)(e,t);return e=Ba(this.A)(e,t),this.K?Yc(t,n,e):Lc(t,n,e)},A(qc,xa),qc.prototype.h=function(e,t){return ba(e=this.s(e,t),(function(){}))},qc.prototype.s=function(e,t){var n,r,a,o=this,u=t.h,i=t.o,c=t.B,l=[],s=[],p=[];return{next:function(){if(s.length!==o.l.length)for(var f={},d=s.length;d<o.l.length;f={lb:f.lb},d++){var m=o.l[d],y=l[d];if(y||(l[d]=y=Ba(m.jb)(e,t)),1!==(y=y.next(0)).value.J.length||!se(y.value.J[0].type,53))throw Error("XUTY0013: The source expression of a copy modify expression must return a single node.");f.lb=et($a(y.value.J[0].value,t)),s.push(f.lb.value),p.push(y.value.fa),e=jt(e,((y={})[m.qc]=function(e){return function(){return Ie.m(e.lb)}}(f),y))}return a||(n||(n=Ba(o.K)(e,t)),a=n.next(0).value.fa),a.forEach((function(e){if(e.target&&!Kc(e.target,s,u))throw Error("XUDY0014: The target "+e.target.node.outerHTML+" must be a node created by the copy clause.");if("put"===e.type)throw Error("XUDY0037: The modify expression of a copy modify expression can not contain a fn:put.")})),va(f=a.map((function(e){return Jc(e=e.h(t))})),u,i,c),r||(r=Ba(o.A)(e,t)),ce({J:(f=r.next(0)).value.J,fa:Aa.apply(null,[f.value.fa].concat(h(p)))})}}},qc.prototype.v=function(e){Go(e),this.l.forEach((function(t){return t.qc=Uo(e,t.Rb.namespaceURI,t.Rb.localName)})),xa.prototype.v.call(this,e),Ho(e),this.I=this.l.some((function(e){return e.jb.I}))||this.A.I},A(Vc,ua),Vc.prototype.h=function(e,t){var n,r,a,o=this,u=!1;return Ie.create({next:function(){if(u)return ie;if(!r){if(o.s){if(!n){var i=o.s.h(e,t);n=jc(o.A,t,i)}r=n.next(0).value.value}else r=o.name;if(r){if("xmlns"===r.prefix)throw xo(r);if(""===r.prefix&&"xmlns"===r.localName)throw xo(r);if("http://www.w3.org/2000/xmlns/"===r.namespaceURI)throw xo(r);if("xml"===r.prefix&&"http://www.w3.org/XML/1998/namespace"!==r.namespaceURI)throw xo(r);if(""!==r.prefix&&"xml"!==r.prefix&&"http://www.w3.org/XML/1998/namespace"===r.namespaceURI)throw xo(r)}}return o.l.wb?(i=o.l.wb,a||(a=Lt(i.map((function(n){return Vt(n.h(e,t),t).M((function(e){return Ie.m(ne(e.map((function(e){return e.value})).join(" "),1))}))}))).M((function(e){return Ie.m(et(_c(r,e.map((function(e){return e.value})).join(""))))})).value),a.next(0)):(u=!0,ce(et(_c(r,o.l.value))))}})},Vc.prototype.v=function(e){if(this.A=So(e),this.name&&this.name.prefix&&!this.name.namespaceURI){var t=e.aa(this.name.prefix);if(void 0===t&&this.name.prefix)throw qt(this.name.prefix);this.name.namespaceURI=t||null}ua.prototype.v.call(this,e)},A(Wc,ua),Wc.prototype.h=function(e,t){var n={data:"",Ta:!0,nodeType:8},r={node:n,F:null};return this.l?Vt(e=ia(this.l,e,t),t).M((function(e){if(-1!==(e=e.map((function(e){return Hn(e,1).value})).join(" ")).indexOf("--\x3e"))throw Error('XQDY0072: The contents of the data of a comment may not include "--\x3e"');return n.data=e,Ie.m(et(r))})):Ie.m(et(r))},A(Zc,ua),Zc.prototype.h=function(e,t){var n,r,a,o,u,i=this,c=!1,l=!1,s=!1;return Ie.create({next:function(){if(s)return ie;if(c||(n||(n=Lt(i.K.map((function(n){return ia(n,e,t)})))),r=n.O(),c=!0),!l){a||(a=i.la.map((function(n){return ia(n,e,t)})));for(var p=[],f=0;f<a.length;f++){var h=a[f].O();p.push(h)}o=p,l=!0}if(i.s&&(u||(p=i.s.h(e,t),u=jc(i.A,t,p)),p=u.next(0),i.l=p.value.value),"xmlns"===i.l.prefix||"http://www.w3.org/2000/xmlns/"===i.l.namespaceURI||"xml"===i.l.prefix&&"http://www.w3.org/XML/1998/namespace"!==i.l.namespaceURI||i.l.prefix&&"xml"!==i.l.prefix&&"http://www.w3.org/XML/1998/namespace"===i.l.namespaceURI)throw Error('XQDY0096: The node name "'+i.l.Ca()+'" is invalid for a computed element constructor.');var d={nodeType:1,Ta:!0,attributes:[],childNodes:[],nodeName:i.l.Ca(),namespaceURI:i.l.namespaceURI,prefix:i.l.prefix,localName:i.l.localName};for(p={node:d,F:null},r.forEach((function(e){d.attributes.push(e.value.node)})),(f=Gc(o,t,Ao)).attributes.forEach((function(e){if(d.attributes.find((function(t){return t.namespaceURI===e.namespaceURI&&t.localName===e.localName})))throw Error("XQDY0025: The attribute "+e.name+" does not have an unique name in the constructed element.");d.attributes.push(e)})),f.Xa.forEach((function(e){d.childNodes.push(e)})),f=0;f<d.childNodes.length;f++)if(Pe(h=d.childNodes[f])&&3===h.nodeType){var m=d.childNodes[f-1];m&&Pe(m)&&3===m.nodeType&&(m.data+=h.data,d.childNodes.splice(f,1),f--)}return s=!0,ce(et(p))}})},Zc.prototype.v=function(e){var t=this;if(Go(e),Object.keys(this.S).forEach((function(n){return ko(e,n,t.S[n])})),this.ta.forEach((function(t){return t.v(e)})),this.K.reduce((function(t,n){if(n.name){if(n="Q{"+(null===n.name.namespaceURI?e.aa(n.name.prefix):n.name.namespaceURI)+"}"+n.name.localName,t.includes(n))throw Error("XQST0040: The attribute "+n+" does not have an unique name in the constructed element.");t.push(n)}return t}),[]),this.l&&null===this.l.namespaceURI){var n=e.aa(this.l.prefix);if(void 0===n&&this.l.prefix)throw qt(this.l.prefix);this.l.namespaceURI=n}this.A=So(e),Ho(e)},A(el,ua),el.prototype.h=function(e,t){var n=this;return Vt(ia(this.s,e,t),t).M((function(r){var a=r.map((function(e){return Hn(e,1).value})).join(" ");if(-1!==a.indexOf("?>"))throw Error('XQDY0026: The contents of the data of a processing instruction may not include "?>"');if(null!==n.l.Nb)return $c(r=n.l.Nb),Ie.m(et(zc(r,a)));r=ia(n.l.Fb,e,t);var o=Pc(t,r);return Ie.create({next:function(){var e=o.next(0);return e.done?e:($c(e=e.value.value),ce(et(zc(e,a))))}})}))},A(tl,ua),tl.prototype.h=function(e,t){return this.l?Vt(e=ia(this.l,e,t),t).M((function(e){return 0===e.length?Ie.empty():(e={node:{data:e.map((function(e){return Hn(e,1).value})).join(" "),Ta:!0,nodeType:3},F:null},Ie.m(et(e)))})):Ie.empty()},A(nl,Ea),nl.prototype.A=function(e,t,n){var r=this;return n[0](e).M((function(a){for(var o=0;o<r.l;o++)if(r.S[o].some((function(n){switch(n.oc){case"?":if(1<a.length)return!1;break;case"*":break;case"+":if(1>a.length)return!1;break;default:if(1!==a.length)return!1}var r=Ie.create(a);return a.every((function(a,o){return a=Pt(e,o,a,r),ia(n.Ob,a,t).ha()}))})))return n[o+1](e);return n[r.l+1](e)}))},nl.prototype.v=function(e){if(Ea.prototype.v.call(this,e),this.K.I)throw Vr()};var rl={$:!1,ua:!1},al={$:!0,ua:!1},ol={$:!0,ua:!0};function ul(e){return e.$?e.ua?ol:al:rl}function il(e,t){switch(e[0]){case"andOp":var n=Xo(e,"type");return new gi(pl("andOp",e,ul(t)),n);case"orOp":return n=Xo(e,"type"),new vi(pl("orOp",e,ul(t)),n);case"unaryPlusOp":return n=Po(Po(e,"operand"),"*"),e=Xo(e,"type"),new yi("+",il(n,t),e);case"unaryMinusOp":return n=Po(Po(e,"operand"),"*"),e=Xo(e,"type"),new yi("-",il(n,t),e);case"addOp":case"subtractOp":case"multiplyOp":case"divOp":case"idivOp":case"modOp":var r=e[0],a=il(Lo(e,["firstOperand","*"]),ul(t));t=il(Lo(e,["secondOperand","*"]),ul(t));var o=Xo(e,"type"),u=Xo(Lo(e,["firstOperand","*"]),"type"),i=Xo(Lo(e,["secondOperand","*"]),"type");return u&&i&&Xo(e,"type")&&(n=nu(r,u.type,i.type)),new uu(r,a,t,o,n);case"sequenceExpr":return Bl(e,t);case"unionOp":return n=Xo(e,"type"),new Vi([il(Lo(e,["firstOperand","*"]),ul(t)),il(Lo(e,["secondOperand","*"]),ul(t))],n);case"exceptOp":case"intersectOp":return n=Xo(e,"type"),new Pi(e[0],il(Lo(e,["firstOperand","*"]),ul(t)),il(Lo(e,["secondOperand","*"]),ul(t)),n);case"stringConcatenateOp":return El(e,t);case"rangeSequenceExpr":return Nl(e,t);case"equalOp":case"notEqualOp":case"lessThanOrEqualOp":case"lessThanOp":case"greaterThanOrEqualOp":case"greaterThanOp":return hl("generalCompare",e,t);case"eqOp":case"neOp":case"ltOp":case"leOp":case"gtOp":case"geOp":return hl("valueCompare",e,t);case"isOp":case"nodeBeforeOp":case"nodeAfterOp":return hl("nodeCompare",e,t);case"pathExpr":return Al(e,t);case"contextItemExpr":return new ec(Xo(e,"type"));case"functionCallExpr":return yl(e,t);case"inlineFunctionExpr":return wl(e,t);case"arrowExpr":return gl(e,t);case"dynamicFunctionInvocationExpr":return vl(e,t);case"namedFunctionRef":return t=Po(e,"functionName"),n=Xo(e,"type"),e=jo(Lo(e,["integerConstantExpr","value"])),new hi(Qo(t),parseInt(e,10),n);case"integerConstantExpr":return new pi(jo(Po(e,"value")),{type:5,g:3});case"stringConstantExpr":return new pi(jo(Po(e,"value")),{type:1,g:3});case"decimalConstantExpr":return new pi(jo(Po(e,"value")),{type:4,g:3});case"doubleConstantExpr":return new pi(jo(Po(e,"value")),{type:3,g:3});case"varRef":return new dc((e=Qo(Po(e,"name"))).prefix,e.namespaceURI,e.localName);case"flworExpr":return ml(e,t);case"quantifiedExpr":return xl(e,t);case"ifThenElseExpr":return n=Xo(e,"type"),new ei(il(Po(Po(e,"ifClause"),"*"),ul(t)),il(Po(Po(e,"thenClause"),"*"),t),il(Po(Po(e,"elseClause"),"*"),t),n);case"instanceOfExpr":return n=il(Lo(e,["argExpr","*"]),t),r=Lo(e,["sequenceType","*"]),a=Lo(e,["sequenceType","occurrenceIndicator"]),e=Xo(e,"type"),new Ji(n,il(r,ul(t)),a?jo(a):"",e);case"castExpr":return t=il(Po(Po(e,"argExpr"),"*"),ul(t)),n=Po(e,"singleType"),new Yi(t,e=Qo(Po(n,"atomicType")),n=null!==Po(n,"optional"));case"castableExpr":return t=il(Po(Po(e,"argExpr"),"*"),ul(t)),n=Po(e,"singleType"),new Li(t,e=Qo(Po(n,"atomicType")),n=null!==Po(n,"optional"));case"simpleMapExpr":return bl(e,t);case"mapConstructor":return sl(e,t);case"arrayConstructor":return ll(e,t);case"unaryLookup":return n=Xo(e,"type"),new ic(fl(e,t),n);case"typeswitchExpr":return Ol(e,t);case"elementConstructor":return Tl(e,t);case"attributeConstructor":return Il(e,t);case"computedAttributeConstructor":return(n=Po(e,"tagName"))?n=Qo(n):(n=Po(e,"tagNameExpr"),n={Oa:il(Po(n,"*"),ul(t))}),new Vc(n,{wb:[e=il(Po(Po(e,"valueExpr"),"*"),ul(t))]});case"computedCommentConstructor":if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");return new Wc(e=(e=Po(e,"argExpr"))?il(Po(e,"*"),ul(t)):null);case"computedTextConstructor":if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");return new tl(e=(e=Po(e,"argExpr"))?il(Po(e,"*"),ul(t)):null);case"computedElementConstructor":return Cl(e,t);case"computedPIConstructor":if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");return n=Po(e,"piTargetExpr"),r=Po(e,"piTarget"),a=Po(e,"piValueExpr"),e=Xo(e,"type"),new el({Fb:n?il(Po(n,"*"),ul(t)):null,Nb:r?jo(r):null},a?il(Po(a,"*"),ul(t)):new ji([],e));case"CDataSection":return new pi(jo(e),{type:1,g:3});case"deleteExpr":return new Oc(e=il(Lo(e,["targetExpr","*"]),t));case"insertExpr":switch(n=il(Lo(e,["sourceExpr","*"]),t),(a=Yo(e,"*")[1])[0]){case"insertAfter":r=1;break;case"insertBefore":r=2;break;case"insertInto":r=(r=Po(a,"*"))?"insertAsFirst"===r[0]?4:5:3}return new Rc(n,r,e=il(Lo(e,["targetExpr","*"]),t));case"renameExpr":return new Xc(n=il(Lo(e,["targetExpr","*"]),t),e=il(Lo(e,["newNameExpr","*"]),t));case"replaceExpr":return new Qc(n=!!Po(e,"replaceValue"),r=il(Lo(e,["targetExpr","*"]),t),e=il(Lo(e,["replacementExpr","*"]),t));case"transformExpr":return Fl(e,t);case"x:stackTrace":for(n=e[1],e=e[2];"x:stackTrace"===e[0];)e=e[2];return new ai(n,e[0],il(e,t));default:return cl(e)}}function cl(e){switch(e[0]){case"nameTest":return new pc(Qo(e));case"piTest":return(e=Po(e,"piTarget"))?new fc(jo(e)):new sc(7);case"commentTest":return new sc(8);case"textTest":return new sc(3);case"documentTest":return new sc(9);case"attributeTest":var t=(e=Po(e,"attributeName"))&&Po(e,"star");return!e||t?new sc(2):new pc(Qo(Po(e,"QName")),{kind:2});case"elementTest":return t=(e=Po(e,"elementName"))&&Po(e,"star"),!e||t?new sc(1):new pc(Qo(Po(e,"QName")),{kind:1});case"anyKindTest":return new hc({prefix:"",namespaceURI:null,localName:"node()"});case"anyMapTest":return new hc({prefix:"",namespaceURI:null,localName:"map(*)"});case"anyArrayTest":return new hc({prefix:"",namespaceURI:null,localName:"array(*)"});case"Wildcard":return Po(e,"star")?(t=Po(e,"uri"))?e=new pc({localName:"*",namespaceURI:jo(t),prefix:""}):(t=Po(e,"NCName"),e="star"===Po(e,"*")[0]?new pc({localName:jo(t),namespaceURI:null,prefix:"*"}):new pc({localName:"*",namespaceURI:null,prefix:jo(t)})):e=new pc({localName:"*",namespaceURI:null,prefix:"*"}),e;case"atomicType":return new hc(Qo(e));case"anyItemType":return new hc({prefix:"",namespaceURI:null,localName:"item()"});default:throw Error("No selector counterpart for: "+e[0]+".")}}function ll(e,t){var n=Xo(e,"type"),r=Yo(e=Po(e,"*"),"arrayElem").map((function(e){return il(Po(e,"*"),ul(t))}));switch(e[0]){case"curlyArray":return new Ou(r,n);case"squareArray":return new Su(r,n);default:throw Error("Unrecognized arrayType: "+e[0])}}function sl(e,t){var n=Xo(e,"type");return new fi(Yo(e,"mapConstructorEntry").map((function(e){return{key:il(Lo(e,["mapKeyExpr","*"]),ul(t)),value:il(Lo(e,["mapValueExpr","*"]),ul(t))}})),n)}function pl(e,t,n){function r(t){var o=Po(Po(t,"firstOperand"),"*");t=Po(Po(t,"secondOperand"),"*"),o[0]===e?r(o):a.push(il(o,n)),t[0]===e?r(t):a.push(il(t,n))}var a=[];return r(t),a}function fl(e,t){switch((e=Po(e,"*"))[0]){case"NCName":return new pi(jo(e),{type:1,g:3});case"star":return"*";default:return il(e,ul(t))}}function hl(e,t,n){var r=Lo(t,["firstOperand","*"]),a=Lo(t,["secondOperand","*"]);switch(r=il(r,ul(n)),n=il(a,ul(n)),e){case"valueCompare":return new Oi(t[0],r,n);case"nodeCompare":return new Mi(t[0],r,n);case"generalCompare":return new Ri(t[0],r,n)}}function dl(e,t,n){return new $i((e=Yo(e,"*")).filter((function(e){return"stable"!==e[0]})).map((function(e){var n=Po(e,"orderModifier"),r=n?Po(n,"orderingKind"):null;return n=n?Po(n,"emptyOrderingMode"):null,r=!r||"ascending"===jo(r),n=!n||"empty least"===jo(n),{ca:il(Lo(e,["orderByExpr","*"]),t),Kb:r,lc:n}})),n)}function ml(e,t){var n=Yo(e,"*");if(e=Po(n[n.length-1],"*"),1<(n=n.slice(0,-1)).length&&!t.$)throw Error("XPST0003: Use of XQuery FLWOR expressions in XPath is no allowed");return n.reduceRight((function(e,n){switch(n[0]){case"forClause":for(var r=(n=Yo(n,"*")).length-1;0<=r;--r){var a=n[r],o=Lo(a,["forExpr","*"]),u=Po(a,"positionalVariableBinding");e=new ci(Qo(Lo(a,["typedVariableBinding","varName"])),il(o,ul(t)),u?Qo(u):null,e)}return e;case"letClause":for(r=(n=Yo(n,"*")).length-1;0<=r;--r)o=Lo(a=n[r],["letExpr","*"]),e=new si(Qo(Lo(a,["typedVariableBinding","varName"])),il(o,ul(t)),e);return e;case"whereClause":for(r=(n=Yo(n,"*")).length-1;0<=r;--r)e=new mc(il(n[r],t),e);return e;case"windowClause":case"groupByClause":case"countClause":throw Error("Not implemented: "+n[0]+" is not implemented yet.");case"orderByClause":return dl(n,t,e);default:throw Error("Not implemented: "+n[0]+" is not supported in a flwor expression")}}),il(e,t))}function yl(e,t){var n=Po(e,"functionName"),r=Yo(Po(e,"arguments"),"*");return e=Xo(e,"type"),new Ra(new hi(Qo(n),r.length,e),r.map((function(e){return"argumentPlaceholder"===e[0]?null:il(e,t)})),e)}function gl(e,t){var n=Xo(e,"type"),r=Lo(e,["argExpr","*"]);e=Yo(e,"*").slice(1),r=[il(r,t)];for(var a=0;a<e.length;a++)if("arguments"!==e[a][0]){if("arguments"===e[a+1][0]){var o=Yo(e[a+1],"*");r=r.concat(o.map((function(e){return"argumentPlaceholder"===e[0]?null:il(e,t)})))}r=[new Ra(o="EQName"===e[a][0]?new hi(Qo(e[a]),r.length,n):il(e[a],ul(t)),r,n)]}return r[0]}function vl(e,t){var n=Lo(e,["functionItem","*"]),r=Xo(e,"type"),a=[];return(e=Po(e,"arguments"))&&(a=Yo(e,"*").map((function(e){return"argumentPlaceholder"===e[0]?null:il(e,t)}))),new Ra(il(n,t),a,r)}function wl(e,t){var n=Yo(Po(e,"paramList"),"*"),r=Lo(e,["functionBody","*"]),a=Xo(e,"type");return new li(n.map((function(e){return{name:Qo(Po(e,"varName")),type:Jo(e)}})),Jo(e),r?il(r,t):new ji([],a))}function Al(e,t){var n=Xo(e,"type"),r=Yo(e,"stepExpr"),a=!1,o=r.map((function(e){for(var r=Po(e,"xpathAxis"),o=Yo(e,"*"),u=[],i=null,c=(o=p(o)).next();!c.done;c=o.next())switch(c=c.value,c[0]){case"lookup":u.push(["lookup",fl(c,t)]);break;case"predicate":case"predicates":for(var l=(c=p(Yo(c,"*"))).next();!l.done;l=c.next())i=Uu(i,(l=il(l.value,ul(t))).B()),u.push(["predicate",l])}if(r)switch(a=!0,e=Po(e,"attributeTest anyElementTest piTest documentTest elementTest commentTest namespaceTest anyKindTest textTest anyFunctionTest typedFunctionTest schemaAttributeTest atomicType anyItemType parenthesizedItemType typedMapTest typedArrayTest nameTest Wildcard".split(" ")),e=cl(e),jo(r)){case"ancestor":var s=new Ru(e,{Ra:!1});break;case"ancestor-or-self":s=new Ru(e,{Ra:!0});break;case"attribute":s=new Mu(e,i);break;case"child":s=new Hu(e,i);break;case"descendant":s=new Xu(e,{Ra:!1});break;case"descendant-or-self":s=new Xu(e,{Ra:!0});break;case"parent":s=new _u(e,i);break;case"following-sibling":s=new qu(e,i);break;case"preceding-sibling":s=new $u(e,i);break;case"following":s=new Ju(e);break;case"preceding":s=new Wu(e);break;case"self":s=new zu(e,i)}else s=il(s=Lo(e,["filterExpr","*"]),ul(t));for(r=(u=p(u)).next();!r.done;r=u.next())switch(r=r.value,r[0]){case"lookup":s=new uc(s,r[1]);break;case"predicate":s=new rc(s,r[1])}return s.type=n,s}));return e=Po(e,"rootExpr"),!(r=a||null!==e||1<r.length)&&1===o.length||!e&&1===o.length&&"sorted"===o[0].da?o[0]:e&&0===o.length?new zi(null):(o=new nc(o,r),e?new zi(o):o)}function xl(e,t){var n=Xo(e,"type"),r=jo(Po(e,"quantifier")),a=Lo(e,["predicateExpr","*"]);return new cc(r,e=Yo(e,"quantifiedExprInClause").map((function(e){return{name:Qo(Lo(e,["typedVariableBinding","varName"])),jb:il(e=Lo(e,["sourceExpr","*"]),ul(t))}})),il(a,ul(t)),n)}function Bl(e,t){var n=Yo(e,"*").map((function(e){return il(e,t)}));return 1===n.length?n[0]:(n=Xo(e,"type"),new ji(Yo(e,"*").map((function(e){return il(e,t)})),n))}function bl(e,t){var n=Xo(e,"type");return Yo(e,"*").reduce((function(e,r){return null===e?il(r,ul(t)):new Xi(e,il(r,ul(t)),n)}),null)}function El(e,t){var n=Xo(e,"type");return new Ra(new hi({localName:"concat",namespaceURI:"http://www.w3.org/2005/xpath-functions",prefix:""},(e=[Lo(e,["firstOperand","*"]),Lo(e,["secondOperand","*"])]).length,n),e.map((function(e){return il(e,ul(t))})),n)}function Nl(e,t){var n=Xo(e,"type");return new Ra(new hi({localName:"to",namespaceURI:"http://fontoxpath/operators",prefix:""},(e=[Po(Po(e,"startExpr"),"*"),Po(Po(e,"endExpr"),"*")]).length,n),e.map((function(e){return il(e,ul(t))})),n)}function Tl(e,t){if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");var n=Qo(Po(e,"tagName")),r=Po(e,"attributeList");return new Zc(n,r?Yo(r,"attributeConstructor").map((function(e){return il(e,ul(t))})):[],r=r?Yo(r,"namespaceDeclaration").map((function(e){var t=Po(e,"prefix");return{prefix:t?jo(t):"",uri:jo(Po(e,"uri"))}})):[],e=(e=Po(e,"elementContent"))?Yo(e,"*").map((function(e){return il(e,ul(t))})):[])}function Il(e,t){if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");var n=Qo(Po(e,"attributeName")),r=Po(e,"attributeValue");return new Vc(n,{value:r=r?jo(r):null,wb:e=(e=Po(e,"attributeValueExpr"))?Yo(e,"*").map((function(e){return il(e,ul(t))})):null})}function Cl(e,t){var n=Po(e,"tagName");return n?n=Qo(n):(n=Po(e,"tagNameExpr"),n={Oa:il(Po(n,"*"),ul(t))}),new Zc(n,[],[],e=(e=Po(e,"contentExpr"))?Yo(e,"*").map((function(e){return il(e,ul(t))})):[])}function Fl(e,t){return new qc(Yo(Po(e,"transformCopies"),"transformCopy").map((function(e){var n=Qo(Po(Po(e,"varRef"),"name"));return{jb:il(Po(Po(e,"copySource"),"*"),t),Rb:new Fe(n.prefix,n.namespaceURI,n.localName)}})),il(Po(Po(e,"modifyExpr"),"*"),t),e=il(Po(Po(e,"returnExpr"),"*"),t))}function Ol(e,t){if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");var n=Xo(e,"type");return new nl(il(Po(Po(e,"argExpr"),"*"),t),Yo(e,"typeswitchExprCaseClause").map((function(e){var n=0===Yo(e,"sequenceTypeUnion").length?[Po(e,"sequenceType")]:Yo(Po(e,"sequenceTypeUnion"),"sequenceType");return{ic:il(Lo(e,["resultExpr","*"]),t),Pb:n.map((function(e){var n=Po(e,"occurrenceIndicator");return{oc:n?jo(n):"",Ob:il(Po(e,"*"),t)}}))}})),e=il(Lo(e,["typeswitchExprDefaultClause","resultExpr","*"]),t),n)}function Sl(e,t){return il(e,t)}var Gl=new Map;function Dl(e,t,n,r,a,o){this.B=e,this.l=t,this.h=n,this.v=r,this.o=a,this.s=o}function Rl(e,t,n,r,a,o,u,i){return(e=Gl.get(e))&&(t=e[t+(o?"_DEBUG":"")])&&(t=t.find((function(e){return e.o===u&&e.B.every((function(e){return n(e.prefix)===e.namespaceURI}))&&e.l.every((function(e){return void 0!==r[e.name]}))&&e.v.every((function(e){return a[e.prefix]===e.namespaceURI}))&&e.s.every((function(e){var t=i(e.nc,e.arity);return t&&t.namespaceURI===e.Lb.namespaceURI&&t.localName===e.Lb.localName}))})))?{ca:t.h,rc:!1}:null}function kl(e,t,n,r,a,o,u){var i=Gl.get(e);i||(i=Object.create(null),Gl.set(e,i)),(t=i[e=t+(o?"_DEBUG":"")])||(t=i[e]=[]),t.push(new Dl(Object.values(n.h),Object.values(n.o),a,Object.keys(r).map((function(e){return{namespaceURI:r[e],prefix:e}})),u,n.B))}function Ul(e){var t=new ke;if("http://www.w3.org/2005/XQueryX"!==e.namespaceURI&&"http://www.w3.org/2005/XQueryX"!==e.namespaceURI&&"http://fontoxml.com/fontoxpath"!==e.namespaceURI&&"http://www.w3.org/2007/xquery-update-10"!==e.namespaceURI)throw Jt("The XML structure passed as an XQueryX program was not valid XQueryX");var n=["stackTrace"===e.localName?"x:stackTrace":e.localName],r=t.getAllAttributes(e);for(r&&0<r.length&&n.push(Array.from(r).reduce((function(t,n){return"start"===n.localName||"end"===n.localName&&"stackTrace"===e.localName?t[n.localName]=JSON.parse(n.value):"type"===n.localName?t[n.localName]=we(n.value):t[n.localName]=n.value,t}),{})),r=(t=p(t=t.getChildNodes(e))).next();!r.done;r=t.next())switch(r=r.value,r.nodeType){case 1:n.push(Ul(r));break;case 3:n.push(r.data)}return n}var Ml=Object.create(null);function Hl(e,t){var n=Ml[e];n||(n=Ml[e]={Ma:[],Va:[],ra:null,source:t.source});var r=n.ra||function(){};n.Ma=n.Ma.concat(t.Ma),n.Va=n.Va.concat(t.Va),n.ra=function(e){r(e),t.ra&&t.ra(e)}}function Pl(e,t){var n=Ml[t];if(!n)throw Error("XQST0051: No modules found with the namespace uri "+t);n.Ma.forEach((function(n){n.hb&&Ro(e,t,n.localName,n.arity,n)})),n.Va.forEach((function(n){Uo(e,t,n.localName),Mo(e,t,n.localName,(function(e,t){return ia(n.ca,e,t)}))}))}function jl(){Object.keys(Ml).forEach((function(e){if((e=Ml[e]).ra)try{e.ra(e)}catch(t){e.ra=null,lo(e.source,t)}e.ra=null}))}function Xl(e){return e.replace(/(\x0D\x0A)|(\x0D(?!\x0A))/g,String.fromCharCode(10))}var Ll=t;function Yl(e,t){return function(n,r){return t.has(r)?t.get(r):(n=e(n,r),t.set(r,n),n)}}function Ql(e,t){return Ll.delimited(t,e,t)}function Jl(e,t){return e.reverse().reduce((function(e,t){return Ll.preceded(t,e)}),t)}function Kl(e,t,n,r){return Ll.then(Ll.then(e,t,(function(e,t){return[e,t]})),n,(function(e,t){var n=p(e);return e=n.next().value,n=n.next().value,r(e,n,t)}))}function ql(e,t,n,r,a){return Ll.then(Ll.then(Ll.then(e,t,(function(e,t){return[e,t]})),n,(function(e,t){var n=p(e);return[e=n.next().value,n=n.next().value,t]})),r,(function(e,t){var n=p(e);e=n.next().value;var r=n.next().value;return n=n.next().value,a(e,r,n,t)}))}function _l(e,t,n,r,a,o){return Ll.then(Ll.then(Ll.then(Ll.then(e,t,(function(e,t){return[e,t]})),n,(function(e,t){var n=p(e);return[e=n.next().value,n=n.next().value,t]})),r,(function(e,t){var n=p(e);return[e=n.next().value,n.next().value,n=n.next().value,t]})),a,(function(e,t){var n=p(e);e=n.next().value;var r=n.next().value,a=n.next().value;return n=n.next().value,o(e,r,a,n,t)}))}function Vl(e){return Ll.map(e,(function(e){return[e]}))}function Wl(e,t){return Ll.map(Ll.or(e),(function(){return t}))}function Zl(e){return function(t,n){return(t=e.exec(t.substring(n)))&&0===t.index?Ll.okWithValue(n+t[0].length,t[0]):Ll.error(n,[e.source],!1)}}var $l=Ll.or([Ll.token(" "),Ll.token("\t"),Ll.token("\r"),Ll.token("\n")]),zl=Ll.token("(:"),es=Ll.token(":)"),ts=Ll.token("(#"),ns=Ll.token("#)"),rs=Ll.token("("),as=Ll.token(")"),os=Ll.token("["),us=Ll.token("]"),is=Ll.token("{"),cs=Ll.token("}"),ls=Ll.token("{{"),ss=Ll.token("}}"),ps=Ll.token("'"),fs=Ll.token("''"),hs=Ll.token('"'),ds=Ll.token('""'),ms=Ll.token("<![CDATA["),ys=Ll.token("]]>"),gs=Ll.token("/>"),vs=Ll.token("</"),ws=Ll.token("\x3c!--"),As=Ll.token("--\x3e"),xs=Ll.token("<?"),Bs=Ll.token("?>"),bs=Ll.token("&#x"),Es=Ll.token("&#"),Ns=Ll.token(":*"),Ts=Ll.token("*:"),Is=Ll.token(":="),Cs=Ll.token("&"),Fs=Ll.token(":"),Os=Ll.token(";"),Ss=Ll.token("*"),Gs=Ll.token("@"),Ds=Ll.token("$"),Rs=Ll.token("#"),ks=Ll.token("%"),Us=Ll.token("?"),Ms=Ll.token("="),Hs=Ll.followed(Ll.token("!"),Ll.not(Ll.peek(Ms),[])),Ps=Ll.followed(Ll.token("|"),Ll.not(Ll.peek(Ll.token("|")),[])),js=Ll.token("||"),Xs=Ll.token("!="),Ls=Ll.token("<"),Ys=Ll.token("<<"),Qs=Ll.token("<="),Js=Ll.token(">"),Ks=Ll.token(">>"),qs=Ll.token(">="),_s=Ll.token(","),Vs=Ll.token("."),Ws=Ll.token(".."),Zs=Ll.token("+"),$s=Ll.token("-"),zs=Ll.token("/"),ep=Ll.token("//"),tp=Ll.token("=>"),np=Ll.token("e"),rp=Ll.token("E");Ll.token("l"),Ll.token("L"),Ll.token("m"),Ll.token("M");var ap=Ll.token("Q");Ll.token("x"),Ll.token("X");var op=Ll.token("as"),up=Ll.token("cast"),ip=Ll.token("castable"),cp=Ll.token("treat"),lp=Ll.token("instance"),sp=Ll.token("of"),pp=Ll.token("node"),fp=Ll.token("nodes"),hp=Ll.token("delete"),dp=Ll.token("value"),mp=Ll.token("function"),yp=Ll.token("map"),gp=Ll.token("element"),vp=Ll.token("attribute"),wp=Ll.token("schema-element"),Ap=Ll.token("intersect"),xp=Ll.token("except"),Bp=Ll.token("union"),bp=Ll.token("to"),Ep=Ll.token("is"),Np=Ll.token("or"),Tp=Ll.token("and"),Ip=Ll.token("div"),Cp=Ll.token("idiv"),Fp=Ll.token("mod"),Op=Ll.token("eq"),Sp=Ll.token("ne"),Gp=Ll.token("lt"),Dp=Ll.token("le"),Rp=Ll.token("gt"),kp=Ll.token("ge"),Up=Ll.token("amp"),Mp=Ll.token("quot"),Hp=Ll.token("apos"),Pp=Ll.token("if"),jp=Ll.token("then"),Xp=Ll.token("else"),Lp=Ll.token("allowing"),Yp=Ll.token("empty"),Qp=Ll.token("at"),Jp=Ll.token("in"),Kp=Ll.token("for"),qp=Ll.token("let"),_p=Ll.token("where"),Vp=Ll.token("collation"),Wp=Ll.token("group"),Zp=Ll.token("by"),$p=Ll.token("order"),zp=Ll.token("stable"),ef=Ll.token("return"),tf=Ll.token("array"),nf=Ll.token("document"),rf=Ll.token("namespace"),af=Ll.token("text"),of=Ll.token("comment"),uf=Ll.token("processing-instruction"),cf=Ll.token("lax"),lf=Ll.token("strict"),sf=Ll.token("validate"),pf=Ll.token("type"),ff=Ll.token("declare"),hf=Ll.token("default"),df=Ll.token("boundary-space"),mf=Ll.token("strip"),yf=Ll.token("preserve"),gf=Ll.token("no-preserve"),vf=Ll.token("inherit"),wf=Ll.token("no-inherit"),Af=Ll.token("greatest"),xf=Ll.token("least"),Bf=Ll.token("copy-namespaces"),bf=Ll.token("decimal-format"),Ef=Ll.token("case"),Nf=Ll.token("typeswitch"),Tf=Ll.token("some"),If=Ll.token("every"),Cf=Ll.token("satisfies"),Ff=Ll.token("replace"),Of=Ll.token("with"),Sf=Ll.token("copy"),Gf=Ll.token("modify"),Df=Ll.token("first"),Rf=Ll.token("last"),kf=Ll.token("before"),Uf=Ll.token("after"),Mf=Ll.token("into"),Hf=Ll.token("insert"),Pf=Ll.token("rename"),jf=Ll.token("switch"),Xf=Ll.token("variable"),Lf=Ll.token("external"),Yf=Ll.token("updating"),Qf=Ll.token("import"),Jf=Ll.token("schema"),Kf=Ll.token("module"),qf=Ll.token("base-uri"),_f=Ll.token("construction"),Vf=Ll.token("ordering"),Wf=Ll.token("ordered"),Zf=Ll.token("unordered"),$f=Ll.token("option"),zf=Ll.token("context"),eh=Ll.token("item"),th=Ll.token("xquery"),nh=Ll.token("version"),rh=Ll.token("encoding"),ah=Ll.token("document-node"),oh=Ll.token("namespace-node"),uh=Ll.token("schema-attribute"),ih=Ll.token("ascending"),ch=Ll.token("descending"),lh=Ll.token("empty-sequence"),sh=Ll.token("child::"),ph=Ll.token("descendant::"),fh=Ll.token("attribute::"),hh=Ll.token("self::"),dh=Ll.token("descendant-or-self::"),mh=Ll.token("following-sibling::"),yh=Ll.token("following::"),gh=Ll.token("parent::"),vh=Ll.token("ancestor::"),wh=Ll.token("preceding-sibling::"),Ah=Ll.token("preceding::"),xh=Ll.token("ancestor-or-self::"),Bh=Ll.token("decimal-separator"),bh=Ll.token("grouping-separator"),Eh=Ll.token("infinity"),Nh=Ll.token("minus-sign"),Th=Ll.token("NaN"),Ih=Ll.token("per-mille"),Ch=Ll.token("zero-digit"),Fh=Ll.token("digit"),Oh=Ll.token("pattern-separator"),Sh=Ll.token("exponent-separator"),Gh=Ll.token("schema-attribute("),Dh=Ll.token("document-node("),Rh=Ll.token("processing-instruction("),kh=Ll.token("processing-instruction()"),Uh=Ll.token("comment()"),Mh=Ll.token("text()"),Hh=Ll.token("namespace-node()"),Ph=Ll.token("node()"),jh=Ll.token("item()"),Xh=Ll.token("empty-sequence()"),Lh=new Map,Yh=new Map,Qh=Ll.or([Zl(/[\t\n\r -\uD7FF\uE000\uFFFD]/),Zl(/[\uD800-\uDBFF][\uDC00-\uDFFF]/)]),Jh=Ll.preceded(Ll.peek(Ll.not(Ll.or([zl,es]),['comment contents cannot contain "(:" or ":)"'])),Qh),Kh=Ll.map(Ll.delimited(zl,Ll.star(Ll.or([Jh,function(e,t){return Kh(e,t)}])),es,!0),(function(e){return e.join("")})),qh=Ll.or([$l,Kh]),_h=Ll.map(Ll.plus($l),(function(e){return e.join("")})),Vh=Yl(Ll.map(Ll.star(qh),(function(e){return e.join("")})),Lh),Wh=Yl(Ll.map(Ll.plus(qh),(function(e){return e.join("")})),Yh),Zh=Ll.or([Zl(/[A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/),Ll.then(Zl(/[\uD800-\uDB7F]/),Zl(/[\uDC00-\uDFFF]/),(function(e,t){return e+t}))]),$h=Ll.or([Zh,Zl(/[\-\.0-9\xB7\u0300-\u036F\u203F\u2040]/)]),zh=Ll.then(Zh,Ll.star($h),(function(e,t){return e+t.join("")})),ed=Ll.map(zh,(function(e){return["prefix",e]})),td=Ll.or([Zh,Fs]),nd=Ll.or([$h,Fs]);Ll.then(td,Ll.star(nd),(function(e,t){return e+t.join("")}));var rd=Ll.map(zh,(function(e){var t={};return[(t.prefix="",t.URI=null,t),e]})),ad=Ll.then(zh,Ll.preceded(Fs,zh),(function(e,t){var n={};return[(n.prefix=e,n.URI=null,n),t]})),od=Ll.or([ad,rd]),ud=Ll.followed(Jl([ap,Vh,is],Ll.map(Ll.star(Zl(/[^{}]/)),(function(e){return e.join("").replace(/\s+/g," ").trim()}))),cs),id=Ll.then(ud,zh,(function(e,t){return[e,t]})),cd=Ll.or([Ll.map(id,(function(e){var t={};return[(t.prefix=null,t.URI=e[0],t),e[1]]})),od]),ld=Ll.or([Ll.map(cd,(function(e){return["QName"].concat(h(e))})),Ll.map(Ss,(function(){return["star"]}))]),sd=Ll.map(Ll.preceded(Ds,cd),(function(e){return["varRef",["name"].concat(h(e))]})),pd=Ll.peek(Ll.or([rs,hs,ps,qh])),fd=Ll.map(Ll.or([sh,ph,fh,hh,dh,mh,yh]),(function(e){return e.substring(0,e.length-2)})),hd=Ll.map(Ll.or([gh,vh,wh,Ah,xh]),(function(e){return e.substring(0,e.length-2)})),dd=Kl(Cs,Ll.or([Gp,Rp,Up,Mp,Hp]),Os,(function(e,t,n){return e+t+n})),md=Ll.or([Kl(bs,Zl(/[0-9a-fA-F]+/),Os,(function(e,t,n){return e+t+n})),Kl(Es,Zl(/[0-9]+/),Os,(function(e,t,n){return e+t+n}))]),yd=Wl([ds],'"'),gd=Wl([fs],"'"),vd=Vl(Wl([Uh],"commentTest")),wd=Vl(Wl([Mh],"textTest")),Ad=Vl(Wl([Hh],"namespaceTest")),xd=Vl(Wl([Ph],"anyKindTest")),Bd=Zl(/[0-9]+/),bd=Ll.then(Ll.or([Ll.then(Vs,Bd,(function(e,t){return e+t})),Ll.then(Bd,Ll.optional(Ll.preceded(Vs,Zl(/[0-9]*/))),(function(e,t){return e+(null!==t?"."+t:"")}))]),Kl(Ll.or([np,rp]),Ll.optional(Ll.or([Zs,$s])),Bd,(function(e,t,n){return e+(t||"")+n})),(function(e,t){return["doubleConstantExpr",["value",e+t]]})),Ed=Ll.or([Ll.map(Ll.preceded(Vs,Bd),(function(e){return["decimalConstantExpr",["value","."+e]]})),Ll.then(Ll.followed(Bd,Vs),Ll.optional(Bd),(function(e,t){return["decimalConstantExpr",["value",e+"."+(null!==t?t:"")]]}))]),Nd=Ll.map(Bd,(function(e){return["integerConstantExpr",["value",e]]})),Td=Ll.followed(Ll.or([bd,Ed,Nd]),Ll.peek(Ll.not(Zl(/[a-zA-Z]/),["no alphabetical characters after numeric literal"]))),Id=Ll.map(Ll.followed(Vs,Ll.peek(Ll.not(Vs,["context item should not be followed by another ."]))),(function(){return["contextItemExpr"]})),Cd=Ll.or([tf,vp,of,ah,gp,lh,mp,Pp,eh,yp,oh,pp,uf,uh,wp,jf,af,Nf]),Fd=Vl(Wl([Us],"argumentPlaceholder")),Od=Ll.or([Us,Ss,Zs]),Sd=Ll.preceded(Ll.peek(Ll.not(Zl(/[{}<&]/),["elementContentChar cannot be {, }, <, or &"])),Qh),Gd=Ll.map(Ll.delimited(ms,Ll.star(Ll.preceded(Ll.peek(Ll.not(ys,['CDataSection content may not contain "]]>"'])),Qh)),ys,!0),(function(e){return["CDataSection",e.join("")]})),Dd=Ll.preceded(Ll.peek(Ll.not(Zl(/["{}<&]/),['quotAttrValueContentChar cannot be ", {, }, <, or &'])),Qh),Rd=Ll.preceded(Ll.peek(Ll.not(Zl(/['{}<&]/),["aposAttrValueContentChar cannot be ', {, }, <, or &"])),Qh),kd=Ll.map(Ll.star(Ll.or([Ll.preceded(Ll.peek(Ll.not($s,[])),Qh),Ll.map(Jl([$s,Ll.peek(Ll.not($s,[]))],Qh),(function(e){return"-"+e}))])),(function(e){return e.join("")})),Ud=Ll.map(Ll.delimited(ws,kd,As,!0),(function(e){return["computedCommentConstructor",["argExpr",["stringConstantExpr",["value",e]]]]})),Md=Ll.filter(zh,(function(e){return"xml"!==e.toLowerCase()}),['A processing instruction target cannot be "xml"']),Hd=Ll.map(Ll.star(Ll.preceded(Ll.peek(Ll.not(Bs,[])),Qh)),(function(e){return e.join("")})),Pd=Ll.then(Ll.preceded(xs,Ll.cut(Md)),Ll.cut(Ll.followed(Ll.optional(Ll.preceded(_h,Hd)),Bs)),(function(e,t){return["computedPIConstructor",["piTarget",e],["piValueExpr",["stringConstantExpr",["value",t]]]]})),jd=Ll.map(ep,(function(){return["stepExpr",["xpathAxis","descendant-or-self"],["anyKindTest"]]})),Xd=Ll.or([cf,lf]),Ld=Ll.map(Ll.star(Ll.followed(Qh,Ll.peek(Ll.not(ns,["Pragma contents should not contain '#)'"])))),(function(e){return e.join("")})),Yd=Ll.map(Ll.followed(Ll.or([Op,Sp,Gp,Dp,Rp,kp]),pd),(function(e){return e+"Op"})),Qd=Ll.or([Ll.followed(Wl([Ep],"isOp"),pd),Wl([Ys],"nodeBeforeOp"),Wl([Ks],"nodeAfterOp")]),Jd=Ll.or([Wl([Ms],"equalOp"),Wl([Xs],"notEqualOp"),Wl([Qs],"lessThanOrEqualOp"),Wl([Ls],"lessThanOp"),Wl([qs],"greaterThanOrEqualOp"),Wl([Js],"greaterThanOp")]),Kd=Ll.map(Yf,(function(){return["annotation",["annotationName","updating"]]})),qd=Ll.or([yf,gf]),_d=Ll.or([vf,wf]),Vd=Ll.or([Bh,bh,Eh,Nh,Th,ks,Ih,Ch,Fh,Oh,Sh]),Wd=Ll.map(Jl([ff,Wh,df,Wh],Ll.or([yf,mf])),(function(e){return["boundarySpaceDecl",e]})),Zd=Ll.map(Jl([ff,Wh,_f,Wh],Ll.or([yf,mf])),(function(e){return["constructionDecl",e]})),$d=Ll.map(Jl([ff,Wh,Vf,Wh],Ll.or([Wf,Zf])),(function(e){return["orderingModeDecl",e]})),zd=Ll.map(Jl([ff,Wh,hf,Wh,$p,Wh,Yp,Wh],Ll.or([Af,xf])),(function(e){return["emptyOrderDecl",e]})),em=Ll.then(Jl([ff,Wh,Bf,Wh],qd),Jl([Vh,_s,Vh],_d),(function(e,t){return["copyNamespacesDecl",["preserveMode",e],["inheritMode",t]]}));function tm(e){switch(e[0]){case"constantExpr":case"varRef":case"contextItemExpr":case"functionCallExpr":case"sequenceExpr":case"elementConstructor":case"computedElementConstructor":case"computedAttributeConstructor":case"computedDocumentConstructor":case"computedTextConstructor":case"computedCommentConstructor":case"computedNamespaceConstructor":case"computedPIConstructor":case"orderedExpr":case"unorderedExpr":case"namedFunctionRef":case"inlineFunctionExpr":case"dynamicFunctionInvocationExpr":case"mapConstructor":case"arrayConstructor":case"stringConstructor":case"unaryLookup":return e}return["sequenceExpr",e]}function nm(e){if(!(1<=e&&55295>=e||57344<=e&&65533>=e||65536<=e&&1114111>=e))throw Error("XQST0090: The character reference "+e+" ("+e.toString(16)+") does not reference a valid codePoint.")}function rm(e){return e.replace(/(&[^;]+);/g,(function(e){if(/^&#x/.test(e))return nm(e=parseInt(e.slice(3,-1),16)),String.fromCodePoint(e);if(/^&#/.test(e))return nm(e=parseInt(e.slice(2,-1),10)),String.fromCodePoint(e);switch(e){case"&lt;":return"<";case"&gt;":return">";case"&amp;":return"&";case"&quot;":return String.fromCharCode(34);case"&apos;":return String.fromCharCode(39)}throw Error('XPST0003: Unknown character reference: "'+e+'"')}))}function am(e,t,n){if(!e.length)return[];for(var r=[e[0]],a=1;a<e.length;++a){var o=r[r.length-1];"string"==typeof o&&"string"==typeof e[a]?r[r.length-1]=o+e[a]:r.push(e[a])}if("string"==typeof r[0]&&0===r.length)return[];if(!(r=r.reduce((function(e,t,a){if("string"!=typeof t)e.push(t);else if(n&&/^\s*$/.test(t)){var o=r[a+1];(o&&"CDataSection"===o[0]||(a=r[a-1])&&"CDataSection"===a[0])&&e.push(rm(t))}else e.push(rm(t));return e}),[])).length)return r;if(1<r.length||t)for(e=0;e<r.length;e++)"string"==typeof r[e]&&(r[e]=["stringConstantExpr",["value",r[e]]]);return r}function om(e){return e[0].prefix?e[0].prefix+":"+e[1]:e[1]}var um=Ll.then(cd,Ll.optional(Us),(function(e,t){return null!==t?["singleType",["atomicType"].concat(h(e)),["optional"]]:["singleType",["atomicType"].concat(h(e))]})),im=Ll.map(cd,(function(e){return["atomicType"].concat(h(e))})),cm=new Map;function lm(e){function t(e,t){return t.reduce((function(e,t){return[t[0],["firstOperand",e],["secondOperand",t[1]]]}),e)}function n(e,t,n){return Ll.then(e,Ll.star(Ll.then(Ql(t,Vh),Ll.cut(e),(function(e,t){return[e,t]}))),n)}function r(e,t,n,r){return n=void 0===n?"firstOperand":n,r=void 0===r?"secondOperand":r,Ll.then(e,Ll.optional(Ll.then(Ql(t,Vh),Ll.cut(e),(function(e,t){return[e,t]}))),(function(e,t){return null===t?e:[t[0],[n,e],[r,t[1]]]}))}function a(t){return e.vb?function(e,n){if(!(e=t(e,n)).success)return e;var r=l.has(n)?l.get(n):{offset:n,line:-1,ja:-1},a=l.has(e.offset)?l.get(e.offset):{offset:e.offset,line:-1,ja:-1};return l.set(n,r),l.set(e.offset,a),Ll.okWithValue(e.offset,["x:stackTrace",{start:r,end:a},e.value])}:t}function o(e,t){return Z(e,t)}function u(e,t){return Pe(e,t)}function i(e,t){return a(Ll.or([It,Dt,Lt,Ot,it,Pt,Rt,jt,kt,Mt,ut]))(e,t)}function c(e,t){return n(i,_s,(function(e,t){return 0===t.length?e:["sequenceExpr",e].concat(h(t.map((function(e){return e[1]}))))}))(e,t)}var l=new Map,s=Ll.preceded(os,Ll.followed(Ql(c,Vh),us)),f=Ll.map(e.Ya?Ll.or([Ql(Ll.star(Ll.or([dd,md,yd,Zl(/[^"&]/)])),hs),Ql(Ll.star(Ll.or([dd,md,gd,Zl(/[^'&]/)])),ps)]):Ll.or([Ql(Ll.star(Ll.or([yd,Zl(/[^"]/)])),hs),Ql(Ll.star(Ll.or([gd,Zl(/[^']/)])),ps)]),(function(e){return e.join("")})),d=Ll.or([Ll.map(Jl([gp,Vh],Ll.delimited(Ll.followed(rs,Vh),Ll.then(ld,Jl([Vh,_s,Vh],cd),(function(e,t){return[["elementName",e],["typeName"].concat(h(t))]})),Ll.preceded(Vh,as))),(function(e){var t=p(e);return["elementTest",e=t.next().value,t=t.next().value]})),Ll.map(Jl([gp,Vh],Ll.delimited(rs,ld,as)),(function(e){return["elementTest",["elementName",e]]})),Ll.map(Jl([gp,Vh],Ll.delimited(rs,Vh,as)),(function(){return["elementTest"]}))]),m=Ll.or([Ll.map(cd,(function(e){return["QName"].concat(h(e))})),Ll.map(Ss,(function(){return["star"]}))]),y=Ll.or([Ll.map(Jl([vp,Vh],Ll.delimited(Ll.followed(rs,Vh),Ll.then(m,Jl([Vh,_s,Vh],cd),(function(e,t){return[["attributeName",e],["typeName"].concat(h(t))]})),Ll.preceded(Vh,as))),(function(e){var t=p(e);return["attributeTest",e=t.next().value,t=t.next().value]})),Ll.map(Jl([vp,Vh],Ll.delimited(rs,m,as)),(function(e){return["attributeTest",["attributeName",e]]})),Ll.map(Jl([vp,Vh],Ll.delimited(rs,Vh,as)),(function(){return["attributeTest"]}))]),g=Ll.map(Jl([wp,Vh,rs],Ll.followed(cd,as)),(function(e){return["schemaElementTest"].concat(h(e))})),v=Ll.map(Ll.delimited(Gh,Ql(cd,Vh),as),(function(e){return["schemaAttributeTest"].concat(h(e))})),w=Ll.map(Ll.preceded(Dh,Ll.followed(Ql(Ll.optional(Ll.or([d,g])),Vh),as)),(function(e){return["documentTest"].concat(h(e?[e]:[]))})),A=Ll.or([Ll.map(Ll.preceded(Rh,Ll.followed(Ql(Ll.or([zh,f]),Vh),as)),(function(e){return["piTest",["piTarget",e]]})),Vl(Wl([kh],"piTest"))]),x=Ll.or([w,d,y,g,v,A,vd,wd,Ad,xd]),B=Ll.or([Ll.map(Ll.preceded(Ts,zh),(function(e){return["Wildcard",["star"],["NCName",e]]})),Vl(Wl([Ss],"Wildcard")),Ll.map(Ll.followed(ud,Ss),(function(e){return["Wildcard",["uri",e],["star"]]})),Ll.map(Ll.followed(zh,Ns),(function(e){return["Wildcard",["NCName",e],["star"]]}))]),b=Ll.or([B,Ll.map(cd,(function(e){return["nameTest"].concat(h(e))}))]),E=Ll.or([x,b]),N=Ll.then(Ll.optional(Gs),E,(function(e,t){return null!==e||"attributeTest"===t[0]||"schemaAttributeTest"===t[0]?["stepExpr",["xpathAxis","attribute"],t]:["stepExpr",["xpathAxis","child"],t]})),T=Ll.or([Ll.then(fd,E,(function(e,t){return["stepExpr",["xpathAxis",e],t]})),N]),I=Ll.map(Ws,(function(){return["stepExpr",["xpathAxis","parent"],["anyKindTest"]]})),C=Ll.or([Ll.then(hd,E,(function(e,t){return["stepExpr",["xpathAxis",e],t]})),I]),F=Ll.map(Ll.star(Ll.preceded(Vh,s)),(function(e){return 0<e.length?["predicates"].concat(h(e)):void 0})),O=Ll.then(Ll.or([C,T]),F,(function(e,t){return void 0===t?e:e.concat([t])})),S=Ll.or([Td,Ll.map(f,(function(t){return["stringConstantExpr",["value",e.Ya?rm(t):t]]}))]),G=Ll.or([Ll.delimited(rs,Ql(c,Vh),as),Ll.map(Ll.delimited(rs,Vh,as),(function(){return["sequenceExpr"]}))]),D=Ll.or([i,Fd]),R=Ll.map(Ll.delimited(rs,Ql(Ll.optional(Ll.then(D,Ll.star(Ll.preceded(Ql(_s,Vh),D)),(function(e,t){return[e].concat(h(t))}))),Vh),as),(function(e){return null!==e?e:[]})),k=Ll.preceded(Ll.not(Kl(Cd,Vh,rs,(function(){})),["cannot use reseved keyword for function names"]),Ll.then(cd,Ll.preceded(Vh,R),(function(e,t){return["functionCallExpr",["functionName"].concat(h(e)),null!==t?["arguments"].concat(h(t)):["arguments"]]}))),U=Ll.then(cd,Ll.preceded(Rs,Nd),(function(e,t){return["namedFunctionRef",["functionName"].concat(h(e)),t]})),M=Ll.delimited(is,Ql(Ll.optional(c),Vh),cs),H=Ll.map(M,(function(e){return e||["sequenceExpr"]})),P=Ll.or([Ll.map(Xh,(function(){return[["voidSequenceType"]]})),Ll.then(o,Ll.optional(Ll.preceded(Vh,Od)),(function(e,t){return[e].concat(h(null!==t?[["occurrenceIndicator",t]]:[]))}))]),j=Ll.then(Jl([ks,Vh],cd),Ll.optional(Ll.followed(Ll.then(Jl([rs,Vh],S),Ll.star(Jl([_s,Vh],S)),(function(e,t){return e.concat(t)})),as)),(function(e,t){return["annotation",["annotationName"].concat(h(e))].concat(h(t?["arguments",t]:[]))})),X=Ll.map(Jl([mp,Vh,rs,Vh,Ss,Vh],as),(function(){return["anyFunctionTest"]})),L=Ll.then(Jl([mp,Vh,rs,Vh],Ll.optional(n(P,_s,(function(e,t){return e.concat.apply(e,t.map((function(e){return e[1]})))})))),Jl([Vh,as,Wh,op,Wh],P),(function(e,t){return["typedFunctionTest",["paramTypeList",["sequenceType"].concat(h(e||[]))],["sequenceType"].concat(h(t))]})),Y=Ll.then(Ll.star(j),Ll.or([X,L]),(function(e,t){return[t[0]].concat(h(e),h(t.slice(1)))})),Q=Ll.map(Jl([yp,Vh,rs,Vh,Ss,Vh],as),(function(){return["anyMapTest"]})),J=Ll.then(Jl([yp,Vh,rs,Vh],im),Jl([Vh,_s],Ll.followed(Ql(P,Vh),as)),(function(e,t){return["typedMapTest",e,["sequenceType"].concat(h(t))]})),K=Ll.or([Q,J]),q=Ll.map(Jl([tf,Vh,rs,Vh,Ss,Vh],as),(function(){return["anyArrayTest"]})),_=Ll.map(Jl([tf,Vh,rs],Ll.followed(Ql(P,Vh),as)),(function(e){return["typedArrayTest",["sequenceType"].concat(h(e))]})),V=Ll.or([q,_]),W=Ll.map(Ll.delimited(rs,Ql(o,Vh),as),(function(e){return["parenthesizedItemType",e]})),Z=Ll.or([x,Vl(Wl([jh],"anyItemType")),Y,K,V,im,W]),$=Ll.map(Jl([op,Wh],P),(function(e){return["typeDeclaration"].concat(h(e))})),z=Ll.then(Ll.preceded(Ds,cd),Ll.optional(Ll.preceded(Wh,$)),(function(e,t){return["param",["varName"].concat(h(e))].concat(h(t?[t]:[]))})),ee=n(z,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))})),te=ql(Ll.star(j),Jl([Vh,mp,Vh,rs,Vh],Ll.optional(ee)),Jl([Vh,as,Vh],Ll.optional(Ll.map(Jl([op,Vh],Ll.followed(P,Vh)),(function(e){return["typeDeclaration"].concat(h(e))})))),H,(function(e,t,n,r){return["inlineFunctionExpr"].concat(h(e),[["paramList"].concat(h(t||[]))],h(n?[n]:[]),[["functionBody",r]])})),ne=Ll.or([U,te]),re=Ll.map(i,(function(e){return["mapKeyExpr",e]})),ae=Ll.map(i,(function(e){return["mapValueExpr",e]})),oe=Ll.then(re,Ll.preceded(Ql(Fs,Vh),ae),(function(e,t){return["mapConstructorEntry",e,t]})),ue=Ll.preceded(yp,Ll.delimited(Ql(is,Vh),Ll.map(Ll.optional(n(oe,Ql(_s,Vh),(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))}))),(function(e){return e?["mapConstructor"].concat(h(e)):["mapConstructor"]})),Ll.preceded(Vh,cs))),ie=Ll.map(Ll.delimited(os,Ql(Ll.optional(n(i,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]})))).map((function(e){return["arrayElem",e]}))}))),Vh),us),(function(e){return["squareArray"].concat(h(null!==e?e:[]))})),ce=Ll.map(Ll.preceded(tf,Ll.preceded(Vh,M)),(function(e){return["curlyArray"].concat(h(null!==e?[["arrayElem",e]]:[]))})),le=Ll.map(Ll.or([ie,ce]),(function(e){return["arrayConstructor",e]})),se=Ll.or([zh,Nd,G,Ss]),pe=Ll.map(Ll.preceded(Us,Ll.preceded(Vh,se)),(function(e){return"*"===e?["unaryLookup",["star"]]:"string"==typeof e?["unaryLookup",["NCName",e]]:["unaryLookup",e]})),fe=Ll.or([dd,md,Wl([ls],"{"),Wl([ss],"}"),Ll.map(M,(function(e){return e||["sequenceExpr"]}))]),he=Ll.or([Gd,function(e,t){return Ae(e,t)},fe,Sd]),de=Ll.or([Ll.map(Dd,(function(e){return e.replace(/[\x20\x0D\x0A\x09]/g," ")})),fe]),me=Ll.or([Ll.map(Rd,(function(e){return e.replace(/[\x20\x0D\x0A\x09]/g," ")})),fe]),ye=Ll.map(Ll.or([Ql(Ll.star(Ll.or([yd,de])),hs),Ql(Ll.star(Ll.or([gd,me])),ps)]),(function(e){return am(e,!1,!1)})),ge=Ll.then(od,Ll.preceded(Ql(Ms,Ll.optional(_h)),ye),(function(e,t){if(""===e[0].prefix&&"xmlns"===e[1]){if(t.length&&"string"!=typeof t[0])throw Error("XQST0022: A namespace declaration may not contain enclosed expressions");return["namespaceDeclaration",t.length?["uri",t[0]]:["uri"]]}if("xmlns"===e[0].prefix){if(t.length&&"string"!=typeof t[0])throw Error("XQST0022: The namespace declaration for 'xmlns:"+e[1]+"' may not contain enclosed expressions");return["namespaceDeclaration",["prefix",e[1]],t.length?["uri",t[0]]:["uri"]]}return["attributeConstructor",["attributeName"].concat(e),0===t.length?["attributeValue"]:1===t.length&&"string"==typeof t[0]?["attributeValue",t[0]]:["attributeValueExpr"].concat(t)]})),ve=Ll.map(Ll.star(Ll.preceded(_h,Ll.optional(ge))),(function(e){return e.filter(Boolean)})),we=Kl(Ll.preceded(Ls,od),ve,Ll.or([Ll.map(gs,(function(){return null})),Ll.then(Ll.preceded(Js,Ll.star(he)),Jl([Vh,vs],Ll.followed(od,Ll.then(Ll.optional(_h),Js,(function(){return null})))),(function(e,t){return[am(e,!0,!0),t]}))]),(function(e,t,n){var r=n;if(n&&n.length){r=om(e);var a=om(n[1]);if(r!==a)throw Error('XQST0118: The start and the end tag of an element constructor must be equal. "'+r+'" does not match "'+a+'"');r=n[0]}return["elementConstructor",["tagName"].concat(h(e))].concat(h(t.length?[["attributeList"].concat(h(t))]:[]),h(r&&r.length?[["elementContent"].concat(h(r))]:[]))})),Ae=Ll.or([we,Ud,Pd]),xe=Ll.map(Jl([nf,Vh],M),(function(e){return["computedDocumentConstructor"].concat(h(e?[["argExpr",e]]:[]))})),Be=Ll.map(M,(function(e){return e?[["contentExpr",e]]:[]})),be=Ll.then(Jl([gp,Vh],Ll.or([Ll.map(cd,(function(e){return["tagName"].concat(h(e))})),Ll.map(Ll.delimited(is,Ql(c,Vh),cs),(function(e){return["tagNameExpr",e]}))])),Ll.preceded(Vh,Be),(function(e,t){return["computedElementConstructor",e].concat(h(t))})),Ee=Ll.then(Ll.preceded(vp,Ll.or([Ll.map(Jl([pd,Vh],cd),(function(e){return["tagName"].concat(h(e))})),Ll.map(Ll.preceded(Vh,Ll.delimited(is,Ql(c,Vh),cs)),(function(e){return["tagNameExpr",e]}))])),Ll.preceded(Vh,M),(function(e,t){return["computedAttributeConstructor",e,["valueExpr",t||["sequenceExpr"]]]})),Ne=Ll.map(M,(function(e){return e?[["prefixExpr",e]]:[]})),Te=Ll.map(M,(function(e){return e?[["URIExpr",e]]:[]})),Ie=Ll.then(Jl([rf,Vh],Ll.or([ed,Ne])),Ll.preceded(Vh,Te),(function(e,t){return["computedNamespaceConstructor"].concat(h(e),h(t))})),Ce=Ll.map(Jl([af,Vh],M),(function(e){return["computedTextConstructor"].concat(h(e?[["argExpr",e]]:[]))})),Fe=Ll.map(Jl([of,Vh],M),(function(e){return["computedCommentConstructor"].concat(h(e?[["argExpr",e]]:[]))})),Oe=Jl([uf,Vh],Ll.then(Ll.or([Ll.map(zh,(function(e){return["piTarget",e]})),Ll.map(Ll.delimited(is,Ql(c,Vh),cs),(function(e){return["piTargetExpr",e]}))]),Ll.preceded(Vh,M),(function(e,t){return["computedPIConstructor",e].concat(h(t?[["piValueExpr",t]]:[]))}))),Se=Ll.or([xe,be,Ee,Ie,Ce,Fe,Oe]),Ge=Ll.or([Ae,Se]),De=Ll.or([S,sd,G,Id,k,Ge,ne,ue,le,pe]),Re=Ll.map(Jl([Us,Vh],se),(function(e){return"*"===e?["lookup",["star"]]:"string"==typeof e?["lookup",["NCName",e]]:["lookup",e]})),ke=Ll.then(Ll.map(De,(function(e){return tm(e)})),Ll.star(Ll.or([Ll.map(Ll.preceded(Vh,s),(function(e){return["predicate",e]})),Ll.map(Ll.preceded(Vh,R),(function(e){return["argumentList",e]})),Ll.preceded(Vh,Re)])),(function(e,t){function n(){i&&1===o.length?u.push(["predicate",o[0]]):0!==o.length&&u.push(["predicates"].concat(h(o))),o.length=0}function r(e){n(),0!==u.length?("sequenceExpr"===a[0][0]&&2<a[0].length&&(a=[["sequenceExpr"].concat(h(a))]),a=[["filterExpr"].concat(h(a))].concat(h(u)),u.length=0):e&&(a=[["filterExpr"].concat(h(a))])}var a=[e],o=[],u=[],i=!1;for(t=(e=p(t)).next();!t.done;t=e.next())switch(t=t.value,t[0]){case"predicate":o.push(t[1]);break;case"lookup":i=!0,n(),u.push(t);break;case"argumentList":r(!1),1<a.length&&(a=[["sequenceExpr",["pathExpr",["stepExpr"].concat(h(a))]]]),a=[["dynamicFunctionInvocationExpr",["functionItem"].concat(h(a))].concat(h(t[1].length?[["arguments"].concat(h(t[1]))]:[]))];break;default:throw Error("unreachable")}return r(!0),a})),Ue=Ll.or([Ll.map(ke,(function(e){return["stepExpr"].concat(h(e))})),O]),Me=Ll.followed(De,Ll.peek(Ll.not(Ll.preceded(Vh,Ll.or([s,R,Re])),["primary expression not followed by predicate, argumentList, or lookup"]))),He=Ll.or([Kl(Ue,Ll.preceded(Vh,jd),Ll.preceded(Vh,u),(function(e,t,n){return["pathExpr",e,t].concat(h(n))})),Ll.then(Ue,Ll.preceded(Ql(zs,Vh),u),(function(e,t){return["pathExpr",e].concat(h(t))})),Me,Ll.map(Ue,(function(e){return["pathExpr",e]}))]),Pe=Ll.or([Kl(Ue,Ll.preceded(Vh,jd),Ll.preceded(Vh,u),(function(e,t,n){return[e,t].concat(h(n))})),Ll.then(Ue,Ll.preceded(Ql(zs,Vh),u),(function(e,t){return[e].concat(h(t))})),Ll.map(Ue,(function(e){return[e]}))]),je=Ll.or([Ll.map(Jl([zs,Vh],Pe),(function(e){return["pathExpr",["rootExpr"]].concat(h(e))})),Ll.then(jd,Ll.preceded(Vh,Pe),(function(e,t){return["pathExpr",["rootExpr"],e].concat(h(t))})),Ll.map(Ll.followed(zs,Ll.not(Ll.preceded(Vh,e.Ya?Zl(/[*<a-zA-Z]/):Zl(/[*a-zA-Z]/)),["Single rootExpr cannot be by followed by something that can be interpreted as a relative path"])),(function(){return["pathExpr",["rootExpr"]]}))]),Xe=Yl(Ll.or([He,je]),cm),Le=Ll.preceded(sf,Ll.then(Ll.optional(Ll.or([Ll.map(Ll.preceded(Vh,Xd),(function(e){return["validationMode",e]})),Ll.map(Jl([Vh,pf,Vh],cd),(function(e){return["type"].concat(h(e))}))])),Ll.delimited(Ll.preceded(Vh,is),Ql(c,Vh),cs),(function(e,t){return["validateExpr"].concat(h(e?[e]:[]),[["argExpr",t]])}))),Ye=Ll.delimited(ts,Ll.then(Ll.preceded(Vh,cd),Ll.optional(Ll.preceded(Wh,Ld)),(function(e,t){return t?["pragma",["pragmaName",e],["pragmaContents",t]]:["pragma",["pragmaName",e]]})),Ll.preceded(Vh,ns)),Qe=Ll.map(Ll.followed(Ll.plus(Ye),Ll.preceded(Vh,Ll.delimited(is,Ql(Ll.optional(c),Vh),cs))),(function(e){return["extensionExpr"].concat(h(e))})),Je=a(n(Xe,Hs,(function(e,t){return 0===t.length?e:["simpleMapExpr","pathExpr"===e[0]?e:["pathExpr",["stepExpr",["filterExpr",tm(e)]]]].concat(t.map((function(e){return"pathExpr"===(e=e[1])[0]?e:["pathExpr",["stepExpr",["filterExpr",tm(e)]]]})))}))),Ke=Ll.or([Le,Qe,Je]),qe=Ll.or([Ll.then(Ll.or([Wl([$s],"unaryMinusOp"),Wl([Zs],"unaryPlusOp")]),Ll.preceded(Vh,(function(e,t){return qe(e,t)})),(function(e,t){return[e,["operand",t]]})),Ke]),_e=Ll.or([Ll.map(cd,(function(e){return["EQName"].concat(h(e))})),sd,G]),Ve=Ll.then(qe,Ll.star(Jl([Vh,tp,Vh],Ll.then(_e,Ll.preceded(Vh,R),(function(e,t){return[e,t]})))),(function(e,t){return t.reduce((function(e,t){return["arrowExpr",["argExpr",e],t[0],["arguments"].concat(h(t[1]))]}),e)})),We=Ll.then(Ve,Ll.optional(Jl([Vh,up,Wh,op,pd,Vh],um)),(function(e,t){return null!==t?["castExpr",["argExpr",e],t]:e})),Ze=Ll.then(We,Ll.optional(Jl([Vh,ip,Wh,op,pd,Vh],um)),(function(e,t){return null!==t?["castableExpr",["argExpr",e],t]:e})),$e=Ll.then(Ze,Ll.optional(Jl([Vh,cp,Wh,op,pd,Vh],P)),(function(e,t){return null!==t?["treatExpr",["argExpr",e],["sequenceType"].concat(h(t))]:e})),ze=Ll.then($e,Ll.optional(Jl([Vh,lp,Wh,sp,pd,Vh],P)),(function(e,t){return null!==t?["instanceOfExpr",["argExpr",e],["sequenceType"].concat(h(t))]:e})),et=n(ze,Ll.followed(Ll.or([Wl([Ap],"intersectOp"),Wl([xp],"exceptOp")]),pd),t),tt=n(et,Ll.or([Wl([Ps],"unionOp"),Ll.followed(Wl([Bp],"unionOp"),pd)]),t),nt=n(tt,Ll.or([Wl([Ss],"multiplyOp"),Ll.followed(Wl([Ip],"divOp"),pd),Ll.followed(Wl([Cp],"idivOp"),pd),Ll.followed(Wl([Fp],"modOp"),pd)]),t),rt=n(nt,Ll.or([Wl([$s],"subtractOp"),Wl([Zs],"addOp")]),t),at=n(r(rt,Ll.followed(Wl([bp],"rangeSequenceExpr"),pd),"startExpr","endExpr"),Wl([js],"stringConcatenateOp"),t),ot=n(r(at,Ll.or([Yd,Qd,Jd])),Ll.followed(Wl([Tp],"andOp"),pd),t),ut=n(ot,Ll.followed(Wl([Np],"orOp"),pd),t),it=Ll.then(Ll.then(Jl([Pp,Vh,rs,Vh],c),Jl([Vh,as,Vh,jp,pd,Vh],i),(function(e,t){return[e,t]})),Jl([Vh,Xp,pd,Vh],i),(function(e,t){return["ifThenElseExpr",["ifClause",e[0]],["thenClause",e[1]],["elseClause",t]]})),ct=Ll.delimited(Lp,Wh,Yp),lt=Ll.map(Jl([Qp,Wh,Ds],cd),(function(e){return["positionalVariableBinding"].concat(h(e))})),st=_l(Ll.preceded(Ds,Ll.cut(cd)),Ll.cut(Ll.preceded(Vh,Ll.optional($))),Ll.cut(Ll.preceded(Vh,Ll.optional(ct))),Ll.cut(Ll.preceded(Vh,Ll.optional(lt))),Ll.cut(Ll.preceded(Ql(Jp,Vh),i)),(function(e,t,n,r,a){return["forClauseItem",["typedVariableBinding",["varName"].concat(h(e),h(t?[t]:[]))]].concat(h(n?[["allowingEmpty"]]:[]),h(r?[r]:[]),[["forExpr",a]])})),pt=Jl([Kp,Wh],n(st,_s,(function(e,t){return["forClause",e].concat(h(t.map((function(e){return e[1]}))))}))),ft=Kl(Ll.preceded(Ds,cd),Ll.preceded(Vh,Ll.optional($)),Ll.preceded(Ql(Is,Vh),i),(function(e,t,n){return["letClauseItem",["typedVariableBinding",["varName"].concat(h(e))].concat(h(t?[t]:[])),["letExpr",n]]})),ht=Ll.map(Jl([qp,Vh],n(ft,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))}))),(function(e){return["letClause"].concat(h(e))})),dt=Ll.or([pt,ht]),mt=Ll.map(Jl([_p,pd,Vh],i),(function(e){return["whereClause",e]})),yt=Ll.map(Ll.preceded(Ds,cd),(function(e){return["varName"].concat(h(e))})),gt=Ll.then(Ll.preceded(Vh,Ll.optional($)),Ll.preceded(Ql(Is,Vh),i),(function(e,t){return["groupVarInitialize"].concat(h(e?[["typeDeclaration"].concat(h(e))]:[]),[["varValue",t]])})),vt=Kl(yt,Ll.optional(gt),Ll.optional(Ll.map(Ll.preceded(Ql(Vp,Vh),f),(function(e){return["collation",e]}))),(function(e,t,n){return["groupingSpec",e].concat(h(t?[t]:[]),h(n?[n]:[]))})),wt=n(vt,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))})),At=Ll.map(Jl([Wp,Wh,Zp,Vh],wt),(function(e){return["groupByClause"].concat(h(e))})),xt=Kl(Ll.optional(Ll.or([ih,ch])),Ll.optional(Jl([Vh,Yp,Vh],Ll.or([Af,xf].map((function(e){return Ll.map(e,(function(e){return"empty "+e}))}))))),Ll.preceded(Vh,Ll.optional(Jl([Vp,Vh],f))),(function(e,t,n){return e||t||n?["orderModifier"].concat(h(e?[["orderingKind",e]]:[]),h(t?[["emptyOrderingMode",t]]:[]),h(n?[["collation",n]]:[])):null})),Bt=Ll.then(i,Ll.preceded(Vh,xt),(function(e,t){return["orderBySpec",["orderByExpr",e]].concat(h(t?[t]:[]))})),bt=n(Bt,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))})),Et=Ll.then(Ll.or([Ll.map(Jl([$p,Wh],Zp),(function(){return!1})),Ll.map(Jl([zp,Wh,$p,Wh],Zp),(function(){return!0}))]),Ll.preceded(Vh,bt),(function(e,t){return["orderByClause"].concat(h(e?[["stable"]]:[]),h(t))})),Nt=Ll.or([dt,mt,At,Et]),Tt=Ll.map(Jl([ef,Vh],i),(function(e){return["returnClause",e]})),It=Kl(dt,Ll.cut(Ll.star(Ll.preceded(Vh,Nt))),Ll.cut(Ll.preceded(Vh,Tt)),(function(e,t,n){return["flworExpr",e].concat(h(t),[n])})),Ct=n(P,Ps,(function(e,t){return 0===t.length?["sequenceType"].concat(h(e)):["sequenceTypeUnion",["sequenceType"].concat(h(e))].concat(h(t.map((function(e){return["sequenceType"].concat(h(e[1]))}))))})),Ft=Kl(Jl([Ef,Vh],Ll.optional(Ll.preceded(Ds,Ll.followed(Ll.followed(cd,Wh),op)))),Ll.preceded(Vh,Ct),Jl([Wh,ef,Wh],i),(function(e,t,n){return["typeswitchExprCaseClause"].concat(e?[["variableBinding"].concat(h(e))]:[],[t],[["resultExpr",n]])})),Ot=ql(Ll.preceded(Nf,Ql(Ll.delimited(rs,Ql(c,Vh),as),Vh)),Ll.plus(Ll.followed(Ft,Vh)),Jl([hf,Wh],Ll.optional(Ll.preceded(Ds,Ll.followed(cd,Wh)))),Jl([ef,Wh],i),(function(e,t,n,r){return["typeswitchExpr",["argExpr",e]].concat(h(t),[["typeswitchExprDefaultClause"].concat(h(n||[]),[["resultExpr",r]])])})),St=Kl(Ll.preceded(Ds,cd),Ll.optional(Ll.preceded(Wh,$)),Ll.preceded(Ql(Jp,Wh),i),(function(e,t,n){return["quantifiedExprInClause",["typedVariableBinding",["varName"].concat(h(e))].concat(h(t?[t]:[])),["sourceExpr",n]]})),Gt=n(St,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))})),Dt=Kl(Ll.or([Tf,If]),Ll.preceded(Wh,Gt),Ll.preceded(Ql(Cf,Vh),i),(function(e,t,n){return["quantifiedExpr",["quantifier",e]].concat(h(t),[["predicateExpr",n]])})),Rt=Ll.map(Jl([hp,Wh,Ll.or([fp,pp]),Wh],i),(function(e){return["deleteExpr",["targetExpr",e]]})),kt=Kl(Jl([Ff,Wh],Ll.optional(Jl([dp,Wh,sp],Wh))),Jl([pp,Wh],i),Ll.preceded(Ql(Of,Wh),i),(function(e,t,n){return e?["replaceExpr",["replaceValue"],["targetExpr",t],["replacementExpr",n]]:["replaceExpr",["targetExpr",t],["replacementExpr",n]]})),Ut=Ll.then(sd,Ll.preceded(Ql(Is,Vh),i),(function(e,t){return["transformCopy",e,["copySource",t]]})),Mt=Kl(Jl([Sf,Wh],n(Ut,_s,(function(e,t){return[e].concat(h(t.map((function(e){return e[1]}))))}))),Jl([Vh,Gf,Wh],i),Ll.preceded(Ql(ef,Wh),i),(function(e,t,n){return["transformExpr",["transformCopies"].concat(h(e)),["modifyExpr",t],["returnExpr",n]]})),Ht=Ll.or([Ll.followed(Ll.map(Ll.optional(Ll.followed(Jl([op,Wh],Ll.or([Ll.map(Df,(function(){return["insertAsFirst"]})),Ll.map(Rf,(function(){return["insertAsLast"]}))])),Wh)),(function(e){return e?["insertInto",e]:["insertInto"]})),Mf),Ll.map(Uf,(function(){return["insertAfter"]})),Ll.map(kf,(function(){return["insertBefore"]}))]),Pt=Kl(Jl([Hf,Wh,Ll.or([fp,pp]),Wh],i),Ll.preceded(Wh,Ht),Ll.preceded(Wh,i),(function(e,t,n){return["insertExpr",["sourceExpr",e],t,["targetExpr",n]]})),jt=Ll.then(Jl([Pf,Wh,pp,Vh],i),Jl([Wh,op,Wh],i),(function(e,t){return["renameExpr",["targetExpr",e],["newNameExpr",t]]})),Xt=Ll.then(Ll.plus(Ll.map(Jl([Ef,Wh],i),(function(e){return["switchCaseExpr",e]}))),Jl([Wh,ef,Wh],i),(function(e,t){return["switchExprCaseClause"].concat(h(e),[["resultExpr",t]])})),Lt=Kl(Jl([jf,Vh,rs],c),Jl([Vh,as,Vh],Ll.plus(Ll.followed(Xt,Vh))),Jl([hf,Wh,ef,Wh],i),(function(e,t,n){return["switchExpr",["argExpr",e]].concat(h(t),[["switchExprDefaultClause",["resultExpr",n]]])})),Yt=Ll.map(c,(function(e){return["queryBody",e]})),Qt=Jl([ff,Wh,rf,Wh],Ll.cut(Ll.then(zh,Ll.preceded(Ql(Ms,Vh),f),(function(e,t){return["namespaceDecl",["prefix",e],["uri",t]]})))),Jt=Ll.then(Jl([Xf,Wh,Ds,Vh],Ll.then(cd,Ll.optional(Ll.preceded(Vh,$)),(function(e,t){return[e,t]}))),Ll.cut(Ll.or([Ll.map(Jl([Vh,Is,Vh],i),(function(e){return["varValue",e]})),Ll.map(Jl([Wh,Lf],Ll.optional(Jl([Vh,Is,Vh],i))),(function(e){return["external"].concat(h(e?[["varValue",e]]:[]))}))])),(function(e,t){var n=p(e);return e=n.next().value,n=n.next().value,["varDecl",["varName"].concat(h(e))].concat(h(null!==n?[n]:[]),[t])})),Kt=ql(Jl([mp,Wh,Ll.peek(Ll.not(Cd,["Cannot use reserved function name"]))],cd),Ll.cut(Jl([Vh,rs,Vh],Ll.optional(ee))),Ll.cut(Jl([Vh,as],Ll.optional(Jl([Wh,op,Wh],P)))),Ll.cut(Ll.preceded(Vh,Ll.or([Ll.map(H,(function(e){return["functionBody",e]})),Ll.map(Lf,(function(){return["externalDefinition"]}))]))),(function(e,t,n,r){return["functionDecl",["functionName"].concat(h(e)),["paramList"].concat(h(t||[]))].concat(h(n?[["typeDeclaration"].concat(h(n))]:[]),[r])})),qt=Jl([ff,Wh],Ll.then(Ll.star(Ll.followed(Ll.or([j,Kd]),Wh)),Ll.or([Jt,Kt]),(function(e,t){return[t[0]].concat(h(e),h(t.slice(1)))}))),_t=Ll.then(Jl([ff,Wh,hf,Wh],Ll.or([gp,mp])),Jl([Wh,rf,Wh],f),(function(e,t){return["defaultNamespaceDecl",["defaultNamespaceCategory",e],["uri",t]]})),Vt=Ll.or([Ll.map(Ll.followed(Jl([rf,Wh],zh),Ll.preceded(Vh,Ms)),(function(e){return["namespacePrefix",e]})),Ll.map(Jl([hf,Wh,gp,Wh],rf),(function(){return["defaultElementNamespace"]}))]),Wt=Jl([Qf,Wh,Jf],Kl(Ll.optional(Ll.preceded(Wh,Vt)),Ll.preceded(Vh,f),Ll.optional(Ll.then(Jl([Wh,Qp,Wh],f),Ll.star(Jl([Vh,_s,Vh],f)),(function(e,t){return[e].concat(h(t))}))),(function(e,t,n){return["schemaImport"].concat(h(e?[e]:[]),[["targetNamespace",t]],h(n?[n]:[]))}))),Zt=Jl([Qf,Wh,Kf],Kl(Ll.optional(Ll.followed(Jl([Wh,rf,Wh],zh),Ll.preceded(Vh,Ms))),Ll.preceded(Vh,f),Ll.optional(Ll.then(Jl([Wh,Qp,Wh],f),Ll.star(Jl([Vh,_s,Vh],f)),(function(e,t){return[e].concat(h(t))}))),(function(e,t){return["moduleImport",["namespacePrefix",e],["targetNamespace",t]]}))),$t=Ll.or([Wt,Zt]),zt=Ll.map(Jl([ff,Wh,hf,Wh,Vp,Wh],f),(function(e){return["defaultCollationDecl",e]})),en=Ll.map(Jl([ff,Wh,qf,Wh],f),(function(e){return["baseUriDecl",e]})),tn=Ll.then(Jl([ff,Wh],Ll.or([Ll.map(Jl([bf,Wh],cd),(function(e){return["decimalFormatName"].concat(h(e))})),Ll.map(Jl([hf,Wh],bf),(function(){return null}))])),Ll.star(Ll.then(Ll.preceded(Wh,Vd),Ll.preceded(Ql(Ms,Wh),f),(function(e,t){return["decimalFormatParam",["decimalFormatParamName",e],["decimalFormatParamValue",t]]}))),(function(e,t){return["decimalFormatDecl"].concat(h(e?[e]:[]),h(t))})),nn=Ll.or([Wd,zt,en,Zd,$d,zd,em,tn]),rn=Ll.then(Jl([ff,Wh,$f,Wh],cd),Ll.preceded(Wh,f),(function(e,t){return["optionDecl",["optionName",e],["optionContents",t]]})),an=Ll.then(Jl([ff,Wh,zf,Wh,eh],Ll.optional(Jl([Wh,op],Z))),Ll.or([Ll.map(Ll.preceded(Ql(Is,Vh),i),(function(e){return["varValue",e]})),Ll.map(Jl([Wh,Lf],Ll.optional(Ll.preceded(Ql(Is,Vh),i))),(function(){return["external"]}))]),(function(e,t){return["contextItemDecl"].concat(h(e?[["contextItemType",e]]:[]),[t])})),on=Ll.then(Ll.star(Ll.followed(Ll.or([_t,nn,Qt,$t]),Ll.cut(Ql(Os,Vh)))),Ll.star(Ll.followed(Ll.or([an,qt,rn]),Ll.cut(Ql(Os,Vh)))),(function(e,t){return 0===e.length&&0===t.length?null:["prolog"].concat(h(e),h(t))})),un=Jl([Kf,Wh,rf,Wh],Ll.then(Ll.followed(zh,Ql(Ms,Vh)),Ll.followed(f,Ql(Os,Vh)),(function(e,t){return["moduleDecl",["prefix",e],["uri",t]]}))),cn=Ll.then(un,Ll.preceded(Vh,on),(function(e,t){return["libraryModule",e].concat(h(t?[t]:[]))})),ln=Ll.then(on,Ll.preceded(Vh,Yt),(function(e,t){return["mainModule"].concat(h(e?[e]:[]),[t])})),sn=Ll.map(Jl([th,Vh],Ll.followed(Ll.or([Ll.then(Ll.preceded(rh,Wh),f,(function(e){return["encoding",e]})),Ll.then(Jl([nh,Wh],f),Ll.optional(Jl([Wh,rh,Wh],f)),(function(e,t){return[["version",e]].concat(h(t?[["encoding",t]]:[]))}))]),Ll.preceded(Vh,Os))),(function(e){return["versionDecl"].concat(h(e))})),pn=Ll.then(Ll.optional(Ql(sn,Vh)),Ll.or([cn,ln]),(function(e,t){return["module"].concat(h(e?[e]:[]),[t])})),fn=Ll.complete(Ql(pn,Vh));return function(e,t){l.clear(),t=fn(e,t);for(var n=1,r=1,a=0;a<e.length+1;a++){if(l.has(a)){var o=l.get(a);o.line=r,o.ja=n}"\r"===(o=e[a])||"\n"===o?(r++,n=1):n++}return t}}var sm=lm({vb:!1,Ya:!1}),pm=lm({vb:!0,Ya:!1}),fm=lm({vb:!1,Ya:!0}),hm=lm({vb:!0,Ya:!0});function dm(e,t){var n=!!t.$;if(t=!!t.debug,Lh.clear(),Yh.clear(),cm.clear(),!0===(n=n?t?hm(e,0):fm(e,0):t?pm(e,0):sm(e,0)).success)return n.value;throw t=(e=e.substring(0,n.offset).split("\n"))[e.length-1].length+1,new ti({start:{offset:n.offset,line:e.length,ja:t},end:{offset:n.offset+1,line:e.length,ja:t+1}},"",Error("XPST0003: Failed to parse script. Expected "+[].concat(h(new Set(n.expected)))))}var mm="http://www.w3.org/XML/1998/namespace http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math http://www.w3.org/2012/xquery http://www.w3.org/2005/xpath-functions/array http://www.w3.org/2005/xpath-functions/map".split(" ");function ym(e,t,n,r,a){var o=Po(e,"functionName"),u=Xo(o,"prefix")||"",i=Xo(o,"URI"),c=jo(o);if(null===i&&!(i=""===u?null===t.v?"http://www.w3.org/2005/xpath-functions":t.v:t.aa(u))&&u)throw Io(u);if(mm.includes(i))throw Bo();if(o=(u=Yo(e,"annotation").map((function(e){return Po(e,"annotationName")}))).every((function(e){return!Xo(e,"URI")&&"private"!==jo(e)})),u=u.some((function(e){return!Xo(e,"URI")&&"updating"===jo(e)})),!i)throw bo();var l=Jo(e),s=Yo(Po(e,"paramList"),"param"),p=s.map((function(e){return Po(e,"varName")})),f=s.map((function(e){return Jo(e)}));if(e=Po(e,"functionBody")){if(t.xa(i,c,f.length))throw Error("XQST0049: The function Q{"+i+"}"+c+"#"+f.length+" has already been declared.");if(!a)return;var d=Sl(e[1],{ua:!1,$:!0}),m=new Oo(t),y=p.map((function(e){var n=Xo(e,"URI"),r=Xo(e,"prefix");return e=jo(e),r&&null===n&&(n=t.aa(r||"")),Uo(m,n,e)}));a=u?{j:f,arity:p.length,callFunction:function(e,t,n){var r=O.apply(3,arguments),a=jt(Pt(e,-1,null,Ie.empty()),y.reduce((function(e,t,n){return e[t]=Ce(r[n]),e}),Object.create(null)));return d.s(a,t)},Eb:!1,I:!0,hb:o,localName:c,namespaceURI:i,i:l}:{j:f,arity:p.length,callFunction:function(e,t,n){var r=O.apply(3,arguments),a=jt(Pt(e,-1,null,Ie.empty()),y.reduce((function(e,t,n){return e[t]=Ce(r[n]),e}),Object.create(null)));return ia(d,a,t)},Eb:!1,I:!1,hb:o,localName:c,namespaceURI:i,i:l},n.push({ca:d,Mb:m}),r.push({arity:p.length,ca:d,Ib:a,localName:c,namespaceURI:i,hb:o})}else{if(u)throw Error("Updating external function declarations are not supported");a={j:f,arity:p.length,callFunction:function(e,t,n){var r=O.apply(3,arguments),a=n.xa(i,c,p.length,!0);if(!a)throw Error("XPST0017: Function Q{"+i+"}"+c+" with arity of "+p.length+" not registered. "+fo(c));if(a.i.type!==l.type||a.j.some((function(e,t){return e.type!==f[t].type})))throw Error("External function declaration types do not match actual function");return a.callFunction.apply(a,[e,t,n].concat(h(r)))},Eb:!0,I:!1,localName:c,namespaceURI:i,hb:o,i:l}}Ro(t,i,c,p.length,a)}function gm(e,t,n,r){var a=[],o=[];Yo(e,"*").forEach((function(e){switch(e[0]){case"moduleImport":case"namespaceDecl":case"defaultNamespaceDecl":case"functionDecl":case"varDecl":break;default:throw Error("Not implemented: only module imports, namespace declarations, and function declarations are implemented in XQuery modules")}}));var u=new Set;Yo(e,"moduleImport").forEach((function(e){var n=jo(Po(e,"namespacePrefix"));if(e=jo(Po(e,"targetNamespace")),u.has(e))throw Error('XQST0047: The namespace "'+e+'" is imported more than once.');u.add(e),ko(t,n,e)})),Yo(e,"namespaceDecl").forEach((function(e){var n=jo(Po(e,"prefix"));if(e=jo(Po(e,"uri")),"xml"===n||"xmlns"===n)throw No();if("http://www.w3.org/XML/1998/namespace"===e||"http://www.w3.org/2000/xmlns/"===e)throw No();ko(t,n,e)}));for(var i=null,c=null,l=p(Yo(e,"defaultNamespaceDecl")),s=l.next();!s.done;s=l.next()){var f=s.value;if(s=jo(Po(f,"defaultNamespaceCategory")),!(f=jo(Po(f,"uri"))))throw bo();if("http://www.w3.org/XML/1998/namespace"===f||"http://www.w3.org/2000/xmlns/"===f)throw No();if("function"===s){if(i)throw Eo();i=f}else if("element"===s){if(c)throw Eo();c=f}}i&&(t.v=i),c&&ko(t,"",c),Yo(e,"functionDecl").forEach((function(e){ym(e,t,a,o,n)}));var h=[];return Yo(e,"varDecl").forEach((function(e){var r=Qo(Po(e,"varName")),o=r.namespaceURI;if(null===o&&!(o=t.aa(r.prefix))&&r.prefix)throw Io(r.prefix);if(mm.includes(o))throw Bo();var u,i,c=Po(e,"external");if(e=Po(e,"varValue"),null!==c?null!==(c=Po(c,"varValue"))&&(u=Po(c,"*")):null!==e&&(u=Po(e,"*")),h.some((function(e){return e.namespaceURI===o&&e.localName===r.localName})))throw Error("XQST0049: The variable "+(o?"Q{"+o+"}":"")+r.localName+" has already been declared.");if(Uo(t,o||"",r.localName),n&&(u&&(i=Sl(u,{ua:!1,$:!0})),u&&!Do(t,o||"",r.localName))){var l=null;Mo(t,o,r.localName,(function(e,t){return l?l():(l=Ce(ia(i,e,t)))()})),a.push({ca:i,Mb:t}),h.push({ca:i,localName:r.localName,namespaceURI:o})}})),o.forEach((function(e){if(!e.Ib.I&&e.ca.I)throw Vr("The function Q{"+e.namespaceURI+"}"+e.localName+" is updating but the %updating annotation is missing.")})),{Ma:o.map((function(e){return e.Ib})),Va:h,source:r,ra:function(e){u.forEach((function(e){Pl(t,e)})),a.forEach((function(t){var n=t.ca,r=t.Mb;u.forEach((function(e){Pl(r,e)})),e.Ma.forEach((function(e){r.xa(e.namespaceURI,e.localName,e.arity,!0)||e.hb&&Ro(r,e.namespaceURI,e.localName,e.arity,e)})),e.Va.forEach((function(e){r.ib(e.namespaceURI,e.localName)||Uo(r,e.namespaceURI,e.localName)})),n.v(r)}))}}}function vm(e,t,n,r,a,o,u){var i=t.$?"XQuery":"XPath";return null!==(n=t.La?null:Rl(e,i,n,r,a,t.debug,o,u))?{state:n.rc?1:2,ca:n.ca}:{state:0,hc:"string"==typeof e?dm(e,t):Ul(e)}}function wm(e,t,n,r){var a=Po(e,"mainModule");if(!a)throw Error("Can not execute a library module.");var o=Po(a,"prolog");if(o){if(!t.$)throw Error("XPST0003: Use of XQuery functionality is not allowed in XPath context");jl(),(r=gm(o,n,!0,r)).ra(r)}return wu(e,new Iu(n)),il(e=Lo(a,["queryBody","*"]),t)}function Am(e,t,n,r,a,o,u){var i=new vo(n,r,o,u),c=new Oo(i);switch(0<Object.keys(a).length&&jl(),Object.keys(a).forEach((function(e){var t=a[e];Pl(c,t),ko(c,e,t)})),"string"==typeof e&&(e=Xl(e)),(n=vm(e,t,n,r,a,o,u)).state){case 2:return{ia:c,ca:n.ca};case 1:return n.ca.v(c),kl(e,t.$?"XQuery":"XPath",i,a,n.ca,t.debug,o),{ia:c,ca:n.ca};case 0:return(n=wm(n.hc,t,c,e)).v(c),t.La||kl(e,t.$?"XQuery":"XPath",i,a,n,t.debug,o),{ia:c,ca:n}}}function xm(e,t,n,r){e=e.first();var a=t.first().h.reduce((function(e,t){return e[t.key.value]=Ce(t.value()),e}),Object.create(null));t=a["."]?a["."]():Ie.empty(),delete a["."];try{if(se(e.type,1))var o=e.value;else{if(!se(e.type,54))throw Jt("Unable to convert selector argument of type "+me[e.type]+" to either an "+me[1]+" or an "+me[54]+" representing an XQueryX program while calling 'fontoxpath:evaluate'");o=e.value.node}var u=Am(o,{ua:!1,$:!0,debug:r.debug,La:r.La},(function(e){return n.aa(e)}),Object.keys(a).reduce((function(e,t){return e[t]=t,e}),{}),{},"http://www.w3.org/2005/xpath-functions",(function(e,t){return n.Ua(e,t)})),i=u.ca,c=u.ia,l=!t.G(),s=new Rt({N:l?t.first():null,Ka:l?0:-1,Da:t,Aa:Object.keys(a).reduce((function(e,t){return e[c.ib(null,t)]=a[t],e}),Object.create(null))});return{sc:i.h(s,r).value,pc:e}}catch(t){lo(e.value,t)}}function Bm(e,t,n){if(1!==t.node.nodeType&&9!==t.node.nodeType)return[];var r=Qe(e,t).reduce((function(t,r){for(var a=(r=p(Bm(e,r,n))).next();!a.done;a=r.next())t.push(a.value);return t}),[]);return n(t)&&r.unshift(t),r}function bm(e,t,n,r,a){if(!(e=a.first()))throw Qt("The context is absent, it needs to be present to use id function.");if(!se(e.type,53))throw Jt("The context item is not a node, it needs to be node to use id function.");var o=t.h,u=r.O().reduce((function(e,t){return t.value.split(/\s+/).forEach((function(t){e[t]=!0})),e}),Object.create(null));for(t=e.value;9!==t.node.nodeType;)if(null===(t=Ve(o,t)))throw Error("FODC0001: the root node of the target node is not a document node.");return t=Bm(o,t,(function(e){return!(1!==e.node.nodeType||!(e=Ye(o,e,"id"))||!u[e]||(u[e]=!1,0))})),Ie.create(t.map((function(e){return et(e)})))}function Em(e,t,n,r,a){if(!(e=a.first()))throw Qt("The context is absent, it needs to be present to use idref function.");if(!se(e.type,53))throw Jt("The context item is not a node, it needs to be node to use idref function.");var o=t.h,u=r.O().reduce((function(e,t){return e[t.value]=!0,e}),Object.create(null));for(t=e.value;9!==t.node.nodeType;)if(null===(t=Ve(o,t)))throw Error("FODC0001: the root node of the context node is not a document node.");return t=Bm(o,t,(function(e){return 1===e.node.nodeType&&!!(e=Ye(o,e,"idref"))&&e.split(/\s+/).some((function(e){return u[e]}))})),Ie.create(t.map((function(e){return et(e)})))}function Nm(e){switch(typeof e){case"object":return Array.isArray(e)?Ie.m(new $e(e.map((function(e){return Ce(Nm(e))})))):null===e?Ie.empty():Ie.m(new at(Object.keys(e).map((function(t){return{key:ne(t,1),value:Ce(Nm(e[t]))}}))));case"number":return Ie.m(ne(e,3));case"string":return Ie.m(ne(e,1));case"boolean":return e?Ie.ba():Ie.W();default:throw Error("Unexpected type in JSON parse")}}function Tm(e,t,n,r,a){var o=(e=rt(e,t,n,a,Ie.m(ne("duplicates",1)))).G()?"use-first":e.first().value;return r.M((function(e){return Ie.m(new at(e.reduce((function(e,t){return t.h.forEach((function(t){var n=e.findIndex((function(e){return nt(e.key,t.key)}));if(0<=n)switch(o){case"reject":throw Error("FOJS0003: Duplicate encountered when merging maps.");case"use-last":return void e.splice(n,1,t);case"combine":return void e.splice(n,1,{key:t.key,value:Ce(Ie.create(e[n].value().O().concat(t.value().O())))});default:return}e.push(t)})),e}),[])))}))}function Im(e,t,n){var r=1,a=e.value;e=e.Qa(!0);var o=null,u=Math.max(t-1,0);return-1!==e&&(o=Math.max(0,(null===n?e:Math.max(0,Math.min(e,n+(t-1))))-u)),Ie.create({next:function(e){for(;r<t;)a.next(e),r++;return null!==n&&r>=t+n?ie:(e=a.next(e),r++,e)}},o)}function Cm(e){return e.map((function(e){return se(e.type,19)?Hn(e,3):e}))}function Fm(e){if((e=Cm(e)).some((function(e){return Number.isNaN(e.value)})))return[ne(NaN,3)];if(!(e=Wi(e)))throw Error("FORG0006: Incompatible types to be converted to a common type");return e}function Om(e,t,n,r,a,o){return tt([a,o],(function(e){var t=p(e);if(e=t.next().value,t=t.next().value,1/0===e.value)return Ie.empty();if(-1/0===e.value)return t&&1/0===t.value?Ie.empty():r;if(t){if(isNaN(t.value))return Ie.empty();1/0===t.value&&(t=null)}return isNaN(e.value)?Ie.empty():Im(r,Math.round(e.value),t?Math.round(t.value):null)}))}function Sm(e,t,n,r,a){if(r.G())return a;if(!(e=Wi(e=Cm(r.O()))))throw Error("FORG0006: Incompatible types to be converted to a common type");if(!e.every((function(e){return se(e.type,2)})))throw Error("FORG0006: items passed to fn:sum are not all numeric.");return t=e.reduce((function(e,t){return e+t.value}),0),e.every((function(e){return se(e.type,5)}))?Ie.m(ne(t,5)):e.every((function(e){return se(e.type,3)}))?Ie.m(ne(t,3)):e.every((function(e){return se(e.type,4)}))?Ie.m(ne(t,4)):Ie.m(ne(t,6))}var Gm=[].concat(Xa,[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"boolean",j:[{type:59,g:2}],i:{type:0,g:3},callFunction:function(e,t,n,r){return r.ha()?Ie.ba():Ie.W()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"true",j:[],i:{type:0,g:3},callFunction:function(){return Ie.ba()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"not",j:[{type:59,g:2}],i:{type:0,g:3},callFunction:function(e,t,n,r){return!1===r.ha()?Ie.ba():Ie.W()}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"false",j:[],i:{type:0,g:3},callFunction:function(){return Ie.W()}}],[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"last",j:[],i:{type:5,g:3},callFunction:function(e){if(null===e.N)throw Qt("The fn:last() function depends on dynamic context, which is absent.");var t=!1;return Ie.create({next:function(){if(t)return ie;var n=e.Da.Qa();return t=!0,ce(ne(n,5))}},1)}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"position",j:[],i:{type:5,g:3},callFunction:function(e){if(null===e.N)throw Qt("The fn:position() function depends on dynamic context, which is absent.");return Ie.m(ne(e.Ka+1,5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"current-dateTime",j:[],i:{type:10,g:3},callFunction:function(e){return Ie.m(ne(Ut(e),10))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"current-date",j:[],i:{type:7,g:3},callFunction:function(e){return Ie.m(ne(At(Ut(e),7),7))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"current-time",j:[],i:{type:8,g:3},callFunction:function(e){return Ie.m(ne(At(Ut(e),8),8))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"implicit-timezone",j:[],i:{type:17,g:3},callFunction:function(e){return Ie.m(ne(Mt(e),17))}}],Ya,Za,ao,[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"years-from-duration",j:[{type:18,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.gb(),5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"months-from-duration",j:[{type:18,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.cb(),5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"days-from-duration",j:[{type:18,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.bb(),5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"hours-from-duration",j:[{type:18,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getHours(),5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"minutes-from-duration",j:[{type:18,g:0}],i:{type:5,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getMinutes(),5))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"seconds-from-duration",j:[{type:18,g:0}],i:{type:4,g:0},callFunction:function(e,t,n,r){return r.G()?r:Ie.m(ne(r.first().value.getSeconds(),4))}}],uo,[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"id",j:[{type:1,g:2},{type:53,g:3}],i:{type:54,g:2},callFunction:bm},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"id",j:[{type:1,g:2}],i:{type:54,g:2},callFunction:function(e,t,n,r){return bm(e,t,n,r,Ie.m(e.N))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"idref",j:[{type:1,g:2},{type:53,g:3}],i:{type:53,g:2},callFunction:Em},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"idref",j:[{type:1,g:2}],i:{type:53,g:2},callFunction:function(e,t,n,r){return Em(e,t,n,r,Ie.m(e.N))}}],[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"parse-json",j:[{type:1,g:3}],i:{type:59,g:0},callFunction:function(e,t,n,r){try{var a=JSON.parse(r.first().value)}catch(e){throw Error("FOJS0001: parsed JSON string contains illegal JSON.")}return Nm(a)}}],[{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"contains",j:[{type:61,g:3},{type:46,g:3}],i:{type:0,g:3},callFunction:function(e,t,n,r,a){return tt([r,a],(function(e){var t=(e=p(e)).next().value,n=e.next().value;return t.h.some((function(e){return nt(e.key,n)}))?Ie.ba():Ie.W()}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"entry",j:[{type:46,g:3},{type:59,g:2}],i:{type:61,g:3},callFunction:function(e,t,n,r,a){return r.map((function(e){return new at([{key:e,value:Ce(a)}])}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"for-each",j:[{type:61,g:3},{type:59,g:2}],i:{type:59,g:2},callFunction:function(e,t,n,r,a){return tt([r,a],(function(r){var a=(r=p(r)).next().value,o=r.next().value;return Lt(a.h.map((function(r){return o.value.call(void 0,e,t,n,Ie.m(r.key),r.value())})))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"get",j:[{type:61,g:3},{type:46,g:3}],i:{type:59,g:2},callFunction:rt},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"keys",j:[{type:61,g:3}],i:{type:46,g:2},callFunction:function(e,t,n,r){return tt([r],(function(e){return e=p(e).next().value,Ie.create(e.h.map((function(e){return e.key})))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"merge",j:[{type:61,g:2},{type:61,g:3}],i:{type:61,g:3},callFunction:Tm},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"merge",j:[{type:61,g:2}],i:{type:61,g:3},callFunction:function(e,t,n,r){return Tm(e,t,n,r,Ie.m(new at([{key:ne("duplicates",1),value:function(){return Ie.m(ne("use-first",1))}}])))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"put",j:[{type:61,g:3},{type:46,g:3},{type:59,g:2}],i:{type:61,g:3},callFunction:function(e,t,n,r,a,o){return tt([r,a],(function(e){var t=(e=p(e)).next().value,n=e.next().value;return e=t.h.concat(),0<=(t=e.findIndex((function(e){return nt(e.key,n)})))?e.splice(t,1,{key:n,value:Ce(o)}):e.push({key:n,value:Ce(o)}),Ie.m(new at(e))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"remove",j:[{type:61,g:3},{type:46,g:2}],i:{type:61,g:3},callFunction:function(e,t,n,r,a){return tt([r],(function(e){var t=p(e).next().value.h.concat();return a.M((function(e){return e.forEach((function(e){var n=t.findIndex((function(t){return nt(t.key,e)}));0<=n&&t.splice(n,1)})),Ie.m(new at(t))}))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/map",localName:"size",j:[{type:61,g:3}],i:{type:5,g:3},callFunction:function(e,t,n,r){return r.map((function(e){return ne(e.h.length,5)}))}}],[{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"pi",j:[],i:{type:3,g:3},callFunction:function(){return Ie.m(ne(Math.PI,3))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"exp",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.pow(Math.E,e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"exp10",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.pow(10,e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"log",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.log(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"log10",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.log10(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"pow",j:[{type:3,g:0},{type:2,g:3}],i:{type:3,g:0},callFunction:function(e,t,n,r,a){return a.M((function(e){var t=p(e).next().value;return r.map((function(e){return 1!==Math.abs(e.value)||Number.isFinite(t.value)?ne(Math.pow(e.value,t.value),3):ne(1,3)}))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"sqrt",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.sqrt(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"sin",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.sin(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"cos",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.cos(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"tan",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.tan(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"asin",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.asin(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"acos",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.acos(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"atan",j:[{type:3,g:0}],i:{type:3,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(Math.atan(e.value),3)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions/math",localName:"atan2",j:[{type:3,g:0},{type:3,g:3}],i:{type:3,g:0},callFunction:function(e,t,n,r,a){return a.M((function(e){var t=p(e).next().value;return r.map((function(e){return ne(Math.atan2(e.value,t.value),3)}))}))}}],Ur,hr,[{namespaceURI:"http://fontoxpath/operators",localName:"to",j:[{type:5,g:0},{type:5,g:0}],i:{type:5,g:2},callFunction:function(e,t,n,r,a){if(e=r.first(),a=a.first(),null===e||null===a)return Ie.empty();var o=e.value;return a=a.value,o>a?Ie.empty():Ie.create({next:function(){return ce(ne(o++,5))}},a-o+1)}}],[{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"QName",j:[{type:1,g:0},{type:1,g:3}],i:{type:23,g:3},callFunction:function(e,t,n,r,a){return tt([r,a],(function(e){var t=p(e);if(e=t.next().value,!$t(t=t.next().value.value,23))throw Error("FOCA0002: The provided QName is invalid.");if(null===(e=e&&e.value||null)&&t.includes(":"))throw Error("FOCA0002: The URI of a QName may not be empty if a prefix is provided.");if(r.G())return Ie.m(ne(new Fe("",null,t),23));if(!t.includes(":"))return Ie.m(ne(new Fe("",e,t),23));var n=p(t.split(":"));return t=n.next().value,n=n.next().value,Ie.m(ne(new Fe(t,e,n),23))}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"prefix-from-QName",j:[{type:23,g:0}],i:{type:24,g:0},callFunction:function(e,t,n,r){return tt([r],(function(e){return null===(e=p(e).next().value)?Ie.empty():(e=e.value).prefix?Ie.m(ne(e.prefix,24)):Ie.empty()}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"local-name-from-QName",j:[{type:23,g:0}],i:{type:24,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(e.value.localName,24)}))}},{namespaceURI:"http://www.w3.org/2005/xpath-functions",localName:"namespace-uri-from-QName",j:[{type:23,g:0}],i:{type:20,g:0},callFunction:function(e,t,n,r){return r.map((function(e){return ne(e.value.namespaceURI||"",20)}))}}],[{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return r.Z({empty:function(){return Ie.ba()},multiple:function(){return Ie.W()},m:function(){return Ie.W()}})},localName:"empty",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return r.Z({empty:function(){return Ie.W()},multiple:function(){return Ie.ba()},m:function(){return Ie.ba()}})},localName:"exists",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return Im(r,1,1)},localName:"head",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:0}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return Im(r,2,null)},localName:"tail",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:5,g:3},{type:59,g:2}],callFunction:function(e,t,n,r,a,o){return r.G()?o:o.G()?r:(e=r.O(),0>(a=a.first().value-1)?a=0:a>e.length&&(a=e.length),t=e.slice(a),Ie.create(e.slice(0,a).concat(o.O(),t)))},localName:"insert-before",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:5,g:3}],callFunction:function(e,t,n,r,a){return e=a.first().value,!(r=r.O()).length||1>e||e>r.length||r.splice(e-1,1),Ie.create(r)},localName:"remove",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return r.M((function(e){return Ie.create(e.reverse())}))},localName:"reverse",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:3,g:3}],callFunction:function(e,t,n,r,a){return Om(e,t,n,r,a,Ie.empty())},localName:"subsequence",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:3,g:3},{type:3,g:3}],callFunction:Om,localName:"subsequence",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){return r},localName:"unordered",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:46,g:2}],callFunction:function(e,t,n,r){var a=Vt(r,t).O();return Ie.create(a).filter((function(e,t){return a.slice(0,t).every((function(t){return!Pr(e,t)}))}))},localName:"distinct-values",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:2}},{j:[{type:46,g:2},{type:1,g:3}],callFunction:function(){throw Error("FOCH0002: No collations are supported")},localName:"distinct-values",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:2}},{j:[{type:46,g:2},{type:46,g:3}],callFunction:function(e,t,n,r,a){return a.M((function(n){var a=p(n).next().value;return Vt(r,t).map((function(t,n){return Fi("eqOp",t.type,a.type)(t,a,e)?ne(n+1,5):ne(-1,5)})).filter((function(e){return-1!==e.value}))}))},localName:"index-of",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:5,g:2}},{j:[{type:46,g:2},{type:46,g:3},{type:1,g:3}],callFunction:function(){throw Error("FOCH0002: No collations are supported")},localName:"index-of",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:5,g:2}},{j:[{type:59,g:2},{type:59,g:2}],callFunction:function(e,t,n,r,a){var o=!1,u=Lr(e,t,n,r,a);return Ie.create({next:function(){if(o)return ie;var e=u.next(0);return e.done?e:(o=!0,ce(ne(e.value,0)))}})},localName:"deep-equal",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:59,g:2},{type:59,g:2},{type:1,g:3}],callFunction:function(){throw Error("FOCH0002: No collations are supported")},localName:"deep-equal",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:0,g:3}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){var a=!1;return Ie.create({next:function(){if(a)return ie;var e=r.Qa();return a=!0,ce(ne(e,5))}})},localName:"count",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:5,g:3}},{j:[{type:46,g:2}],callFunction:function(e,t,n,r){if(r.G())return r;if(!(e=Wi(e=Cm(r.O()))))throw Error("FORG0006: Incompatible types to be converted to a common type");if(!e.every((function(e){return se(e.type,2)})))throw Error("FORG0006: items passed to fn:avg are not all numeric.");return t=e.reduce((function(e,t){return e+t.value}),0)/e.length,e.every((function(e){return se(e.type,5)||se(e.type,3)}))?Ie.m(ne(t,3)):e.every((function(e){return se(e.type,4)}))?Ie.m(ne(t,4)):Ie.m(ne(t,6))},localName:"avg",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:46,g:2}],callFunction:function(e,t,n,r){return r.G()?r:(e=Fm(r.O()),Ie.m(e.reduce((function(e,t){return e.value<t.value?t:e}))))},localName:"max",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:46,g:2},{type:1,g:3}],callFunction:function(){throw Error("FOCH0002: No collations are supported")},localName:"max",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:46,g:2}],callFunction:function(e,t,n,r){return r.G()?r:(e=Fm(r.O()),Ie.m(e.reduce((function(e,t){return e.value>t.value?t:e}))))},localName:"min",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:46,g:2},{type:1,g:3}],callFunction:function(){throw Error("FOCH0002: No collations are supported")},localName:"min",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:46,g:2}],callFunction:function(e,t,n,r){return Sm(e,t,n,r,Ie.m(ne(0,5)))},localName:"sum",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:3}},{j:[{type:46,g:2},{type:46,g:0}],callFunction:Sm,localName:"sum",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:46,g:0}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){if(!r.G()&&!r.wa())throw Error("FORG0003: The argument passed to fn:zero-or-one contained more than one item.");return r},localName:"zero-or-one",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:0}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){if(r.G())throw Error("FORG0004: The argument passed to fn:one-or-more was empty.");return r},localName:"one-or-more",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:1}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){if(!r.wa())throw Error("FORG0005: The argument passed to fn:exactly-one is empty or contained more than one item.");return r},localName:"exactly-one",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:3}},{j:[{type:59,g:2},{type:60,g:3}],callFunction:function(e,t,n,r,a){if(r.G())return r;var o=a.first(),u=o.o;if(1!==u.length)throw Error("XPTY0004: signature of function passed to fn:filter is incompatible.");return r.filter((function(r){if(r=tr(u[0],Ie.m(r),t,"fn:filter",!1),!(r=o.value.call(void 0,e,t,n,r)).wa()||!se(r.first().type,0))throw Error("XPTY0004: signature of function passed to fn:filter is incompatible.");return r.first().value}))},localName:"filter",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:60,g:3}],callFunction:function(e,t,n,r,a){if(r.G())return r;var o=a.first(),u=o.o;if(1!==u.length)throw Error("XPTY0004: signature of function passed to fn:for-each is incompatible.");var i,c=r.value;return Ie.create({next:function(r){for(;;){if(!i){var a=c.next(0);if(a.done)return a;a=tr(u[0],Ie.m(a.value),t,"fn:for-each",!1),i=o.value.call(void 0,e,t,n,a).value}if(!(a=i.next(r)).done)return a;i=null}}})},localName:"for-each",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:59,g:2},{type:60,g:3}],callFunction:function(e,t,n,r,a,o){if(r.G())return r;var u=o.first(),i=u.o;if(2!==i.length)throw Error("XPTY0004: signature of function passed to fn:fold-left is incompatible.");return r.M((function(r){return r.reduce((function(r,a){return r=tr(i[0],r,t,"fn:fold-left",!1),a=tr(i[1],Ie.m(a),t,"fn:fold-left",!1),u.value.call(void 0,e,t,n,r,a)}),a)}))},localName:"fold-left",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2},{type:59,g:2},{type:60,g:3}],callFunction:function(e,t,n,r,a,o){if(r.G())return r;var u=o.first(),i=u.o;if(2!==i.length)throw Error("XPTY0004: signature of function passed to fn:fold-right is incompatible.");return r.M((function(r){return r.reduceRight((function(r,a){return r=tr(i[0],r,t,"fn:fold-right",!1),a=tr(i[1],Ie.m(a),t,"fn:fold-right",!1),u.value.call(void 0,e,t,n,a,r)}),a)}))},localName:"fold-right",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:59,g:2}},{j:[{type:59,g:2}],callFunction:function(e,t,n,r){if(!t.v)throw Error("serialize() called but no xmlSerializer set in execution parameters.");if(!(e=r.O()).every((function(e){return se(e.type,53)})))throw Error("Expected argument to fn:serialize to resolve to a sequence of Nodes.");return Ie.m(ne(e.map((function(e){return t.v.serializeToString(no(e.value,t,!1))})).join(""),1))},localName:"serialize",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:1,g:3}}],Nr,[{j:[{type:59,g:3},{type:61,g:3}],callFunction:function(e,t,n,r,a){var o,u;return Ie.create({next:function(){if(!o){var e=xm(r,a,n,t);o=e.sc,u=e.pc}try{return o.next(0)}catch(e){lo(u.value,e)}}})},localName:"evaluate",namespaceURI:"http://fontoxml.com/fontoxpath",i:{type:59,g:2}},{j:[],callFunction:function(){return Ie.m(ne(n,1))},localName:"version",namespaceURI:"http://fontoxml.com/fontoxpath",i:{type:1,g:3}}],[{j:[{type:23,g:3},{type:5,g:3}],callFunction:function(e,t,n,r,a){return tt([r,a],(function(e){var t=p(e);e=t.next().value,t=t.next().value;var r=n.xa(e.value.namespaceURI,e.value.localName,t.value);return null===r?Ie.empty():(e=new Oe({j:r.j,arity:t.value,localName:e.value.localName,namespaceURI:e.value.namespaceURI,i:r.i,value:r.callFunction}),Ie.m(e))}))},localName:"function-lookup",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{g:0,type:60}},{j:[{type:60,g:3}],callFunction:function(e,t,n,r){return tt([r],(function(e){return(e=p(e).next().value).Sa()?Ie.empty():Ie.m(ne(new Fe("",e.l,e.B),23))}))},localName:"function-name",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:23,g:0}},{j:[{type:60,g:3}],callFunction:function(e,t,n,r){return tt([r],(function(e){return e=p(e).next().value,Ie.m(ne(e.v,5))}))},localName:"function-arity",namespaceURI:"http://www.w3.org/2005/xpath-functions",i:{type:5,g:3}}]);function Dm(e){this.h=e}(a=Dm.prototype).createAttributeNS=function(e,t){return this.h.createAttributeNS(e,t)},a.createCDATASection=function(e){return this.h.createCDATASection(e)},a.createComment=function(e){return this.h.createComment(e)},a.createDocument=function(){return this.h.createDocument()},a.createElementNS=function(e,t){return this.h.createElementNS(e,t)},a.createProcessingInstruction=function(e,t){return this.h.createProcessingInstruction(e,t)},a.createTextNode=function(e){return this.h.createTextNode(e)};var Rm=Symbol("IS_XPATH_VALUE_SYMBOL");function km(e){return function(t,n){return t=Ot(new Xe(null===n?new ke:n),t,we(e)),(n={})[Rm]=!0,n.Hb=t,n}}function Um(e){return e&&"object"==typeof e&&"lookupNamespaceURI"in e?function(t){return e.lookupNamespaceURI(t||null)}:function(){return null}}function Mm(e){return function(t){var n=t.localName;return t.prefix?null:{namespaceURI:e,localName:n}}}function Hm(e,t,n,r,a,o){if(null==r&&(r=r||{}),a)var u=a.logger||{trace:console.log.bind(console)},i=a.documentWriter,c=a.moduleImports,l=a.namespaceResolver,s=a.functionNameResolver,f=a.nodesFactory,h=a.xmlSerializer;else u={trace:console.log.bind(console)},c={},h=i=f=l=null,s=void 0;var d=new Xe(null===n?new ke:n);n=c||Object.create(null),c=void 0===a.defaultFunctionNamespaceURI?"http://www.w3.org/2005/xpath-functions":a.defaultFunctionNamespaceURI;var m=Am(e,o,l||Um(t),r,n,c,s||Mm(c));for(e=t?St(d,t):Ie.empty(),t=!f&&o.$?new la(t):new Dm(f),i=i?new He(i):Me,f=Object.keys(r).reduce((function(e,t){var n=r[t];return e["Q{}"+t+"[0]"]=n&&"object"==typeof n&&Rm in n?function(){return Ie.create(n.Hb)}:function(){return St(d,r[t])},e}),Object.create(null)),l={},n=(s=p(Object.keys(m.ia.Ia))).next();!n.done;l={Za:l.Za},n=s.next())l.Za=n.value,f[l.Za]||(f[l.Za]=function(e){return function(){return(0,m.ia.Ia[e.Za])(y,g)}}(l));var y=new Rt({N:e.first(),Ka:0,Da:e,Aa:f}),g=new Xt(o.debug,o.La,d,t,i,a.currentContext,new Map,u,h);return{Bb:y,Cb:g,ca:m.ca}}function Pm(e,t){var n={},r=0,a=!1,o=null;return{next:function(){if(a)return ie;for(var u={};r<e.h.length;){e:{var i=e.h[r].key.value;if(!o){u.pb=e.h[r];var c=u.pb.value().Z({default:function(e){return e},multiple:function(e){return function(){throw Error("Serialization error: The value of an entry in a map is expected to be a single item or an empty sequence. Use arrays when putting multiple values in a map. The value of the key "+e.pb.key.value+" holds multiple items")}}(u)}).first();if(null===c){n[i]=null,r++;break e}o=Xm(c,t)}c=o.next(0),o=null,n[i]=c.value,r++}u={pb:u.pb}}return a=!0,ce(n)}}}function jm(e,t){var n=[],r=0,a=!1,o=null;return{next:function(){if(a)return ie;for(;r<e.P.length;){if(!o){var u=e.P[r]().Z({default:function(e){return e},multiple:function(){throw Error("Serialization error: The value of an entry in an array is expected to be a single item or an empty sequence. Use nested arrays when putting multiple values in an array.")}}).first();if(null===u){n[r++]=null;continue}o=Xm(u,t)}u=o.next(0),o=null,n[r++]=u.value}return a=!0,ce(n)}}}function Xm(e,t){if(se(e.type,61))return Pm(e,t);if(se(e.type,62))return jm(e,t);if(se(e.type,23)){var n=e.value;return{next:function(){return ce("Q{"+(n.namespaceURI||"")+"}"+n.localName)}}}switch(e.type){case 7:case 8:case 9:case 11:case 12:case 13:case 14:case 15:var r=e.value;return{next:function(){return ce(xt(r))}};case 47:case 53:case 54:case 55:case 56:case 57:case 58:var a=e.value;return{next:function(){return ce(no(a,t,!1))}};default:return{next:function(){return ce(e.value)}}}}Gm.forEach((function(e){mo(e.namespaceURI,e.localName,e.j,e.i,e.callFunction)}));var Lm={ANY:0,NUMBER:1,STRING:2,BOOLEAN:3,NODES:7,FIRST_NODE:9,STRINGS:10,MAP:11,ARRAY:12,NUMBERS:13,ALL_RESULTS:14,ASYNC_ITERATOR:99};function Ym(e,t,n,r){switch(n){case 3:return t.ha();case 2:return(t=Vt(t,r).O()).length?t.map((function(e){return Hn(e,1).value})).join(" "):"";case 10:return(t=Vt(t,r).O()).length?t.map((function(e){return e.value+""})):[];case 1:return null!==(t=t.first())&&se(t.type,2)?t.value:NaN;case 9:if(null===(t=t.first()))return null;if(!se(t.type,53))throw Error("Expected XPath "+io(e)+" to resolve to Node. Got "+me[t.type]);return no(t.value,r,!1);case 7:if(!(t=t.O()).every((function(e){return se(e.type,53)})))throw Error("Expected XPath "+io(e)+" to resolve to a sequence of Nodes.");return t.map((function(e){return no(e.value,r,!1)}));case 11:if(1!==(t=t.O()).length)throw Error("Expected XPath "+io(e)+" to resolve to a single map.");if(!se((t=t[0]).type,61))throw Error("Expected XPath "+io(e)+" to resolve to a map");return Pm(t,r).next(0).value;case 12:if(1!==(t=t.O()).length)throw Error("Expected XPath "+io(e)+" to resolve to a single array.");if(!se((t=t[0]).type,62))throw Error("Expected XPath "+io(e)+" to resolve to an array");return jm(t,r).next(0).value;case 13:return t.O().map((function(t){if(!se(t.type,2))throw Error("Expected XPath "+io(e)+" to resolve to numbers");return t.value}));case 99:var a=t.value,o=null,u=!1,i=function(){for(;!u;){if(!o){var e=a.next(0);if(e.done){u=!0;break}o=Xm(e.value,r)}return e=o.next(0),o=null,e}return Promise.resolve({done:!0,value:null})};return"asyncIterator"in Symbol?((t={})[Symbol.asyncIterator]=function(){return this},t.next=function(){return new Promise((function(e){return e(i())})).catch((function(t){lo(e,t)}))}):t={next:function(){return new Promise((function(e){return e(i())}))}},t;case 14:return t.O().map((function(e){return Xm(e,r).next(0).value}));default:return(t=t.O()).every((function(e){return se(e.type,53)&&!se(e.type,47)}))?1===(t=t.map((function(e){return no(e.value,r,!1)}))).length?t[0]:t:1===t.length?se((t=t[0]).type,62)?jm(t,r).next(0).value:se(t.type,61)?Pm(t,r).next(0).value:_t(t,r).first().value:Vt(Ie.create(t),r).O().map((function(e){return e.value}))}}Lm[Lm.ANY]="ANY",Lm[Lm.NUMBER]="NUMBER",Lm[Lm.STRING]="STRING",Lm[Lm.BOOLEAN]="BOOLEAN",Lm[Lm.NODES]="NODES",Lm[Lm.FIRST_NODE]="FIRST_NODE",Lm[Lm.STRINGS]="STRINGS",Lm[Lm.MAP]="MAP",Lm[Lm.ARRAY]="ARRAY",Lm[Lm.NUMBERS]="NUMBERS",Lm[Lm.ALL_RESULTS]="ALL_RESULTS",Lm[Lm.ASYNC_ITERATOR]="ASYNC_ITERATOR";var Qm=!1,Jm=null,Km={getPerformanceSummary:function(){var e=Jm.getEntriesByType("measure").filter((function(e){return e.name.startsWith("XPath: ")}));return Array.from(e.reduce((function(e,t){var n=t.name.substring(7);return e.has(n)?((n=e.get(n)).times+=1,n.totalDuration+=t.duration):e.set(n,{xpath:n,times:1,totalDuration:t.duration,average:0}),e}),new Map).values()).map((function(e){return e.average=e.totalDuration/e.times,e})).sort((function(e,t){return t.totalDuration-e.totalDuration}))},setPerformanceImplementation:function(e){Jm=e},startProfiling:function(){if(null===Jm)throw Error("Performance API object must be set using `profiler.setPerformanceImplementation` before starting to profile");Jm.clearMarks(),Jm.clearMeasures(),Qm=!0},stopProfiling:function(){Qm=!1}},qm=0,_m={XPATH_3_1_LANGUAGE:"XPath3.1",XQUERY_3_1_LANGUAGE:"XQuery3.1",XQUERY_UPDATE_3_1_LANGUAGE:"XQueryUpdate3.1"};function Vm(e,t,n,r,a,o){if(a=a||0,!e||"string"!=typeof e&&!("nodeType"in e))throw new TypeError("Failed to execute 'evaluateXPath': xpathExpression must be a string or an element depicting an XQueryX DOM tree.");o=o||{};try{var u=Hm(e,t,n||null,r||{},o,{ua:"XQueryUpdate3.1"===o.language,$:"XQuery3.1"===o.language||"XQueryUpdate3.1"===o.language,debug:!!o.debug,La:!!o.disableCache}),i=u.Bb,c=u.Cb,l=u.ca}catch(t){lo(e,t)}if(l.I)throw Error("XUST0001: Updating expressions should be evaluated as updating expressions");if(3===a&&t&&"object"==typeof t&&"nodeType"in t&&(n=l.B(),t=Re(t),null!==n&&!t.includes(n)))return!1;try{t=e,Qm&&("string"!=typeof t&&(t=io(t)),Jm.mark(t+(0===qm?"":"@"+qm)),qm++);var s=Ym(e,ia(l,i,c),a,c);return a=e,Qm&&("string"!=typeof a&&(a=io(a)),i=a+(0==--qm?"":"@"+qm),Jm.measure("XPath: "+a,i),Jm.clearMarks(i)),s}catch(t){lo(e,t)}}Object.assign(Vm,{tc:14,ANY_TYPE:0,Tb:12,Ub:99,BOOLEAN_TYPE:3,Wb:9,Zb:11,ac:7,bc:13,NUMBER_TYPE:1,cc:10,STRING_TYPE:2,uc:"XPath3.1",vc:"XQuery3.1",fc:"XQueryUpdate3.1"});var Wm={};function Zm(e,t,n,r,a){return Vm(e,t,n,r,Vm.Ub,a)}function $m(e,t,n,r){var a={};return a.pendingUpdateList=e.fa.map((function(e){return e.h(r)})),a.xdmValue=Ym(t,Ie.create(e.J),n,r),a}function zm(e,t,n,r,a){var o,u,i,c,l,s,p,f,h,d;return F(new C(new E((function(m){switch(m.h){case 1:a=a||{},jl();try{c=Hm(e,t,n||null,r||{},a||{},{ua:!0,$:!0,debug:!!a.debug,La:!!a.disableCache}),o=c.Bb,u=c.Cb,i=c.ca}catch(t){lo(e,t)}if(i.I){m.h=2;break}l=[];var y=(s=Zm(e,t,n,r,Object.assign(Object.assign({},a),{language:"XQueryUpdate3.1"}))).next();return m.h=3,{value:y};case 3:p=m.l;case 4:if(p.done){m.h=6;break}return l.push(p.value),y=s.next(),m.h=7,{value:y};case 7:p=m.l,m.h=4;break;case 6:return f={},m.return(Promise.resolve((f.pendingUpdateList=[],f.xdmValue=l,f)));case 2:try{d=i.s(o,u),h=d.next(0)}catch(t){lo(e,t)}return m.return($m(h.value,e,a.returnType,u))}}))))}function ey(e,t,n,r,a){a=a||{},jl();try{var o=Hm(e,t,n||null,r||{},a||{},{ua:!0,$:!0,debug:!!a.debug,La:!!a.disableCache}),u=o.Bb,i=o.Cb,c=o.ca}catch(t){lo(e,t)}if(!c.I)return u={},(i={}).pendingUpdateList=[],i.xdmValue=Vm(e,t,n,r,a.i,Object.assign(Object.assign({},a),(u.language=Vm.fc,u))),i;try{var l=c.s(u,i).next(0)}catch(t){lo(e,t)}return $m(l.value,e,a.returnType,i)}function ty(e,t,n,r,a){return Vm(e,t,n,r,Vm.Tb,a)}function ny(e,t,n,r,a){return Vm(e,t,n,r,Vm.BOOLEAN_TYPE,a)}function ry(e,t,n,r,a){return Vm(e,t,n,r,Vm.Wb,a)}function ay(e,t,n,r,a){return Vm(e,t,n,r,Vm.Zb,a)}function oy(e,t,n,r,a){return Vm(e,t,n,r,Vm.ac,a)}function uy(e,t,n,r,a){return Vm(e,t,n,r,Vm.NUMBER_TYPE,a)}function iy(e,t,n,r,a){return Vm(e,t,n,r,Vm.bc,a)}function cy(e,t,n,r,a){return Vm(e,t,n,r,Vm.STRING_TYPE,a)}function ly(e,t,n,r,a){return Vm(e,t,n,r,Vm.cc,a)}function sy(e,t,n,r){t=new Xe(t||new ke),r=r?new He(r):Me,n=n?n=new Dm(n):null,va(e=e.map(Jc),t,n,r)}function py(e,t,n){return{code:e,va:t,H:n,isAstAccepted:!0}}function fy(e){return{isAstAccepted:!1,reason:e}}function hy(e,t){return e.isAstAccepted?t(e):e}function dy(e,t){return e.isAstAccepted?t(e):[e,null]}function my(e,t,n){return hy(e,(function(e){switch(e.va.type){case 0:return e;case 1:return hy(hg(n,e,"nodes"),(function(e){return hy(hg(n,t,"contextItem"),(function(t){return py("(function () {\n\t\t\t\t\t\t\tconst { done, value } = "+e.code+"("+t.code+").next();\n\t\t\t\t\t\t\treturn done ? null : value;\n\t\t\t\t\t\t})()",{type:0},[].concat(h(e.H),h(t.H)))}))}));default:throw Error("invalid generated code type to convert to value: "+e.va.type)}}))}function yy(e,t,n,r){return e=my(e,n,r),t&&0===t.type&&3===t.g?e:hy(e,(function(e){return py("!!"+e.code,{type:0},e.H)}))}function gy(e,t,n){return t?e.isAstAccepted&&0!==e.va.type?fy("Atomization only implemented for single value"):se(t.type,1)?e:se(t.type,47)?hy(hg(n,e,"attr"),(function(e){return py("("+e.code+" ? domFacade.getData("+e.code+") : null)",{type:0},e.H)})):fy("Atomization only implemented for string and attribute"):fy("Can not atomize value if type was not annotated")}function vy(e,t,n,r){return r=gy(e=my(e,n,r),t,r),tn(t)?hy(r,(function(e){return py(e.code+" ?? ''",{type:0},e.H)})):r}function wy(e,t,n){return hy(hg(n,e,"node"),(function(e){return 1===e.va.type?e:t&&!se(t.type,53)?fy("Can not evaluate to node if expression does not result in nodes"):py("(function () {\n\t\t\t\tif ("+e.code+" !== null && !"+e.code+".nodeType) {\n\t\t\t\t\tthrow new Error('XPDY0050: The result of the expression was not a node');\n\t\t\t\t}\n\t\t\t\treturn "+e.code+";\n\t\t\t})()",{type:0},e.H)}))}function Ay(e,t,n,r){return hy(e,(function(e){switch(e.va.type){case 1:return hy(hg(r,e,"nodes"),(function(e){return hy(hg(r,n,"contextItem"),(function(t){return py("Array.from("+e.code+"("+t.code+"))",{type:0},[].concat(h(e.H),h(t.H)))}))}));case 0:return hy(hg(r,wy(e,t,r),"node"),(function(e){return py("("+e.code+" === null ? [] : ["+e.code+"])",{type:0},e.H)}));default:return fy("Unsupported code type to evaluate to nodes")}}))}function xy(e,t){return hy(e,(function(e){return hy(t,(function(t){if(0!==e.va.type||0!==t.va.type)throw Error("can only use emitAnd with value expressions");return py(e.code+" && "+t.code,{type:0},[].concat(h(e.H),h(t.H)))}))}))}function By(e,t,n,r){return(e=Lo(e,[t,"*"]))?r.h(e,n,r):[fy(t+" expression not found"),null]}Object.assign(Vm,(Wm.ALL_RESULTS_TYPE=14,Wm.ANY_TYPE=0,Wm.ARRAY_TYPE=12,Wm.ASYNC_ITERATOR_TYPE=99,Wm.BOOLEAN_TYPE=3,Wm.FIRST_NODE_TYPE=9,Wm.MAP_TYPE=11,Wm.NODES_TYPE=7,Wm.NUMBERS_TYPE=13,Wm.NUMBER_TYPE=1,Wm.STRINGS_TYPE=10,Wm.STRING_TYPE=2,Wm.XPATH_3_1_LANGUAGE="XPath3.1",Wm.XQUERY_3_1_LANGUAGE="XQuery3.1",Wm.XQUERY_UPDATE_3_1_LANGUAGE="XQueryUpdate3.1",Wm));var by={},Ey=(by.equalOp="eqOp",by.notEqualOp="neOp",by.lessThanOrEqualOp="leOp",by.lessThanOp="ltOp",by.greaterThanOrEqualOp="geOp",by.greaterThanOp="gtOp",by),Ny={},Ty=(Ny.eqOp="eqOp",Ny.neOp="neOp",Ny.leOp="geOp",Ny.ltOp="gtOp",Ny.geOp="leOp",Ny.gtOp="ltOp",Ny);function Iy(e,t,n,r){var a=Xo(Lo(e,["firstOperand","*"]),"type"),o=Xo(Lo(e,["secondOperand","*"]),"type");if(!a||!o)return fy("Can not generate code for value compare without both types");var u=[47,1];if(!u.includes(a.type)||!u.includes(o.type))return fy("Unsupported types in compare: ["+me[a.type]+", "+me[o.type]+"]");if(!(u=new Map([["eqOp","==="],["neOp","!=="]])).has(t))return fy(t+" not yet implemented");var i=u.get(t);return u=(t=p(By(e,"firstOperand",n,r))).next().value,t.next(),t=gy(t=my(u,n,r),a,r),hy(hg(r,t,"first"),(function(t){var u=p(By(e,"secondOperand",n,r)),c=u.next().value;return u.next(),u=gy(u=my(c,n,r),o,r),hy(hg(r,u,"second"),(function(e){var n=[];return tn(a)&&n.push(t.code+" === null"),tn(o)&&n.push(e.code+" === null"),py("("+(n.length?n.join(" || ")+" ? null : ":"")+t.code+" "+i+" "+e.code+")",{type:0},[].concat(h(t.H),h(e.H)))}))}))}function Cy(e,t,n,r,a,o){var u=Xo(Lo(e,[t,"*"]),"type"),i=Xo(Lo(e,[n,"*"]),"type");if(!u||!i)return fy("Can not generate code for general compare without both types");var c=[47,1];if(!c.includes(u.type)||!c.includes(i.type))return fy("Unsupported types in compare: ["+me[u.type]+", "+me[i.type]+"]");if(!(c=new Map([["eqOp","==="],["neOp","!=="]])).has(r))return fy(r+" not yet implemented");var l=c.get(r);return r=(t=p(By(e,t,a,o))).next().value,t.next(),u=gy(t=my(r,a,o),u,o),hy(hg(o,u,"single"),(function(t){var r=p(By(e,n,a,o)),u=r.next().value;return r.next(),hy(hg(o,u,"multiple"),(function(e){if(1!==e.va.type)return fy("can only generate general compare for a single value and a generator");var n=dg(o,mg(o,"n")),r=gy(n,i,o);return hy(a,(function(a){return hy(r,(function(r){return py("(function () {\n\t\t\t\t\t\t\t\t\tfor (const "+n.code+" of "+e.code+"("+a.code+")) {\n\t\t\t\t\t\t\t\t\t\t"+r.H.join("\n")+"\n\t\t\t\t\t\t\t\t\t\tif ("+r.code+" "+l+" "+t.code+") {\n\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t})()",{type:0},[].concat(h(t.H),h(n.H),h(a.H),h(e.H)))}))}))}))}))}function Fy(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}var Oy={"false#0":Ly,"local-name#0":jy,"local-name#1":jy,"name#0":Py,"name#1":Py,"not#1":Xy,"true#0":Yy},Sy={},Gy=(Sy["http://fontoxml.com/fontoxpath"]=["version#0"],Sy[""]=["root#1","path#1"],Sy);function Dy(e,t,n,r){var a=p(r.h(e,n,r)),o=a.next().value;if(a.next(),e=Xo(e,"type"),!t||2===t.g||1===t.g)return fy("Not supported: sequence arguments with multiple items");if(se(t.type,53))return wy(t=my(o,n,r),e,r);switch(t.type){case 59:return my(o,n,r);case 0:return yy(o,e,n,r);case 1:return vy(o,e,n,r)}return fy("Argument types not supported: "+(e?me[e.type]:"unknown")+" -> "+me[t.type])}function Ry(e,t,n,r){if(e.length!==t.length||t.some((function(e){return 4===e})))return fy("Not supported: variadic function or mismatch in argument count");if(0===e.length)return py("",{type:0},[]);var a=p(e);e=a.next().value;var o=f(a);a=(t=p(t)).next().value;var u=f(t);return e=hg(r,Dy(e,a,n,r),"arg"),0===o.length?e:hy(e,(function(e){return hy(Ry(o,u,n,r),(function(t){return py(e.code+", "+t.code,{type:0},[].concat(h(e.H),h(t.H)))}))}))}function ky(e,t){return hy(e,(function(e){return t&&2!==t.g&&1!==t.g&&([0,1].includes(t.type)||se(t.type,53))?e:fy("Function return type "+me[t.type]+" not supported")}))}function Uy(e,t,n){var r=Qo(Po(e,"functionName")),a=r.localName,o=r.namespaceURI,u=(r=Yo(Po(e,"arguments"),"*")).length,i=a+"#"+u,c=o===n.B;if(c){var l=Oy[i];if(void 0!==l)return l(e,t,n)}return(e=Gy[c?"":o])&&!e.includes(i)?fy("Not supported: built-in function not on allow list: "+i):(e=ho(o,a,u))?e.I?fy("Not supported: updating functions"):ky(t=hy(t=Ry(r,e.j,t,n),(function(e){return py("runtimeLib.callFunction(domFacade, "+Fy(o)+", "+Fy(a)+", ["+e.code+"], options)",{type:0},e.H)})),e.i):fy("Unknown function / arity: "+i)}function My(e,t){return hy(hg(t,e,"contextItem"),(function(e){return py(e.code,{type:0},[].concat(h(e.H),["if ("+e.code+" === undefined || "+e.code+" === null) {\n\t\t\t\t\tthrow errXPDY0002('The function which was called depends on dynamic context, which is absent.');\n\t\t\t\t}"]))}))}function Hy(e,t,n,r){if((e=Lo(e,["arguments","*"]))&&"contextItemExpr"!==e[0]){var a=Xo(e,"type");if(!a||!se(a.type,53))return fy("name function only implemented if arg is a node");a=(e=p(n.h(e,t,n))).next().value,e.next(),e=a}else e=My(t,n);return hy(hg(n,t=my(e,t,n),"arg"),(function(e){return py("("+e.code+" ? "+r(e.code)+" : '')",{type:0},e.H)}))}function Py(e,t,n){return Hy(e,t,n,(function(e){return"((("+e+".prefix || '').length !== 0 ? "+e+".prefix + ':' : '')\n\t\t+ ("+e+".localName || "+e+".target || ''))"}))}function jy(e,t,n){return Hy(e,t,n,(function(e){return"("+e+".localName || "+e+".target || '')"}))}function Xy(e,t,n){var r=Lo(e,["arguments","*"]);e=Xo(r,"type");var a=(r=p(n.h(r,t,n))).next().value;return r.next(),hy(t=yy(a,e,t,n),(function(e){return py("!"+e.code,{type:0},e.H)}))}function Ly(){return py("false",{type:0},[])}function Yy(){return py("true",{type:0},[])}function Qy(e,t,n,r){var a=p(By(e,"firstOperand",n,r)),o=a.next().value;a=a.next().value;var u=Xo(Lo(e,["firstOperand","*"]),"type");o=yy(o,u,n,r);var i=(u=p(By(e,"secondOperand",n,r))).next().value;return u=u.next().value,[o=hy(o,(function(a){var o=Xo(Lo(e,["secondOperand","*"]),"type");return hy(o=yy(i,o,n,r),(function(e){return py("("+a.code+" "+t+" "+e.code+")",{type:0},[].concat(h(a.H),h(e.H)))}))})),a="&&"===t?Uu(a,u):a===u?a:null]}function Jy(e,t,n){return hy(e,(function(e){return hy(t,(function(t){return hy(n,(function(n){return py("for ("+e.code+") {\n\t\t\t\t\t\t"+t.H.join("\n")+"\n\t\t\t\t\t\tif (!("+t.code+")) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t"+n.H.join("\n")+"\n\t\t\t\t\t\t"+n.code+"\n\t\t\t\t\t}",{type:2},e.H)}))}))}))}function Ky(e,t,n,r,a){var o=t?', "'+t+'"':"";return Jy(t=hy(r,(function(e){return hy(a,(function(t){return py("let "+e.code+" = domFacade.getFirstChild("+t.code+o+");\n\t\t\t\t\t\t\t"+e.code+";\n\t\t\t\t\t\t\t"+e.code+" = domFacade.getNextSibling("+e.code+o+")",{type:2},[].concat(h(e.H),h(t.H)))}))})),e,n)}function qy(e,t,n,r,a){var o=Uu(t,"type-2"),u=hy(a,(function(e){return py("("+e.code+" && "+e.code+".nodeType === /*ELEMENT_NODE*/ 1 ? domFacade.getAllAttributes("+e.code+(o?', "'+o+'"':"")+") : [])",{type:0},e.H)}));return Jy(t=hy(r,(function(e){return hy(u,(function(t){return py("const "+e.code+" of "+t.code,{type:2},[].concat(h(e.H),h(t.H)))}))})),e,n)}function _y(e,t,n,r,a){var o=t?', "'+t+'"':"";return Vy(r,t=hy(a,(function(e){return py("domFacade.getParentNode("+e.code+o+")",{type:0},e.H)})),e,n)}function Vy(e,t,n,r){var a=xy(e,n);return hy(e,(function(e){return hy(t,(function(t){return hy(a,(function(n){return hy(r,(function(r){return py("const "+e.code+" = "+t.code+";\n\t\t\t\t\t\t"+n.H.join("\n")+"\n\t\t\t\t\t\tif ("+n.code+") {\n\t\t\t\t\t\t\t"+r.H.join("\n")+"\n\t\t\t\t\t\t\t"+r.code+"\n\t\t\t\t\t\t}",{type:2},[].concat(h(e.H),h(t.H)))}))}))}))}))}function Wy(e,t,n,r,a,o){switch(e=jo(e)){case"attribute":return[qy(t,n,r,a,o),"type-1"];case"child":return[Ky(t,n,r,a,o),null];case"parent":return[_y(t,n,r,a,o),null];case"self":return[Vy(a,o,t,r),n];default:return[fy("Unsupported: the "+e+" axis"),null]}}var Zy={dc:"textTest",Vb:"elementTest",$b:"nameTest",ec:"Wildcard",Sb:"anyKindTest"},$y=Object.values(Zy);function zy(e){return[hy(e,(function(e){return py(e.code+".nodeType === /*TEXT_NODE*/ 3",{type:0},[])})),"type-3"]}function eg(e,t){if(null===e.namespaceURI&&"*"!==e.prefix){if(!(t=t.aa(e.prefix||"")||null)&&e.prefix)throw Error("XPST0081: The prefix "+e.prefix+" could not be resolved.");e.namespaceURI=t}}function tg(e,t,n,r){eg(e,r);var a=e.prefix,o=e.namespaceURI,u=e.localName;return dy(n,(function(e){var n=py(t?e.code+".nodeType\n\t\t\t\t\t\t&& ("+e.code+".nodeType === /*ELEMENT_NODE*/ 1\n\t\t\t\t\t\t|| "+e.code+".nodeType === /*ATTRIBUTE_NODE*/ 2)":e.code+".nodeType\n\t\t\t\t\t\t&& "+e.code+".nodeType === /*ELEMENT_NODE*/ 1",{type:0},[]);if("*"===a)return"*"===u?[n,t?"type-1-or-type-2":"type-1"]:[xy(n,py(e.code+".localName === "+Fy(u),{type:0},[])),"name-"+u];n="*"===u?n:xy(n,py(e.code+".localName === "+Fy(u),{type:0},[]));var r=py(Fy(o),{type:0},[]);return r=""===a&&t?hy(r,(function(t){return py(e.code+".nodeType === /*ELEMENT_NODE*/ 1 ? "+t.code+" : null",{type:0},t.H)})):r,[xy(n,r=hy(r,(function(t){return py("("+e.code+".namespaceURI || null) === (("+t.code+") || null)",{type:0},t.H)}))),"name-"+u]}))}function ng(e,t,n){var r=(e=Po(e,"elementName"))&&Po(e,"star");return null===e||r?[hy(t,(function(e){return py(e.code+".nodeType === /*ELEMENT_NODE*/ 1",{type:0},[])})),"type-1"]:tg(e=Qo(Po(e,"QName")),!1,t,n)}function rg(e){return[hy(e,(function(e){return py("!!"+e.code+".nodeType",{type:0},[])})),null]}function ag(e,t,n,r){var a=e[0];switch(a){case Zy.Vb:return ng(e,n,r);case Zy.dc:return zy(n);case Zy.$b:return tg(Qo(e),t,n,r);case Zy.ec:return Po(e,"star")?null!==(a=Po(e,"uri"))?e=tg({localName:"*",namespaceURI:jo(a),prefix:""},t,n,r):(a=Po(e,"NCName"),e="star"===Po(e,"*")[0]?tg({localName:jo(a),namespaceURI:null,prefix:"*"},t,n,r):tg({localName:"*",namespaceURI:null,prefix:jo(a)},t,n,r)):e=tg({localName:"*",namespaceURI:null,prefix:"*"},t,n,r),e;case Zy.Sb:return rg(n);default:return[fy("Test not implemented: '"+a),null]}}function og(e,t,n){var r=p(n.h(e,t,n)),a=r.next().value;return r=r.next().value,[yy(a,Xo(e,"type"),t,n),r]}function ug(e,t,n){var r=p((e=e?Yo(e,"*"):[]).reduce((function(e,r){var a=(e=p(e)).next().value,o=e.next().value;if(!a)return og(r,t,n);var u=o;return dy(a,(function(e){var a=p(og(r,t,n)),i=a.next().value;return a=a.next().value,u=Uu(o,a),[hy(i,(function(t){return py(e.code+" && "+t.code,{type:0},[].concat(h(e.H),h(t.H)))})),u]}))}),[null,null]));return e=r.next().value,r=r.next().value,[e?hy(e,(function(e){return py("(function () {\n\t\t\t\t\t\t\t"+e.H.join("\n")+"\n\t\t\t\t\t\t\treturn "+e.code+";\n\t\t\t\t\t\t})()",{type:0},[])})):null,r]}function ig(e,t,n,r){if(0===e.length)return[hy(n,(function(e){return py("yield "+e.code+";",{type:2},e.H)})),null];var a=(e=p(e)).next().value,o=f(e);if(0<Yo(a,"lookup").length)return[fy("Unsupported: lookups"),null];var u=dg(r,mg(r,"contextItem")),i=(e=p(ug(e=Po(a,"predicates"),u,r))).next().value,c=e.next().value;if(e=Po(a,"xpathAxis")){if(!(a=Po(a,$y)))return[fy("Unsupported test in step"),null];var l=jo(e);return a=(l=p(ag(a,t="attribute"===l||"self"===l&&t,u,r))).next().value,l=l.next().value,a=null===i?a:xy(a,i),c=Uu(l,c),l=(t=p(ig(o,t,u,r))).next().value,t.next(),Wy(e,a,c,l,u,n)}return(e=Lo(a,["filterExpr","*"]))?(e=(c=p(r.h(e,n,r))).next().value,c=c.next().value,[hy(e,(function(e){var t=0===o.length?py("",{type:2},[]):py("if ("+u.code+" !== null && !"+u.code+".nodeType) {\n\t\t\t\t\t\t\t\t\tthrow new Error('XPTY0019: The result of E1 in a path expression E1/E2 should evaluate to a sequence of nodes.');\n\t\t\t\t\t\t\t\t}",{type:2},[]),a=p(ig(o,!0,u,r)),c=a.next().value;return a.next(),a=null===i?c:hy(i,(function(e){return hy(c,(function(t){return py("if ("+e.code+") {\n\t\t\t\t\t\t\t\t\t"+t.H.join("\n")+"\n\t\t\t\t\t\t\t\t\t"+t.code+"\n\t\t\t\t\t\t\t\t}",{type:2},e.H)}))})),hy(a,(function(r){switch(e.va.type){case 1:return hy(n,(function(n){return py("for (const "+u.code+" of "+e.code+"("+n.code+")) {\n\t\t\t\t\t\t\t\t\t"+r.H.join("\n")+"\n\t\t\t\t\t\t\t\t\t"+r.code+"\n\t\t\t\t\t\t\t\t}",{type:2},[].concat(h(u.H),h(e.H),h(t.H)))}));case 0:return py("const "+u.code+" = "+e.code+";\n\t\t\t\t\t\t\t"+t.code+"\n\t\t\t\t\t\t\tif ("+u.code+" !== null) {\n\t\t\t\t\t\t\t\t"+r.H.join("\n")+"\n\t\t\t\t\t\t\t\t"+r.code+"\n\t\t\t\t\t\t\t}",{type:2},[].concat(h(u.H),h(e.H),h(t.H)));default:return fy("Unsupported generated code type for filterExpr")}}))})),c]):[fy("Unsupported: unknown step type"),null]}function cg(e){return hy(e,(function(e){return py("(function () {\n\t\t\t\tlet n = "+e.code+";\n\t\t\t\twhile (n.nodeType !== /*DOCUMENT_NODE*/9) {\n\t\t\t\t\tn = domFacade.getParentNode(n);\n\t\t\t\t\tif (n === null) {\n\t\t\t\t\t\tthrow new Error('XPDY0050: the root node of the context node is not a document node.');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn n;\n\t\t\t})()",{type:0},e.H)}))}function lg(e,t,n){return dy(t,(function(t){if(0<Yo(e,"lookup").length)return[fy("Unsupported: lookups"),null];var r=Po(e,"predicates"),a=p(ug(r,t,n));r=a.next().value,a=a.next().value;var o=Po(e,$y);if(!o)return[fy("Unsupported test in step"),null];var u=p(ag(o,!0,t,n));return o=u.next().value,u=u.next().value,r=null===r?o:xy(o,r),a=Uu(u,a),[hy(r,(function(e){return py("(("+e.code+") ? "+t.code+" : null)",{type:0},[].concat(h(t.H),h(e.H)))})),a]}))}function sg(e,t,n){var r=Yo(e,"stepExpr");if(1===r.length){var a=Po(r[0],"xpathAxis");if(a&&"self"===jo(a))return lg(r[0],t,n)}var o=dg(n,mg(n,"contextItem"));return t=(e=Po(e,"rootExpr"))?hg(n,cg(o),"root"):o,n=(r=p(ig(r,!e,t,n))).next().value,r=r.next().value,[hy(n,(function(e){return py("(function* ("+o.code+") {\n\t\t\t"+e.H.join("\n")+"\n\t\t\t"+e.code+"\n\t\t})",{type:1},[])})),r]}function pg(e,t,n){var r=e[0];switch(r){case"contextItemExpr":return[t,null];case"pathExpr":return sg(e,t,n);case"andOp":return Qy(e,"&&",t,n);case"orOp":return Qy(e,"||",t,n);case"stringConstantExpr":return[py(e=Fy(e=Po(e,"value")[1]||""),{type:0},[]),null];case"equalOp":case"notEqualOp":case"lessThanOrEqualOp":case"lessThanOp":case"greaterThanOrEqualOp":case"greaterThanOp":case"eqOp":case"neOp":case"ltOp":case"leOp":case"gtOp":case"geOp":case"isOp":case"nodeBeforeOp":case"nodeAfterOp":e:switch(r){case"eqOp":case"neOp":case"ltOp":case"leOp":case"gtOp":case"geOp":case"isOp":e=Iy(e,r,t,n);break e;case"equalOp":case"notEqualOp":case"lessThanOrEqualOp":case"lessThanOp":case"greaterThanOrEqualOp":case"greaterThanOp":var a=Xo(Lo(e,["firstOperand","*"]),"type"),o=Xo(Lo(e,["secondOperand","*"]),"type");e=a&&o?3===a.g&&3===o.g?Iy(e,Ey[r],t,n):3===a.g?Cy(e,"firstOperand","secondOperand",Ey[r],t,n):3===o.g?Cy(e,"secondOperand","firstOperand",Ty[Ey[r]],t,n):fy("General comparison for sequences is not implemented"):fy("types of compare are not known");break e;default:e=fy("Unsupported compare type: "+r)}return[e,null];case"functionCallExpr":return[Uy(e,t,n),null];default:return[fy("Unsupported: the base expression '"+r+"'."),null]}}function fg(e,t){this.o=new Map,this.v=new Map,this.aa=e,this.B=t,this.h=pg}function hg(e,t,n){return hy(t,(function(t){var r=e.o.get(t);return r||(r=py(r=mg(e,n),t.va,[].concat(h(t.H),["const "+r+" = "+t.code+";"])),e.o.set(t,r),e.o.set(r,r)),r}))}function dg(e,t){return t=py(t,{type:0},[]),e.o.set(t,t),t}function mg(e,t){t=void 0===t?"v":t;var n=e.v.get(t)||0;return e.v.set(t,n+1),t+n}function yg(e){var t=Yo(e,"*");if("pathExpr"===e[0])return!0;for(t=(e=p(t)).next();!t.done;t=e.next())if(yg(t.value))return!0;return!1}function gg(e,t,n){if(n=n||{},t=t||0,"string"==typeof e){e=Xl(e);var r={$:"XQuery3.1"===n.language||"XQueryUpdate3.1"===n.language,debug:!1};try{var a=dm(e,r)}catch(t){lo(e,t)}}else a=Ul(e);if(!(e=Po(a,"mainModule")))return fy("Unsupported: XQuery Library modules are not supported.");if(Po(e,"prolog"))return fy("Unsupported: XQuery Prologs are not supported.");if(r=void 0===n.defaultFunctionNamespaceURI?"http://www.w3.org/2005/xpath-functions":n.defaultFunctionNamespaceURI,wu(a,n=new Iu(new Oo(new vo((e=new fg(n.namespaceResolver||Um(null),r)).aa,{},r,n.functionNameResolver||Mm("http://www.w3.org/2005/xpath-functions"))))),n=Po(a,"mainModule"))if(Po(n,"prolog"))e=fy("Unsupported: XQuery.");else{var o=Lo(n,["queryBody","*"]);n=dg(e,"contextItem");var u=p(e.h(o,n,e));r=u.next().value,u.next();e:switch(o=Xo(o,"type"),t){case 9:e=wy(t=my(r,n,e),o,e);break e;case 7:e=Ay(r,o,n,e);break e;case 3:e=yy(r,o,n,e);break e;case 2:e=vy(r,o,n,e);break e;default:e=fy("Unsupported: the return type '"+t+"'.")}e.isAstAccepted&&(e="\n\t\t"+e.H.join("\n")+"\n\t\treturn "+e.code+";",t="\n\treturn (contextItem, domFacade, runtimeLib, options) => {\n\t\tconst {\n\t\t\terrXPDY0002,\n\t\t} = runtimeLib;",yg(a)&&(t+='\n\t\tif (!contextItem) {\n\t\t\tthrow errXPDY0002("Context is needed to evaluate the given path expression.");\n\t\t}\n\n\t\tif (!contextItem.nodeType) {\n\t\t\tthrow new Error("Context item must be subtype of node().");\n\t\t}\n\t\t'),e={code:t+(e+"}\n//# sourceURL=generated.js"),isAstAccepted:!0})}else e=fy("Unsupported: Can not execute a library module.");return e}function vg(e,t,n){var r=e.stack;r&&(r.includes(e.message)&&(r=r.substr(r.indexOf(e.message)+e.message.length).trim()),(r=r.split("\n")).splice(10),r=(r=r.map((function(e){return e.startsWith("    ")||e.startsWith("\t")?e:"    "+e}))).join("\n")),e=Error.call(this,"Custom XPath function Q{"+n+"}"+t+" raised:\n"+e.message+"\n"+r),this.message=e.message,"stack"in e&&(this.stack=e.stack)}function wg(e,t,n){return 0===t.g?e.G()?null:Xm(e.first(),n).next(0).value:2===t.g||1===t.g?e.O().map((function(e){if(se(e.type,47))throw Error("Cannot pass attribute nodes to custom functions");return Xm(e,n).next(0).value})):Xm(e.first(),n).next(0).value}function Ag(e){if("object"==typeof e)return e;if(2!==(e=e.split(":")).length)throw Error("Do not register custom functions in the default function namespace");var t=p(e);e=t.next().value,t=t.next().value;var n=go[e];if(!n){if(n="generated_namespace_uri_"+e,go[e])throw Error("Prefix already registered: Do not register the same prefix twice.");go[e]=n}return{localName:t,namespaceURI:n}}function xg(e,t,n,r){var a=(e=Ag(e)).namespaceURI,o=e.localName;if(!a)throw bo();var u=t.map((function(e){return we(e)})),i=we(n);mo(a,o,u,i,(function(e,t,n){var c=Array.from(arguments);c.splice(0,3),c=c.map((function(e,n){return wg(e,u[n],t)}));var l={};l.currentContext=t.l,l.domFacade=t.h.h;try{var s=r.apply(void 0,[l].concat(h(c)))}catch(e){throw new vg(e,o,a)}return s&&"object"==typeof s&&Object.getOwnPropertySymbols(s).includes(Rm)?Ie.create(s.Hb):St(t.h,s,i)}))}A(vg,Error);var Bg={callFunction:function(e,t,n,r,a){var o=ho(t,n,r.length);if(!o)throw Error("function not found for codegen function call");t=new Rt({N:null,Ka:0,Da:Ie.empty(),Aa:{}});var u=new Xe(e);return e=new Xt(!1,!1,u,null,null,a?a.currentContext:null,null),wg(r=o.callFunction.apply(o,[t,e,null].concat(h(r.map((function(e,t){return St(u,e,o.j[t])}))))),{type:59,g:0},e)},errXPDY0002:Qt};function bg(e,t,n,r){return n=n||new ke,e()(null!=t?t:null,n,Bg,r)}var Eg={},Ng=(Eg["http://www.w3.org/2005/XQueryX"]="xqx",Eg["http://www.w3.org/2007/xquery-update-10"]="xquf",Eg["http://fontoxml.com/fontoxpath"]="x",Eg);function Tg(e,t){switch(e){case"copySource":case"insertAfter":case"insertAsFirst":case"insertAsLast":case"insertBefore":case"insertInto":case"modifyExpr":case"newNameExpr":case"replacementExpr":case"replaceValue":case"returnExpr":case"sourceExpr":case"targetExpr":case"transformCopies":case"transformCopy":return{localName:e,ub:t||"http://www.w3.org/2005/XQueryX"};case"deleteExpr":case"insertExpr":case"renameExpr":case"replaceExpr":case"transformExpr":return{localName:e,ub:"http://www.w3.org/2007/xquery-update-10"};case"x:stackTrace":return{localName:"stackTrace",ub:"http://fontoxml.com/fontoxpath"};default:return{localName:e,ub:"http://www.w3.org/2005/XQueryX"}}}function Ig(e,t,n,r,a){if("string"==typeof n)return 0===n.length?null:t.createTextNode(n);if(!Array.isArray(n))throw new TypeError("JsonML element should be an array or string");var o=(r=Tg(n[0],r)).localName;r=r.ub;var u=t.createElementNS(r,Ng[r]+":"+o),i=n[1],c=1;if("object"==typeof i&&!Array.isArray(i)){if(null!==i)for(var l=(c=p(Object.keys(i))).next();!l.done;l=c.next()){var s=i[l=l.value];null!==s&&("type"===l?void 0!==s&&e.setAttributeNS(u,r,"fontoxpath:"+l,ge(s)):("start"!==l&&"end"!==l||"stackTrace"!==o||(s=JSON.stringify(s)),a&&"prefix"===l&&""===s||e.setAttributeNS(u,r,Ng[r]+":"+l,s)))}c=2}for(o=c,i=n.length;o<i;++o)null!==(c=Ig(e,t,n[o],r,a))&&e.insertBefore(u,c,null);return u}function Cg(e,t,n,r){r=void 0===r?Me:r,e=Xl(e);try{var a=dm(e,{$:"XQuery3.1"===t.language||"XQueryUpdate3.1"===t.language,debug:t.debug})}catch(t){lo(e,t)}var o=new vo(t.namespaceResolver||function(){return null},{},void 0===t.defaultFunctionNamespaceURI?"http://www.w3.org/2005/xpath-functions":t.defaultFunctionNamespaceURI,t.functionNameResolver||function(){return null});o=new Oo(o);var u=Po(a,["mainModule","libraryModule"]),i=Po(u,"moduleDecl");return i&&ko(o,jo(Po(i,"prefix")),i=jo(Po(i,"uri"))),(u=Po(u,"prolog"))&&gm(u,o,!1,e),!1!==t.annotateAst&&vu(a,new Iu(o)),o=new ke,t=Ig(r,n,a,null,!1===t.wc),r.insertBefore(t,n.createComment(e),o.getFirstChild(t)),t}function Fg(e){return Promise.resolve(e)}function Og(e,t){if(vu(t=dm(e,{$:!0,debug:(t=void 0===t?{debug:!1}:t).debug}),new Iu(void 0)),!(t=Po(t,"libraryModule")))throw Error("XQuery module must be declared in a library module.");var n=Po(t,"moduleDecl"),r=Po(n,"uri"),a=jo(r);if(r=jo(n=Po(n,"prefix")),ko(n=new Oo(new vo((function(){return null}),Object.create(null),"http://www.w3.org/2005/xpath-functions",Mm("http://www.w3.org/2005/xpath-functions"))),r,a),null!==(t=Po(t,"prolog"))){try{var o=gm(t,n,!0,e)}catch(t){lo(e,t)}o.Ma.forEach((function(e){if(a!==e.namespaceURI)throw Error("XQST0048: Functions and variables declared in a module must reside in the module target namespace.")})),Hl(a,o)}else Hl(a,{Ma:[],Va:[],ra:null,source:e});return a}var Sg=new Map;function Gg(e){var t;e:{if(t=Gl.get(e))for(var n=p(Object.keys(t)),r=n.next();!r.done;r=n.next())if(t[r=r.value]&&t[r].length){t=t[r][0].h;break e}t=null}if(t)return t;if(Sg.has(e))return Sg.get(e);if(null===(t=Lo(t="string"==typeof e?dm(e,{$:!1}):Ul(e),["mainModule","queryBody","*"])))throw Error("Library modules do not have a specificity");return t=Sl(t,{ua:!1,$:!1}),Sg.set(e,t),t}function Dg(e){return Gg(e).B()}function Rg(e,t){return Fa(Gg(e).o,Gg(t).o)}var kg=new ke;return void 0!==r&&(r.compareSpecificity=Rg,r.compileXPathToJavaScript=gg,r.domFacade=kg,r.evaluateXPath=Vm,r.evaluateXPathToArray=ty,r.evaluateXPathToAsyncIterator=Zm,r.evaluateXPathToBoolean=ny,r.evaluateXPathToFirstNode=ry,r.evaluateXPathToMap=ay,r.evaluateXPathToNodes=oy,r.evaluateXPathToNumber=uy,r.evaluateXPathToNumbers=iy,r.evaluateXPathToString=cy,r.evaluateXPathToStrings=ly,r.evaluateUpdatingExpression=zm,r.evaluateUpdatingExpressionSync=ey,r.executeJavaScriptCompiledXPath=bg,r.executePendingUpdateList=sy,r.getBucketForSelector=Dg,r.getBucketsForNode=Re,r.precompileXPath=Fg,r.registerXQueryModule=Og,r.registerCustomXPathFunction=xg,r.parseScript=Cg,r.profiler=Km,r.createTypedValueFactory=km,r.finalizeModuleRegistration=jl,r.Language=_m,r.ReturnType=Lm),r}(a,o))}],["hide-if-classifies",null]]);
callback.get = snippet => graph.get(snippet);
callback.has = snippet => graph.has(snippet);
/* harmony default export */ const ml = (callback);
;// CONCATENATED MODULE: ./node_modules/@eyeo/snippets/webext/main.mjs
/*!
 * This file is part of eyeo's Anti-Circumvention Snippets module (@eyeo/snippets),
 * Copyright (C) 2006-present eyeo GmbH
 * 
 * @eyeo/snippets is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 * 
 * @eyeo/snippets 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 @eyeo/snippets.  If not, see <http://www.gnu.org/licenses/>.
 */

const main_callback = (environment, ...filters) => {
const e=Proxy,{apply:t,bind:n,call:r}=Function,o=r.bind(t),i=r.bind(n),s=r.bind(r),a={get:(e,t)=>i(r,e[t])},l=t=>new e(t,a),c=(t,n)=>new e(t,{apply:(e,t,r)=>o(n,t,r)}),u={get:(e,t)=>i(e[t],e)},f=t=>new e(t,u),{assign:p,defineProperties:d,freeze:h,getOwnPropertyDescriptor:w,getOwnPropertyDescriptors:g,getPrototypeOf:y}=f(Object),{hasOwnProperty:m}=l({}),{species:b}=Symbol,v={get(e,t){const n=e[t];class r extends n{}const o=g(n.prototype);delete o.constructor,h(d(r.prototype,o));const i=g(n);return delete i.length,delete i.prototype,i[b]={value:r},h(d(r,i))}},E=t=>new e(t,v),S="undefined"!=typeof environment?environment:{};"undefined"==typeof globalThis&&(window.globalThis=window);const{apply:M,ownKeys:T}=f(Reflect),x="world"in S,O=x&&"ISOLATED"===S.world,j=x&&"MAIN"===S.world,P="object"==typeof chrome&&!!chrome.runtime,k="object"==typeof browser&&!!browser.runtime,N=!j&&(O||P||k),$=e=>N?e:L(e,H(e)),{create:L,defineProperties:C,defineProperty:A,freeze:W,getOwnPropertyDescriptor:D,getOwnPropertyDescriptors:H}=f(Object),R=f(globalThis),z=N?globalThis:E(globalThis),{Map:F,RegExp:I,Set:B,WeakMap:J,WeakSet:V}=z,U=(e,t,n=null)=>{const r=T(t);for(const o of T(e)){if(r.includes(o))continue;const i=D(e,o);if(n&&"value"in i){const{value:e}=i;"function"==typeof e&&(i.value=n(e))}A(t,o,i)}},q=e=>{const t=z[e];class n extends t{}const{toString:r,valueOf:o}=t.prototype;C(n.prototype,{toString:{value:r},valueOf:{value:o}});const i=e.toLowerCase(),s=e=>function(){const t=M(e,this,arguments);return typeof t===i?new n(t):t};return U(t,n,s),U(t.prototype,n.prototype,s),n},_=W({frozen:new J,hidden:new V,iframePropertiesToAbort:{read:new B,write:new B},abortedIframes:new J}),X=new I("^[A-Z]");var G=new Proxy(new F([["chrome",N&&(P&&chrome||k&&browser)||void 0],["isExtensionContext",N],["variables",_],["console",$(console)],["document",globalThis.document],["performance",$(performance)],["JSON",$(JSON)],["Map",F],["Math",$(Math)],["Number",N?Number:q("Number")],["RegExp",I],["Set",B],["String",N?String:q("String")],["WeakMap",J],["WeakSet",V],["MouseEvent",MouseEvent]]),{get(e,t){if(e.has(t))return e.get(t);let n=globalThis[t];return"function"==typeof n&&(n=(X.test(t)?z:R)[t]),e.set(t,n),n},has:(e,t)=>e.has(t)});const K={WeakSet:WeakSet,WeakMap:WeakMap,WeakValue:class{has(){return!1}set(){}}},{apply:Y}=Reflect;const{Map:Z,WeakMap:Q,WeakSet:ee,setTimeout:te}=G;let ne=!0,re=e=>{e.clear(),ne=!ne};var oe=function(e){const{WeakSet:t,WeakMap:n,WeakValue:r}=this||K,o=new t,i=new n,s=new r;return function(t){if(o.has(t))return t;if(i.has(t))return i.get(t);if(s.has(t))return s.get(t);const n=Y(e,this,arguments);return o.add(n),n!==t&&("object"==typeof t&&t?i:s).set(t,n),n}}.bind({WeakMap:Q,WeakSet:ee,WeakValue:class extends Z{set(e,t){return ne&&(ne=!ne,te(re,0,this)),super.set(e,t)}}});const{concat:ie,includes:se,join:ae,reduce:le,unshift:ce}=l([]),ue=E(globalThis),{Map:fe,WeakMap:pe}=ue,de=new fe,he=t=>{const n=(e=>{const t=[];let n=e;for(;n;){if(de.has(n))ce(t,de.get(n));else{const e=g(n);de.set(n,e),ce(t,e)}n=y(n)}return ce(t,{}),o(p,null,t)})("function"==typeof t?t.prototype:t),r={get(e,t){if(t in n){const{value:r,get:o}=n[t];if(o)return s(o,e);if("function"==typeof r)return i(r,e)}return e[t]},set(e,t,r){if(t in n){const{set:o}=n[t];if(o)return s(o,e,r),!0}return e[t]=r,!0}};return t=>new e(t,r)},{isExtensionContext:we,Array:ge,Number:ye,String:me,Object:be}=G,{isArray:ve}=ge,{getOwnPropertyDescriptor:Ee,setPrototypeOf:Se}=be,{toString:Me}=be.prototype,{slice:Te}=me.prototype,{get:xe}=Ee(Node.prototype,"nodeType"),Oe=we?{}:{Attr:he(Attr),CanvasRenderingContext2D:he(CanvasRenderingContext2D),CSSStyleDeclaration:he(CSSStyleDeclaration),Document:he(Document),Element:he(Element),HTMLCanvasElement:he(HTMLCanvasElement),HTMLElement:he(HTMLElement),HTMLImageElement:he(HTMLImageElement),HTMLScriptElement:he(HTMLScriptElement),MutationRecord:he(MutationRecord),Node:he(Node),ShadowRoot:he(ShadowRoot),get CSS2Properties(){return Oe.CSSStyleDeclaration}},je=(e,t)=>{if("Element"!==t&&t in Oe)return Oe[t](e);if(ve(e))return Se(e,ge.prototype);const n=(e=>s(Te,s(Me,e),8,-1))(e);if(n in Oe)return Oe[n](e);if(n in G)return Se(e,G[n].prototype);if("nodeType"in e)switch(s(xe,e)){case 1:if(!(t in Oe))throw new Error("unknown hint "+t);return Oe[t](e);case 2:return Oe.Attr(e);case 3:return Oe.Node(e);case 9:return Oe.Document(e)}throw new Error("unknown brand "+n)};var Pe=we?e=>e===window||e===globalThis?G:e:oe(((e,t="Element")=>{if(e===window||e===globalThis)return G;switch(typeof e){case"object":return e&&je(e,t);case"string":return new me(e);case"number":return new ye(e);default:throw new Error("unsupported value")}}));const ke={get(e,t){const n=e;for(;!m(e,t);)e=y(e);const{get:r,set:i}=w(e,t);return function(){return arguments.length?o(i,n,arguments):s(r,n)}}},Ne=t=>new e(t,ke);let $e=!1;function Le(){return $e}const{console:Ce}=Pe(window),Ae=()=>{};function We(...e){Le()&&Pe(e).unshift("%c DEBUG","font-weight: bold"),Ce.log(...e)}function De(e){return i(Le()?We:Ae,null,e)}let{Math:He,RegExp:Re}=Pe(window);function ze(e){let{length:t}=e;if(t>1&&"/"===e[0]){let n="/"===e[t-1];if(n||t>2&&Pe(e).endsWith("/i")){let t=[Pe(e).slice(1,n?-1:-2)];return n||t.push("i"),new Re(...t)}}return new Re(Pe(e).replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"))}function Fe(){return Pe(He.floor(2116316160*He.random()+60466176)).toString(36)}let{parseFloat:Ie,variables:Be,Array:Je,Error:Ve,Map:Ue,Object:qe,ReferenceError:_e,Set:Xe,WeakMap:Ge}=Pe(window),{onerror:Ke}=Ne(window),Ye=Node.prototype,Ze=Element.prototype,Qe=null;function et(e,t,n,r=!0){let o=Pe(t),i=o.indexOf(".");if(-1==i){let o=qe.getOwnPropertyDescriptor(e,t);if(o&&!o.configurable)return;let i=qe.assign({},n,{configurable:r});if(!o&&!i.get&&i.set){let n=e[t];i.get=()=>n}return void qe.defineProperty(e,t,i)}let s=o.slice(0,i).toString();t=o.slice(i+1).toString();let a=e[s];!a||"object"!=typeof a&&"function"!=typeof a||et(a,t,n);let l=qe.getOwnPropertyDescriptor(e,s);if(l&&!l.configurable)return;Qe||(Qe=new Ge),Qe.has(e)||Qe.set(e,new Ue);let c=Qe.get(e);if(c.has(s))return void c.get(s).set(t,n);let u=new Ue([[t,n]]);c.set(s,u),qe.defineProperty(e,s,{get:()=>a,set(e){if(a=e,a&&("object"==typeof a||"function"==typeof a))for(let[e,t]of u)et(a,e,t)},configurable:r})}function tt(e){let t=Ke();Ke(((...n)=>{let r=n.length&&n[0];return!("string"!=typeof r||!Pe(r).includes(e))||("function"==typeof t?o(t,this,n):void 0)}))}function nt(e,t,n,r=!0){let o=De(e);if(!n)return void o("no property to abort on read");let i=Fe();o(`aborting on ${n} access`),et(t,n,{get:function(){throw o(`${n} access aborted`),new _e(i)},set(){}},r),tt(i)}function rt(e,t,n,r=!0){let o=De(e);if(!n)return void o("no property to abort on write");let i=Fe();o(`aborting when setting ${n}`),et(t,n,{set:function(){throw o(`setting ${n} aborted`),new _e(i)}},r),tt(i)}function ot(e,t=!1,n=!1){let r=Be.abortedIframes,i=Be.iframePropertiesToAbort;for(let o of Je.from(window.frames))if(r.has(o))for(let i of e)t&&r.get(o).read.add(i),n&&r.get(o).write.add(i);for(let r of e)t&&i.read.add(r),n&&i.write.add(r);function a(){for(let e of Je.from(window.frames)){r.has(e)||r.set(e,{read:new Xe(i.read),write:new Xe(i.write)});let t=r.get(e).read;if(t.size>0){let n=Je.from(t);t.clear();for(let t of n)nt("abort-on-iframe-property-read",e,t)}let n=r.get(e).write;if(n.size>0){let t=Je.from(n);n.clear();for(let n of t)rt("abort-on-iframe-property-write",e,n)}}}a(),r.has(document)||(r.set(document,!0),function(e){let t;function n(e,t){for(let n of t){et(e,n,r(e,n))}}function r(t,n){let r=t[n];return{get:()=>function(...t){let n;return n=o(r,this,t),e&&e(),n}}}function i(t,n){let r=qe.getOwnPropertyDescriptor(t,n),{set:o}=r||{};return{set(t){let n;return n=s(o,this,t),e&&e(),n}}}n(Ye,["appendChild","insertBefore","replaceChild"]),n(Ze,["append","prepend","replaceWith","after","before","insertAdjacentElement","insertAdjacentHTML"]),t=i(Ze,"innerHTML"),et(Ze,"innerHTML",t),t=i(Ze,"outerHTML"),et(Ze,"outerHTML",t)}(a))}let{Object:it}=window;function st(e,t){if(!(e instanceof it))return;let n=e,r=Pe(t).split(".");if(0===r.length)return;for(let e=0;e<r.length-1;e++){let t=r[e];if(!m(n,t))return;if(n=n[t],!(n instanceof it))return}let o=r[r.length-1];return m(n,o)?[n,o]:void 0}const at=Pe(/^\d+$/);function lt(e){switch(e){case"false":return!1;case"true":return!0;case"null":return null;case"noopFunc":return()=>{};case"trueFunc":return()=>!0;case"falseFunc":return()=>!1;case"emptyArray":return[];case"emptyObj":return{};case"undefined":return;case"":return e;default:if(at.test(e))return Ie(e);throw new Ve(`[override-property-read snippet]: Value "${e}" is not valid.`)}}let{HTMLScriptElement:ct,Object:ut,ReferenceError:ft}=Pe(window),pt=ut.getPrototypeOf(ct);let{Error:dt,URL:ht}=Pe(window),{cookie:wt}=Ne(document);let{console:gt,document:yt,getComputedStyle:mt,isExtensionContext:bt,variables:vt,Array:Et,MutationObserver:St,Object:Mt,XPathEvaluator:Tt,XPathExpression:xt,XPathResult:Ot}=Pe(window);const{querySelectorAll:jt}=yt,Pt=jt&&i(jt,yt);function kt(e,t=!1){return Lt(e,Pt.bind(yt),yt,t)}function Nt(e,t,n,r){const o=t.getAttribute("xlink:href")||t.getAttribute("href");if(o){const s=Pt(o)[0];if(!s&&Le())return gt.log("No elements found matching",o),!1;if(!(i=e)||0===i.length||i.every((e=>""===e.trim()))){const e=r.length>0?r:[];return n.push({element:s,rootParents:[...e,t]}),!1}const a=s.querySelectorAll.bind(s);return{nextBoundElement:s,nestedSelectorsString:e.join("^^"),next$$:a}}var i}function $t(e,t){const n=function(e){try{const t=navigator.userAgent.includes("Firefox")?e.openOrClosedShadowRoot:browser.dom.openOrClosedShadowRoot(e);return null===t&&Le()&&gt.log("Shadow root not found or not added in element yet",e),t}catch(t){return Le()&&gt.log("Error while accessing shadow root",e,t),null}}(t);if(n){const{querySelectorAll:r}=n,o=r&&i(r,n).bind(n);return{nextBoundElement:t,nestedSelectorsString:":host "+e.join("^^"),next$$:o}}return!1}function Lt(e,t,n,r,o=[]){if(e.includes("^^")){const[i,s,...a]=e.split("^^");let l,c;switch(s){case"svg":c=Nt;break;case"sh":c=$t;break;default:return Le()&&gt.log(s," is not supported. Supported commands are: \n^^sh^^\n^^svg^^"),[]}l=""===i.trim()?[n]:t(i);const u=[];for(const e of l){const t=c(a,e,u,o);if(!t)continue;const{next$$:n,nestedSelectorsString:i,nextBoundElement:s}=t,l=Lt(i,n,s,r,[...o,e]);l&&u.push(...l)}return u}const i=t(e);return r?[...i].map((e=>({element:e,rootParents:o.length>0?o:[]}))):i}const{assign:Ct,setPrototypeOf:At}=Mt;class Wt extends xt{evaluate(...e){return At(o(super.evaluate,this,e),Ot.prototype)}}class Dt extends Tt{createExpression(...e){return At(o(super.createExpression,this,e),Wt.prototype)}}function Ht(e){if(vt.hidden.has(e))return!1;!function(e){bt&&"function"==typeof checkElement&&checkElement(e)}(e),vt.hidden.add(e);let{style:t}=Pe(e),n=Pe(t,"CSSStyleDeclaration"),r=Pe([]),{debugCSSProperties:o}=S;for(let[e,t]of o||[["display","none"]])n.setProperty(e,t,"important"),r.push([e,n.getPropertyValue(e)]);return new St((()=>{for(let[e,t]of r){let r=n.getPropertyValue(e),o=n.getPropertyPriority(e);r==t&&"important"==o||n.setProperty(e,t,"important")}})).observe(e,{attributes:!0,attributeFilter:["style"]}),!0}function Rt(e){let t=e;if(t.startsWith("xpath(")&&t.endsWith(")")){let t=function(e){let t=e;if(t.startsWith("xpath(")&&t.endsWith(")")){let e=t.slice(6,-1),n=(new Dt).createExpression(e,null),r=Ot.ORDERED_NODE_SNAPSHOT_TYPE;return e=>{if(!e)return;let t=n.evaluate(yt,r,null),{snapshotLength:o}=t;for(let n=0;n<o;n++)e(t.snapshotItem(n))}}return t=>kt(e).forEach(t)}(e);return()=>{let e=Pe([]);return t((t=>e.push(t))),e}}return()=>Et.from(kt(e))}let{ELEMENT_NODE:zt,TEXT_NODE:Ft,prototype:It}=Node,{prototype:Bt}=Element,{prototype:Jt}=HTMLElement,{console:Vt,variables:Ut,DOMParser:qt,Error:_t,MutationObserver:Xt,Object:Gt,ReferenceError:Kt}=Pe(window),{getOwnPropertyDescriptor:Yt}=Gt;Pe(window);const{Map:Zt,MutationObserver:Qt,Object:en,Set:tn,WeakSet:nn}=Pe(window);let rn=Element.prototype,{attachShadow:on}=rn,sn=new nn,an=new Zt,ln=null;const{Error:cn,JSON:un,Map:fn,Response:pn,Object:dn}=Pe(window);let hn=null;let{Error:wn,JSON:gn,Map:yn,Object:mn,Response:bn}=Pe(window),vn=null;let{Error:En}=Pe(window);let{Error:Sn,Map:Mn,Object:Tn,console:xn}=Pe(window),{toString:On}=Function.prototype,jn=EventTarget.prototype,{addEventListener:Pn}=jn,kn=null;let Nn,{URL:$n,fetch:Ln}=Pe(window),{delete:Cn,has:An}=l(URLSearchParams.prototype);const Wn={"abort-current-inline-script":function(e,t=null){const n=De("abort-current-inline-script"),r=t?ze(t):null,o=Fe(),i=Pe(document).currentScript;let a=window;const l=Pe(e).split("."),c=Pe(l).pop();for(let e of Pe(l))if(a=a[e],!a||"object"!=typeof a&&"function"!=typeof a)return void n(l," is not found");const{get:u,set:f}=ut.getOwnPropertyDescriptor(a,c)||{};let p=a[c];void 0===p&&n("The property",c,"doesn't exist yet. Check typos.");const d=()=>{const e=Pe(document).currentScript;if(e instanceof pt&&""==Pe(e,"HTMLScriptElement").src&&e!=i&&(!r||r.test(Pe(e).textContent)))throw n(l," is aborted \n",e),new ft(o)};et(a,c,{get(){return d(),u?s(u,this):p},set(e){d(),f?s(f,this,e):p=e}}),tt(o)},"abort-on-iframe-property-read":function(...e){ot(e,!0,!1)},"abort-on-iframe-property-write":function(...e){ot(e,!1,!0)},"abort-on-property-read":function(e,t){nt("abort-on-property-read",window,e,!("false"===t))},"abort-on-property-write":function(e,t){rt("abort-on-property-write",window,e,!("false"===t))},"cookie-remover":function(e,t=!1){if(!e)throw new dt("[cookie-remover snippet]: No cookie to remove.");let n=De("cookie-remover"),r=ze(e);if(!Pe(/^http|^about/).test(location.protocol))return void n("Snippet only works for http or https and about.");function o(){return Pe(wt()).split(";").filter((e=>r.test(Pe(e).split("=")[0])))}const i=()=>{n("Parsing cookies for matches");for(const e of Pe(o())){let t=Pe(location.hostname);!t&&Pe(location.ancestorOrigins)&&Pe(location.ancestorOrigins[0])&&(t=new ht(Pe(location.ancestorOrigins[0])).hostname);const r=Pe(e).split("=")[0],o="expires=Thu, 01 Jan 1970 00:00:00 GMT",i="path=/",s=t.split(".");for(let e=s.length;e>0;e--){const t=s.slice(s.length-e).join(".");wt(`${Pe(r).trim()}=;${o};${i};domain=${t}`),wt(`${Pe(r).trim()}=;${o};${i};domain=.${t}`),n(`Set expiration date on ${r}`)}}};if(i(),t){let e=o();setInterval((()=>{let t=o();if(t!==e)try{i()}finally{e=t}}),1e3)}},debug:function(){$e=!0},"freeze-element":function(e,t="",...n){let r,i,a=!1,l=!1,c=Pe(n).filter((e=>!h(e))),u=Pe(n).filter((e=>h(e))).map(ze),f=Fe(),p=Rt(e);!function(){let n=Pe(t).split("+");1===n.length&&""===n[0]&&(n=[]);for(let t of n)switch(t){case"subtree":a=!0;break;case"abort":l=!0;break;default:throw new _t("[freeze] Unknown option passed to the snippet. [selector]: "+e+" [option]: "+t)}}();let d={selector:e,shouldAbort:l,rid:f,exceptionSelectors:c,regexExceptions:u,changeId:0};function h(e){return e.length>=2&&"/"==e[0]&&"/"==e[e.length-1]}function w(){i=p(),g(i,!1)}function g(e,t=!0){for(let n of e)Ut.frozen.has(n)||(Ut.frozen.set(n,d),!t&&a&&new Xt((e=>{for(let t of Pe(e))g(Pe(t,"MutationRecord").addedNodes)})).observe(n,{childList:!0,subtree:!0}),a&&Pe(n).nodeType===zt&&g(Pe(n).childNodes))}function y(e,...t){We(`[freeze][${e}] `,...t)}function m(e,t,n,r){let o=r.selector,i=r.changeId,s="string"==typeof e,a=r.shouldAbort?"aborting":"watching";switch(Vt.groupCollapsed(`[freeze][${i}] ${a}: ${o}`),n){case"appendChild":case"append":case"prepend":case"insertBefore":case"replaceChild":case"insertAdjacentElement":case"insertAdjacentHTML":case"insertAdjacentText":case"innerHTML":case"outerHTML":y(i,s?"text: ":"node: ",e),y(i,"added to node: ",t);break;case"replaceWith":case"after":case"before":y(i,s?"text: ":"node: ",e),y(i,"added to node: ",Pe(t).parentNode);break;case"textContent":case"innerText":case"nodeValue":y(i,"content of node: ",t),y(i,"changed to: ",e)}y(i,`using the function "${n}"`),Vt.groupEnd(),r.changeId++}function b(e,t){if(t)for(let n of t)if(n.test(e))return!0;return!1}function v(e){throw new Kt(e)}function E(e,t,n,r){let o=new qt,{body:i}=Pe(o.parseFromString(e,"text/html")),s=S(Pe(i).childNodes,t,n,r);return Pe(s).map((e=>{switch(Pe(e).nodeType){case zt:return Pe(e).outerHTML;case Ft:return Pe(e).textContent;default:return""}})).join("")}function S(e,t,n,r){let o=Pe([]);for(let i of e)M(i,t,n,r)&&o.push(i);return o}function M(e,t,n,r){let o=r.shouldAbort,i=r.regexExceptions,s=r.exceptionSelectors,a=r.rid;if("string"==typeof e){let s=e;return!!b(s,i)||(Le()&&m(s,t,n,r),o&&v(a),Le())}let l=e;switch(Pe(l).nodeType){case zt:return!!function(e,t){if(t){let n=Pe(e);for(let e of t)if(n.matches(e))return!0}return!1}(l,s)||(o&&(Le()&&m(l,t,n,r),v(a)),!!Le()&&(Ht(l),m(l,t,n,r),!0));case Ft:return!!b(Pe(l).textContent,i)||(Le()&&m(l,t,n,r),o&&v(a),!1);default:return!0}}function T(e,t,n,r){let i=Yt(e,t)||{},a=i.get&&s(i.get,e)||i.value;if(a)return{get:()=>function(...e){if(n(this)){let n=r(this);if(n){let r=e[0];if(!M(r,this,t,n))return r}}return o(a,this,e)}}}function x(e,t,n,r){let i=Yt(e,t)||{},a=i.get&&s(i.get,e)||i.value;if(a)return{get:()=>function(...e){if(!n(this))return o(a,this,e);let i=r(this);if(!i)return o(a,this,e);let s=S(e,this,t,i);return s.length>0?o(a,this,s):void 0}}}function O(e,t,n,r){let i=Yt(e,t)||{},a=i.get&&s(i.get,e)||i.value;if(a)return{get:()=>function(...e){let[i,l]=e,c="afterbegin"===i||"beforeend"===i;if(n(this,c)){let e=r(this,c);if(e){let n,r=c?this:Pe(this).parentNode;switch(t){case"insertAdjacentElement":if(!M(l,r,t,e))return l;break;case"insertAdjacentHTML":return n=E(l,r,t,e),n?s(a,this,i,n):void 0;case"insertAdjacentText":if(!M(l,r,t,e))return}}}return o(a,this,e)}}}function j(e,t,n,r){let o=Yt(e,t)||{},{set:i}=o;if(i)return{set(e){if(!n(this))return s(i,this,e);let o=r(this);if(!o)return s(i,this,e);let a=E(e,this,t,o);return a?s(i,this,a):void 0}}}function P(e,t,n,r){let o=Yt(e,t)||{},{set:i}=o;if(i)return{set(e){if(!n(this))return s(i,this,e);let o=r(this);return o?M(e,this,t,o)?s(i,this,e):void 0:s(i,this,e)}}}Ut.frozen.has(document)||(Ut.frozen.set(document,!0),function(){let e;function t(e){return e&&Ut.frozen.has(e)}function n(e){try{return e&&(Ut.frozen.has(e)||Ut.frozen.has(Pe(e).parentNode))}catch(e){return!1}}function r(e,t){try{return e&&(Ut.frozen.has(e)&&t||Ut.frozen.has(Pe(e).parentNode)&&!t)}catch(e){return!1}}function o(e){return Ut.frozen.get(e)}function i(e){try{if(Ut.frozen.has(e))return Ut.frozen.get(e);let t=Pe(e).parentNode;return Ut.frozen.get(t)}catch(e){}}function s(e,t){try{if(Ut.frozen.has(e)&&t)return Ut.frozen.get(e);let n=Pe(e).parentNode;return Ut.frozen.get(n)}catch(e){}}e=T(It,"appendChild",t,o),et(It,"appendChild",e),e=T(It,"insertBefore",t,o),et(It,"insertBefore",e),e=T(It,"replaceChild",t,o),et(It,"replaceChild",e),e=x(Bt,"append",t,o),et(Bt,"append",e),e=x(Bt,"prepend",t,o),et(Bt,"prepend",e),e=x(Bt,"replaceWith",n,i),et(Bt,"replaceWith",e),e=x(Bt,"after",n,i),et(Bt,"after",e),e=x(Bt,"before",n,i),et(Bt,"before",e),e=O(Bt,"insertAdjacentElement",r,s),et(Bt,"insertAdjacentElement",e),e=O(Bt,"insertAdjacentHTML",r,s),et(Bt,"insertAdjacentHTML",e),e=O(Bt,"insertAdjacentText",r,s),et(Bt,"insertAdjacentText",e),e=j(Bt,"innerHTML",t,o),et(Bt,"innerHTML",e),e=j(Bt,"outerHTML",n,i),et(Bt,"outerHTML",e),e=P(It,"textContent",t,o),et(It,"textContent",e),e=P(Jt,"innerText",t,o),et(Jt,"innerText",e),e=P(It,"nodeValue",t,o),et(It,"nodeValue",e)}()),r=new Xt(w),r.observe(document,{childList:!0,subtree:!0}),w()},"hide-if-shadow-contains":function(e,t="*"){let n=`${e}\\${t}`;an.has(n)||an.set(n,[ze(e),t,Ae]);const r=De("hide-if-shadow-contain");ln||(ln=new Qt((e=>{let t=new tn;for(let{target:n}of Pe(e)){let e=Pe(n).parentNode;for(;e;)[n,e]=[e,Pe(n).parentNode];if(!sn.has(n)&&!t.has(n)){t.add(n);for(let[e,t,o]of an.values())if(e.test(Pe(n).textContent)){let e=Pe(n.host).closest(t);e&&(o(),Pe(n).appendChild(document.createElement("style")).textContent=":host {display: none !important}",Ht(e),sn.add(n),r("Hiding: ",e," for params: ",...arguments))}}}})),en.defineProperty(rn,"attachShadow",{value:c(on,(function(){let e=o(on,this,arguments);return r("attachShadow is called for: ",e),ln.observe(e,{childList:!0,characterData:!0,subtree:!0}),e}))}))},"json-override":function(e,t,n="",r=""){if(!e)throw new cn("[json-override snippet]: Missing paths to override.");if(void 0===t)throw new cn("[json-override snippet]: No value to override with.");if(!hn){let i=De("json-override");function s(e,t){for(let{prune:n,needle:r,filter:o,value:s}of hn.values())if(!o||o.test(t)){if(Pe(r).some((t=>!st(e,t))))return e;for(let t of n){let n=st(e,t);void 0!==n&&(i(`Found ${t} replaced it with ${s}`),n[0][n[1]]=lt(s))}}return e}let{parse:a}=un;hn=new fn,dn.defineProperty(window.JSON,"parse",{value:c(a,(function(e){return s(o(a,this,arguments),e)}))}),i("Wrapped JSON.parse for override");let{json:l}=pn.prototype;dn.defineProperty(window.Response.prototype,"json",{value:c(l,(function(e){return o(l,this,arguments).then((t=>s(t,e)))}))}),i("Wrapped Response.json for override")}hn.set(e,{prune:Pe(e).split(/ +/),needle:n.length?Pe(n).split(/ +/):[],filter:r?ze(r):null,value:t})},"json-prune":function(e,t=""){if(!e)throw new wn("Missing paths to prune");if(!vn){let n=De("json-prune");function r(e){for(let{prune:t,needle:r}of vn.values()){if(Pe(r).some((t=>!st(e,t))))return e;for(let r of t){let t=st(e,r);void 0!==t&&(n(`Found ${r} and deleted`),delete t[0][t[1]])}}return e}let{parse:i}=gn;vn=new yn,mn.defineProperty(window.JSON,"parse",{value:c(i,(function(){return r(o(i,this,arguments))}))}),n("Wrapped JSON.parse for prune");let{json:s}=bn.prototype;mn.defineProperty(window.Response.prototype,"json",{value:c(s,(function(){return o(s,this,arguments).then((e=>r(e)))}))}),n("Wrapped Response.json for prune")}vn.set(e,{prune:Pe(e).split(/ +/),needle:t.length?Pe(t).split(/ +/):[]})},"override-property-read":function(e,t,n){if(!e)throw new En("[override-property-read snippet]: No property to override.");if(void 0===t)throw new En("[override-property-read snippet]: No value to override with.");let r=De("override-property-read"),o=lt(t);r(`Overriding ${e}.`),et(window,e,{get:()=>(r(`${e} override done.`),o),set(){}},!("false"===n))},"prevent-listener":function(e,t,n){if(!e)throw new Sn("[prevent-listener snippet]: No event type.");if(!kn){kn=new Mn;let e=De("[prevent]");Tn.defineProperty(jn,"addEventListener",{value:c(Pn,(function(t,n){for(let{evt:r,handlers:o,selectors:i}of kn.values()){if(!r.test(t))continue;let a=this instanceof Element;for(let l=0;l<o.length;l++){const c=o[l],u=i[l];if(!u||a&&Pe(this).matches(u)){if(c){const t=function(){try{const e=String("function"==typeof n?n:n.handleEvent);return c.test(e)}catch(t){return e("Error while trying to stringify listener: ",t),!1}};if(!function(){try{const e=s(On,"function"==typeof n?n:n.handleEvent);return c.test(e)}catch(t){return e("Error while trying to stringify listener: ",t),!1}}()&&!t())continue}return void(Le()&&(xn.groupCollapsed("DEBUG [prevent] was successful"),e(`type: ${t} matching ${r}`),e("handler:",n),c&&e(`matching ${c}`),u&&e("on element: ",this,` matching ${u}`),e("was prevented from being added"),xn.groupEnd()))}}}return o(Pn,this,arguments)}))}),e("Wrapped addEventListener")}kn.has(e)||kn.set(e,{evt:ze(e),handlers:[],selectors:[]});let{handlers:r,selectors:i}=kn.get(e);r.push(t?ze(t):null),i.push(n)},"strip-fetch-query-parameter":function(e,t=null){const n=De("strip-fetch-query-parameter");Nn||(Nn=new Map,window.fetch=c(Ln,((...e)=>{let[t]=e;if("string"==typeof t){let r=new $n(t);for(let[o,i]of Nn)i&&!i.test(t)||An(r.searchParams,o)&&(n(`${o} has been stripped from url ${t}`),Cn(r.searchParams,o),e[0]=r.href)}return o(Ln,self,e)}))),Nn.set(e,t&&ze(t))},trace:function(...e){o(We,null,e)}};
const snippets=Wn;
let context;
for (const [name, ...args] of filters) {
if (snippets.hasOwnProperty(name)) {
try { context = snippets[name].apply(context, args); }
catch (error) { console.error(error); }
}
}
context = void 0;
};
const main_graph = new Map([["abort-current-inline-script",null],["abort-on-iframe-property-read",null],["abort-on-iframe-property-write",null],["abort-on-property-read",null],["abort-on-property-write",null],["cookie-remover",null],["debug",null],["freeze-element",null],["hide-if-shadow-contains",null],["json-override",null],["json-prune",null],["override-property-read",null],["prevent-listener",null],["strip-fetch-query-parameter",null],["trace",null]]);
main_callback.get = snippet => main_graph.get(snippet);
main_callback.has = snippet => main_graph.has(snippet);
/* harmony default export */ const main = (main_callback);
;// CONCATENATED MODULE: ./node_modules/@eyeo/snippets/index.mjs






;// CONCATENATED MODULE: ./node_modules/@eyeo/mlaf/lib/webextension/service.min.js
/*
 * This file is part of eyeo's mlaf module (@eyeo/mlaf),
 * Copyright (C) 2006-present eyeo GmbH
 *
 * @eyeo/mlaf is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * @eyeo/mlaf 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 @eyeo/mlaf.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The following npm packages may be included in this file:
 *
 * - tfjs
 * - tfjs-backend-cpu
 * - tfjs-backend-webgl
 * - tfjs-converter
 * - tfjs-core
 * - tfjs-data
 * - tfjs-layers
 *
 * These packages contain the following information about the license:
 *
 *  * @license
 *  * Copyright 2018-2022 Google LLC. All Rights Reserved.
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  * http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *  * =============================================================================
 */
function _mergeNamespaces(e,t){t.forEach((function(t){t&&typeof t!=="string"&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if(n!=="default"&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:true,get:function(){return t[n]}})}}))}));return Object.freeze(e)}const EPSILON_FLOAT32$1=1e-7;const EPSILON_FLOAT16$1=1e-4;class DataStorage{constructor(e,t){this.backend=e;this.dataMover=t;this.data=new WeakMap;this.dataIdsCount=0}get(e){if(!this.data.has(e)){this.dataMover.moveData(this.backend,e)}return this.data.get(e)}set(e,t){this.dataIdsCount++;this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){this.dataIdsCount--;return this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class KernelBackend{refCount(e){return notYetImplemented("refCount")}incRef(e){return notYetImplemented("incRef")}timerAvailable(){return true}time(e){return notYetImplemented("time")}read(e){return notYetImplemented("read")}readSync(e){return notYetImplemented("readSync")}readToGPU(e,t){return notYetImplemented("readToGPU")}numDataIds(){return notYetImplemented("numDataIds")}disposeData(e,t){return notYetImplemented("disposeData")}write(e,t,n){return notYetImplemented("write")}move(e,t,n,r,a){return notYetImplemented("move")}memory(){return notYetImplemented("memory")}floatPrecision(){return notYetImplemented("floatPrecision")}epsilon(){return this.floatPrecision()===32?EPSILON_FLOAT32$1:EPSILON_FLOAT16$1}dispose(){return notYetImplemented("dispose")}}function nearestLargerEven(e){return e%2===0?e:e+1}function sum$2(e){let t=0;for(let n=0;n<e.length;n++){t+=e[n]}return t}function assert(e,t){if(!e){throw new Error(typeof t==="string"?t:t())}}function assertShapesMatch(e,t,n=""){assert(arraysEqual(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function assertNonNull(e){assert(e!=null,(()=>`The input to the tensor constructor must be a non-null value.`))}function flatten(e,t=[],n=false){if(t==null){t=[]}if(Array.isArray(e)||isTypedArray(e)&&!n){for(let r=0;r<e.length;++r){flatten(e[r],t,n)}}else{t.push(e)}return t}function sizeFromShape(e){if(e.length===0){return 1}let t=e[0];for(let n=1;n<e.length;n++){t*=e[n]}return t}function arraysEqual(e,t){if(e===t){return true}if(e==null||t==null){return false}if(e.length!==t.length){return false}for(let n=0;n<e.length;n++){if(e[n]!==t[n]){return false}}return true}function isInt(e){return e%1===0}function sizeToSquarishShape(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function rightPad(e,t){if(t<=e.length){return e}return e+" ".repeat(t-e.length)}function repeatedTry(e,t=(e=>0),n){return new Promise(((r,a)=>{let s=0;const o=()=>{if(e()){r();return}s++;const i=t(s);if(n!=null&&s>=n){a();return}setTimeout(o,i)};o()}))}function inferFromImplicitShape(e,t){let n=1;let r=-1;for(let t=0;t<e.length;++t){if(e[t]>=0){n*=e[t]}else if(e[t]===-1){if(r!==-1){throw Error(`Shapes can only have 1 implicit size. `+`Found -1 at dim ${r} and dim ${t}`)}r=t}else if(e[t]<0){throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`)}}if(r===-1){if(t>0&&t!==n){throw Error(`Size(${t}) must match the product of shape ${e}`)}return e}if(n===0){throw Error(`Cannot infer the missing size in [${e}] when `+`there are 0 elements`)}if(t%n!==0){throw Error(`The implicit shape can't be a fractional number. `+`Got ${t} / ${n}`)}const a=e.slice();a[r]=t/n;return a}function parseAxisParam(e,t){const n=t.length;e=e==null?t.map(((e,t)=>t)):[].concat(e);assert(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but `+`got axis ${e}`));assert(e.every((e=>isInt(e))),(()=>`All values in axis param must be integers but `+`got axis ${e}`));return e.map((e=>e<0?n+e:e))}function squeezeShape(e,t){const n=[];const r=[];const a=t!=null&&Array.isArray(t)&&t.length===0;const s=t==null||a?null:parseAxisParam(t,e).sort();let o=0;for(let t=0;t<e.length;++t){if(s!=null){if(s[o]===t&&e[t]!==1){throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`)}if((s[o]==null||s[o]>t)&&e[t]===1){n.push(e[t]);r.push(t)}if(s[o]<=t){o++}}if(e[t]!==1){n.push(e[t]);r.push(t)}}return{newShape:n,keptDims:r}}function getTypedArrayFromDType(e,t){let n=null;if(e==null||e==="float32"){n=new Float32Array(t)}else if(e==="int32"){n=new Int32Array(t)}else if(e==="bool"){n=new Uint8Array(t)}else{throw new Error(`Unknown data type ${e}`)}return n}function getArrayFromDType(e,t){let n=null;if(e==null||e==="float32"){n=new Float32Array(t)}else if(e==="int32"){n=new Int32Array(t)}else if(e==="bool"){n=new Uint8Array(t)}else if(e==="string"){n=new Array(t)}else{throw new Error(`Unknown data type ${e}`)}return n}function isValidDtype(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function hasEncodingLoss(e,t){if(t==="complex64"){return false}if(t==="float32"&&e!=="complex64"){return false}if(t==="int32"&&e!=="float32"&&e!=="complex64"){return false}if(t==="bool"&&e==="bool"){return false}return true}function isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function bytesPerElement(e){if(e==="float32"||e==="int32"){return 4}else if(e==="complex64"){return 8}else if(e==="bool"){return 1}else{throw new Error(`Unknown dtype ${e}`)}}function bytesFromStringArray(e){if(e==null){return 0}let t=0;e.forEach((e=>t+=e.length));return t}function isNumber(e){return typeof e==="number"}function inferDtype(e){if(Array.isArray(e)){return inferDtype(e[0])}if(e instanceof Float32Array){return"float32"}else if(e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray){return"int32"}else if(isNumber(e)){return"float32"}else if(isString(e)){return"string"}else if(isBoolean(e)){return"bool"}return"float32"}function isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)}function nearestDivisor(e,t){for(let n=t;n<e;++n){if(e%n===0){return n}}return e}function computeStrides(e){const t=e.length;if(t<2){return[]}const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r){n[r]=n[r+1]*e[r+1]}return n}function createNestedArray(e,t,n,r=false){const a=new Array;if(t.length===1){const s=t[0]*(r?2:1);for(let t=0;t<s;t++){a[t]=n[e+t]}}else{const s=t[0];const o=t.slice(1);const i=o.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<s;t++){a[t]=createNestedArray(e+t*i,o,n,r)}}return a}function toNestedArray(e,t,n=false){if(e.length===0){return t[0]}const r=e.reduce(((e,t)=>e*t))*(n?2:1);if(r===0){return[]}if(r!==t.length){throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`)}return createNestedArray(0,e,t,n)}function makeOnesTypedArray(e,t){const n=makeZerosTypedArray(e,t);for(let e=0;e<n.length;e++){n[e]=1}return n}function makeZerosTypedArray(e,t){if(t==null||t==="float32"||t==="complex64"){return new Float32Array(e)}else if(t==="int32"){return new Int32Array(e)}else if(t==="bool"){return new Uint8Array(e)}else{throw new Error(`Unknown data type ${t}`)}}function assertNonNegativeIntegerDimensions(e){e.forEach((t=>{assert(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got `+`shape [${e}].`))}))}function locToIndex(e,t,n){if(t===0){return 0}else if(t===1){return e[0]}let r=e[e.length-1];for(let t=0;t<e.length-1;++t){r+=n[t]*e[t]}return r}function indexToLoc(e,t,n){if(t===0){return[]}else if(t===1){return[e]}const r=new Array(t);for(let t=0;t<r.length-1;++t){r[t]=Math.floor(e/n[t]);e-=r[t]*n[t]}r[r.length-1]=e;return r}function isPromise(e){return e&&e.then&&typeof e.then==="function"}const TENSORFLOWJS_FLAGS_PREFIX="tfjsflags";class Environment{constructor(e){this.global=e;this.flags={};this.flagRegistry={};this.urlFlags={};this.getQueryParams=getQueryParams;this.populateURLFlags()}setPlatform(e,t){if(this.platform!=null){if(!(env().getBool("IS_TEST")||env().getBool("PROD"))){console.warn(`Platform ${this.platformName} has already been set. `+`Overwriting the platform with ${e}.`)}}this.platformName=e;this.platform=t}registerFlag(e,t,n){this.flagRegistry[e]={evaluationFn:t,setHook:n};if(this.urlFlags[e]!=null){const t=this.urlFlags[e];if(!(env().getBool("IS_TEST")||env().getBool("PROD"))){console.warn(`Setting feature override from URL ${e}: ${t}.`)}this.set(e,t)}}async getAsync(e){if(e in this.flags){return this.flags[e]}this.flags[e]=await this.evaluateFlag(e);return this.flags[e]}get(e){if(e in this.flags){return this.flags[e]}const t=this.evaluateFlag(e);if(isPromise(t)){throw new Error(`Flag ${e} cannot be synchronously evaluated. `+`Please use getAsync() instead.`)}this.flags[e]=t;return this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null){throw new Error(`Cannot set flag ${e} as it has not been registered.`)}this.flags[e]=t;if(this.flagRegistry[e].setHook!=null){this.flagRegistry[e].setHook(t)}}evaluateFlag(e){if(this.flagRegistry[e]==null){throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`)}return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={};this.urlFlags={};this.populateURLFlags()}populateURLFlags(){if(typeof this.global==="undefined"||typeof this.global.location==="undefined"||typeof this.global.location.search==="undefined"){return}const e=this.getQueryParams(this.global.location.search);if(TENSORFLOWJS_FLAGS_PREFIX in e){const t=e[TENSORFLOWJS_FLAGS_PREFIX].split(",");t.forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=parseValue(t,n)}))}}}function getQueryParams(e){const t={};e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>{decodeParam(t,n[0],n[1]);return n.join("=")}));return t}function decodeParam(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function env(){return ENV$3}let ENV$3=null;function setEnvironmentGlobal(e){ENV$3=e}let globalNameSpace;function getGlobalNamespace(){if(globalNameSpace==null){let e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof process!=="undefined"){e=process}else if(typeof self!=="undefined"){e=self}else{throw new Error("Could not find a global object")}globalNameSpace=e}return globalNameSpace}function getGlobalMap(){const e=getGlobalNamespace();if(e._tfGlobals==null){e._tfGlobals=new Map}return e._tfGlobals}function getGlobal(e,t){const n=getGlobalMap();if(n.has(e)){return n.get(e)}else{const r=t();n.set(e,r);return n.get(e)}}const Abs="Abs";const Add="Add";const BatchMatMul="BatchMatMul";const Bincount="Bincount";const Cast="Cast";const Complex="Complex";const ComplexAbs="ComplexAbs";const Concat="Concat";const Conv2DBackpropFilter="Conv2DBackpropFilter";const Conv2DBackpropInput="Conv2DBackpropInput";const DepthwiseConv2dNativeBackpropFilter="DepthwiseConv2dNativeBackpropFilter";const DepthwiseConv2dNativeBackpropInput="DepthwiseConv2dNativeBackpropInput";const RealDiv="RealDiv";const Equal="Equal";const Exp="Exp";const ExpandDims="ExpandDims";const FFT="FFT";const GatherV2="GatherV2";const Greater="Greater";const Identity="Identity";const IsFinite="IsFinite";const Log="Log";const Log1p="Log1p";const LogicalAnd="LogicalAnd";const Max="Max";const Maximum="Maximum";const Mean="Mean";const Minimum="Minimum";const Multiply="Multiply";const Neg="Neg";const NotEqual="NotEqual";const OneHot="OneHot";const Pack="Pack";const PadV2="PadV2";const Pow="Pow";const Prod="Prod";const Range="Range";const Real="Real";const Relu="Relu";const Reshape="Reshape";const Reverse="Reverse";const Select="Select";const Slice="Slice";const Sigmoid="Sigmoid";const Sum="Sum";const SquaredDifference="SquaredDifference";const Sub="Sub";const Tile="Tile";const Unpack="Unpack";const ZerosLike="ZerosLike";const _FusedMatMul="_FusedMatMul";function warn(...e){if(!(env().getBool("IS_TEST")||env().getBool("PROD"))){console.warn(...e)}}function log$1(...e){if(!(env().getBool("IS_TEST")||env().getBool("PROD"))){console.log(...e)}}const kernelRegistry=getGlobal("kernelRegistry",(()=>new Map));const gradRegistry=getGlobal("gradRegistry",(()=>new Map));function getKernel(e,t){const n=makeKey(e,t);return kernelRegistry.get(n)}function getGradient(e){return gradRegistry.get(e)}function getKernelsForBackend(e){const t=kernelRegistry.entries();const n=[];while(true){const{done:r,value:a}=t.next();if(r){break}const[s,o]=a;const[i]=s.split("_");if(i===e){n.push(o)}}return n}function registerKernel(e){const{kernelName:t,backendName:n}=e;const r=makeKey(t,n);if(kernelRegistry.has(r)){warn(`The kernel '${t}' for backend `+`'${n}' is already registered`)}kernelRegistry.set(r,e)}function makeKey(e,t){return`${t}_${e}`}var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};var service_min_long=Long$1;var wasm=null;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function Long$1(e,t,n){this.low=e|0;this.high=t|0;this.unsigned=!!n}Long$1.prototype.__isLong__;Object.defineProperty(Long$1.prototype,"__isLong__",{value:true});function isLong(e){return(e&&e["__isLong__"])===true}Long$1.isLong=isLong;var INT_CACHE={};var UINT_CACHE={};function fromInt(e,t){var n,r,a;if(t){e>>>=0;if(a=0<=e&&e<256){r=UINT_CACHE[e];if(r)return r}n=fromBits(e,(e|0)<0?-1:0,true);if(a)UINT_CACHE[e]=n;return n}else{e|=0;if(a=-128<=e&&e<128){r=INT_CACHE[e];if(r)return r}n=fromBits(e,e<0?-1:0,false);if(a)INT_CACHE[e]=n;return n}}Long$1.fromInt=fromInt;function fromNumber(e,t){if(isNaN(e))return t?UZERO:ZERO;if(t){if(e<0)return UZERO;if(e>=TWO_PWR_64_DBL)return MAX_UNSIGNED_VALUE}else{if(e<=-TWO_PWR_63_DBL)return MIN_VALUE;if(e+1>=TWO_PWR_63_DBL)return MAX_VALUE}if(e<0)return fromNumber(-e,t).neg();return fromBits(e%TWO_PWR_32_DBL|0,e/TWO_PWR_32_DBL|0,t)}Long$1.fromNumber=fromNumber;function fromBits(e,t,n){return new Long$1(e,t,n)}Long$1.fromBits=fromBits;var pow_dbl=Math.pow;function fromString(e,t,n){if(e.length===0)throw Error("empty string");if(e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return ZERO;if(typeof t==="number"){n=t,t=false}else{t=!!t}n=n||10;if(n<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");else if(r===0){return fromString(e.substring(1),t,n).neg()}var a=fromNumber(pow_dbl(n,8));var s=ZERO;for(var o=0;o<e.length;o+=8){var i=Math.min(8,e.length-o),u=parseInt(e.substring(o,o+i),n);if(i<8){var l=fromNumber(pow_dbl(n,i));s=s.mul(l).add(fromNumber(u))}else{s=s.mul(a);s=s.add(fromNumber(u))}}s.unsigned=t;return s}Long$1.fromString=fromString;function fromValue(e,t){if(typeof e==="number")return fromNumber(e,t);if(typeof e==="string")return fromString(e,t);return fromBits(e.low,e.high,typeof t==="boolean"?t:e.unsigned)}Long$1.fromValue=fromValue;var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var TWO_PWR_24=fromInt(TWO_PWR_24_DBL);var ZERO=fromInt(0);Long$1.ZERO=ZERO;var UZERO=fromInt(0,true);Long$1.UZERO=UZERO;var ONE=fromInt(1);Long$1.ONE=ONE;var UONE=fromInt(1,true);Long$1.UONE=UONE;var NEG_ONE=fromInt(-1);Long$1.NEG_ONE=NEG_ONE;var MAX_VALUE=fromBits(4294967295|0,2147483647|0,false);Long$1.MAX_VALUE=MAX_VALUE;var MAX_UNSIGNED_VALUE=fromBits(4294967295|0,4294967295|0,true);Long$1.MAX_UNSIGNED_VALUE=MAX_UNSIGNED_VALUE;var MIN_VALUE=fromBits(0,2147483648|0,false);Long$1.MIN_VALUE=MIN_VALUE;var LongPrototype=Long$1.prototype;LongPrototype.toInt=function e(){return this.unsigned?this.low>>>0:this.low};LongPrototype.toNumber=function e(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)};LongPrototype.toString=function e(t){t=t||10;if(t<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(MIN_VALUE)){var n=fromNumber(t),r=this.div(n),a=r.mul(n).sub(this);return r.toString(t)+a.toInt().toString(t)}else return"-"+this.neg().toString(t)}var s=fromNumber(pow_dbl(t,6),this.unsigned),o=this;var i="";while(true){var u=o.div(s),l=o.sub(u.mul(s)).toInt()>>>0,c=l.toString(t);o=u;if(o.isZero())return c+i;else{while(c.length<6)c="0"+c;i=""+c+i}}};LongPrototype.getHighBits=function e(){return this.high};LongPrototype.getHighBitsUnsigned=function e(){return this.high>>>0};LongPrototype.getLowBits=function e(){return this.low};LongPrototype.getLowBitsUnsigned=function e(){return this.low>>>0};LongPrototype.getNumBitsAbs=function e(){if(this.isNegative())return this.eq(MIN_VALUE)?64:this.neg().getNumBitsAbs();var t=this.high!=0?this.high:this.low;for(var n=31;n>0;n--)if((t&1<<n)!=0)break;return this.high!=0?n+33:n+1};LongPrototype.isZero=function e(){return this.high===0&&this.low===0};LongPrototype.eqz=LongPrototype.isZero;LongPrototype.isNegative=function e(){return!this.unsigned&&this.high<0};LongPrototype.isPositive=function e(){return this.unsigned||this.high>=0};LongPrototype.isOdd=function e(){return(this.low&1)===1};LongPrototype.isEven=function e(){return(this.low&1)===0};LongPrototype.equals=function e(t){if(!isLong(t))t=fromValue(t);if(this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1)return false;return this.high===t.high&&this.low===t.low};LongPrototype.eq=LongPrototype.equals;LongPrototype.notEquals=function e(t){return!this.eq(t)};LongPrototype.neq=LongPrototype.notEquals;LongPrototype.ne=LongPrototype.notEquals;LongPrototype.lessThan=function e(t){return this.comp(t)<0};LongPrototype.lt=LongPrototype.lessThan;LongPrototype.lessThanOrEqual=function e(t){return this.comp(t)<=0};LongPrototype.lte=LongPrototype.lessThanOrEqual;LongPrototype.le=LongPrototype.lessThanOrEqual;LongPrototype.greaterThan=function e(t){return this.comp(t)>0};LongPrototype.gt=LongPrototype.greaterThan;LongPrototype.greaterThanOrEqual=function e(t){return this.comp(t)>=0};LongPrototype.gte=LongPrototype.greaterThanOrEqual;LongPrototype.ge=LongPrototype.greaterThanOrEqual;LongPrototype.compare=function e(t){if(!isLong(t))t=fromValue(t);if(this.eq(t))return 0;var n=this.isNegative(),r=t.isNegative();if(n&&!r)return-1;if(!n&&r)return 1;if(!this.unsigned)return this.sub(t).isNegative()?-1:1;return t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1};LongPrototype.comp=LongPrototype.compare;LongPrototype.negate=function e(){if(!this.unsigned&&this.eq(MIN_VALUE))return MIN_VALUE;return this.not().add(ONE)};LongPrototype.neg=LongPrototype.negate;LongPrototype.add=function e(t){if(!isLong(t))t=fromValue(t);var n=this.high>>>16;var r=this.high&65535;var a=this.low>>>16;var s=this.low&65535;var o=t.high>>>16;var i=t.high&65535;var u=t.low>>>16;var l=t.low&65535;var c=0,p=0,m=0,d=0;d+=s+l;m+=d>>>16;d&=65535;m+=a+u;p+=m>>>16;m&=65535;p+=r+i;c+=p>>>16;p&=65535;c+=n+o;c&=65535;return fromBits(m<<16|d,c<<16|p,this.unsigned)};LongPrototype.subtract=function e(t){if(!isLong(t))t=fromValue(t);return this.add(t.neg())};LongPrototype.sub=LongPrototype.subtract;LongPrototype.multiply=function e(t){if(this.isZero())return ZERO;if(!isLong(t))t=fromValue(t);if(wasm){var n=wasm.mul(this.low,this.high,t.low,t.high);return fromBits(n,wasm.get_high(),this.unsigned)}if(t.isZero())return ZERO;if(this.eq(MIN_VALUE))return t.isOdd()?MIN_VALUE:ZERO;if(t.eq(MIN_VALUE))return this.isOdd()?MIN_VALUE:ZERO;if(this.isNegative()){if(t.isNegative())return this.neg().mul(t.neg());else return this.neg().mul(t).neg()}else if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(TWO_PWR_24)&&t.lt(TWO_PWR_24))return fromNumber(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16;var a=this.high&65535;var s=this.low>>>16;var o=this.low&65535;var i=t.high>>>16;var u=t.high&65535;var l=t.low>>>16;var c=t.low&65535;var p=0,m=0,d=0,h=0;h+=o*c;d+=h>>>16;h&=65535;d+=s*c;m+=d>>>16;d&=65535;d+=o*l;m+=d>>>16;d&=65535;m+=a*c;p+=m>>>16;m&=65535;m+=s*l;p+=m>>>16;m&=65535;m+=o*u;p+=m>>>16;m&=65535;p+=r*c+a*l+s*u+o*i;p&=65535;return fromBits(d<<16|h,p<<16|m,this.unsigned)};LongPrototype.mul=LongPrototype.multiply;LongPrototype.divide=function e(t){if(!isLong(t))t=fromValue(t);if(t.isZero())throw Error("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1){return this}var n=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,t.low,t.high);return fromBits(n,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?UZERO:ZERO;var r,a,s;if(!this.unsigned){if(this.eq(MIN_VALUE)){if(t.eq(ONE)||t.eq(NEG_ONE))return MIN_VALUE;else if(t.eq(MIN_VALUE))return ONE;else{var o=this.shr(1);r=o.div(t).shl(1);if(r.eq(ZERO)){return t.isNegative()?ONE:NEG_ONE}else{a=this.sub(t.mul(r));s=r.add(a.div(t));return s}}}else if(t.eq(MIN_VALUE))return this.unsigned?UZERO:ZERO;if(this.isNegative()){if(t.isNegative())return this.neg().div(t.neg());return this.neg().div(t).neg()}else if(t.isNegative())return this.div(t.neg()).neg();s=ZERO}else{if(!t.unsigned)t=t.toUnsigned();if(t.gt(this))return UZERO;if(t.gt(this.shru(1)))return UONE;s=UZERO}a=this;while(a.gte(t)){r=Math.max(1,Math.floor(a.toNumber()/t.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2),u=i<=48?1:pow_dbl(2,i-48),l=fromNumber(r),c=l.mul(t);while(c.isNegative()||c.gt(a)){r-=u;l=fromNumber(r,this.unsigned);c=l.mul(t)}if(l.isZero())l=ONE;s=s.add(l);a=a.sub(c)}return s};LongPrototype.div=LongPrototype.divide;LongPrototype.modulo=function e(t){if(!isLong(t))t=fromValue(t);if(wasm){var n=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,t.low,t.high);return fromBits(n,wasm.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};LongPrototype.mod=LongPrototype.modulo;LongPrototype.rem=LongPrototype.modulo;LongPrototype.not=function e(){return fromBits(~this.low,~this.high,this.unsigned)};LongPrototype.and=function e(t){if(!isLong(t))t=fromValue(t);return fromBits(this.low&t.low,this.high&t.high,this.unsigned)};LongPrototype.or=function e(t){if(!isLong(t))t=fromValue(t);return fromBits(this.low|t.low,this.high|t.high,this.unsigned)};LongPrototype.xor=function e(t){if(!isLong(t))t=fromValue(t);return fromBits(this.low^t.low,this.high^t.high,this.unsigned)};LongPrototype.shiftLeft=function e(t){if(isLong(t))t=t.toInt();if((t&=63)===0)return this;else if(t<32)return fromBits(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned);else return fromBits(0,this.low<<t-32,this.unsigned)};LongPrototype.shl=LongPrototype.shiftLeft;LongPrototype.shiftRight=function e(t){if(isLong(t))t=t.toInt();if((t&=63)===0)return this;else if(t<32)return fromBits(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned);else return fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};LongPrototype.shr=LongPrototype.shiftRight;LongPrototype.shiftRightUnsigned=function e(t){if(isLong(t))t=t.toInt();t&=63;if(t===0)return this;else{var n=this.high;if(t<32){var r=this.low;return fromBits(r>>>t|n<<32-t,n>>>t,this.unsigned)}else if(t===32)return fromBits(n,0,this.unsigned);else return fromBits(n>>>t-32,0,this.unsigned)}};LongPrototype.shru=LongPrototype.shiftRightUnsigned;LongPrototype.shr_u=LongPrototype.shiftRightUnsigned;LongPrototype.toSigned=function e(){if(!this.unsigned)return this;return fromBits(this.low,this.high,false)};LongPrototype.toUnsigned=function e(){if(this.unsigned)return this;return fromBits(this.low,this.high,true)};LongPrototype.toBytes=function e(t){return t?this.toBytesLE():this.toBytesBE()};LongPrototype.toBytesLE=function e(){var t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};LongPrototype.toBytesBE=function e(){var t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};Long$1.fromBytes=function e(t,n,r){return r?Long$1.fromBytesLE(t,n):Long$1.fromBytesBE(t,n)};Long$1.fromBytesLE=function e(t,n){return new Long$1(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};Long$1.fromBytesBE=function e(t,n){return new Long$1(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};var LongExports=_mergeNamespaces({__proto__:null,default:service_min_long},[service_min_long]);const Long=service_min_long||LongExports;function hexToLong(e){return Long.fromString(e,true,16)}hexToLong("c3a5c85c97cb3127");hexToLong("b492b66fbe98f273");hexToLong("9ae16a3b2f90404f");function createScalarValue(e,t){if(t==="string"){return encodeString(e)}return toTypedArray([e],t)}function noConversionNeeded(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function toTypedArray(e,t){if(t==="string"){throw new Error("Cannot convert a string[] to a TypedArray")}if(Array.isArray(e)){e=flatten(e)}if(env().getBool("DEBUG")){checkConversionForErrors(e,t)}if(noConversionNeeded(e,t)){return e}if(t==null||t==="float32"||t==="complex64"){return new Float32Array(e)}else if(t==="int32"){return new Int32Array(e)}else if(t==="bool"){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n){if(Math.round(e[n])!==0){t[n]=1}}return t}else{throw new Error(`Unknown data type ${t}`)}}function now(){return env().platform.now()}class Profiler{constructor(e,t){this.backendTimer=e;this.logger=t;if(t==null){this.logger=new Logger}}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=now();if(this.backendTimer.timerAvailable()){s=this.backendTimer.time(a)}else{a();for(const e of r){e.dataSync()}s=Promise.resolve({kernelMs:now()-o})}if(env().getBool("CHECK_COMPUTATION_FOR_ERRORS")){for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{checkComputationForErrors(t,n.dtype,e)}))}}const i={kernelName:e,outputs:r,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>e.getExtraProfileInfo!=null?e.getExtraProfileInfo():""))};return i}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach((e=>{Promise.all([e.data(),r,s]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}class Logger{logKernelProfile(e,t,n,r,a,s){const o=typeof r==="number"?rightPad(`${r}ms`,9):r["error"];const i=rightPad(e,25);const u=t.rank;const l=t.size;const c=rightPad(t.shape.toString(),14);let p="";for(const e in a){const n=a[e];if(n!=null){const r=n.shape||t.shape;const a=r.length;p+=`${e}: ${a}D ${a>0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${p}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function getFilteredNodesXToY(e,t,n){const r={};const a={};for(let e=0;e<t.length;e++){r[t[e].id]=true}for(let n=0;n<e.length;n++){const s=e[n];const o=s.inputs;for(const e in o){const n=o[e];let i=false;for(let e=0;e<t.length;e++){if(r[n.id]){s.outputs.forEach((e=>r[e.id]=true));i=true;a[s.id]=true;break}}if(i){break}}}const s={};s[n.id]=true;const o={};for(let t=e.length-1;t>=0;t--){const n=e[t];const r=n.inputs;for(let e=0;e<n.outputs.length;e++){if(s[n.outputs[e].id]){for(const e in r){s[r[e].id]=true;o[n.id]=true}break}}}const i=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&o[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];if(r[a.id]){e[t]=a}}const t=Object.assign({},n);t.inputs=e;t.outputs=n.outputs;i.push(t)}}return i}class TensorBuffer{constructor(e,t,n){this.dtype=t;this.shape=e.slice();this.size=sizeFromShape(e);if(n!=null){const e=n.length;assert(e===this.size,(()=>`Length of values '${e}' does not match the size `+`inferred by the shape '${this.size}'.`))}if(t==="complex64"){throw new Error(`complex64 dtype TensorBuffers are not supported. Please create `+`a TensorBuffer for the real and imaginary parts separately and `+`call tf.complex(real, imag).`)}this.values=n||getArrayFromDType(t,this.size);this.strides=computeStrides(e)}set(e,...t){if(t.length===0){t=[0]}assert(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must `+`match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){if(e.length===0){e=[0]}let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. `+`  Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t){n+=this.strides[t]*e[t]}return this.values[n]}locToIndex(e){if(this.rank===0){return 0}else if(this.rank===1){return e[0]}let t=e[e.length-1];for(let n=0;n<e.length-1;++n){t+=this.strides[n]*e[n]}return t}indexToLoc(e){if(this.rank===0){return[]}else if(this.rank===1){return[e]}const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n){t[n]=Math.floor(e/this.strides[n]);e-=t[n]*this.strides[n]}t[t.length-1]=e;return t}get rank(){return this.shape.length}toTensor(){return trackerFn().makeTensor(this.values,this.shape,this.dtype)}}let trackerFn=null;let opHandler$1=null;function setTensorTracker(e){trackerFn=e}function setOpHandler(e){opHandler$1=e}class Tensor{constructor(e,t,n,r){this.kept=false;this.isDisposedInternal=false;this.shape=e.slice();this.dtype=t||"float32";this.size=sizeFromShape(e);this.strides=computeStrides(e);this.dataId=n;this.id=r;this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return opHandler$1.buffer(this.shape,this.dtype,e)}bufferSync(){return opHandler$1.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return toNestedArray(this.shape,e,this.dtype==="complex64")}arraySync(){return toNestedArray(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();const e=trackerFn().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map((e=>decodeString(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. "+"To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){this.throwIfDisposed();return trackerFn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=trackerFn().readSync(this.dataId);if(this.dtype==="string"){try{return e.map((e=>decodeString(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. "+"To get the original bytes, call tensor.bytes().")}}return e}async bytes(){this.throwIfDisposed();const e=await trackerFn().read(this.dataId);if(this.dtype==="string"){return e}else{return new Uint8Array(e.buffer)}}dispose(){if(this.isDisposed){return}trackerFn().disposeTensor(this);this.isDisposedInternal=true}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed){throw new Error(`Tensor is disposed.`)}}print(e=false){return opHandler$1.print(this,e)}clone(){this.throwIfDisposed();return opHandler$1.clone(this)}toString(e=false){const t=this.dataSync();return tensorToString(t,this.shape,this.dtype,e)}cast(e){this.throwIfDisposed();return opHandler$1.cast(this,e)}variable(e=true,t,n){this.throwIfDisposed();return trackerFn().makeVariable(this,e,t,n)}}Object.defineProperty(Tensor,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function getGlobalTensorClass(){return getGlobal("Tensor",(()=>Tensor))}getGlobalTensorClass();class Variable extends Tensor{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t;this.name=n}assign(e){if(e.dtype!==this.dtype){throw new Error(`dtype of the new value (${e.dtype}) and `+`previous value (${this.dtype}) must match`)}if(!arraysEqual(e.shape,this.shape)){throw new Error(`shape of the new value (${e.shape}) and `+`previous value (${this.shape}) must match`)}trackerFn().disposeTensor(this);this.dataId=e.dataId;trackerFn().incRef(this,null)}dispose(){trackerFn().disposeVariable(this);this.isDisposedInternal=true}}Object.defineProperty(Variable,Symbol.hasInstance,{value:e=>e instanceof Tensor&&e.assign!=null&&e.assign instanceof Function});var Rank;(function(e){e["R0"]="R0";e["R1"]="R1";e["R2"]="R2";e["R3"]="R3";e["R4"]="R4";e["R5"]="R5";e["R6"]="R6"})(Rank||(Rank={}));var UpcastInt32AndMap;(function(e){e["float32"]="float32";e["int32"]="int32";e["bool"]="int32";e["complex64"]="complex64"})(UpcastInt32AndMap||(UpcastInt32AndMap={}));var UpcastBoolAndMap;(function(e){e["float32"]="float32";e["int32"]="int32";e["bool"]="bool";e["complex64"]="complex64"})(UpcastBoolAndMap||(UpcastBoolAndMap={}));var UpcastFloat32AndMap;(function(e){e["float32"]="float32";e["int32"]="float32";e["bool"]="float32";e["complex64"]="complex64"})(UpcastFloat32AndMap||(UpcastFloat32AndMap={}));var UpcastComplex64AndMap;(function(e){e["float32"]="complex64";e["int32"]="complex64";e["bool"]="complex64";e["complex64"]="complex64"})(UpcastComplex64AndMap||(UpcastComplex64AndMap={}));const upcastTypeMap={float32:UpcastFloat32AndMap,int32:UpcastInt32AndMap,bool:UpcastBoolAndMap,complex64:UpcastComplex64AndMap};function upcastType(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string"){return"string"}throw new Error(`Can not upcast ${e} with ${t}`)}return upcastTypeMap[e][t]}function sumOutType(e){return upcastType(e,"int32")}function makeTypesMatch(e,t){if(e.dtype===t.dtype){return[e,t]}const n=upcastType(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function getTensorsInContainer(e){const t=[];const n=new Set;walkTensorContainer(e,t,n);return t}function walkTensorContainer(e,t,n){if(e==null){return}if(e instanceof Tensor){t.push(e);return}if(!isIterable(e)){return}const r=e;for(const e in r){const a=r[e];if(!n.has(a)){n.add(a);walkTensorContainer(a,t,n)}}}function isIterable(e){return Array.isArray(e)||typeof e==="object"}function isRegisteredKernelInvocation(e){return e.kernelName!=null}class EngineState{constructor(){this.registeredVariables={};this.nextTapeNodeId=0;this.numBytes=0;this.numTensors=0;this.numStringTensors=0;this.numDataBuffers=0;this.gradientDepth=0;this.kernelDepth=0;this.scopeStack=[];this.numDataMovesStack=[];this.nextScopeId=0;this.tensorInfo=new WeakMap;this.profiling=false;this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables){this.registeredVariables[e].dispose()}}}class Engine{constructor(e){this.ENV=e;this.registry={};this.registryFactory={};this.pendingBackendInitId=0;this.state=new EngineState}async ready(){if(this.pendingBackendInit!=null){return this.pendingBackendInit.then((()=>{}))}if(this.backendInstance!=null){return}const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];const r=await this.initializeBackend(n).success;if(r){await this.setBackend(n);return}}throw new Error(`Could not initialize any backends, all backend initializations `+`failed.`)}get backend(){if(this.pendingBackendInit!=null){throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make `+`sure to await tf.ready() or await tf.setBackend() before calling `+`other methods`)}if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t){throw new Error(`The highest priority backend '${e}' has not yet been `+`initialized. Make sure to await tf.ready() or `+`await tf.setBackend() before calling other methods`)}this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t){return null}}else{return null}}return this.registry[e]}findBackendFactory(e){if(!(e in this.registryFactory)){return null}return this.registryFactory[e].factory}registerBackend(e,t,n=1){if(e in this.registryFactory){warn(`${e} backend was already registered. `+`Reusing existing backend factory.`);return false}this.registryFactory[e]={factory:t,priority:n};return true}async setBackend(e){if(this.registryFactory[e]==null){throw new Error(`Backend name '${e}' not found in registry`)}this.backendName=e;if(this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);const r=n?await t:t;if(!r){return false}}this.backendInstance=this.registry[e];this.setupRegisteredKernels();this.profiler=new Profiler(this.backendInstance);return true}setupRegisteredKernels(){const e=getKernelsForBackend(this.backendName);e.forEach((e=>{if(e.setupFunc!=null){e.setupFunc(this.backendInstance)}}))}disposeRegisteredKernels(e){const t=getKernelsForBackend(e);t.forEach((t=>{if(t.disposeFunc!=null){t.disposeFunc(this.registry[e])}}))}initializeBackend(e){const t=this.registryFactory[e];if(t==null){throw new Error(`Cannot initialize backend ${e}, no registration found.`)}try{const n=t.factory();if(n&&!(n instanceof KernelBackend)&&typeof n.then==="function"){const t=++this.pendingBackendInitId;const r=n.then((n=>{if(t<this.pendingBackendInitId){return false}this.registry[e]=n;this.pendingBackendInit=null;return true})).catch((n=>{if(t<this.pendingBackendInitId){return false}this.pendingBackendInit=null;warn(`Initialization of backend ${e} failed`);warn(n.stack||n.message);return false}));this.pendingBackendInit=r;return{success:r,asyncInit:true}}else{this.registry[e]=n;return{success:true,asyncInit:false}}}catch(t){warn(`Initialization of backend ${e} failed`);warn(t.stack||t.message);return{success:false,asyncInit:false}}}removeBackend(e){if(!(e in this.registryFactory)){throw new Error(`${e} backend not found in registry`)}if(this.backendName===e&&this.pendingBackendInit!=null){this.pendingBackendInitId++}if(e in this.registry){this.disposeRegisteredKernels(e);this.registry[e].dispose();delete this.registry[e]}delete this.registryFactory[e];if(this.backendName===e){this.pendingBackendInit=null;this.backendName=null;this.backendInstance=null}}getSortedBackends(){if(Object.keys(this.registryFactory).length===0){throw new Error("No backend found in registry.")}return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];const{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r){return{name:n,asyncInit:a}}}throw new Error(`Could not initialize any backends, all backend initializations `+`failed.`)}moveData(e,t){const n=this.state.tensorInfo.get(t);const r=n.backend;const a=this.readSync(t);const s=r.refCount(t);r.disposeData(t,true);n.backend=e;e.move(t,a,n.shape,n.dtype,s);if(this.shouldCheckForMemLeaks()){this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}}tidy(e,t){let n=null;if(t==null){if(typeof e!=="function"){throw new Error("Please provide a function to tidy()")}t=e}else{if(typeof e!=="string"&&!(e instanceof String)){throw new Error("When calling with two arguments, the first argument "+"to tidy() must be a string")}if(typeof t!=="function"){throw new Error("When calling with two arguments, the 2nd argument "+"to tidy() must be a function")}n=e}let r;return this.scopedRun((()=>this.startScope(n)),(()=>this.endScope(r)),(()=>{r=t();if(r instanceof Promise){console.error("Cannot return a Promise inside of tidy.")}return r}))}scopedRun(e,t,n){e();try{const e=n();t();return e}catch(e){t();throw e}}nextTensorId(){return Engine.nextTensorId++}nextVariableId(){return Engine.nextVariableId++}clone(e){const t=ENGINE.runKernel(Identity,{x:e});const n={x:e};const r=e=>({x:()=>{const t="float32";const n={x:e};const r={dtype:t};return ENGINE.runKernel(Cast,n,r)}});const a=[];this.addTapeNode(this.state.activeScope.name,n,[t],r,a,{});return t}runKernel(e,t,n){if(this.backendName==null){this.backend}const r=getKernel(e,this.backendName)!=null;if(!r){throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`)}return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach((e=>{a+=e.dtype==="complex64"?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1];const o=r-t-a-s;if(o>0){throw new Error(`Backend '${this.backendName}' has an internal memory leak `+`(${o} data ids) after running '${e}'`)}}runKernelFunc(e){let t;let n=[];const r=this.isTapeOn();const a=this.state.numBytes;const s=this.state.numTensors;if(this.shouldCheckForMemLeaks()){this.state.numDataMovesStack.push(0)}let o;if(this.backendName==null){this.backend}let i;const u=isRegisteredKernelInvocation(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(isRegisteredKernelInvocation(e)){const{kernelName:t,inputs:a,attrs:s}=e;if(this.backendName==null){this.backend}const u=getKernel(t,this.backendName);assert(u!=null,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`));o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(i)?i:[i];if(this.shouldCheckForMemLeaks()){this.checkKernelForMemLeak(t,e,o)}const l=o.map((e=>{if(e.rank!=null){return e}return this.makeTensorFromTensorInfo(e)}));if(r){const e=this.getTensorsForGradient(t,a,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e;const a=e=>{if(!r){return}n=e.map((e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(i)?i:[i];if(this.shouldCheckForMemLeaks()){this.checkKernelForMemLeak(u,e,n)}return n}}const{inputs:l,attrs:c}=e;const p=isRegisteredKernelInvocation(e)?null:e.backwardsFunc;let m;this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{if(!this.ENV.getBool("DEBUG")&&!this.state.profiling){t=o()}else{m=this.profiler.profileKernel(u,l,(()=>o()));if(this.ENV.getBool("DEBUG")){this.profiler.logKernelProfile(m)}t=m.outputs}}));if(r){this.addTapeNode(u,l,t,p,n,c)}if(this.state.profiling){this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map((e=>l[e]!=null?l[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:m.timeMs,extraInfo:m.extraInfo})}return Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=getGradient(e);if(r!=null){const e=r.inputsToSave||[];const a=r.outputsToSave||[];let s;if(r.saveAllInputs){assert(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array."));s=Object.keys(t).map((e=>t[e]))}else{s=e.map((e=>t[e]))}const o=n.filter(((e,t)=>a[t]));return s.concat(o)}return[]}makeTensor(e,t,n,r){if(e==null){throw new Error("Values passed to engine.makeTensor() are null")}n=n||"float32";r=r||this.backend;let a=e;if(n==="string"&&isString(e[0])){a=e.map((e=>encodeString(e)))}const s=r.write(a,t,n);const o=new Tensor(t,n,s,this.nextTensorId());this.trackTensor(o,r);if(n==="string"){const e=this.state.tensorInfo.get(s);const t=bytesFromStringArray(a);this.state.numBytes+=t-e.bytes;e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){n=n||"float32";const a={dataId:e,shape:t,dtype:n};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e;const s=new Tensor(r,a,n,this.nextTensorId());this.trackTensor(s,t);return s}makeVariable(e,t=true,n,r){n=n||this.nextVariableId().toString();if(r!=null&&r!==e.dtype){e=e.cast(r)}const a=new Variable(e,t,n,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null){throw new Error(`Variable with name ${a.name} was already registered`)}this.state.registeredVariables[a.name]=a;this.incRef(a,this.backend);return a}trackTensor(e,t){this.state.numTensors++;if(e.dtype==="string"){this.state.numStringTensors++}let n=0;if(e.dtype!=="complex64"&&e.dtype!=="string"){n=e.size*bytesPerElement(e.dtype)}this.state.numBytes+=n;if(!this.state.tensorInfo.has(e.dataId)){this.state.numDataBuffers++;this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})}if(!(e instanceof Variable)){this.track(e)}}incRef(e,t){this.trackTensor(e,t);this.backend.incRef(e.dataId)}removeDataId(e,t){if(this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t){this.state.tensorInfo.delete(e);this.state.numDataBuffers--}}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId)){return}const t=this.state.tensorInfo.get(e.dataId);this.state.numTensors--;if(e.dtype==="string"){this.state.numStringTensors--;this.state.numBytes-=t.bytes}if(e.dtype!=="complex64"&&e.dtype!=="string"){const t=e.size*bytesPerElement(e.dtype);this.state.numBytes-=t}if(t.backend.disposeData(e.dataId)){this.removeDataId(e.dataId,t.backend)}}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e);if(this.state.registeredVariables[e.name]!=null){delete this.state.registeredVariables[e.name]}}memory(){const e=this.backend.memory();e.numTensors=this.state.numTensors;e.numDataBuffers=this.state.numDataBuffers;e.numBytes=this.state.numBytes;if(this.state.numStringTensors>0){e.unreliable=true;if(e.reasons==null){e.reasons=[]}e.reasons.push("Memory usage by string tensors is approximate "+"(2 bytes per character)")}return e}async profile(e){this.state.profiling=true;const t=this.state.numBytes;const n=this.state.numTensors;this.state.activeProfile.kernels=[];this.state.activeProfile.result=await e();this.state.profiling=false;this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot)));this.state.activeProfile.newBytes=this.state.numBytes-t;this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels){e.kernelTimeMs=await e.kernelTimeMs;e.extraInfo=await e.extraInfo}return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a};const i=getGradient(e);if(i!=null){r=i.gradFunc}if(r!=null){o.gradient=e=>{e=e.map(((e,t)=>{if(e==null){const e=n[t];const r=makeZerosTypedArray(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}));return r(e.length>1?e:e[0],a,s)}}this.state.activeTape.push(o)}keep(e){e.kept=true;return e}startTape(){if(this.state.gradientDepth===0){this.state.activeTape=[]}this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};if(e){t.name=e}this.state.scopeStack.push(t);this.state.activeScope=t}endScope(e){const t=getTensorsInContainer(e);const n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];if(!t.kept&&!n.has(t.id)){t.dispose()}}const r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1];t.forEach((e=>{if(!e.kept&&e.scopeId===r.id){this.track(e)}}))}gradients(e,t,n,r=false){assert(t.length>0,(()=>"gradients() received an empty list of xs."));if(n!=null&&n.dtype!=="float32"){throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`)}const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));assert(a instanceof Tensor,(()=>"The result y returned by f() must be a tensor."));const s=getFilteredNodesXToY(this.state.activeTape,t,a);if(!r&&s.length===0&&t.length>0){throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure "+"that the f you passed encloses all operations that lead from x "+"to y.")}return this.tidy("backward",(()=>{const e={};e[a.id]=n==null?ones$1(a.shape):n;backpropagateGradients(e,s,(e=>this.tidy(e)),add$1);const r=t.map((t=>e[t.id]));if(this.state.gradientDepth===0){this.state.activeTape.forEach((e=>{for(const t of e.saved){t.dispose()}}));this.state.activeTape=null}return{value:a,grads:r}}))}customGrad(e){assert(isFunction(e),(()=>"The f passed in customGrad(f) must be a function."));return(...t)=>{assert(t.every((e=>e instanceof Tensor)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be "+"tensors"));let n;const r={};t.forEach(((e,t)=>{r[t]=e}));const a=(r,a)=>{n=e(...[...t,a]);assert(n.value instanceof Tensor,(()=>"The function f passed in customGrad(f) must return an "+"object where `obj.value` is a tensor"));assert(isFunction(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an "+"object where `obj.gradFunc` is a function."));return n.value};const s=(e,r)=>{const a=n.gradFunc(e,r);const s=Array.isArray(a)?a:[a];assert(s.length===t.length,(()=>"The function f passed in customGrad(f) must return an "+"object where `obj.gradFunc` is a function that returns "+"the same number of tensors as inputs passed to f(...)."));assert(s.every((e=>e instanceof Tensor)),(()=>"The function f passed in customGrad(f) must return an "+"object where `obj.gradFunc` is a function that returns "+"a list of only tensors."));const o={};s.forEach(((e,t)=>{o[t]=()=>e}));return o};return this.runKernelFunc({forwardFunc:a,backwardsFunc:s,inputs:r})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}readToGPU(e,t){const n=this.state.tensorInfo.get(e);return n.backend.readToGPU(e,t)}async time(e){const t=now();const n=await this.backend.time(e);n.wallMs=now()-t;return n}track(e){if(this.state.activeScope!=null){e.scopeId=this.state.activeScope.id;this.state.activeScope.track.push(e)}return e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++;this.state.dispose();this.ENV.reset();this.state=new EngineState;for(const e in this.registry){this.disposeRegisteredKernels(e);this.registry[e].dispose();delete this.registry[e]}this.backendName=null;this.backendInstance=null;this.pendingBackendInit=null}}Engine.nextTensorId=0;Engine.nextVariableId=0;function ones$1(e){const t=makeOnesTypedArray(sizeFromShape(e),"float32");return ENGINE.makeTensor(t,e,"float32")}function getOrMakeEngine(){const e=getGlobalNamespace();if(e._tfengine==null){const t=new Environment(e);e._tfengine=new Engine(t)}setEnvironmentGlobal(e._tfengine.ENV);setTensorTracker((()=>e._tfengine));return e._tfengine}const ENGINE=getOrMakeEngine();function add$1(e,t){const n={a:e,b:t};return ENGINE.runKernel(Add,n)}function _isNavigatorDefined(){return typeof navigator!=="undefined"&&navigator!=null}function isMobile(e){if(e||_isNavigatorDefined()){if(!e){e=navigator}if(e.product==="ReactNative"){return true}const t=e.userAgent||e.vendor||(typeof window!=="undefined"?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return false}function isBrowser(){return typeof window!=="undefined"&&window.document!=null||typeof WorkerGlobalScope!=="undefined"}const ENV$2=env();ENV$2.registerFlag("DEBUG",(()=>false),(e=>{if(e){console.warn("Debugging mode is ON. The output of every math call will "+"be downloaded to CPU and checked for NaNs. "+"This significantly impacts performance.")}}));ENV$2.registerFlag("IS_BROWSER",(()=>isBrowser()));ENV$2.registerFlag("IS_NODE",(()=>typeof process!=="undefined"&&typeof process.versions!=="undefined"&&typeof process.versions.node!=="undefined"));ENV$2.registerFlag("IS_CHROME",(()=>typeof navigator!=="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)));ENV$2.registerFlag("PROD",(()=>false));ENV$2.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>ENV$2.getBool("DEBUG")));ENV$2.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>true));ENV$2.registerFlag("IS_TEST",(()=>false));ENV$2.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>true));ENV$2.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>false));ENV$2.registerFlag("ENGINE_COMPILE_ONLY",(()=>false));function inferShape(e,t){let n=e;if(isTypedArray(e)){return t==="string"?[]:[e.length]}if(!Array.isArray(e)){return[]}const r=[];while(Array.isArray(n)||isTypedArray(n)&&t!=="string"){r.push(n.length);n=n[0]}if(Array.isArray(e)&&env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")){deepAssertShapeConsistency(e,r,[])}return r}function assertDtype(e,t,n,r){if(e==="string_or_numeric"){return}if(e==null){throw new Error(`Expected dtype cannot be null.`)}if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string"){throw new Error(`Argument '${n}' passed to '${r}' must `+`be ${e} tensor, but got ${t} tensor`)}}function convertToTensor(e,t,n,r="numeric"){if(e instanceof Tensor){assertDtype(r,e.dtype,t,n);return e}let a=inferDtype(e);if(a!=="string"&&["bool","int32","float32"].indexOf(r)>=0){a=r}assertDtype(r,a,t,n);if(e==null||!isTypedArray(e)&&!Array.isArray(e)&&typeof e!=="number"&&typeof e!=="boolean"&&typeof e!=="string"){const r=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a `+`Tensor or TensorLike, but got '${r}'`)}const s=inferShape(e,a);if(!isTypedArray(e)&&!Array.isArray(e)){e=[e]}const o=true;const i=a!=="string"?toTypedArray(e,a):flatten(e,[],o);return ENGINE.makeTensor(i,s,a)}function convertToTensorArray(e,t,n,r="numeric"){if(!Array.isArray(e)){throw new Error(`Argument ${t} passed to ${n} must be a `+"`Tensor[]` or `TensorLike[]`")}const a=e;return a.map(((e,a)=>convertToTensor(e,`${t}[${a}]`,n,r)))}const OP_SCOPE_SUFFIX="__op";function op(e){const t=Object.keys(e);if(t.length!==1){throw new Error(`Please provide an object with a single key `+`(operation name) mapping to a function. Got an object with `+`${t.length} keys.`)}let n=t[0];const r=e[n];if(n.endsWith("_")){n=n.substring(0,n.length-1)}n=n+OP_SCOPE_SUFFIX;const a=(...e)=>{ENGINE.startScope(n);try{const t=r(...e);if(isPromise(t)){console.error("Cannot return a Promise inside of tidy.")}ENGINE.endScope(t);return t}catch(e){ENGINE.endScope(null);throw e}};Object.defineProperty(a,"name",{value:n,configurable:true});return a}function complex_(e,t){const n=convertToTensor(e,"real","complex");const r=convertToTensor(t,"imag","complex");assertShapesMatch(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, `+`must match in call to tf.complex().`);const a={real:n,imag:r};return ENGINE.runKernel(Complex,a)}const complex$1=op({complex_:complex_});function makeTensor(e,t,n,r){if(r==null){r=inferDtype(e)}if(r==="complex64"){throw new Error(`Cannot construct a complex64 tensor directly. `+`Please use tf.complex(real, imag).`)}if(!isTypedArray(e)&&!Array.isArray(e)&&typeof e!=="number"&&typeof e!=="boolean"&&typeof e!=="string"){throw new Error("values passed to tensor(values) must be a number/boolean/string or "+"an array of numbers/booleans/strings, or a TypedArray")}if(t!=null){assertNonNegativeIntegerDimensions(t);const e=sizeFromShape(t);const r=sizeFromShape(n);assert(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have `+`${e} values but has ${r}`));for(let e=0;e<n.length;++e){const r=n[e];const a=e===n.length-1?r!==sizeFromShape(t.slice(e)):true;assert(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape `+`(${n}) does not match the provided `+`shape (${t}). `))}}if(!isTypedArray(e)&&!Array.isArray(e)){e=[e]}t=t||n;e=r!=="string"?toTypedArray(e,r):flatten(e,[],true);return ENGINE.makeTensor(e,t,r)}function tensor(e,t,n){const r=inferShape(e,n);return makeTensor(e,t,r,n)}const DTYPE_VALUE_SIZE_MAP={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const NUM_BYTES_STRING_LENGTH=4;function decodeWeights(e,t){const n={};let r;let a=0;for(const s of t){const t=s.name;const o=s.dtype;const i=s.shape;const u=sizeFromShape(i);let l;if("quantization"in s){const n=s.quantization;if(n.dtype==="uint8"||n.dtype==="uint16"){if(!("min"in n&&"scale"in n)){throw new Error(`Weight ${s.name} with quantization ${n.dtype} `+`doesn't have corresponding metadata min and scale.`)}}else if(n.dtype==="float16"){if(o!=="float32"){throw new Error(`Weight ${s.name} is quantized with ${n.dtype} `+`which only supports weights of type float32 not ${o}.`)}}else{throw new Error(`Weight ${s.name} has unknown `+`quantization dtype ${n.dtype}. `+`Supported quantization dtypes are: `+`'uint8', 'uint16', and 'float16'.`)}const i=DTYPE_VALUE_SIZE_MAP[n.dtype];const c=e.slice(a,a+u*i);const p=n.dtype==="uint8"?new Uint8Array(c):new Uint16Array(c);if(o==="float32"){if(n.dtype==="uint8"||n.dtype==="uint16"){l=new Float32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=t*n.scale+n.min}}else if(n.dtype==="float16"){if(r===undefined){r=getFloat16Decoder()}l=r(p)}else{throw new Error(`Unsupported quantization type ${n.dtype} `+`for weight type float32.`)}}else if(o==="int32"){if(n.dtype!=="uint8"&&n.dtype!=="uint16"){throw new Error(`Unsupported quantization type ${n.dtype} `+`for weight type int32.`)}l=new Int32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=Math.round(t*n.scale+n.min)}}else{throw new Error(`Unsupported dtype in weight '${t}': ${o}`)}a+=u*i}else if(o==="string"){const t=sizeFromShape(s.shape);l=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+NUM_BYTES_STRING_LENGTH))[0];a+=NUM_BYTES_STRING_LENGTH;const n=new Uint8Array(e.slice(a,a+t));l.push(n);a+=t}}else{const r=DTYPE_VALUE_SIZE_MAP[o];const s=e.slice(a,a+u*r);if(o==="float32"){l=new Float32Array(s)}else if(o==="int32"){l=new Int32Array(s)}else if(o==="bool"){l=new Uint8Array(s)}else if(o==="complex64"){l=new Float32Array(s);const e=new Float32Array(l.length/2);const r=new Float32Array(l.length/2);for(let t=0;t<e.length;t++){e[t]=l[t*2];r[t]=l[t*2+1]}const a=tensor(e,i,"float32");const o=tensor(r,i,"float32");n[t]=complex$1(a,o);a.dispose();o.dispose()}else{throw new Error(`Unsupported dtype in weight '${t}': ${o}`)}a+=u*r}if(o!=="complex64"){n[t]=tensor(l,i,o)}}return n}function getModelJSONForModelArtifacts(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};if(e.signature!=null){n.signature=e.signature}if(e.userDefinedMetadata!=null){n.userDefinedMetadata=e.userDefinedMetadata}if(e.modelInitializer!=null){n.modelInitializer=e.modelInitializer}if(e.trainingConfig!=null){n.trainingConfig=e.trainingConfig}return n}async function getModelArtifactsForJSON(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null){n.trainingConfig=e.trainingConfig}if(e.weightsManifest!=null){const[r,a]=await t(e.weightsManifest);n.weightSpecs=r;n.weightData=a}if(e.signature!=null){n.signature=e.signature}if(e.userDefinedMetadata!=null){n.userDefinedMetadata=e.userDefinedMetadata}if(e.modelInitializer!=null){n.modelInitializer=e.modelInitializer}return n}function getModelArtifactsInfoForJSON(e){if(e.modelTopology instanceof ArrayBuffer){throw new Error("Expected JSON model topology, received ArrayBuffer.")}return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:stringByteLength(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:stringByteLength(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}class IORouterRegistry{constructor(){this.saveRouters=[];this.loadRouters=[]}static getInstance(){if(IORouterRegistry.instance==null){IORouterRegistry.instance=new IORouterRegistry}return IORouterRegistry.instance}static registerSaveRouter(e){IORouterRegistry.getInstance().saveRouters.push(e)}static registerLoadRouter(e){IORouterRegistry.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return IORouterRegistry.getHandlers(e,"save")}static getLoadHandlers(e,t){return IORouterRegistry.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];const a=t==="load"?IORouterRegistry.getInstance().loadRouters:IORouterRegistry.getInstance().saveRouters;a.forEach((t=>{const a=t(e,n);if(a!==null){r.push(a)}}));return r}}const registerSaveRouter=e=>IORouterRegistry.registerSaveRouter(e);const registerLoadRouter=e=>IORouterRegistry.registerLoadRouter(e);const getSaveHandlers=e=>IORouterRegistry.getSaveHandlers(e);const getLoadHandlers=(e,t)=>IORouterRegistry.getLoadHandlers(e,t);const DATABASE_NAME$1="tensorflowjs";const DATABASE_VERSION=1;const MODEL_STORE_NAME="models_store";const INFO_STORE_NAME="model_info_store";class BrowserIndexedDB{constructor(e){this.indexedDB=getIndexedDBFactory();if(e==null||!e){throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.")}this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer){throw new Error("BrowserLocalStorage.save() does not support saving model topology "+"in binary formats yet.")}return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const r=this.indexedDB.open(DATABASE_NAME$1,DATABASE_VERSION);r.onupgradeneeded=()=>setUpDatabase(r);r.onsuccess=()=>{const a=r.result;if(t==null){const t=a.transaction(MODEL_STORE_NAME,"readonly");const r=t.objectStore(MODEL_STORE_NAME);const s=r.get(this.modelPath);s.onsuccess=()=>{if(s.result==null){a.close();return n(new Error(`Cannot find model with path '${this.modelPath}' `+`in IndexedDB.`))}else{e(s.result.modelArtifacts)}};s.onerror=e=>{a.close();return n(s.error)};t.oncomplete=()=>a.close()}else{const r=getModelArtifactsInfoForJSON(t);const s=a.transaction(INFO_STORE_NAME,"readwrite");let o=s.objectStore(INFO_STORE_NAME);const i=o.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;i.onsuccess=()=>{u=a.transaction(MODEL_STORE_NAME,"readwrite");const i=u.objectStore(MODEL_STORE_NAME);const l=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});l.onsuccess=()=>e({modelArtifactsInfo:r});l.onerror=e=>{o=s.objectStore(INFO_STORE_NAME);const t=o.delete(this.modelPath);t.onsuccess=()=>{a.close();return n(l.error)};t.onerror=e=>{a.close();return n(l.error)}}};i.onerror=e=>{a.close();return n(i.error)};s.oncomplete=()=>{if(u==null){a.close()}else{u.oncomplete=()=>a.close()}}}};r.onerror=e=>n(r.error)}))}}BrowserIndexedDB.URL_SCHEME="indexeddb://";const indexedDBRouter=e=>{if(!env().getBool("IS_BROWSER")){return null}else{if(!Array.isArray(e)&&e.startsWith(BrowserIndexedDB.URL_SCHEME)){return browserIndexedDB(e.slice(BrowserIndexedDB.URL_SCHEME.length))}else{return null}}};IORouterRegistry.registerSaveRouter(indexedDBRouter);IORouterRegistry.registerLoadRouter(indexedDBRouter);class BrowserIndexedDBManager{constructor(){this.indexedDB=getIndexedDBFactory()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(DATABASE_NAME$1,DATABASE_VERSION);n.onupgradeneeded=()=>setUpDatabase(n);n.onsuccess=()=>{const r=n.result;const a=r.transaction(INFO_STORE_NAME,"readonly");const s=a.objectStore(INFO_STORE_NAME);const o=s.getAll();o.onsuccess=()=>{const t={};for(const e of o.result){t[e.modelPath]=e.modelArtifactsInfo}e(t)};o.onerror=e=>{r.close();return t(o.error)};a.oncomplete=()=>r.close()};n.onerror=e=>t(n.error)}))}async removeModel(e){e=maybeStripScheme$1(e);return new Promise(((t,n)=>{const r=this.indexedDB.open(DATABASE_NAME$1,DATABASE_VERSION);r.onupgradeneeded=()=>setUpDatabase(r);r.onsuccess=()=>{const a=r.result;const s=a.transaction(INFO_STORE_NAME,"readwrite");const o=s.objectStore(INFO_STORE_NAME);const i=o.get(e);let u;i.onsuccess=()=>{if(i.result==null){a.close();return n(new Error(`Cannot find model with path '${e}' `+`in IndexedDB.`))}else{const r=o.delete(e);const s=()=>{u=a.transaction(MODEL_STORE_NAME,"readwrite");const r=u.objectStore(MODEL_STORE_NAME);const s=r.delete(e);s.onsuccess=()=>t(i.result.modelArtifactsInfo);s.onerror=e=>n(i.error)};r.onsuccess=s;r.onerror=e=>{s();a.close();return n(i.error)}}};i.onerror=e=>{a.close();return n(i.error)};s.oncomplete=()=>{if(u==null){a.close()}else{u.oncomplete=()=>a.close()}}};r.onerror=e=>n(r.error)}))}}const PATH_SEPARATOR="/";const PATH_PREFIX="tensorflowjs_models";const INFO_SUFFIX="info";const MODEL_TOPOLOGY_SUFFIX="model_topology";const WEIGHT_SPECS_SUFFIX="weight_specs";const WEIGHT_DATA_SUFFIX="weight_data";const MODEL_METADATA_SUFFIX="model_metadata";function getModelKeys(e){return{info:[PATH_PREFIX,e,INFO_SUFFIX].join(PATH_SEPARATOR),topology:[PATH_PREFIX,e,MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),weightSpecs:[PATH_PREFIX,e,WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),weightData:[PATH_PREFIX,e,WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),modelMetadata:[PATH_PREFIX,e,MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)}}function removeItems(e){for(const t of Object.values(e)){window.localStorage.removeItem(t)}}function getModelPathFromKey(e){const t=e.split(PATH_SEPARATOR);if(t.length<3){throw new Error(`Invalid key format: ${e}`)}return t.slice(1,t.length-1).join(PATH_SEPARATOR)}class BrowserLocalStorage{constructor(e){if(!env().getBool("IS_BROWSER")||typeof window==="undefined"||typeof window.localStorage==="undefined"){throw new Error("The current environment does not support local storage.")}this.LS=window.localStorage;if(e==null||!e){throw new Error("For local storage, modelPath must not be null, undefined or empty.")}this.modelPath=e;this.keys=getModelKeys(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer){throw new Error("BrowserLocalStorage.save() does not support saving model topology "+"in binary formats yet.")}else{const t=JSON.stringify(e.modelTopology);const n=JSON.stringify(e.weightSpecs);const r=getModelArtifactsInfoForJSON(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r));this.LS.setItem(this.keys.topology,t);this.LS.setItem(this.keys.weightSpecs,n);this.LS.setItem(this.keys.weightData,arrayBufferToBase64String(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:undefined,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:undefined,modelInitializer:e.modelInitializer!=null?e.modelInitializer:undefined,trainingConfig:e.trainingConfig!=null?e.trainingConfig:undefined};this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a));return{modelArtifactsInfo:r}}catch(e){removeItems(this.keys);throw new Error(`Failed to save model '${this.modelPath}' to local storage: `+`size quota being exceeded is a possible cause of this failure: `+`modelTopologyBytes=${r.modelTopologyBytes}, `+`weightSpecsBytes=${r.weightSpecsBytes}, `+`weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null){throw new Error(`In local storage, there is no model with name '${this.modelPath}'`)}if(e.modelTopologyType!=="JSON"){throw new Error("BrowserLocalStorage does not support loading non-JSON model "+"topology yet.")}const t={};const n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null){throw new Error(`In local storage, the topology of model '${this.modelPath}' `+`is missing.`)}t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(r==null){throw new Error(`In local storage, the weight specs of model '${this.modelPath}' `+`are missing.`)}t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(a!=null){const e=JSON.parse(a);t.format=e.format;t.generatedBy=e.generatedBy;t.convertedBy=e.convertedBy;if(e.signature!=null){t.signature=e.signature}if(e.userDefinedMetadata!=null){t.userDefinedMetadata=e.userDefinedMetadata}if(e.modelInitializer!=null){t.modelInitializer=e.modelInitializer}if(e.trainingConfig!=null){t.trainingConfig=e.trainingConfig}}const s=this.LS.getItem(this.keys.weightData);if(s==null){throw new Error(`In local storage, the binary weight values of model `+`'${this.modelPath}' are missing.`)}t.weightData=base64StringToArrayBuffer(s);return t}}BrowserLocalStorage.URL_SCHEME="localstorage://";const localStorageRouter=e=>{if(!env().getBool("IS_BROWSER")){return null}else{if(!Array.isArray(e)&&e.startsWith(BrowserLocalStorage.URL_SCHEME)){return browserLocalStorage(e.slice(BrowserLocalStorage.URL_SCHEME.length))}else{return null}}};IORouterRegistry.registerSaveRouter(localStorageRouter);IORouterRegistry.registerLoadRouter(localStorageRouter);class BrowserLocalStorageManager{constructor(){assert(env().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser"));assert(typeof window==="undefined"||typeof window.localStorage!=="undefined",(()=>"Current browser does not appear to support localStorage"));this.LS=window.localStorage}async listModels(){const e={};const t=PATH_PREFIX+PATH_SEPARATOR;const n=PATH_SEPARATOR+INFO_SUFFIX;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);if(a.startsWith(t)&&a.endsWith(n)){const t=getModelPathFromKey(a);e[t]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){e=maybeStripScheme(e);const t=getModelKeys(e);if(this.LS.getItem(t.info)==null){throw new Error(`Cannot find model at path '${e}'`)}const n=JSON.parse(this.LS.getItem(t.info));removeItems(t);return n}}const URL_SCHEME_SUFFIX="://";class ModelStoreManagerRegistry{constructor(){this.managers={}}static getInstance(){if(ModelStoreManagerRegistry.instance==null){ModelStoreManagerRegistry.instance=new ModelStoreManagerRegistry}return ModelStoreManagerRegistry.instance}static registerManager(e,t){assert(e!=null,(()=>"scheme must not be undefined or null."));if(e.endsWith(URL_SCHEME_SUFFIX)){e=e.slice(0,e.indexOf(URL_SCHEME_SUFFIX))}assert(e.length>0,(()=>"scheme must not be an empty string."));const n=ModelStoreManagerRegistry.getInstance();assert(n.managers[e]==null,(()=>`A model store manager is already registered for scheme '${e}'.`));n.managers[e]=t}static getManager(e){const t=ModelStoreManagerRegistry.getInstance().managers[e];if(t==null){throw new Error(`Cannot find model manager for scheme '${e}'`)}return t}static getSchemes(){return Object.keys(ModelStoreManagerRegistry.getInstance().managers)}}class PlatformBrowser{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8"){throw new Error(`Browser's encoder only supports utf-8, but got ${t}`)}if(this.textEncoder==null){this.textEncoder=new TextEncoder}return this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(env().get("IS_BROWSER")){env().setPlatform("browser",new PlatformBrowser);try{ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME,new BrowserLocalStorageManager)}catch(e){}try{ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME,new BrowserIndexedDBManager)}catch(e){}}function buffer(e,t="float32",n){t=t||"float32";assertNonNegativeIntegerDimensions(e);return new TensorBuffer(e,t,n)}function cast_(e,t){const n=convertToTensor(e,"x","cast");if(!isValidDtype(t)){throw new Error(`Failed to cast to unknown dtype ${t}`)}if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string"){throw new Error("Only strings can be casted to strings")}const r={x:n};const a={dtype:t};return ENGINE.runKernel(Cast,r,a)}const cast$1=op({cast_:cast_});function clone_(e){const t=convertToTensor(e,"x","clone","string_or_numeric");const n={x:t};return ENGINE.runKernel(Identity,n)}const clone=op({clone_:clone_});function print(e,t=false){console.log(e.toString(t))}getOrMakeEngine();const opHandler={buffer:buffer,cast:cast$1,clone:clone,print:print};setOpHandler(opHandler);const DEFAULT_FILE_NAME_PREFIX="model";const DEFAULT_JSON_EXTENSION_NAME=".json";const DEFAULT_WEIGHT_DATA_EXTENSION_NAME=".weights.bin";class BrowserDownloads{constructor(e){if(!env().getBool("IS_BROWSER")){throw new Error("browserDownloads() cannot proceed because the current environment "+"is not a browser.")}if(e.startsWith(BrowserDownloads.URL_SCHEME)){e=e.slice(BrowserDownloads.URL_SCHEME.length)}if(e==null||e.length===0){e=DEFAULT_FILE_NAME_PREFIX}this.modelJsonFileName=e+DEFAULT_JSON_EXTENSION_NAME;this.weightDataFileName=e+DEFAULT_WEIGHT_DATA_EXTENSION_NAME}async save(e){if(typeof document==="undefined"){throw new Error("Browser downloads are not supported in "+"this environment since `document` is not present")}const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer){throw new Error("BrowserDownloads.save() does not support saving model topology "+"in binary formats yet.")}else{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}];const r=getModelJSONForModelArtifacts(e,n);const a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"}));const s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;s.download=this.modelJsonFileName;s.href=a;await defer((()=>s.dispatchEvent(new MouseEvent("click"))));if(e.weightData!=null){const e=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName;e.href=t;await defer((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:getModelArtifactsInfoForJSON(e)}}}}BrowserDownloads.URL_SCHEME="downloads://";const browserDownloadsRouter=e=>{if(!env().getBool("IS_BROWSER")){return null}else{if(!Array.isArray(e)&&e.startsWith(BrowserDownloads.URL_SCHEME)){return browserDownloads(e.slice(BrowserDownloads.URL_SCHEME.length))}else{return null}}};IORouterRegistry.registerSaveRouter(browserDownloadsRouter);function weightsLoaderFactory(e){return async(t,n="",r)=>{const a=t.map((()=>false));const s={};const o=r!=null?r.map((()=>false)):[];const i=[];t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype;const l=DTYPE_VALUE_SIZE_MAP[u]*sizeFromShape(e.shape);const c=()=>{a[t]=true;if(s[t]==null){s[t]=[]}s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};if(r!=null){r.forEach(((t,n)=>{if(t===e.name){c();o[n]=true}}))}else{c()}i.push(e.name);n+=l}))}));if(!o.every((e=>e))){const e=r.filter(((e,t)=>!o[t]));throw new Error(`Could not find weights in manifest with names: `+`${e.join(", ")}. \n`+`Manifest JSON has weights with names: `+`${i.join(", ")}.`)}const u=a.reduce(((e,t,n)=>{if(t){e.push(n)}return e}),[]);const l=[];u.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(!n.endsWith("/")?"/":"")+e;l.push(t)}))}));const c=await e(l);const p={};let m=0;u.forEach((e=>{const n=t[e].paths.length;let r=0;for(let e=0;e<n;e++){r+=c[m+e].byteLength}const a=new ArrayBuffer(r);const o=new Uint8Array(a);let i=0;for(let e=0;e<n;e++){const t=new Uint8Array(c[m+e]);o.set(t,i);i+=t.byteLength}const u=s[e];u.forEach((e=>{const t=a.slice(e.groupOffset,e.groupOffset+e.sizeBytes);const n=decodeWeights(t,[e.manifestEntry]);for(const e in n){p[e]=n[e]}}));m+=n}));return p}}const httpRouter=(e,t)=>{if(typeof fetch==="undefined"&&(t==null||t.fetchFunc==null)){return null}else{let n=true;if(Array.isArray(e)){n=e.every((e=>isHTTPScheme(e)))}else{n=isHTTPScheme(e)}if(n){return http(e,t)}}return null};IORouterRegistry.registerSaveRouter(httpRouter);IORouterRegistry.registerLoadRouter(httpRouter);function browserHTTPRequest(e,t){return http(e,t)}var io=Object.freeze({__proto__:null,browserFiles:()=>{},browserHTTPRequest:browserHTTPRequest,concatenateArrayBuffers:()=>{},decodeWeights:decodeWeights,encodeWeights:()=>{},fromMemory:()=>{},fromMemorySync:()=>{},getLoadHandlers:getLoadHandlers,getModelArtifactsForJSON:getModelArtifactsForJSON,getModelArtifactsInfoForJSON:getModelArtifactsInfoForJSON,getSaveHandlers:getSaveHandlers,http:()=>{},isHTTPScheme:()=>{},loadWeights:()=>{},registerLoadRouter:registerLoadRouter,registerSaveRouter:registerSaveRouter,weightsLoaderFactory:weightsLoaderFactory,withSaveHandler:()=>{},withSaveHandlerSync:()=>{},copyModel:()=>{},listModels:()=>{},moveModel:()=>{},removeModel:()=>{}});function matMul_(e,t,n=false,r=false){let a=convertToTensor(e,"a","matMul");let s=convertToTensor(t,"b","matMul");[a,s]=makeTypesMatch(a,s);const o={a:a,b:s};const i={transposeA:n,transposeB:r};return ENGINE.runKernel(BatchMatMul,o,i)}const matMul$1=op({matMul_:matMul_});function oneHot_(e,t,n=1,r=0){if(t<2){throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`)}const a=convertToTensor(e,"indices","oneHot","int32");const s={indices:a};const o={depth:t,onValue:n,offValue:r};return ENGINE.runKernel(OneHot,s,o)}const oneHot=op({oneHot_:oneHot_});function enableProdMode(){env().set("PROD",true)}function engine(){return ENGINE}function tidy(e,t){return ENGINE.tidy(e,t)}function dispose(e){const t=getTensorsInContainer(e);t.forEach((e=>e.dispose()))}function keep(e){return ENGINE.keep(e)}function registerBackend(e,t,n=1){return ENGINE.registerBackend(e,t,n)}function neg_(e){const t=convertToTensor(e,"x","neg");const n={x:t};return ENGINE.runKernel(Neg,n)}const neg=op({neg_:neg_});function real_(e){const t=convertToTensor(e,"input","real");const n={input:t};return ENGINE.runKernel(Real,n)}const real$1=op({real_:real_});op({confusionMatrix_:()=>{}});function getBroadcastDims$1(e,t){const n=e.length;const r=[];for(let a=0;a<n;a++){const s=n-1-a;const o=e[s]||1;const i=t[t.length-1-a]||1;if(i>1&&o===1){r.unshift(s)}}return r}function getReductionAxes(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1];const s=t.length-r-1;const o=t[s];if(a==null||a===1&&o>1){n.unshift(s)}}return n}function assertAndGetBroadcastShape(e,t){const n=[];const r=Math.max(e.length,t.length);for(let a=0;a<r;a++){let r=e[e.length-a-1];if(r==null){r=1}let s=t[t.length-a-1];if(s==null){s=1}if(r===1){n.unshift(s)}else if(s===1){n.unshift(r)}else if(r!==s){const n=`Operands could not be broadcast together with shapes `+`${e} and ${t}.`;throw Error(n)}else{n.unshift(r)}}return n}op({fromPixels_:()=>{}});function validateInput$1(e,t,n){if(t.rank<1){throw new Error("tf.scatterND() expects the indices to be rank 1 or higher,"+` but the rank was ${t.rank}.`)}if(e.rank<1){throw new Error("tf.scatterND() expects the updates to be rank 1 or higher,"+` but the rank was ${e.rank}.`)}if(t.dtype!=="int32"){throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`)}if(n.length<1){throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`)}if(n.length===0){if(t.size===0){throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`)}if(e.size===0){throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}}validateUpdateShape(n,t,e)}function assertParamsValid(e,t,n){const r=e.shape.length;assert(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must `+`match the rank of the array (${r}).`));assert(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must `+`match the rank of the array (${r}).`));for(let a=0;a<r;++a){assert(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${r}D: begin[${a}] + size[${a}] `+`(${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}}function isSliceContinous(e,t,n){let r=n.length;for(let e=0;e<n.length;e++){if(n[e]>1){r=e;break}}for(let a=r+1;a<n.length;a++){if(t[a]>0||n[a]!==e[a]){return false}}return true}function computeFlatOffset(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++){n+=e[r]*t[r]}return n}function parseSliceParams(e,t,n){let r;const a=e.shape.length;if(typeof t==="number"){r=[t,...new Array(a-1).fill(0)]}else if(t.length<a){r=t.concat(new Array(a-t.length).fill(0))}else{r=t.slice()}r.forEach((e=>{assert(e!==-1,(()=>"slice() does not support negative begin indexing."))}));let s;if(n==null){s=new Array(a).fill(-1)}else if(typeof n==="number"){s=[n,...new Array(a-1).fill(-1)]}else if(n.length<a){s=n.concat(new Array(a-n.length).fill(-1))}else{s=n}s=s.map(((t,n)=>{if(t>=0){return t}else{assert(t===-1,(()=>`Negative size values should be exactly -1 but got `+`${t} for the slice() size at index ${n}.`));return e.shape[n]-r[n]}}));return[r,s]}var slice_util=Object.freeze({__proto__:null,assertParamsValid:assertParamsValid,maskToAxes:()=>{},computeOutShape$2:()=>{},stridesWithElidedDims:()=>{},getNormalizedAxes:()=>{},startIndicesWithElidedDims:()=>{},stopIndicesWithElidedDims:()=>{},stridesForAxis:()=>{},startForAxis:()=>{},stopForAxis:()=>{},isSliceContinous:isSliceContinous,computeFlatOffset:computeFlatOffset,parseSliceParams:parseSliceParams,sliceInfo:()=>{}});class Serializable{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class SerializationMap{constructor(){this.classNameMap={}}static getMap(){if(SerializationMap.instance==null){SerializationMap.instance=new SerializationMap}return SerializationMap.instance}static register(e){SerializationMap.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function registerClass(e){assert(e.className!=null,(()=>`Class being registered does not have the static className `+`property defined.`));assert(typeof e.className==="string",(()=>`className is required to be a string, but got type `+typeof e.className));assert(e.className.length>0,(()=>`Class being registered has an empty-string as its className, `+`which is disallowed.`));SerializationMap.register(e)}function add_(e,t){let n=convertToTensor(e,"a","add");let r=convertToTensor(t,"b","add");[n,r]=makeTypesMatch(n,r);const a={a:n,b:r};return ENGINE.runKernel(Add,a)}const add=op({add_:add_});function div_(e,t){let n=convertToTensor(e,"a","div");let r=convertToTensor(t,"b","div");[n,r]=makeTypesMatch(n,r);if(n.dtype==="int32"&&r.dtype==="int32"){return floorDiv(n,r)}const a={a:n,b:r};const s={};return ENGINE.runKernel(RealDiv,a,s)}const div=op({div_:div_});function mul_(e,t){let n=convertToTensor(e,"a","mul");let r=convertToTensor(t,"b","mul");[n,r]=makeTypesMatch(n,r);const a={a:n,b:r};return ENGINE.runKernel(Multiply,a)}const mul=op({mul_:mul_});function abs_(e){const t=convertToTensor(e,"x","abs");if(t.dtype==="complex64"){const e={x:t};return ENGINE.runKernel(ComplexAbs,e)}else{const e={x:t};return ENGINE.runKernel(Abs,e)}}const abs=op({abs_:abs_});function computePool2DInfo(e,t,n,r,a,s,o="channelsLast"){const[i,u]=parseTupleParam(t);let l;if(o==="channelsLast"){l=[i,u,e[3],e[3]]}else if(o==="channelsFirst"){l=[i,u,e[1],e[1]]}else{throw new Error(`Unknown dataFormat ${o}`)}return computeConv2DInfo(e,l,n,r,a,s,false,o)}function computeConv2DInfo(e,t,n,r,a,s,o=false,i="channelsLast"){let[u,l,c,p]=[-1,-1,-1,-1];if(i==="channelsLast"){[u,l,c,p]=e}else if(i==="channelsFirst"){[u,p,l,c]=e}else{throw new Error(`Unknown dataFormat ${i}`)}const[m,d,,h]=t;const[f,g]=parseTupleParam(n);const[y,x]=parseTupleParam(r);const T=getEffectiveFilterSize(m,y);const E=getEffectiveFilterSize(d,x);const{padInfo:b,outHeight:N,outWidth:S}=getPadAndOutInfo(a,l,c,f,g,T,E,s,i);const _=o?h*p:h;let I;if(i==="channelsFirst"){I=[u,_,N,S]}else if(i==="channelsLast"){I=[u,N,S,_]}return{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:p,outHeight:N,outWidth:S,outChannels:_,padInfo:b,strideHeight:f,strideWidth:g,filterHeight:m,filterWidth:d,effectiveFilterHeight:T,effectiveFilterWidth:E,dilationHeight:y,dilationWidth:x,inShape:e,outShape:I,filterShape:t}}function getEffectiveFilterSize(e,t){if(t<=1){return e}return e+(e-1)*(t-1)}function convertConv2DDataFormat(e){if(e==="NHWC"){return"channelsLast"}else if(e==="NCHW"){return"channelsFirst"}else{throw new Error(`Unknown dataFormat ${e}`)}}function reshape_(e,t){const n=convertToTensor(e,"x","reshape","string_or_numeric");const r={x:n};const a={shape:t};return ENGINE.runKernel(Reshape,r,a)}const reshape$1=op({reshape_:reshape_});function concat_(e,t=0){assert(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=convertToTensorArray(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"){n.forEach((e=>{if(e.dtype!=="complex64"){throw new Error(`Cannot concatenate complex64 tensors with a tensor\n          with dtype ${e.dtype}. `)}}))}if(n.length===1){return clone(n[0])}const r=n;const a={axis:t};return ENGINE.runKernel(Concat,r,a)}const concat$1=op({concat_:concat_});function sigmoid_(e){const t=convertToTensor(e,"x","sigmoid","float32");const n={x:t};return ENGINE.runKernel(Sigmoid,n)}const sigmoid$1=op({sigmoid_:sigmoid_});function slice_(e,t,n){const r=convertToTensor(e,"x","slice","string_or_numeric");if(r.rank===0){throw new Error("Slicing scalar is not possible")}const a={x:r};const s={begin:t,size:n};return ENGINE.runKernel(Slice,a,s)}const slice$1=op({slice_:slice_});op({batchNorm2d_:()=>{}});op({batchNorm3d_:()=>{}});op({batchNorm4d_:()=>{}});function bincount_(e,t,n){const r=convertToTensor(e,"x","bincount");const a=convertToTensor(t,"weights","bincount");assert(r.dtype==="int32",(()=>`Error in bincount: input `+`dtype must be int32, but got ${r.dtype}`));assert(n>=0,(()=>`size must be non-negative, but got ${n}.`));assert(a.size===r.size||a.size===0,(()=>`Error in bincount: weights must have the same size as input or`+`0-length, but got input shape: ${r.shape}, weights shape: `+`${a.shape}.`));const s={x:r,weights:a};const o={size:n};return ENGINE.runKernel(Bincount,s,o)}const bincount=op({bincount_:bincount_});function broadcastTo_(e,t){let n=convertToTensor(e,"broadcastTo","x");const r=n.shape;if(t.some((e=>!(e>0)||e%1!==0))){throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`)}if(t.length<n.rank){throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`)}if(t.length>n.rank){const e=n.shape.slice();while(e.length<t.length){e.unshift(1)}n=reshape$1(n,e)}const a=n.shape;const s=Array.from(t);for(let e=t.length-1;e>=0;e--){if(a[e]===t[e]){s[e]=1}else if(n.shape[e]!==1){throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`)}}const o=s.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0));if(o.length===0){return clone(n)}const i={x:n};const u={reps:s};return ENGINE.runKernel(Tile,i,u)}const broadcastTo=op({broadcastTo_:broadcastTo_});op({concat1d_:()=>{}});op({concat2d_:()=>{}});op({concat3d_:()=>{}});op({concat4d_:()=>{}});op({conv1d_:()=>{}});function conv2DBackpropInput_(e,t,n,r,a,s="NHWC",o){assert(e.length===t.rank,(()=>`Length of inShape `+`(${e.length}) and rank of dy (${t.rank}) must match`));let i=e;let u=t;let l=false;if(t.rank===3){l=true;u=reshape$1(t,[1,t.shape[0],t.shape[1],t.shape[2]]);i=[1,e[0],e[1],e[2]]}assert(i.length===4,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length `+`${i.length}.`));assert(u.rank===4,(()=>`Error in conv2dDerInput: dy must be rank 4, but got `+`rank ${u.rank}`));assert(n.rank===4,(()=>`Error in conv2dDerInput: filter must be rank 4, but got `+`rank ${n.rank}`));const c=s==="NHWC"?i[3]:i[1];const p=s==="NHWC"?u.shape[3]:u.shape[1];assert(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must `+`match input depth for filter ${n.shape[2]}.`));assert(p===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${p}) must `+`match output depth for filter ${n.shape[3]}.`));checkPadOnDimRoundingMode("conv2dDerInput",a,o);const m={dy:u,filter:n};const d={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:i};const h=ENGINE.runKernel(Conv2DBackpropInput,m,d);if(l){return reshape$1(h,[h.shape[1],h.shape[2],h.shape[3]])}return h}op({conv2DBackpropInput_:conv2DBackpropInput_});op({conv2dTranspose_:()=>{}});op({conv3dTranspose_:()=>{}});function equal_(e,t){let n=convertToTensor(e,"a","equal","string_or_numeric");let r=convertToTensor(t,"b","equal","string_or_numeric");[n,r]=makeTypesMatch(n,r);assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(Equal,a)}const equal=op({equal_:equal_});function where_(e,t,n){const r=convertToTensor(t,"a","where");const a=convertToTensor(n,"b","where");const s=convertToTensor(e,"condition","where","bool");const o=assertAndGetBroadcastShape(assertAndGetBroadcastShape(s.shape,r.shape),a.shape);const i=broadcastTo(s,o);const u=broadcastTo(r,o);const l=broadcastTo(a,o);const c={condition:i,t:u,e:l};return ENGINE.runKernel(Select,c)}const where=op({where_:where_});function zerosLike_(e){const t=convertToTensor(e,"x","zerosLike");const n={x:t};return ENGINE.runKernel(ZerosLike,n)}const zerosLike=op({zerosLike_:zerosLike_});function dot_(e,t){const n=convertToTensor(e,"t1","dot");const r=convertToTensor(t,"t2","dot");assert((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks `+`${n.rank} and ${r.rank}.`));const a=n.rank===1?n.size:n.shape[1];const s=r.rank===1?r.size:r.shape[0];assert(a===s,(()=>`Error in dot: inner dimensions of inputs must match, but got `+`${a} and ${s}.`));if(n.rank===1&&r.rank===1){const e=reshape$1(n,[1,-1]);const t=reshape$1(r,[-1,1]);const a=matMul$1(e,t);return reshape$1(a,[])}else if(n.rank===1&&r.rank===2){const e=reshape$1(n,[1,-1]);const t=reshape$1(r,[r.shape[0],r.shape[1]]);const a=matMul$1(e,t);return reshape$1(a,[a.size])}else if(n.rank===2&&r.rank===1){const e=reshape$1(r,[-1,1]);const t=matMul$1(n,e);return reshape$1(t,[t.size])}else{const e=reshape$1(r,[r.shape[0],r.shape[1]]);const t=matMul$1(n,e);return t}}const dot=op({dot_:dot_});function axesAreInnerMostDims(e,t){for(let n=0;n<e.length;++n){if(e[e.length-n-1]!==t-1-n){return false}}return true}function computeOutAndReduceShapes(e,t){const n=[];const r=e.length;for(let a=0;a<r;a++){if(t.indexOf(a)===-1){n.push(e[a])}}const a=t.map((t=>e[t]));return[n,a]}function expandShapeToKeepDim(e,t){const n=t.map((e=>1));return combineLocations(e,n,t)}function assertAxesAreInnerMostDims(e,t,n){assert(axesAreInnerMostDims(t,n),(()=>`${e} supports only inner-most axes for now. `+`Got axes ${t} and rank-${n} input.`))}function getAxesPermutation(e,t){if(axesAreInnerMostDims(e,t)){return null}const n=[];for(let r=0;r<t;++r){if(e.indexOf(r)===-1){n.push(r)}}e.forEach((e=>n.push(e)));return n}function getInnerMostAxes(e,t){const n=[];for(let r=t-e;r<t;++r){n.push(r)}return n}function max_(e,t=null,n=false){const r=convertToTensor(e,"x","max");const a={x:r};const s={reductionIndices:t,keepDims:n};return ENGINE.runKernel(Max,a,s)}const max=op({max_:max_});function scalar(e,t){if((isTypedArray(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64"){throw new Error("Error creating a new Scalar: value must be a primitive "+"(number|boolean|string)")}if(t==="string"&&isTypedArray(e)&&!(e instanceof Uint8Array)){throw new Error("When making a scalar from encoded string, "+"the value must be `Uint8Array`.")}const n=[];const r=[];return makeTensor(e,n,r,t)}function square_(e){const t=convertToTensor(e,"x","square");const n={};return ENGINE.runKernel("Square",{x:t},n)}const square=op({square_:square_});function sum_(e,t=null,n=false){let r=convertToTensor(e,"x","sum");if(r.dtype==="bool"){r=cast$1(r,"int32")}const a={x:r};const s={axis:t,keepDims:n};return ENGINE.runKernel(Sum,a,s)}const sum$1=op({sum_:sum_});function norm_(e,t="euclidean",n=null,r=false){e=convertToTensor(e,"x","norm");const a=normImpl(e,t,n);let s=a.shape;if(r){const t=parseAxisParam(n,e.shape);s=expandShapeToKeepDim(a.shape,t)}return reshape$1(a,s)}function normImpl(e,t,n=null){if(e.rank===0){return abs(e)}if(e.rank!==1&&n===null){return normImpl(reshape$1(e,[-1]),t,n)}if(e.rank===1||typeof n==="number"||Array.isArray(n)&&n.length===1){if(t===1){return sum$1(abs(e),n)}if(t===Infinity){return max(abs(e),n)}if(t===-Infinity){return min(abs(e),n)}if(t==="euclidean"||t===2){return sqrt(sum$1(pow$1(abs(e),scalar(2,"int32")),n))}throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1){return max(sum$1(abs(e),n[0]),n[1]-1)}if(t===Infinity){return max(sum$1(abs(e),n[1]),n[0])}if(t===-Infinity){return min(sum$1(abs(e),n[1]),n[0])}if(t==="fro"||t==="euclidean"){return sqrt(sum$1(square(e),n))}throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const norm=op({norm_:norm_});function exp_(e){const t=convertToTensor(e,"x","exp");const n={x:t};return ENGINE.runKernel(Exp,n)}const exp=op({exp_:exp_});function expandDims_(e,t=0){const n=convertToTensor(e,"x","expandDims","string_or_numeric");assert(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n};const a={dim:t};return ENGINE.runKernel(ExpandDims,r,a)}const expandDims$1=op({expandDims_:expandDims_});function gather_(e,t,n=0,r=0){const a=convertToTensor(e,"x","gather");const s=convertToTensor(t,"indices","gather","int32");const o={x:a,indices:s};const i={axis:n,batchDims:r};return ENGINE.runKernel(GatherV2,o,i)}const gather=op({gather_:gather_});function greater_(e,t){let n=convertToTensor(e,"a","greater","string_or_numeric");let r=convertToTensor(t,"b","greater","string_or_numeric");[n,r]=makeTypesMatch(n,r);assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(Greater,a)}const greater=op({greater_:greater_});function log_(e){const t=convertToTensor(e,"x","log","float32");const n={x:t};return ENGINE.runKernel(Log,n)}const log=op({log_:log_});function log1p_(e){const t=convertToTensor(e,"x","log1p");const n={x:t};return ENGINE.runKernel(Log1p,n)}const log1p=op({log1p_:log1p_});function customGrad(e){return ENGINE.customGrad(e)}function sub_(e,t){let n=convertToTensor(e,"a","sub");let r=convertToTensor(t,"b","sub");[n,r]=makeTypesMatch(n,r);const a={a:n,b:r};return ENGINE.runKernel(Sub,a)}const sub=op({sub_:sub_});function logSumExp_(e,t=null,n=false){const r=convertToTensor(e,"x","logSumExp");const a=parseAxisParam(t,r.shape);const s=max(r,a,true);const o=sub(r,s);const i=exp(o);const u=sum$1(i,a);const l=log(u);const c=add(reshape$1(s,l.shape),l);if(n){const e=expandShapeToKeepDim(c.shape,a);return reshape$1(c,e)}return c}const logSumExp=op({logSumExp_:logSumExp_});function logicalAnd_(e,t){const n=convertToTensor(e,"a","logicalAnd","bool");const r=convertToTensor(t,"b","logicalAnd","bool");assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(LogicalAnd,a)}const logicalAnd=op({logicalAnd_:logicalAnd_});op({searchSorted_:()=>{}});function maximum_(e,t){let n=convertToTensor(e,"a","maximum");let r=convertToTensor(t,"b","maximum");[n,r]=makeTypesMatch(n,r);if(n.dtype==="bool"){n=cast$1(n,"int32");r=cast$1(r,"int32")}assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(Maximum,a)}const maximum=op({maximum_:maximum_});function mean_(e,t=null,n=false){const r=convertToTensor(e,"x","mean");const a={x:r};const s={axis:t,keepDims:n};return ENGINE.runKernel(Mean,a,s)}const mean=op({mean_:mean_});function zeros$1(e,t="float32"){if(t==="complex64"){const t=zeros$1(e,"float32");const n=zeros$1(e,"float32");return complex$1(t,n)}const n=makeZerosTypedArray(sizeFromShape(e),t);return ENGINE.makeTensor(n,e,t)}function ones(e,t="float32"){if(t==="complex64"){const t=ones(e,"float32");const n=zeros$1(e,"float32");return complex$1(t,n)}const n=makeOnesTypedArray(sizeFromShape(e),t);return ENGINE.makeTensor(n,e,t)}function minimum_(e,t){let n=convertToTensor(e,"a","minimum");let r=convertToTensor(t,"b","minimum");[n,r]=makeTypesMatch(n,r);if(n.dtype==="bool"){n=cast$1(n,"int32");r=cast$1(r,"int32")}assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(Minimum,a)}const minimum=op({minimum_:minimum_});op({multiRNNCell_:()=>{}});function notEqual_(e,t){let n=convertToTensor(e,"a","notEqual","string_or_numeric");let r=convertToTensor(t,"b","notEqual","string_or_numeric");[n,r]=makeTypesMatch(n,r);assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};return ENGINE.runKernel(NotEqual,a)}const notEqual$1=op({notEqual_:notEqual_});op({outerProduct_:()=>{}});function pad_(e,t,n=0){const r=convertToTensor(e,"x","pad");if(r.rank===0){throw new Error("pad(scalar) is not defined. Pass non-scalar to pad")}const a={paddings:t,constantValue:n};const s={x:r};return ENGINE.runKernel(PadV2,s,a)}const pad=op({pad_:pad_});op({pad1d_:()=>{}});op({pad2d_:()=>{}});op({pad3d_:()=>{}});op({pad4d_:()=>{}});function prod_(e,t=null,n=false){let r=convertToTensor(e,"x","prod");if(r.dtype==="bool"){r=cast$1(r,"int32")}const a={x:r};const s={axis:t,keepDims:n};return ENGINE.runKernel(Prod,a,s)}const prod$1=op({prod_:prod_});var alea$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*2.3283064365386963e-10;t.s0=t.s1;t.s1=t.s2;return t.s2=e-(t.c=e|0)};t.c=1;t.s0=n(" ");t.s1=n(" ");t.s2=n(" ");t.s0-=n(e);if(t.s0<0){t.s0+=1}t.s1-=n(e);if(t.s1<0){t.s1+=1}t.s2-=n(e);if(t.s2<0){t.s2+=1}n=null}function a(e,t){t.c=e.c;t.s0=e.s0;t.s1=e.s1;t.s2=e.s2;return t}function s(e,t){var n=new r(e),s=t&&t.state,o=n.next;o.int32=function(){return n.next()*4294967296|0};o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32};o.quick=o;if(s){if(typeof s=="object")a(s,n);o.state=function(){return a(n,{})}}return o}function o(){var e=4022871197;var t=function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0;r-=e;r*=e;e=r>>>0;r-=e;e+=r*4294967296}return(e>>>0)*2.3283064365386963e-10};return t}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.alea=s}})(commonjsGlobal,e,typeof undefined=="function")})(alea$1);var xor128$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this,n="";t.x=0;t.y=0;t.z=0;t.w=0;t.next=function(){var e=t.x^t.x<<11;t.x=t.y;t.y=t.z;t.z=t.w;return t.w^=t.w>>>19^e^e>>>8};if(e===(e|0)){t.x=e}else{n+=e}for(var r=0;r<n.length+64;r++){t.x^=n.charCodeAt(r)|0;t.next()}}function a(e,t){t.x=e.x;t.y=e.y;t.z=e.z;t.w=e.w;return t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};o.double=function(){do{var e=n.next()>>>11,t=(n.next()>>>0)/4294967296,r=(e+t)/(1<<21)}while(r===0);return r};o.int32=n.next;o.quick=o;if(s){if(typeof s=="object")a(s,n);o.state=function(){return a(n,{})}}return o}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.xor128=s}})(commonjsGlobal,e,typeof undefined=="function")})(xor128$1);var xorwow$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;t.x=t.y;t.y=t.z;t.z=t.w;t.w=t.v;return(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0};t.x=0;t.y=0;t.z=0;t.w=0;t.v=0;if(e===(e|0)){t.x=e}else{n+=e}for(var r=0;r<n.length+64;r++){t.x^=n.charCodeAt(r)|0;if(r==n.length){t.d=t.x<<10^t.x>>>4}t.next()}}function a(e,t){t.x=e.x;t.y=e.y;t.z=e.z;t.w=e.w;t.v=e.v;t.d=e.d;return t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};o.double=function(){do{var e=n.next()>>>11,t=(n.next()>>>0)/4294967296,r=(e+t)/(1<<21)}while(r===0);return r};o.int32=n.next;o.quick=o;if(s){if(typeof s=="object")a(s,n);o.state=function(){return a(n,{})}}return o}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.xorwow=s}})(commonjsGlobal,e,typeof undefined=="function")})(xorwow$1);var xorshift7$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r,a;r=e[n];r^=r>>>7;a=r^r<<24;r=e[n+1&7];a^=r^r>>>10;r=e[n+3&7];a^=r^r>>>3;r=e[n+4&7];a^=r^r<<7;r=e[n+7&7];r=r^r<<13;a^=r^r<<9;e[n]=a;t.i=n+1&7;return a};function n(e,t){var n,r=[];if(t===(t|0)){r[0]=t}else{t=""+t;for(n=0;n<t.length;++n){r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13}}while(r.length<8)r.push(0);for(n=0;n<8&&r[n]===0;++n);if(n==8)r[7]=-1;else r[n];e.x=r;e.i=0;for(n=256;n>0;--n){e.next()}}n(t,e)}function a(e,t){t.x=e.x.slice();t.i=e.i;return t}function s(e,t){if(e==null)e=+new Date;var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};o.double=function(){do{var e=n.next()>>>11,t=(n.next()>>>0)/4294967296,r=(e+t)/(1<<21)}while(r===0);return r};o.int32=n.next;o.quick=o;if(s){if(s.x)a(s,n);o.state=function(){return a(n,{})}}return o}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.xorshift7=s}})(commonjsGlobal,e,typeof undefined=="function")})(xorshift7$1);var xor4096$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,a,s;t.w=e=e+1640531527|0;s=n[r+34&127];a=n[r=r+1&127];s^=s<<13;a^=a<<17;s^=s>>>15;a^=a>>>12;s=n[r]=s^a;t.i=r;return s+(e^e>>>16)|0};function n(e,t){var n,r,a,s,o,i=[],u=128;if(t===(t|0)){r=t;t=null}else{t=t+"\0";r=0;u=Math.max(u,t.length)}for(a=0,s=-32;s<u;++s){if(t)r^=t.charCodeAt((s+32)%t.length);if(s===0)o=r;r^=r<<10;r^=r>>>15;r^=r<<4;r^=r>>>13;if(s>=0){o=o+1640531527|0;n=i[s&127]^=r+o;a=0==n?a+1:0}}if(a>=128){i[(t&&t.length||0)&127]=-1}a=127;for(s=4*128;s>0;--s){r=i[a+34&127];n=i[a=a+1&127];r^=r<<13;n^=n<<17;r^=r>>>15;n^=n>>>12;i[a]=r^n}e.w=o;e.X=i;e.i=a}n(t,e)}function a(e,t){t.i=e.i;t.w=e.w;t.X=e.X.slice();return t}function s(e,t){if(e==null)e=+new Date;var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};o.double=function(){do{var e=n.next()>>>11,t=(n.next()>>>0)/4294967296,r=(e+t)/(1<<21)}while(r===0);return r};o.int32=n.next;o.quick=o;if(s){if(s.X)a(s,n);o.state=function(){return a(n,{})}}return o}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.xor4096=s}})(commonjsGlobal,e,typeof undefined=="function")})(xor4096$1);var tychei$1={exports:{}};(function(e){(function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;e=e<<25^e>>>7^n;n=n-r|0;r=r<<24^r>>>8^a;a=a-e|0;t.b=e=e<<20^e>>>12^n;t.c=n=n-r|0;t.d=r<<16^n>>>16^a;return t.a=a-e|0};t.a=0;t.b=0;t.c=2654435769|0;t.d=1367130551;if(e===Math.floor(e)){t.a=e/4294967296|0;t.b=e|0}else{n+=e}for(var r=0;r<n.length+20;r++){t.b^=n.charCodeAt(r)|0;t.next()}}function a(e,t){t.a=e.a;t.b=e.b;t.c=e.c;t.d=e.d;return t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};o.double=function(){do{var e=n.next()>>>11,t=(n.next()>>>0)/4294967296,r=(e+t)/(1<<21)}while(r===0);return r};o.int32=n.next;o.quick=o;if(s){if(typeof s=="object")a(s,n);o.state=function(){return a(n,{})}}return o}if(t&&t.exports){t.exports=s}else if(n&&n.amd){n((function(){return s}))}else{this.tychei=s}})(commonjsGlobal,e,typeof undefined=="function")})(tychei$1);var seedrandom$1={exports:{}};(function(e){(function(t,n,r){var a=256,s=6,o=52,i="random",u=r.pow(a,s),l=r.pow(2,o),c=l*2,p=a-1,m;function d(e,t,o){var p=[];t=t==true?{entropy:true}:t||{};var m=y(g(t.entropy?[e,T(n)]:e==null?x():e,3),p);var d=new h(p);var E=function(){var e=d.g(s),t=u,n=0;while(e<l){e=(e+n)*a;t*=a;n=d.g(1)}while(e>=c){e/=2;t/=2;n>>>=1}return(e+n)/t};E.int32=function(){return d.g(4)|0};E.quick=function(){return d.g(4)/4294967296};E.double=E;y(T(d.S),n);return(t.pass||o||function(e,t,n,a){if(a){if(a.S){f(a,d)}e.state=function(){return f(d,{})}}if(n){r[i]=e;return t}else return e})(E,m,"global"in t?t.global:this==r,t.state)}function h(e){var t,n=e.length,r=this,s=0,o=r.i=r.j=0,i=r.S=[];if(!n){e=[n++]}while(s<a){i[s]=s++}for(s=0;s<a;s++){i[s]=i[o=p&o+e[s%n]+(t=i[s])];i[o]=t}(r.g=function(e){var t,n=0,s=r.i,o=r.j,i=r.S;while(e--){t=i[s=p&s+1];n=n*a+i[p&(i[s]=i[o=p&o+t])+(i[o]=t)]}r.i=s;r.j=o;return n})(a)}function f(e,t){t.i=e.i;t.j=e.j;t.S=e.S.slice();return t}function g(e,t){var n=[],r=typeof e,a;if(t&&r=="object"){for(a in e){try{n.push(g(e[a],t-1))}catch(e){}}}return n.length?n:r=="string"?e:e+"\0"}function y(e,t){var n=e+"",r,a=0;while(a<n.length){t[p&a]=p&(r^=t[p&a]*19)+n.charCodeAt(a++)}return T(t)}function x(){try{var e;if(m&&(e=m.randomBytes)){e=e(a)}else{e=new Uint8Array(a);(t.crypto||t.msCrypto).getRandomValues(e)}return T(e)}catch(e){var r=t.navigator,s=r&&r.plugins;return[+new Date,t,s,t.screen,T(n)]}}function T(e){return String.fromCharCode.apply(0,e)}y(r.random(),n);if(e.exports){e.exports=d;try{m=require("crypto")}catch(e){}}else{r["seed"+i]=d}})(typeof self!=="undefined"?self:commonjsGlobal,[],Math)})(seedrandom$1);var alea=alea$1.exports;var xor128=xor128$1.exports;var xorwow=xorwow$1.exports;var xorshift7=xorshift7$1.exports;var xor4096=xor4096$1.exports;var tychei=tychei$1.exports;var sr=seedrandom$1.exports;sr.alea=alea;sr.xor128=xor128;sr.xorwow=xorwow;sr.xorshift7=xorshift7;sr.xor4096=xor4096;sr.tychei=tychei;function range(e,t,n=1,r="float32"){if(n===0){throw new Error("Cannot have a step of zero")}const a={start:e,stop:t,step:n,dtype:r};return ENGINE.runKernel(Range,{},a)}function relu_(e){const t=convertToTensor(e,"x","relu");const n={x:t};return ENGINE.runKernel(Relu,n)}const relu$1=op({relu_:relu_});function reverse_(e,t){const n=convertToTensor(e,"x","reverse");const r={x:n};const a={dims:t};return ENGINE.runKernel(Reverse,r,a)}const reverse=op({reverse_:reverse_});op({separableConv2d_:()=>{}});function fft_(e){assert(e.dtype==="complex64",(()=>`The dtype for tf.spectral.fft() must be complex64 `+`but got ${e.dtype}.`));const t={input:e};return ENGINE.runKernel(FFT,t)}const fft=op({fft_:fft_});function squaredDifference_(e,t){let n=convertToTensor(e,"a","squaredDifference");let r=convertToTensor(t,"b","squaredDifference");[n,r]=makeTypesMatch(n,r);assertAndGetBroadcastShape(n.shape,r.shape);const a={a:n,b:r};const s={};return ENGINE.runKernel(SquaredDifference,a,s)}const squaredDifference=op({squaredDifference_:squaredDifference_});function squeeze_(e,t){const n=convertToTensor(e,"x","squeeze","string_or_numeric");return reshape$1(n,squeezeShape(n.shape,t).newShape)}const squeeze=op({squeeze_:squeeze_});function stack_(e,t=0){const n=convertToTensorArray(e,"tensors","stack","string_or_numeric");assert(n.length>=1,(()=>"Pass at least one tensor to tf.stack"));if(n.length>0){assert(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"))}const r=n;const a={axis:t};return ENGINE.runKernel(Pack,r,a)}const stack=op({stack_:stack_});function tensor1d(e,t){assertNonNull(e);const n=inferShape(e,t);if(n.length!==1){throw new Error("tensor1d() requires values to be a flat/TypedArray")}const r=null;return makeTensor(e,r,n,t)}function tensor2d(e,t,n){assertNonNull(e);if(t!=null&&t.length!==2){throw new Error("tensor2d() requires shape to have two numbers")}const r=inferShape(e,n);if(r.length!==2&&r.length!==1){throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray")}if(r.length===1&&t==null){throw new Error("tensor2d() requires shape to be provided when `values` "+"are a flat/TypedArray")}return makeTensor(e,t,r,n)}function unstack_(e,t=0){const n=convertToTensor(e,"x","unstack","string_or_numeric");assert(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n};const a={axis:t};return ENGINE.runKernel(Unpack,r,a)}const unstack=op({unstack_:unstack_});function conv2DBackpropFilter_(e,t,n,r,a,s="NHWC",o){let i=e;if(e.rank===3){i=reshape$1(e,[1,e.shape[0],e.shape[1],e.shape[2]])}let u=t;if(u.rank===3){u=reshape$1(t,[1,t.shape[0],t.shape[1],t.shape[2]])}assert(i.rank===4,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape `+`${i.shape}.`));assert(u.rank===4,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape `+`${u.shape}.`));assert(n.length===4,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got `+`${n}.`));const l=s==="NHWC"?i.shape[3]:i.shape[1];const c=s==="NHWC"?u.shape[3]:u.shape[1];assert(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must `+`match input depth in filter (${n[2]}.`));assert(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must `+`match output depth for filter (${n[3]}).`));checkPadOnDimRoundingMode("conv2dDerFilter",a,o);const p={x:i,dy:u};const m={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return ENGINE.runKernel(Conv2DBackpropFilter,p,m)}op({conv2DBackpropFilter_:conv2DBackpropFilter_});function getFusedDyActivation(e,t,n){if(n==null||n==="linear"){return e}if(n==="relu"){return mul(e,step(t))}throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function getFusedBiasGradient(e,t){let n=t;const r=getReductionAxes(e.shape,t.shape);if(r.length>0){n=sum$1(n,r)}return reshape$1(n,e.shape)}const shouldFuse=(e,t)=>{const n=e>0;return!n||t==="linear"};function depthwiseConv2dNativeBackpropFilter_(e,t,n,r,a,s=[1,1],o){let i=e;if(e.rank===3){i=reshape$1(e,[1,e.shape[0],e.shape[1],e.shape[2]])}let u=t;if(u.rank===3){u=reshape$1(t,[1,t.shape[0],t.shape[1],t.shape[2]])}const l={x:i,dy:u};const c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter,l,c)}op({depthwiseConv2dNativeBackpropFilter_:depthwiseConv2dNativeBackpropFilter_});function depthwiseConv2dNativeBackpropInput_(e,t,n,r,a,s=[1,1],o){let i=t;let u=false;if(t.rank===3){u=true;i=reshape$1(t,[1,t.shape[0],t.shape[1],t.shape[2]])}const l={dy:i,filter:n};const c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e};const p=ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput,l,c);if(u){return reshape$1(p,[p.shape[1],p.shape[2],p.shape[3]])}return p}op({depthwiseConv2dNativeBackpropInput_:depthwiseConv2dNativeBackpropInput_});function fusedMatMul_({a:e,b:t,transposeA:n=false,transposeB:r=false,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(shouldFuse(ENGINE.state.gradientDepth,s)===false){let u=matMul$1(e,t,n,r);if(a!=null){u=add(u,a)}return applyActivation(u,s,o,i)}let u=convertToTensor(e,"a","fused matMul");let l=convertToTensor(t,"b","fused matMul");[u,l]=makeTypesMatch(u,l);const c=n?u.shape[u.rank-2]:u.shape[u.rank-1];const p=r?l.shape[l.rank-1]:l.shape[l.rank-2];const m=n?u.shape[u.rank-1]:u.shape[u.rank-2];const d=r?l.shape[l.rank-2]:l.shape[l.rank-1];const h=u.shape.slice(0,-2);const f=l.shape.slice(0,-2);const g=sizeFromShape(h);const y=sizeFromShape(f);assert(c===p,(()=>`Error in fused matMul: inner shapes (${c}) and (`+`${p}) of Tensors with shapes ${u.shape} and `+`${l.shape} and transposeA=${n}`+` and transposeB=${r} must match.`));const x=assertAndGetBroadcastShape(u.shape.slice(0,-2),l.shape.slice(0,-2));const T=x.concat([m,d]);const E=n?reshape$1(u,[g,c,m]):reshape$1(u,[g,m,c]);const b=r?reshape$1(l,[y,d,p]):reshape$1(l,[y,p,d]);let N;if(a!=null){N=convertToTensor(a,"bias","fused matMul");[N]=makeTypesMatch(N,u);assertAndGetBroadcastShape(T,N.shape)}let S;if(o!=null){S=convertToTensor(o,"prelu weights","fused matMul")}const _=(e,t)=>{const[o,i,u,l]=t;const c=getFusedDyActivation(reshape$1(e,u.shape),u,s);let p;let m;if(!n&&!r){p=matMul$1(c,i,false,true);m=matMul$1(o,c,true,false)}else if(!n&&r){p=matMul$1(c,i,false,false);m=matMul$1(c,o,true,false)}else if(n&&!r){p=matMul$1(i,c,false,true);m=matMul$1(o,c,false,false)}else{p=matMul$1(i,c,true,true);m=matMul$1(c,o,true,true)}if(a!=null){const e=getFusedBiasGradient(l,c);return[p,m,e]}else{return[p,m]}};const I={a:E,b:b,bias:N,preluActivationWeights:S};const v={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:i};if(a==null){const e=customGrad(((e,t,n)=>{const r=ENGINE.runKernel(_FusedMatMul,I,v);n([e,t,r]);return{value:reshape$1(r,T),gradFunc:_}}));return e(E,b)}else{const e=customGrad(((e,t,n,r)=>{const a=ENGINE.runKernel(_FusedMatMul,I,v);r([e,t,a,n]);return{value:reshape$1(a,T),gradFunc:_}}));return e(E,b,N)}}const matMul=op({fusedMatMul_:fusedMatMul_});var fused_ops=Object.freeze({__proto__:null,conv2d_:()=>{},depthwiseConv2d_:()=>{},matMul:matMul});function frame_(e,t,n,r=false,a=0){let s=0;const o=[];while(s+t<=e.size){o.push(slice$1(e,s,t));s+=n}if(r){while(s<e.size){const r=s+t-e.size;const i=concat$1([slice$1(e,s,t-r),fill$1([r],a)]);o.push(i);s+=n}}if(o.length===0){return tensor2d([],[0,t])}return reshape$1(concat$1(o),[o.length,t])}const service_min_frame=op({frame_:frame_});var Reduction;(function(e){e[e["NONE"]=0]="NONE";e[e["MEAN"]=1]="MEAN";e[e["SUM"]=2]="SUM";e[e["SUM_BY_NONZERO_WEIGHTS"]=3]="SUM_BY_NONZERO_WEIGHTS"})(Reduction||(Reduction={}));op({computeWeightedLoss_:()=>{}});op({cosineDistance_:()=>{}});op({hingeLoss_:()=>{}});op({sigmoidCrossEntropy_:()=>{}});op({softmaxCrossEntropy_:()=>{}});const spectral$1={fft:fft,ifft_:()=>{},rfft_:()=>{},irfft_:()=>{}};const signal={hammingWindow_:()=>{},hannWindow_:()=>{},frame:service_min_frame,stft_:()=>{}};const image$1={flipLeftRight_:()=>{},grayscaleToRGB_:()=>{},resizeNearestNeighbor_:()=>{},resizeBilinear_:()=>{},rotateWithOffset_:()=>{},cropAndResize_:()=>{},nonMaxSuppression_:()=>{},nonMaxSuppressionAsync_:()=>{},nonMaxSuppressionWithScore_:()=>{},nonMaxSuppressionWithScoreAsync_:()=>{},nonMaxSuppressionPadded_:()=>{},nonMaxSuppressionPaddedAsync_:()=>{},threshold_:()=>{},transform_:()=>{}};const linalg={bandPart_:()=>{},gramSchmidt_:()=>{},qr_:()=>{}};const losses={absoluteDifference_:()=>{},computeWeightedLoss_:()=>{},cosineDistance_:()=>{},hingeLoss_:()=>{},huberLoss_:()=>{},logLoss_:()=>{},meanSquaredError_:()=>{},sigmoidCrossEntropy_:()=>{},softmaxCrossEntropy_:()=>{}};const sparse$1={sparseFillEmptyRows_:()=>{},sparseReshape_:()=>{},sparseSegmentMean_:()=>{},sparseSegmentSum_:()=>{}};const string$1={stringNGrams_:()=>{},stringSplit_:()=>{},stringToHashBucketFast_:()=>{}};class Optimizer extends Serializable{minimize(e,t=false,n){const{value:r,grads:a}=this.computeGradients(e,n);if(n!=null){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else{this.applyGradients(a)}dispose(a);if(t){return r}else{r.dispose();return null}}get iterations(){if(this.iterations_==null){this.iterations_=0}return this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return variableGrads(e,t)}dispose(){if(this.iterations_!=null){dispose(this.iterations_)}}async saveIterations(){if(this.iterations_==null){this.iterations_=0}return{name:"iter",tensor:scalar(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class `+`${this.getClassName()}`)}async extractIterations(e){this.iterations_=(await e[0].tensor.data())[0];return e.slice(1)}}Object.defineProperty(Optimizer,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class AdadeltaOptimizer extends Optimizer{constructor(e,t,n=null){super();this.learningRate=e;this.rho=t;this.epsilon=n;this.accumulatedGrads=[];this.accumulatedUpdates=[];if(n==null){this.epsilon=ENGINE.backend.epsilon()}}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);t.forEach(((t,n)=>{const r=ENGINE.registeredVariables[t];const a=false;if(this.accumulatedGrads[n]==null){this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:tidy((()=>zerosLike(r).variable(a)))}}if(this.accumulatedUpdates[n]==null){this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:tidy((()=>zerosLike(r).variable(a)))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(s==null){return}const o=this.accumulatedGrads[n].variable;const i=this.accumulatedUpdates[n].variable;tidy((()=>{const e=add(mul(o,this.rho),mul(square(s),1-this.rho));const t=mul(div(sqrt(add(i,this.epsilon)),sqrt(add(o,this.epsilon))),s);const n=add(mul(i,this.rho),mul(square(t),1-this.rho));o.assign(e);i.assign(n);const a=add(mul(t,-this.learningRate),r);r.assign(a)}))}));this.incrementIterations()}dispose(){if(this.accumulatedUpdates!=null){dispose(this.accumulatedGrads.map((e=>e.variable)));dispose(this.accumulatedUpdates.map((e=>e.variable)))}}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2;const n=false;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})));this.accumulatedUpdates=e.slice(t,t*2).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t["learningRate"],t["rho"],t["epsilon"])}}AdadeltaOptimizer.className="Adadelta";registerClass(AdadeltaOptimizer);class AdagradOptimizer extends Optimizer{constructor(e,t=.1){super();this.learningRate=e;this.initialAccumulatorValue=t;this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);t.forEach(((t,n)=>{const r=ENGINE.registeredVariables[t];if(this.accumulatedGrads[n]==null){const e=false;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:tidy((()=>fill$1(r.shape,this.initialAccumulatorValue).variable(e)))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(a==null){return}const s=this.accumulatedGrads[n].variable;tidy((()=>{const e=add(s,square(a));s.assign(e);const t=add(mul(div(a,sqrt(add(e,ENGINE.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))}));this.incrementIterations()}dispose(){if(this.accumulatedGrads!=null){dispose(this.accumulatedGrads.map((e=>e.variable)))}}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=false;this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(t)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t["learningRate"],t["initialAccumulatorValue"])}}AdagradOptimizer.className="Adagrad";registerClass(AdagradOptimizer);class AdamOptimizer extends Optimizer{constructor(e,t,n,r=null){super();this.learningRate=e;this.beta1=t;this.beta2=n;this.epsilon=r;this.accumulatedFirstMoment=[];this.accumulatedSecondMoment=[];tidy((()=>{this.accBeta1=scalar(t).variable();this.accBeta2=scalar(n).variable()}));if(r==null){this.epsilon=ENGINE.backend.epsilon()}}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);tidy((()=>{const n=sub(1,this.accBeta1);const r=sub(1,this.accBeta2);t.forEach(((t,a)=>{const s=ENGINE.registeredVariables[t];const o=false;if(this.accumulatedFirstMoment[a]==null){this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:tidy((()=>zerosLike(s).variable(o)))}}if(this.accumulatedSecondMoment[a]==null){this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:tidy((()=>zerosLike(s).variable(o)))}}const i=Array.isArray(e)?e[a].tensor:e[t];if(i==null){return}const u=this.accumulatedFirstMoment[a].variable;const l=this.accumulatedSecondMoment[a].variable;const c=add(mul(u,this.beta1),mul(i,1-this.beta1));const p=add(mul(l,this.beta2),mul(square(i),1-this.beta2));const m=div(c,n);const d=div(p,r);u.assign(c);l.assign(p);const h=add(mul(div(m,add(sqrt(d),this.epsilon)),-this.learningRate),s);s.assign(h)}));this.accBeta1.assign(mul(this.accBeta1,this.beta1));this.accBeta2.assign(mul(this.accBeta2,this.beta2))}));this.incrementIterations()}dispose(){this.accBeta1.dispose();this.accBeta2.dispose();if(this.accumulatedFirstMoment!=null){dispose(this.accumulatedFirstMoment.map((e=>e.variable)))}if(this.accumulatedSecondMoment!=null){dispose(this.accumulatedSecondMoment.map((e=>e.variable)))}}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);tidy((()=>{this.accBeta1.assign(pow$1(this.beta1,this.iterations_+1));this.accBeta2.assign(pow$1(this.beta2,this.iterations_+1))}));const t=e.length/2;const n=false;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})));this.accumulatedSecondMoment=e.slice(t,t*2).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t["learningRate"],t["beta1"],t["beta2"],t["epsilon"])}}AdamOptimizer.className="Adam";registerClass(AdamOptimizer);class AdamaxOptimizer extends Optimizer{constructor(e,t,n,r=null,a=0){super();this.learningRate=e;this.beta1=t;this.beta2=n;this.epsilon=r;this.decay=a;this.accumulatedFirstMoment=[];this.accumulatedWeightedInfNorm=[];tidy((()=>{this.iteration=scalar(0).variable();this.accBeta1=scalar(t).variable()}));if(r==null){this.epsilon=ENGINE.backend.epsilon()}}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);tidy((()=>{const n=sub(1,this.accBeta1);const r=div(-this.learningRate,add(mul(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=ENGINE.registeredVariables[t];const o=false;if(this.accumulatedFirstMoment[a]==null){this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:zerosLike(s).variable(o)}}if(this.accumulatedWeightedInfNorm[a]==null){this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:zerosLike(s).variable(o)}}const i=Array.isArray(e)?e[a].tensor:e[t];if(i==null){return}const u=this.accumulatedFirstMoment[a].variable;const l=this.accumulatedWeightedInfNorm[a].variable;const c=add(mul(u,this.beta1),mul(i,1-this.beta1));const p=mul(l,this.beta2);const m=abs(i);const d=maximum(p,m);u.assign(c);l.assign(d);const h=add(mul(div(r,n),div(c,add(d,this.epsilon))),s);s.assign(h)}));this.iteration.assign(add(this.iteration,1));this.accBeta1.assign(mul(this.accBeta1,this.beta1))}));this.incrementIterations()}dispose(){this.accBeta1.dispose();this.iteration.dispose();if(this.accumulatedFirstMoment!=null){dispose(this.accumulatedFirstMoment.map((e=>e.variable)))}if(this.accumulatedWeightedInfNorm!=null){dispose(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t["learningRate"],t["beta1"],t["beta2"],t["epsilon"],t["decay"])}}AdamaxOptimizer.className="Adamax";registerClass(AdamaxOptimizer);class SGDOptimizer extends Optimizer{constructor(e){super();this.learningRate=e;this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);t.forEach(((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(r==null){return}const a=ENGINE.registeredVariables[t];tidy((()=>{const e=add(mul(this.c,r),a);a.assign(e)}))}));this.incrementIterations()}setLearningRate(e){this.learningRate=e;if(this.c!=null){this.c.dispose()}this.c=keep(scalar(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){e=await this.extractIterations(e);if(e.length!==0){throw new Error("SGD optimizer does not have settable weights.")}}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t["learningRate"])}}SGDOptimizer.className="SGD";registerClass(SGDOptimizer);class MomentumOptimizer extends SGDOptimizer{constructor(e,t,n=false){super(e);this.learningRate=e;this.momentum=t;this.useNesterov=n;this.accumulations=[];this.m=scalar(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);t.forEach(((t,n)=>{const r=ENGINE.registeredVariables[t];if(this.accumulations[n]==null){const e=false;this.accumulations[n]={originalName:`${t}/momentum`,variable:tidy((()=>zerosLike(r).variable(e)))}}const a=this.accumulations[n].variable;const s=Array.isArray(e)?e[n].tensor:e[t];if(s==null){return}tidy((()=>{let e;const t=add(mul(this.m,a),s);if(this.useNesterov){e=add(mul(this.c,add(s,mul(t,this.m))),r)}else{e=add(mul(this.c,t),r)}a.assign(t);r.assign(e)}))}));this.incrementIterations()}dispose(){this.m.dispose();if(this.accumulations!=null){dispose(this.accumulations.map((e=>e.variable)))}}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=false;this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(t)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t["learningRate"],t["momentum"],t["useNesterov"])}}MomentumOptimizer.className="Momentum";registerClass(MomentumOptimizer);class RMSPropOptimizer extends Optimizer{constructor(e,t=.9,n=0,r=null,a=false){super();this.learningRate=e;this.decay=t;this.momentum=n;this.epsilon=r;this.accumulatedMeanSquares=[];this.accumulatedMoments=[];this.accumulatedMeanGrads=[];this.centered=a;if(r==null){this.epsilon=ENGINE.backend.epsilon()}if(e==null){throw new Error(`learningRate for RMSPropOptimizer must be defined.`)}}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);t.forEach(((t,n)=>{const r=ENGINE.registeredVariables[t];const a=false;if(this.accumulatedMeanSquares[n]==null){this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:tidy((()=>zerosLike(r).variable(a)))}}if(this.accumulatedMoments[n]==null){this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:tidy((()=>zerosLike(r).variable(a)))}}if(this.accumulatedMeanGrads[n]==null&&this.centered){this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:tidy((()=>zerosLike(r).variable(a)))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(s==null){return}const o=this.accumulatedMeanSquares[n].variable;const i=this.accumulatedMoments[n].variable;tidy((()=>{const e=add(mul(o,this.decay),mul(square(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable;const a=add(mul(t,this.decay),mul(s,1-this.decay));const u=div(mul(s,this.learningRate),sqrt(sub(e,add(square(a),this.epsilon))));const l=add(mul(i,this.momentum),u);o.assign(e);t.assign(a);i.assign(l);const c=sub(r,l);r.assign(c)}else{const e=add(mul(o,this.decay),mul(square(s),1-this.decay));const t=add(mul(i,this.momentum),div(mul(s,this.learningRate),sqrt(add(e,this.epsilon))));o.assign(e);i.assign(t);const n=sub(r,t);r.assign(n)}}))}));this.incrementIterations()}dispose(){if(this.accumulatedMeanSquares!=null){dispose(this.accumulatedMeanSquares.map((e=>e.variable)))}if(this.accumulatedMeanGrads!=null&&this.centered){dispose(this.accumulatedMeanGrads.map((e=>e.variable)))}if(this.accumulatedMoments!=null){dispose(this.accumulatedMoments.map((e=>e.variable)))}}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];if(this.centered){e.push(...this.accumulatedMeanGrads)}return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2;const n=false;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})));this.accumulatedMoments=e.slice(t,t*2).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})));if(this.centered){this.accumulatedMeanGrads=e.slice(t*2,t*3).map((e=>({originalName:e.name,variable:e.tensor.variable(n)})))}}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t["learningRate"],t["decay"],t["momentum"],t["epsilon"],t["centered"])}}RMSPropOptimizer.className="RMSProp";registerClass(RMSPropOptimizer);(()=>{if(typeof requestAnimationFrame!=="undefined"){return requestAnimationFrame}else if(typeof setImmediate!=="undefined"){return setImmediate}return e=>e()})();function assertParamsConsistent(e,t){const n=e[0].length;e.forEach(((e,t)=>{assert(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same `+`as the rank of the rest (${n})`))}));assert(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,a)=>{for(let s=0;s<n;s++){assert(s===t||e[s]===r[s],(()=>`Error in concat${n}D: Shape of tensors[${a}] (${e}) `+`does not match the shape of the rest (${r}) `+`along the non-concatenated axis ${a}.`))}}))}function computeOutShape$1(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++){n[t]+=e[r][t]}return n}const PARALLELIZE_THRESHOLD=30;function computeOptimalWindowSize(e){if(e<=PARALLELIZE_THRESHOLD){return e}return nearestDivisor(e,Math.floor(Math.sqrt(e)))}const SELU_SCALEALPHA=1.7580993408473768;const SELU_SCALE=1.0507009873554805;const ERF_P=.3275911;const ERF_A1=.254829592;const ERF_A2=-.284496736;const ERF_A3=1.421413741;const ERF_A4=-1.453152027;const ERF_A5=1.061405429;function collectGatherOpShapeInfo(e,t,n,r){const a=t.shape.length;const s=e.shape.length;if(r!==0){if(r<-a||r>a){throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`)}}if(r<0){r+=a}if(r>s){throw new Error(`batchDims (${r}) must be less than rank(x) (\n    ${s}).`)}if(n<r){throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`)}for(let n=0;n<r;++n){if(e.shape[n]!==t.shape[n]){throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`)}}const o=e.shape[n];const i=[];let u=1;let l=1;let c=1;for(let t=0;t<r;++t){i.push(e.shape[t]);u*=e.shape[t]}for(let t=r;t<n;t++){i.push(e.shape[t]);l*=e.shape[t]}for(let e=r;e<a;e++){i.push(t.shape[e])}for(let t=n+1;t<s;t++){i.push(e.shape[t]);c*=e.shape[t]}return{batchSize:u,sliceSize:c,outerSize:l,dimSize:o,outputShape:i}}var segment_util=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:()=>{},computeOutShape$2:()=>{},collectGatherOpShapeInfo:collectGatherOpShapeInfo});var backend_util=Object.freeze({__proto__:null,slice_util:slice_util,segment_util:segment_util,fromUint8ToStringArray:()=>{},fromStringArrayToUint8:()=>{},upcastType:upcastType,axesAreInnerMostDims:axesAreInnerMostDims,combineLocations:()=>{},computeOutAndReduceShapes:computeOutAndReduceShapes,expandShapeToKeepDim:expandShapeToKeepDim,assertAxesAreInnerMostDims:assertAxesAreInnerMostDims,getAxesPermutation:getAxesPermutation,getUndoAxesPermutation:()=>{},getInnerMostAxes:getInnerMostAxes,getBroadcastDims:getBroadcastDims$1,getReductionAxes:getReductionAxes,assertAndGetBroadcastShape:assertAndGetBroadcastShape,assertParamsConsistent:assertParamsConsistent,computeOutShape$2:()=>{},computeDilation2DInfo:()=>{},computePool2DInfo:computePool2DInfo,computePool3DInfo:()=>{},computeConv2DInfo:computeConv2DInfo,computeConv3DInfo:()=>{},computeDefaultPad:()=>{},tupleValuesAreOne:()=>{},eitherStridesOrDilationsAreOne:()=>{},convertConv2DDataFormat:convertConv2DDataFormat,checkPadOnDimRoundingMode:()=>{},getFusedDyActivation:getFusedDyActivation,getFusedBiasGradient:getFusedBiasGradient,applyActivation:()=>{},shouldFuse:shouldFuse,PARALLELIZE_THRESHOLD:PARALLELIZE_THRESHOLD,computeOptimalWindowSize:computeOptimalWindowSize,getImageCenter:()=>{},getReshaped:()=>{},getPermuted:()=>{},getReshapedPermuted:()=>{},getSliceBeginCoords:()=>{},getSliceSize:()=>{},prepareAndValidate:()=>{},validateUpdateShape:()=>{},validateInput:validateInput$1,calculateShapes:()=>{},SELU_SCALEALPHA:SELU_SCALEALPHA,SELU_SCALE:SELU_SCALE,ERF_P:ERF_P,ERF_A1:ERF_A1,ERF_A2:ERF_A2,ERF_A3:ERF_A3,ERF_A4:ERF_A4,ERF_A5:ERF_A5,warn:warn,log:log$1,mergeRealAndImagArrays:()=>{},splitRealAndImagArrays:()=>{},complexWithEvenIndex:()=>{},complexWithOddIndex:()=>{},getComplexWithIndex:()=>{},assignToTypedArray:()=>{},exponents:()=>{},exponent:()=>{},decodeEinsumEquation:()=>{},getEinsumPermutation:()=>{},checkEinsumDimSizes:()=>{},getEinsumComputePath:()=>{},isIdentityPermutation:()=>{},prepareSplitSize:()=>{},getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>{},getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>{},getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>{},getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>{},getSparseReshapeNegativeOutputDimErrorMessage:()=>{},getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>{},getSparseReshapeInputOutputMultipleErrorMessage:()=>{},getSparseReshapeInputOutputMismatchErrorMessage:()=>{},getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>{},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>{},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>{},getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>{}});const ENV$1=env();ENV$1.registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>false),(e=>{if(e){console.warn("Keep intermediate tensors is ON. This will print the values of all "+"intermediate tensors during model inference. Not all models "+"support this mode. For details, check e2e/benchmarks/ "+"model_config.js. This significantly impacts performance.")}}));var DataType;(function(e){e[e["DT_INVALID"]=0]="DT_INVALID";e[e["DT_FLOAT"]=1]="DT_FLOAT";e[e["DT_DOUBLE"]=2]="DT_DOUBLE";e[e["DT_INT32"]=3]="DT_INT32";e[e["DT_UINT8"]=4]="DT_UINT8";e[e["DT_INT16"]=5]="DT_INT16";e[e["DT_INT8"]=6]="DT_INT8";e[e["DT_STRING"]=7]="DT_STRING";e[e["DT_COMPLEX64"]=8]="DT_COMPLEX64";e[e["DT_INT64"]=9]="DT_INT64";e[e["DT_BOOL"]=10]="DT_BOOL";e[e["DT_QINT8"]=11]="DT_QINT8";e[e["DT_QUINT8"]=12]="DT_QUINT8";e[e["DT_QINT32"]=13]="DT_QINT32";e[e["DT_BFLOAT16"]=14]="DT_BFLOAT16";e[e["DT_QINT16"]=15]="DT_QINT16";e[e["DT_QUINT16"]=16]="DT_QUINT16";e[e["DT_UINT16"]=17]="DT_UINT16";e[e["DT_COMPLEX128"]=18]="DT_COMPLEX128";e[e["DT_HALF"]=19]="DT_HALF";e[e["DT_RESOURCE"]=20]="DT_RESOURCE";e[e["DT_VARIANT"]=21]="DT_VARIANT";e[e["DT_UINT32"]=22]="DT_UINT32";e[e["DT_UINT64"]=23]="DT_UINT64";e[e["DT_FLOAT_REF"]=101]="DT_FLOAT_REF";e[e["DT_DOUBLE_REF"]=102]="DT_DOUBLE_REF";e[e["DT_INT32_REF"]=103]="DT_INT32_REF";e[e["DT_UINT8_REF"]=104]="DT_UINT8_REF";e[e["DT_INT16_REF"]=105]="DT_INT16_REF";e[e["DT_INT8_REF"]=106]="DT_INT8_REF";e[e["DT_STRING_REF"]=107]="DT_STRING_REF";e[e["DT_COMPLEX64_REF"]=108]="DT_COMPLEX64_REF";e[e["DT_INT64_REF"]=109]="DT_INT64_REF";e[e["DT_BOOL_REF"]=110]="DT_BOOL_REF";e[e["DT_QINT8_REF"]=111]="DT_QINT8_REF";e[e["DT_QUINT8_REF"]=112]="DT_QUINT8_REF";e[e["DT_QINT32_REF"]=113]="DT_QINT32_REF";e[e["DT_BFLOAT16_REF"]=114]="DT_BFLOAT16_REF";e[e["DT_QINT16_REF"]=115]="DT_QINT16_REF";e[e["DT_QUINT16_REF"]=116]="DT_QUINT16_REF";e[e["DT_UINT16_REF"]=117]="DT_UINT16_REF";e[e["DT_COMPLEX128_REF"]=118]="DT_COMPLEX128_REF";e[e["DT_HALF_REF"]=119]="DT_HALF_REF";e[e["DT_RESOURCE_REF"]=120]="DT_RESOURCE_REF";e[e["DT_VARIANT_REF"]=121]="DT_VARIANT_REF";e[e["DT_UINT32_REF"]=122]="DT_UINT32_REF";e[e["DT_UINT64_REF"]=123]="DT_UINT64_REF"})(DataType||(DataType={}));var SaverDef;(function(e){(function(e){e[e["LEGACY"]=0]="LEGACY";e[e["V1"]=1]="V1";e[e["V2"]=2]="V2"})(e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(SaverDef||(SaverDef={}));const CUSTOM_OPS={};function getRegisteredOp(e){return CUSTOM_OPS[e]}function getParamValue(e,t,n,r,a){const s=t.inputParams[e];if(s&&s.inputIndexStart!==undefined){const e=s.inputIndexStart;const o=s.inputIndexEnd===0?undefined:s.inputIndexEnd===undefined?e+1:s.inputIndexEnd;if(s.type==="tensor"){return getTensor(t.inputNames[s.inputIndexStart],n,r,a)}if(s.type==="tensors"){const s=t.inputNames.slice(e,o);return s.map((e=>getTensor(e,n,r,a)))}const i=getTensor(t.inputNames.slice(e)[0],n,r,a);const u=i.dataSync();return s.type==="number"?u[0]:toNestedArray(i.shape,u)}const o=t.attrParams[e];return o&&o.value}function getTensor(e,t,n,r){const[a,s]=parseNodeName(e);if(r!=null){const e=r.getHashTableHandleByName(a);if(e!=null){return e}}const o=n.currentContextIds.find((e=>!!t[getNodeNameWithContextId(a,e)]));return o!==undefined?t[getNodeNameWithContextId(a,o)][s]:undefined}function getTensorsForCurrentContenxt(e,t,n){return t[getNodeNameWithContextId(e,n.currentContextId)]}function getNodeNameAndIndex(e,t){const[n,r,a]=parseNodeName(e);return[getNodeNameWithContextId(n,t&&t.currentContextId),r,a]}function getNodeNameWithContextId(e,t){return!!t?`${e}-${t}`:e}function parseNodeName(e){const t=e.split(":");if(t.length===1){return[e,0,undefined]}const n=t[0];const r=t.length===3?t[1]:undefined;const a=Number(t[t.length-1]);return[n,a,r]}function getPadding(e,t,n){let r=getParamValue("pad",e,t,n);if(r==="explicit"){r=getParamValue("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++){a[e][0]=r[e*2];a[e][1]=r[e*2+1]}return a}return r}function cloneTensor(e){return e.kept?e:clone(e)}const json$i=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]}];var arithmetic=Object.freeze({__proto__:null,json:json$i});const json$h=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:true}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:true}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:true},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]}];var basicMath=Object.freeze({__proto__:null,json:json$h});const json$g=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:true}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}];var control=Object.freeze({__proto__:null,json:json$g});const json$f=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:true},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:true},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:true}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var convolution=Object.freeze({__proto__:null,json:json$f});const json$e=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:true},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:true},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:true}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:true},{tfName:"T",name:"T",type:"number",notSupported:true}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:true},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:true}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var creation=Object.freeze({__proto__:null,json:json$e});const json$d=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:true},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]}];var dynamic=Object.freeze({__proto__:null,json:json$d});const json$c=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var evaluation=Object.freeze({__proto__:null,json:json$c});const json$b=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:true},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var service_min_graph=Object.freeze({__proto__:null,json:json$b});const json$a=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:true},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:true}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:true},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:true}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:true},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:true}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:true},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:true}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}];var hashTable=Object.freeze({__proto__:null,json:json$a});const json$9=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}];var service_min_image=Object.freeze({__proto__:null,json:json$9});const json$8=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]}];var logical=Object.freeze({__proto__:null,json:json$8});const json$7=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:false},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:false},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:false},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:false},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:false},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:false},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:false},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:false},{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}];var matrices=Object.freeze({__proto__:null,json:json$7});const json$6=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:false}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:true}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:true,notSupported:true}]}];var normalization=Object.freeze({__proto__:null,json:json$6});const json$5=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var reduction=Object.freeze({__proto__:null,json:json$5});const json$4=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:true}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:true}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:false,notSupported:true}]}];var sliceJoin=Object.freeze({__proto__:null,json:json$4});const json$3=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:true}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}];var sparse=Object.freeze({__proto__:null,json:json$3});const json$2=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:true}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:true}]}];var spectral=Object.freeze({__proto__:null,json:json$2});const json$1=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}];var string=Object.freeze({__proto__:null,json:json$1});const json=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:true},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}];var transformation=Object.freeze({__proto__:null,json:json});class OperationMapper{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[arithmetic,basicMath,control,convolution,creation,dynamic,evaluation,service_min_graph,hashTable,service_min_image,logical,matrices,normalization,reduction,sliceJoin,sparse,spectral,string,transformation];const t=[].concat(...e.map((e=>e.json)));this.opMappers=t.reduce(((e,t)=>{e[t.tfOpName]=t;return e}),{})}transformGraph(e,t={}){const n=e.node;const r=[];const a=[];const s=[];const o=n.reduce(((e,t)=>{e[t.name]=this.mapNode(t);if(t.op.startsWith("Placeholder")){r.push(e[t.name])}else if(t.op==="Const"){a.push(e[t.name])}else if(t.input==null||t.input.length===0){s.push(e[t.name])}return e}),{});let i=[];const u=[];let l={};let c={};if(t!=null){l=this.mapSignatureEntries(t.inputs);c=this.mapSignatureEntries(t.outputs)}const p=Object.keys(o);p.forEach((e=>{const t=o[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=getNodeNameAndIndex(e);const s=o[r];if(s.outputs!=null){const e=s.outputs.indexOf(a);if(e!==-1){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s);s.children.push(t)}))}));if(Object.keys(c).length===0){p.forEach((e=>{const t=o[e];if(t.children.length===0){u.push(t)}}))}else{Object.keys(c).forEach((e=>{const[t]=getNodeNameAndIndex(e);const n=o[t];if(n!=null){n.signatureKey=c[e];u.push(n)}}))}if(Object.keys(l).length>0){Object.keys(l).forEach((e=>{const[t]=getNodeNameAndIndex(e);const n=o[t];if(n){n.signatureKey=l[e];i.push(n)}}))}else{i=r}let m={};if(e.library!=null&&e.library.function!=null){m=e.library.function.reduce(((e,t)=>{e[t.signature.name]=this.mapFunction(t);return e}),{})}const d={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:m};if(s.length>0){d.initNodes=s}return d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>{t[e[n].name]=n;return t}),{})}mapNode(e){const t=getRegisteredOp(e.op)||this.opMappers[e.op]||{};if(e.attr==null){e.attr={}}const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};if(t.inputs!=null){n.inputParams=t.inputs.reduce(((e,t)=>{e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end};return e}),{})}if(t.attrs!=null){n.attrParams=t.attrs.reduce(((t,n)=>{const r=n.type;let a=undefined;switch(n.type){case"string":a=getStringParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getStringParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"string[]":a=getStringArrayParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getStringArrayParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"number":a=getNumberParam(e.attr,n.tfName,n.defaultValue||0);if(a===undefined&&!!n.tfDeprecatedName){a=getNumberParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"number[]":a=getNumericArrayParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getNumericArrayParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"bool":a=getBoolParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getBoolParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"bool[]":a=getBoolArrayParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getBoolArrayParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"shape":a=getTensorShapeParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getTensorShapeParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"shape[]":a=getTensorShapeArrayParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getTensorShapeArrayParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"dtype":a=getDtypeParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getDtypeParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"dtype[]":a=getDtypeArrayParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getDtypeArrayParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"func":a=getFuncParam(e.attr,n.tfName,n.defaultValue);if(a===undefined&&!!n.tfDeprecatedName){a=getFuncParam(e.attr,n.tfDeprecatedName,n.defaultValue)}break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}t[n.name]={value:a,type:r};return t}),{})}return n}mapFunction(e){const t=e.nodeDef;const n=[];const r=[];let a={};if(t!=null){a=t.reduce(((e,t)=>{e[t.name]=this.mapNode(t);if(t.op==="Const"){r.push(e[t.name])}return e}),{})}const s=[];const o=[];e.signature.inputArg.forEach((e=>{const[t]=getNodeNameAndIndex(e.name);const n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:parseDtypeParam(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name;s.push(n);a[t]=n}));const i=Object.keys(a);i.forEach((e=>{const t=a[e];t.inputNames.forEach(((e,n)=>{const[r,,s]=getNodeNameAndIndex(e);const o=a[r];if(o.outputs!=null){const e=o.outputs.indexOf(s);if(e!==-1){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(o);o.children.push(t)}))}));const u=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=getNodeNameAndIndex(u[e.name]);const r=a[t];if(r!=null){r.defaultOutput=n;o.push(r)}}));const l=this.mapArgsToSignature(e);return{nodes:a,inputs:s,outputs:o,weights:r,placeholders:n,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>{e[t.name]=this.mapArgToTensorInfo(t);return e}),{}),outputs:e.signature.outputArg.reduce(((t,n)=>{t[n.name]=this.mapArgToTensorInfo(n,e.ret);return t}),{})}}mapArgToTensorInfo(e,t){let n=e.name;if(t!=null){n=t[n]}return{name:n,dtype:e.type}}}function decodeBase64(e){const t=env().global;if(typeof t.atob!=="undefined"){return t.atob(e)}else if(typeof Buffer!=="undefined"){return new Buffer(e,"base64").toString()}else{throw new Error("Unable to decode base64 in this environment. "+"Missing built-in atob() or Buffer()")}}function parseStringParam(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):decodeBase64(e);return t?n:n.toLowerCase()}function getStringParam(e,t,n,r=false){const a=e[t];if(a!=null){return parseStringParam(a.s,r)}return n}function getBoolParam(e,t,n){const r=e[t];return r?r.b:n}function getNumberParam(e,t,n){const r=e[t]||{};const a=r["i"]!=null?r["i"]:r["f"]!=null?r["f"]:n;return typeof a==="number"?a:parseInt(a,10)}function parseDtypeParam(e){if(typeof e==="string"){e=DataType[e]}switch(e){case DataType.DT_FLOAT:case DataType.DT_HALF:return"float32";case DataType.DT_INT32:case DataType.DT_INT64:case DataType.DT_INT8:case DataType.DT_UINT8:return"int32";case DataType.DT_BOOL:return"bool";case DataType.DT_DOUBLE:return"float32";case DataType.DT_STRING:return"string";default:return null}}function getDtypeParam(e,t,n){const r=e[t];if(r&&r.type){return parseDtypeParam(r.type)}return n}function parseTensorShapeParam(e){if(e.unknownRank){return undefined}if(e.dim!=null){return e.dim.map((e=>typeof e.size==="number"?e.size:parseInt(e.size,10)))}return[]}function getTensorShapeParam(e,t,n){const r=e[t];if(r&&r.shape){return parseTensorShapeParam(r.shape)}return n}function getStringArrayParam(e,t,n,r=false){const a=e[t];if(a&&a.list&&a.list.s){return a.list.s.map((e=>parseStringParam(e,r)))}return n}class NodeValueImpl{constructor(e,t,n){this.node=e;this.tensorMap=t;this.context=n;this.inputs=[];this.attrs={};this.inputs=e.inputNames.map((e=>this.getInput(e)));if(e.rawAttrs!=null){this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>{e[t]=this.getAttr(t);return e}),{})}}getInput(e){return getTensor(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(n.tensor!=null){return getTensor(e,this.tensorMap,this.context)}if(n.i!=null||n.f!=null){return getNumberParam(this.node.rawAttrs,e,t)}if(n.s!=null){return getStringParam(this.node.rawAttrs,e,t)}if(n.b!=null){return getBoolParam(this.node.rawAttrs,e,t)}if(n.shape!=null){return getTensorShapeParam(this.node.rawAttrs,e,t)}if(n.type!=null){return getDtypeParam(this.node.rawAttrs,e,t)}if(n.list!=null){if(n.list.i!=null||n.list.f!=null){return getNumericArrayParam(this.node.rawAttrs,e,t)}if(n.list.s!=null){return getStringArrayParam(this.node.rawAttrs,e,t)}if(n.list.shape!=null){return getTensorShapeArrayParam(this.node.rawAttrs,e,t)}if(n.list.b!=null){return getBoolArrayParam(this.node.rawAttrs,e,t)}if(n.list.type!=null){return getDtypeArrayParam(this.node.rawAttrs,e,t)}}return t}}var tfOps=Object.freeze({__proto__:null,abs:abs,acos_:()=>{},acosh_:()=>{},add:add,addN_:()=>{},all_:()=>{},any_:()=>{},argMax_:()=>{},argMin_:()=>{},asin_:()=>{},asinh_:()=>{},atan_:()=>{},atan_:()=>{},atanh_:()=>{},avgPool_:()=>{},avgPool3d_:()=>{},basicLSTMCell_:()=>{},batchToSpaceND_:()=>{},batchNorm_:()=>{},batchNorm2d_:()=>{},batchNorm3d_:()=>{},batchNorm4d_:()=>{},bincount:bincount,broadcastArgs_:()=>{},broadcastTo:broadcastTo,buffer:buffer,cast:cast$1,ceil_:()=>{},clipByValue_:()=>{},clone:clone,complex:complex$1,concat:concat$1,concat1d_:()=>{},concat2d_:()=>{},concat3d_:()=>{},concat4d_:()=>{},conv1d_:()=>{},conv2d_:()=>{},conv2dTranspose_:()=>{},conv3d_:()=>{},conv3dTranspose_:()=>{},cos_:()=>{},cosh_:()=>{},cumprod_:()=>{},cumsum_:()=>{},denseBincount_:()=>{},depthToSpace_:()=>{},depthwiseConv2d_:()=>{},diag_:()=>{},dilation2d_:()=>{},div:div,divNoNan_:()=>{},dot:dot,einsum_:()=>{},elu_:()=>{},equal:equal,erf_:()=>{},euclideanNorm_:()=>{},exp:exp,expandDims:expandDims$1,expm1_:()=>{},eye_:()=>{},fill$1:()=>{},floor_:()=>{},floorDiv_:()=>{},gather:gather,greater:greater,greaterEqual_:()=>{},imag_:()=>{},isFinite_:()=>{},isInf_:()=>{},isNaN_:()=>{},leakyRelu_:()=>{},less_:()=>{},lessEqual_:()=>{},linspace:()=>{},localResponseNormalization_:()=>{},log:log,log1p:log1p,logSigmoid_:()=>{},logSoftmax_:()=>{},logSumExp:logSumExp,logicalAnd:logicalAnd,logicalNot_:()=>{},logicalOr_:()=>{},logicalXor_:()=>{},lowerBound:()=>{},matMul:matMul$1,max:max,maxPool_:()=>{},maxPool3d_:()=>{},maxPoolWithArgmax_:()=>{},maximum:maximum,mean:mean,meshgrid:()=>{},min_:()=>{},minimum:minimum,mirrorPad_:()=>{},mod_:()=>{},moments_:()=>{},mul:mul,multiRNNCell_:()=>{},multinomial_:()=>{},neg:neg,notEqual:notEqual$1,oneHot:oneHot,ones:ones,onesLike_:()=>{},outerProduct_:()=>{},pad:pad,pad1d_:()=>{},pad2d_:()=>{},pad3d_:()=>{},pad4d_:()=>{},pool_:()=>{},pow_:()=>{},prelu_:()=>{},print:print,prod:prod$1,rand_:()=>{},randomGamma_:()=>{},randomNormal_:()=>{},randomStandardNormal_:()=>{},randomUniform_:()=>{},range:range,real:real$1,reciprocal_:()=>{},relu:relu$1,relu6_:()=>{},reshape:reshape$1,reverse:reverse,reverse1d_:()=>{},reverse2d_:()=>{},reverse3d_:()=>{},reverse4d_:()=>{},round$1:()=>{},rsqrt_:()=>{},scalar:scalar,selu_:()=>{},separableConv2d_:()=>{},setdiff1dAsync_:()=>{},sigmoid:sigmoid$1,sign_:()=>{},sin_:()=>{},sinh_:()=>{},slice:slice$1,slice1d_:()=>{},slice2d_:()=>{},slice3d_:()=>{},slice4d_:()=>{},softmax_:()=>{},softplus_:()=>{},spaceToBatchND_:()=>{},fft:fft,ifft_:()=>{},irfft_:()=>{},rfft_:()=>{},split_:()=>{},sqrt_:()=>{},square:square,squaredDifference:squaredDifference,squeeze:squeeze,stack:stack,step_:()=>{},stridedSlice_:()=>{},sub:sub,sum:sum$1,tan_:()=>{},tanh_:()=>{},tensor:tensor,tensor1d:tensor1d,tensor2d:tensor2d,tensor3d:()=>{},tensor4d:()=>{},tensor5d:()=>{},tensor6d:()=>{},tile_:()=>{},topk_:()=>{},truncatedNormal_:()=>{},unique_:()=>{},unsortedSegmentSum_:()=>{},unstack:unstack,upperBound:()=>{},variable:()=>{},where:where,whereAsync_:()=>{},zeros:zeros$1,zerosLike:zerosLike,op:op,OP_SCOPE_SUFFIX:OP_SCOPE_SUFFIX,booleanMaskAsync_:()=>{},transpose_:()=>{},norm:norm,movingAverage_:()=>{},scatterND_:()=>{},searchSorted_:()=>{},sparseToDense_:()=>{},gatherND_:()=>{},dropout_:()=>{},enclosingPowerOfTwo:()=>{},cosineWindow:()=>{},inTopKAsync_:()=>{},image:image$1,linalg:linalg,losses:losses,spectral:spectral$1,fused:fused_ops,signal:signal,sparse:sparse$1,string:string$1});const executeOp$j=(e,t,n,r=tfOps)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":{return[r.add(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"AddN":{return[r.addN(getParamValue("tensors",e,t,n))]}case"FloorMod":case"Mod":return[r.mod(getParamValue("a",e,t,n),getParamValue("b",e,t,n))];case"Mul":return[r.mul(getParamValue("a",e,t,n),getParamValue("b",e,t,n))];case"RealDiv":case"Div":{return[r.div(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"DivNoNan":{return[r.divNoNan(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"FloorDiv":{return[r.floorDiv(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Sub":{return[r.sub(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Minimum":{return[r.minimum(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Maximum":{return[r.maximum(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Pow":{return[r.pow(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"SquaredDifference":{return[r.squaredDifference(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$i=(e,t,n,r=tfOps)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(getParamValue("x",e,t,n))];case"Acos":return[r.acos(getParamValue("x",e,t,n))];case"Acosh":return[r.acosh(getParamValue("x",e,t,n))];case"Asin":return[r.asin(getParamValue("x",e,t,n))];case"Asinh":return[r.asinh(getParamValue("x",e,t,n))];case"Atan":return[r.atan(getParamValue("x",e,t,n))];case"Atan2":return[r.atan2(getParamValue("x",e,t,n),getParamValue("y",e,t,n))];case"Atanh":return[r.atanh(getParamValue("x",e,t,n))];case"Ceil":return[r.ceil(getParamValue("x",e,t,n))];case"Complex":return[r.complex(getParamValue("real",e,t,n),getParamValue("imag",e,t,n))];case"Cos":return[r.cos(getParamValue("x",e,t,n))];case"Cosh":return[r.cosh(getParamValue("x",e,t,n))];case"Elu":return[r.elu(getParamValue("x",e,t,n))];case"Erf":return[r.erf(getParamValue("x",e,t,n))];case"Exp":return[r.exp(getParamValue("x",e,t,n))];case"Expm1":{return[r.expm1(getParamValue("x",e,t,n))]}case"Floor":return[r.floor(getParamValue("x",e,t,n))];case"Log":return[r.log(getParamValue("x",e,t,n))];case"Log1p":{return[r.log1p(getParamValue("x",e,t,n))]}case"Imag":return[r.imag(getParamValue("x",e,t,n))];case"Neg":return[r.neg(getParamValue("x",e,t,n))];case"Reciprocal":{return[r.reciprocal(getParamValue("x",e,t,n))]}case"Real":return[r.real(getParamValue("x",e,t,n))];case"Relu":return[r.relu(getParamValue("x",e,t,n))];case"Round":{return[r.round(getParamValue("x",e,t,n))]}case"Selu":return[r.selu(getParamValue("x",e,t,n))];case"Sigmoid":return[r.sigmoid(getParamValue("x",e,t,n))];case"Sin":return[r.sin(getParamValue("x",e,t,n))];case"Sign":{return[r.sign(getParamValue("x",e,t,n))]}case"Sinh":{return[r.sinh(getParamValue("x",e,t,n))]}case"Softplus":{return[r.softplus(getParamValue("x",e,t,n))]}case"Sqrt":{return[r.sqrt(getParamValue("x",e,t,n))]}case"Square":{return[r.square(getParamValue("x",e,t,n))]}case"Tanh":{return[r.tanh(getParamValue("x",e,t,n))]}case"Tan":return[r.tan(getParamValue("x",e,t,n))];case"ClipByValue":return[r.clipByValue(getParamValue("x",e,t,n),getParamValue("clipValueMin",e,t,n),getParamValue("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(getParamValue("x",e,t,n))];case"Rsqrt":return[r.rsqrt(getTensor(e.inputNames[0],t,n))];case"Prod":return[r.prod(getParamValue("x",e,t,n),getParamValue("axes",e,t,n))];case"LeakyRelu":return[r.leakyRelu(getParamValue("x",e,t,n),getParamValue("alpha",e,t,n))];case"Prelu":return[r.prelu(getParamValue("x",e,t,n),getParamValue("alpha",e,t,n))];case"IsNan":return[r.isNaN(getTensor(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function inferElementShape(e,t,n){let r=mergeElementShape(e,n);const a=!fullDefinedShape(r);if(a&&t.length===0){throw new Error(`Tried to calculate elements of an empty list`+` with non-fully-defined elementShape: ${r}`)}if(a){t.forEach((e=>{r=mergeElementShape(e.shape,r)}))}if(!fullDefinedShape(r)){throw new Error(`Non-fully-defined elementShape: ${r}`)}return r}function mergeElementShape(e,t){if(typeof e==="number"){return t}if(typeof t==="number"){return e}if(e.length!==t.length){throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`)}const n=[];for(let r=0;r<e.length;++r){const a=e[r];const s=t[r];if(a>=0&&s>=0&&a!==s){throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`)}n[r]=a>=0?a:s}return n}class TensorArray{constructor(e,t,n,r,a,s,o){this.name=e;this.dtype=t;this.maxSize=n;this.elementShape=r;this.identicalElementShapes=a;this.dynamicSize=s;this.clearAfterRead=o;this.tensors=[];this.closed_=false;this.idTensor=scalar(0);keep(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{if(e==null||!e.has(t.tensor.id)){t.tensor.dispose()}}));this.tensors=[];this.closed_=true;this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_){throw new Error(`TensorArray ${this.name} has already been closed.`)}if(e<0||e>=this.size()){throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`)}const t=this.tensors[e];if(t.cleared){throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read `+`(perhaps try setting clear_after_read = false?).`)}if(this.clearAfterRead){t.cleared=true}t.read=true;return t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_){throw new Error(`TensorArray ${this.name} has already been closed.`)}if(e<0||!this.dynamicSize&&e>=this.maxSize){throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`)}const n=this.tensors[e]||{};if(t.dtype!==this.dtype){throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n          because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`)}if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)){this.elementShape=t.shape}assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`);if(n.read){throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`)}if(n.written){throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`)}n.tensor=t;keep(t);n.written=true;this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length){throw new Error(`TensorArray ${this.name}: could not write multiple tensors,`+`because the index size: ${e.length} is not the same as tensors size: ${t.length}.`)}e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(!!t&&t!==this.dtype){throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`)}if(!e){e=[];for(let t=0;t<this.size();t++){e.push(t)}}else{e=e.slice(0,this.size())}if(e.length===0){return tensor([],[0].concat(this.elementShape))}const n=this.readMany(e);assertShapesMatchAllowUndefinedSize(this.elementShape,n[0].shape,"TensorArray shape mismatch: ");return stack(n,0)}concat(e){if(!!e&&e!==this.dtype){throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`)}if(this.size()===0){return tensor([],[0].concat(this.elementShape))}const t=[];for(let e=0;e<this.size();e++){t.push(e)}const n=this.readMany(t);assertShapesMatchAllowUndefinedSize(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`);return concat$1(n,0)}scatter(e,t){if(t.dtype!==this.dtype){throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`)}if(e.length!==t.shape[0]){throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`)}const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize){throw new Error(`Max index must be < array size (${n}  vs. ${this.maxSize})`)}this.writeMany(e,unstack(t,0))}split(e,t){if(t.dtype!==this.dtype){throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`)}let n=0;const r=e.map((e=>{n+=e;return n}));if(n!==t.shape[0]){throw new Error(`Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ${n}, and tensor's shape is: ${t.shape}`)}if(!this.dynamicSize&&e.length!==this.maxSize){throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), `+"and the TensorArray is not marked as dynamically resizeable")}const a=n===0?0:t.size/n;const s=[];tidy((()=>{t=reshape$1(t,[1,n,a]);for(let n=0;n<e.length;++n){const o=n===0?0:r[n-1];const i=[0,o,0];const u=[1,e[n],a];s[n]=reshape$1(slice$1(t,i,u),this.elementShape)}return s}));const o=[];for(let t=0;t<e.length;t++){o[t]=t}this.writeMany(o,s)}}class TensorList{constructor(e,t,n,r=-1){this.tensors=e;this.elementShape=t;this.elementDtype=n;if(e!=null){e.forEach((e=>{if(n!==e.dtype){throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`)}assertShapesMatchAllowUndefinedSize(t,e.shape,"TensorList shape mismatch: ");keep(e)}))}this.idTensor=scalar(0);this.maxNumElements=r;keep(this.idTensor)}get id(){return this.idTensor.id}copy(){return new TensorList([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{if(e==null||!e.has(t.id)){t.dispose()}}));this.tensors.length=0;this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype){throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`)}if(n!==-1&&this.tensors.length!==n){throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`)}assertShapesMatchAllowUndefinedSize(e,this.elementShape,"TensorList shape mismatch: ");const r=inferElementShape(this.elementShape,this.tensors,e);return tidy((()=>{const e=this.tensors.map((e=>reshape$1(e,r)));return stack(e,0)}))}popBack(e,t){if(t!==this.elementDtype){throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`)}if(this.size()===0){throw new Error("Trying to pop from an empty list.")}const n=inferElementShape(this.elementShape,this.tensors,e);const r=this.tensors.pop();assertShapesMatchAllowUndefinedSize(r.shape,e,"TensorList shape mismatch: ");return reshape$1(r,n)}pushBack(e){if(e.dtype!==this.elementDtype){throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`)}assertShapesMatchAllowUndefinedSize(e.shape,this.elementShape,"TensorList shape mismatch: ");if(this.maxNumElements===this.size()){throw new Error(`Trying to push element into a full list.`)}keep(e);this.tensors.push(e)}resize(e){if(e<0){throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`)}if(this.maxNumElements!==-1&&e>this.maxNumElements){throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`)}const t=new TensorList([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n){t.tensors[n]=this.tensors[n]}return t}getItem(e,t,n){if(n!==this.elementDtype){throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`)}if(e<0||e>this.tensors.length){throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`)}if(this.tensors[e]==null){throw new Error(`element at index ${e} is null.`)}assertShapesMatchAllowUndefinedSize(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=inferElementShape(this.elementShape,this.tensors,t);return reshape$1(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype){throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`)}if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements){throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`)}assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,"TensorList shape mismatch: ");keep(t);this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype){throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`)}assertShapesMatchAllowUndefinedSize(this.elementShape,n,"TensorList shape mismatch: ");e=e.slice(0,this.size());const r=inferElementShape(this.elementShape,this.tensors,n);if(e.length===0){return tensor([],[0].concat(r))}return tidy((()=>{const t=e.map((e=>reshape$1(this.tensors[e],r)));return stack(t,0)}))}concat(e,t){if(!!e&&e!==this.elementDtype){throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`)}assertShapesMatchAllowUndefinedSize(this.elementShape,t,"TensorList shape mismatch: ");const n=inferElementShape(this.elementShape,this.tensors,t);if(this.size()===0){return tensor([],[0].concat(n))}return tidy((()=>{const e=this.tensors.map((e=>reshape$1(e,n)));return concat$1(e,0)}))}}function fromTensor(e,t,n){const r=e.dtype;if(e.shape.length<1){throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`)}if(e.dtype!==n){throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`)}const a=e.shape.slice(1);assertShapesMatchAllowUndefinedSize(a,t,"TensorList shape mismatch: ");const s=unstack(e);return new TensorList(s,t,r)}function reserve(e,t,n,r){return new TensorList([],e,t,r)}function scatter(e,t,n,r){if(t.length!==e.shape[0]){throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`)}const a=Math.max(...t);if(r!=null&&r!==-1&&a>=r){throw new Error(`Max index must be < array size (${a}  vs. ${r})`)}const s=new TensorList([],n,e.dtype,r);const o=unstack(e,0);t.forEach(((e,t)=>{s.setItem(e,o[t])}));return s}const executeOp$h=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=getParamValue("thenBranch",e,t,n);const a=getParamValue("elseBranch",e,t,n);const s=getParamValue("cond",e,t,n);const o=getParamValue("args",e,t,n);const i=await s.data();if(i[0]){return n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}else{return n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}}case"While":case"StatelessWhile":{const r=getParamValue("body",e,t,n);const a=getParamValue("cond",e,t,n);const s=getParamValue("args",e,t,n);const o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap);const i=s.map((e=>e.id));let u=await o[0].data();o.forEach((e=>{if(!e.kept&&i.indexOf(e.id)===-1){e.dispose()}}));let l=s;while(u[0]){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map((e=>e.id));e.forEach((e=>{if(!e.kept&&i.indexOf(e.id)===-1&&t.indexOf(e.id)===-1){e.dispose()}}));const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data();s.forEach((e=>{if(!e.kept&&i.indexOf(e.id)===-1&&t.indexOf(e.id)===-1){e.dispose()}}))}return l}case"LoopCond":{const r=getParamValue("pred",e,t,n);return[cloneTensor(r)]}case"Switch":{const r=getParamValue("pred",e,t,n);let a=getParamValue("data",e,t,n);if(!a.kept){a=cloneTensor(a)}return(await r.data())[0]?[undefined,a]:[a,undefined]}case"Merge":{const r=e.inputNames.find((e=>getTensor(e,t,n)!==undefined));if(r){const e=getTensor(r,t,n);return[cloneTensor(e)]}return undefined}case"Enter":{const r=getParamValue("frameName",e,t,n);const a=getParamValue("tensor",e,t,n);n.enterFrame(r);return[cloneTensor(a)]}case"Exit":{const r=getParamValue("tensor",e,t,n);n.exitFrame();return[cloneTensor(r)]}case"NextIteration":{const r=getParamValue("tensor",e,t,n);n.nextIteration();return[cloneTensor(r)]}case"TensorArrayV3":{const r=getParamValue("size",e,t,n);const a=getParamValue("dtype",e,t,n);const s=getParamValue("elementShape",e,t,n);const o=getParamValue("dynamicSize",e,t,n);const i=getParamValue("clearAfterRead",e,t,n);const u=getParamValue("identicalElementShapes",e,t,n);const l=getParamValue("name",e,t,n);const c=new TensorArray(l,a,r,s,u,o,i);n.addTensorArray(c);return[c.idTensor,scalar(1)]}case"TensorArrayWriteV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=getParamValue("index",e,t,n);const s=getParamValue("tensor",e,t,n);const o=n.getTensorArray(r.id);o.write(a,s);return[o.idTensor]}case"TensorArrayReadV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=getParamValue("index",e,t,n);const s=n.getTensorArray(r.id);return[s.read(a)]}case"TensorArrayGatherV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=getParamValue("indices",e,t,n);const s=getParamValue("dtype",e,t,n);const o=n.getTensorArray(r.id);return[o.gather(a,s)]}case"TensorArrayScatterV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=getParamValue("indices",e,t,n);const s=getParamValue("tensor",e,t,n);const o=n.getTensorArray(r.id);o.scatter(a,s);return[o.idTensor]}case"TensorArrayConcatV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=n.getTensorArray(r.id);const s=getParamValue("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=getParamValue("tensor",e,t,n);const s=getParamValue("lengths",e,t,n);const o=n.getTensorArray(r.id);o.split(s,a);return[o.idTensor]}case"TensorArraySizeV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=n.getTensorArray(r.id);return[scalar(a.size(),"int32")]}case"TensorArrayCloseV3":{const r=getParamValue("tensorArrayId",e,t,n);const a=n.getTensorArray(r.id);a.clearAndClose();return[a.idTensor]}case"TensorListSetItem":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("index",e,t,n);const s=getParamValue("tensor",e,t,n);const o=n.getTensorList(r.id);o.setItem(a,s);return[o.idTensor]}case"TensorListGetItem":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("index",e,t,n);const s=getParamValue("elementShape",e,t,n);const o=getParamValue("elementDType",e,t,n);const i=n.getTensorList(r.id);return[i.getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=getParamValue("indices",e,t,n);const a=getParamValue("tensor",e,t,n);const s=getParamValue("elementShape",e,t,n);const o=getParamValue("numElements",e,t,n);const i=scatter(a,r,s,o);n.addTensorList(i);return[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=getParamValue("elementShape",e,t,n);const a=getParamValue("elementDType",e,t,n);let s;if(e.op==="TensorListReserve"){s="numElements"}else{s="maxNumElements"}const o=getParamValue(s,e,t,n);const i=e.op==="TensorListReserve"?-1:o;const u=reserve(r,a,o,i);n.addTensorList(u);return[u.idTensor]}case"TensorListGather":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("indices",e,t,n);const s=getParamValue("elementShape",e,t,n);const o=getParamValue("elementDType",e,t,n);const i=n.getTensorList(r.id);return[i.gather(a,o,s)]}case"TensorListStack":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("elementShape",e,t,n);const s=getParamValue("elementDType",e,t,n);const o=getParamValue("numElements",e,t,n);const i=n.getTensorList(r.id);return[i.stack(a,s,o)]}case"TensorListFromTensor":{const r=getParamValue("tensor",e,t,n);const a=getParamValue("elementShape",e,t,n);const s=getParamValue("elementDType",e,t,n);const o=fromTensor(r,a,s);n.addTensorList(o);return[o.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=getParamValue("tensorListId",e,t,n);const a=n.getTensorList(r.id);const s=getParamValue("dtype",e,t,n);const o=getParamValue("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("tensor",e,t,n);const s=n.getTensorList(r.id);s.pushBack(a);return[s.idTensor]}case"TensorListPopBack":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("elementShape",e,t,n);const s=getParamValue("elementDType",e,t,n);const o=n.getTensorList(r.id);return[o.popBack(a,s)]}case"TensorListSplit":{const r=getParamValue("tensor",e,t,n);const a=getParamValue("elementShape",e,t,n);const s=getParamValue("lengths",e,t,n);const o=split$1(r,s,a);n.addTensorList(o);return[o.idTensor]}case"TensorListLength":{const r=getParamValue("tensorListId",e,t,n);const a=n.getTensorList(r.id);return[scalar(a.size(),"int32")]}case"TensorListResize":{const r=getParamValue("tensorListId",e,t,n);const a=getParamValue("size",e,t,n);const s=n.getTensorList(r.id);const o=s.resize(a);n.addTensorList(o);return[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$g=(e,t,n,r=tfOps)=>{switch(e.op){case"Conv1D":{const a=getParamValue("stride",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("dataFormat",e,t,n).toUpperCase();const i=getParamValue("dilation",e,t,n);return[r.conv1d(getParamValue("x",e,t,n),getParamValue("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=getParamValue("strides",e,t,n);const s=getPadding(e,t,n);const o=getParamValue("dataFormat",e,t,n).toUpperCase();const i=getParamValue("dilations",e,t,n);return[r.conv2d(getParamValue("x",e,t,n),getParamValue("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=fusedConvAndDepthWiseParams(e,t,n);return[r.fused.conv2d({x:getParamValue("x",e,t,n),filter:getParamValue("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=fusedConvAndDepthWiseParams(e,t,n);return[r.fused.depthwiseConv2d({x:getParamValue("x",e,t,n),filter:getParamValue("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=getParamValue("outputShape",e,t,n);const s=getParamValue("strides",e,t,n);const o=getPadding(e,t,n);return[r.conv2dTranspose(getParamValue("x",e,t,n),getParamValue("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=getParamValue("strides",e,t,n);const s=getPadding(e,t,n);const o=getParamValue("dilations",e,t,n);const i=getParamValue("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(getParamValue("input",e,t,n),getParamValue("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("dataFormat",e,t,n).toUpperCase();const i=getParamValue("dilations",e,t,n);return[r.conv3d(getParamValue("x",e,t,n),getParamValue("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("kernelSize",e,t,n);return[r.avgPool(getParamValue("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("kernelSize",e,t,n);return[r.maxPool(getParamValue("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("kernelSize",e,t,n);const i=getParamValue("includeBatchInIndex",e,t,n);const{result:u,indexes:l}=r.maxPoolWithArgmax(getParamValue("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("kernelSize",e,t,n);return[r.avgPool3d(getParamValue("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("kernelSize",e,t,n);return[r.maxPool3d(getParamValue("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=getParamValue("strides",e,t,n);const s=getParamValue("pad",e,t,n);const o=getParamValue("dilations",e,t,n);const i=a[1];const u=a[2];const l=o[1];const c=o[2];return[r.dilation2d(getParamValue("x",e,t,n),getParamValue("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$f=(e,t,n,r=tfOps)=>{switch(e.op){case"Fill":{const a=getParamValue("shape",e,t,n);const s=getParamValue("dtype",e,t,n);const o=getParamValue("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=getParamValue("start",e,t,n);const s=getParamValue("stop",e,t,n);const o=getParamValue("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=getParamValue("logits",e,t,n);const s=getParamValue("numSamples",e,t,n);const o=getParamValue("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=getParamValue("indices",e,t,n);const s=getParamValue("depth",e,t,n);const o=getParamValue("onValue",e,t,n);const i=getParamValue("offValue",e,t,n);return[r.oneHot(a,s,o,i)]}case"Ones":{return[r.ones(getParamValue("shape",e,t,n),getParamValue("dtype",e,t,n))]}case"OnesLike":{return[r.onesLike(getParamValue("x",e,t,n))]}case"RandomStandardNormal":{return[r.randomStandardNormal(getParamValue("shape",e,t,n),getParamValue("dtype",e,t,n),getParamValue("seed",e,t,n))]}case"RandomUniform":{return[r.randomUniform(getParamValue("shape",e,t,n),getParamValue("minval",e,t,n),getParamValue("maxval",e,t,n),getParamValue("dtype",e,t,n))]}case"Range":{const a=getParamValue("start",e,t,n);const s=getParamValue("stop",e,t,n);const o=getParamValue("step",e,t,n);return[r.range(a,s,o,getParamValue("dtype",e,t,n))]}case"TruncatedNormal":{const a=getParamValue("shape",e,t,n);const s=getParamValue("mean",e,t,n);const o=getParamValue("stdDev",e,t,n);const i=getParamValue("seed",e,t,n);return[r.truncatedNormal(a,s,o,getParamValue("dtype",e,t,n),i)]}case"Zeros":{return[r.zeros(getParamValue("shape",e,t,n),getParamValue("dtype",e,t,n))]}case"ZerosLike":{return[r.zerosLike(getParamValue("x",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$e=async(e,t,n,r,a=tfOps)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=nmsParams(e,t,n);const c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=nmsParams(e,t,n);const l=getParamValue("padToMaxOutputSize",e,t,n);const c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=nmsParams(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(getParamValue("condition",e,t,n),"bool");const s=[await a.whereAsync(r)];r.dispose();return s}case"ListDiff":{return a.setdiff1dAsync(getParamValue("x",e,t,n),getParamValue("y",e,t,n))}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$d=(e,t,n,r=tfOps)=>{switch(e.op){case"LowerBound":{const a=getParamValue("sortedSequence",e,t,n);const s=getParamValue("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=getParamValue("x",e,t,n);const s=getParamValue("k",e,t,n);const o=getParamValue("sorted",e,t,n);const i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=getParamValue("sortedSequence",e,t,n);const s=getParamValue("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=getParamValue("x",e,t,n);const s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=getParamValue("x",e,t,n);const s=getParamValue("axis",e,t,n);const o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$c=(e,t,n,r=tfOps)=>{switch(e.op){case"Const":{return t[e.name]}case"PlaceholderWithDefault":const a=getParamValue("default",e,t,n);return[getTensor(e.name,t,n)||a];case"Placeholder":return[getTensor(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const r=getParamValue("x",e,t,n);return[cloneTensor(r)]}case"IdentityN":return getParamValue("x",e,t,n).map((e=>cloneTensor(e)));case"Snapshot":const s=getParamValue("x",e,t,n);return[cloneTensor(s)];case"Shape":return[r.tensor1d(getParamValue("x",e,t,n).shape,"int32")];case"ShapeN":return getParamValue("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(getParamValue("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(getParamValue("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const o=getParamValue("x",e,t,n);const i=getParamValue("data",e,t,n);const u=getParamValue("message",e,t,n);const l=getParamValue("summarize",e,t,n);console.warn("The graph has a tf.print() operation,"+"usually used for debugging, which slows down performance.");console.log(u);for(let e=0;e<i.length;e++){console.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,l))}return[o];default:throw TypeError(`Node type ${e.op} is not implemented`)}};class HashTable{constructor(e,t){this.keyDType=e;this.valueDType=t;this.handle=scalar(0);this.tensorMap=new Map;keep(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose()));this.tensorMap.clear();this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return scalar(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();this.tensorMap.forEach((e=>e.dispose()));this.tensorMap.clear();return tidy((()=>{const e=unstack(t);const r=n.length;const a=e.length;assert(r===a,(()=>`The number of elements doesn't match, keys has `+`${r} elements, the values has ${a} `+`elements.`));for(let t=0;t<r;t++){const r=n[t];const a=e[t];keep(a);this.tensorMap.set(r,a)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return tidy((()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r];const s=this.findWithDefault(a,t);e.push(s)}return stack(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType){throw new Error(`Expect key dtype ${this.keyDType}, but got `+`${e.dtype}`)}if(t.dtype!==this.valueDType){throw new Error(`Expect value dtype ${this.valueDType}, but got `+`${t.dtype}`)}}}const executeOp$b=async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=getParamValue("keyDType",e,t,n);const s=getParamValue("valueDType",e,t,n);const o=new HashTable(a,s);r.addHashTable(e.name,o);return[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{const a=getParamValue("tableHandle",e,t,n,r);const s=getParamValue("keys",e,t,n);const o=getParamValue("values",e,t,n);const i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=getParamValue("tableHandle",e,t,n,r);const s=getParamValue("keys",e,t,n);const o=getParamValue("defaultValue",e,t,n);const i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=getParamValue("tableHandle",e,t,n,r);const s=r.getHashTableById(a.id);return[s.tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$a=(e,t,n,r=tfOps)=>{switch(e.op){case"ResizeBilinear":{const a=getParamValue("images",e,t,n);const s=getParamValue("size",e,t,n);const o=getParamValue("alignCorners",e,t,n);const i=getParamValue("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=getParamValue("images",e,t,n);const s=getParamValue("size",e,t,n);const o=getParamValue("alignCorners",e,t,n);const i=getParamValue("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=getParamValue("image",e,t,n);const s=getParamValue("boxes",e,t,n);const o=getParamValue("boxInd",e,t,n);const i=getParamValue("cropSize",e,t,n);const u=getParamValue("method",e,t,n);const l=getParamValue("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=getParamValue("images",e,t,n);const s=getParamValue("transforms",e,t,n);const o=getParamValue("outputShape",e,t,n);const i=getParamValue("fillValue",e,t,n);const u=getParamValue("interpolation",e,t,n);const l=getParamValue("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$9=(e,t,n,r=tfOps)=>{switch(e.op){case"Equal":{return[r.equal(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"NotEqual":{return[r.notEqual(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Greater":{return[r.greater(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"GreaterEqual":{return[r.greaterEqual(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Less":{return[r.less(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"LessEqual":{return[r.lessEqual(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"LogicalAnd":{return[r.logicalAnd(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"LogicalNot":{return[r.logicalNot(getParamValue("a",e,t,n))]}case"LogicalOr":{return[r.logicalOr(getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}case"Select":case"SelectV2":{return[r.where(getParamValue("condition",e,t,n),getParamValue("a",e,t,n),getParamValue("b",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$8=(e,t,n,r=tfOps)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(getParamValue("a",e,t,n),getParamValue("b",e,t,n),getParamValue("transposeA",e,t,n),getParamValue("transposeB",e,t,n))];case"Einsum":return[r.einsum(getParamValue("equation",e,t,n),...getParamValue("tensors",e,t,n))];case"Transpose":return[r.transpose(getParamValue("x",e,t,n),getParamValue("perm",e,t,n))];case"_FusedMatMul":const[a,s]=getParamValue("fusedOps",e,t,n);const o=a==="biasadd";const i=s==="prelu";const u=getParamValue("numArgs",e,t,n);const l=getParamValue("leakyreluAlpha",e,t,n);if(o){if(i&&u!==2){throw new Error("Fused MatMul with BiasAdd and Prelu must have two "+"extra arguments: bias and alpha.")}if(!i&&u!==1){throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}}const[c,p]=getParamValue("args",e,t,n);return[r.fused.matMul({a:getParamValue("a",e,t,n),b:getParamValue("b",e,t,n),transposeA:getParamValue("transposeA",e,t,n),transposeB:getParamValue("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$7=(e,t,n,r=tfOps)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(getParamValue("x",e,t,n),getParamValue("axis",e,t,n),getParamValue("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":{return[r.batchNorm(getParamValue("x",e,t,n),getParamValue("mean",e,t,n),getParamValue("variance",e,t,n),getParamValue("offset",e,t,n),getParamValue("scale",e,t,n),getParamValue("epsilon",e,t,n))]}case"FusedBatchNormV3":{return[r.batchNorm(getParamValue("x",e,t,n),getParamValue("mean",e,t,n),getParamValue("variance",e,t,n),getParamValue("offset",e,t,n),getParamValue("scale",e,t,n),getParamValue("epsilon",e,t,n))]}case"LRN":{return[r.localResponseNormalization(getParamValue("x",e,t,n),getParamValue("radius",e,t,n),getParamValue("bias",e,t,n),getParamValue("alpha",e,t,n),getParamValue("beta",e,t,n))]}case"Softmax":{return[r.softmax(getParamValue("x",e,t,n))]}case"LogSoftmax":{return[r.logSoftmax(getParamValue("x",e,t,n))]}case"SparseToDense":{return[r.sparseToDense(getParamValue("sparseIndices",e,t,n),getParamValue("outputShape",e,t,n),getParamValue("sparseValues",e,t,n),getParamValue("defaultValue",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$6=(e,t,n,r=tfOps)=>{switch(e.op){case"Max":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.max(getParamValue("x",e,t,n),a,s)]}case"Mean":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.mean(getParamValue("x",e,t,n),a,s)]}case"Min":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.min(getParamValue("x",e,t,n),a,s)]}case"Sum":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.sum(getParamValue("x",e,t,n),a,s)]}case"All":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.all(getParamValue("x",e,t,n),a,s)]}case"Any":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.any(getParamValue("x",e,t,n),a,s)]}case"ArgMax":{const a=getParamValue("axis",e,t,n);return[r.argMax(getParamValue("x",e,t,n),a)]}case"ArgMin":{const a=getParamValue("axis",e,t,n);return[r.argMin(getParamValue("x",e,t,n),a)]}case"Prod":{const a=getParamValue("axis",e,t,n);const s=getParamValue("keepDims",e,t,n);return[r.prod(getParamValue("x",e,t,n),a,s)]}case"Cumprod":{const a=getParamValue("axis",e,t,n);const s=getParamValue("exclusive",e,t,n);const o=getParamValue("reverse",e,t,n);return[r.cumprod(getParamValue("x",e,t,n),a,s,o)]}case"Cumsum":{const a=getParamValue("axis",e,t,n);const s=getParamValue("exclusive",e,t,n);const o=getParamValue("reverse",e,t,n);return[r.cumsum(getParamValue("x",e,t,n),a,s,o)]}case"Bincount":const a=getParamValue("x",e,t,n);const s=getParamValue("weights",e,t,n);const o=getParamValue("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=getParamValue("x",e,t,n);const s=getParamValue("weights",e,t,n);const o=getParamValue("size",e,t,n);const i=getParamValue("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$5=(e,t,n,r=tfOps)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=getParamValue("n",e,t,n);const s=getParamValue("axis",e,t,n);let o=getParamValue("tensors",e,t,n);o=o.slice(0,a);return[r.concat(o,s)]}case"Gather":{const a=getParamValue("x",e,t,n);const s=getParamValue("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=getParamValue("axis",e,t,n);const s=getParamValue("batchDims",e,t,n);const o=getParamValue("x",e,t,n);const i=getParamValue("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=getParamValue("dims",e,t,n);const s=[];for(let e=0;e<a.length;e++){if(a[e]){s.push(e)}}const o=getParamValue("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=getParamValue("axis",e,t,n);const s=getParamValue("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=getParamValue("begin",e,t,n);const s=getParamValue("size",e,t,n);return[r.slice(getParamValue("x",e,t,n),a,s)]}case"StridedSlice":{const a=getParamValue("begin",e,t,n);const s=getParamValue("end",e,t,n);const o=getParamValue("strides",e,t,n);const i=getParamValue("beginMask",e,t,n);const u=getParamValue("endMask",e,t,n);const l=getParamValue("ellipsisMask",e,t,n);const c=getParamValue("newAxisMask",e,t,n);const p=getParamValue("shrinkAxisMask",e,t,n);const m=getParamValue("x",e,t,n);return[r.stridedSlice(m,a,s,o,i,u,l,c,p)]}case"Pack":{return tidy((()=>{const a=getParamValue("axis",e,t,n);const s=getParamValue("tensors",e,t,n);const o=s[0].shape;const i=r.squeeze(s[0]).shape;const u=s.map((e=>{const t=arraysEqual(e.shape,o);if(!t&&!arraysEqual(r.squeeze(e).shape,i)){throw new Error("the input tensors shape does not match")}return t?e:r.reshape(e,o)}));return[r.stack(u,a)]}))}case"Unpack":{const a=getParamValue("axis",e,t,n);const s=getParamValue("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=getParamValue("reps",e,t,n);return[r.tile(getParamValue("x",e,t,n),a)]}case"Split":case"SplitV":{const a=getParamValue("axis",e,t,n);const s=getParamValue("numOrSizeSplits",e,t,n);const o=getParamValue("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=getParamValue("indices",e,t,n);const s=getParamValue("values",e,t,n);const o=getParamValue("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=getParamValue("x",e,t,n);const s=getParamValue("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=getParamValue("sparseIndices",e,t,n);const s=getParamValue("outputShape",e,t,n);const o=getParamValue("sparseValues",e,t,n);const i=getParamValue("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$4=(e,t,n,r=tfOps)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(getParamValue("indices",e,t,n),getParamValue("values",e,t,n),getParamValue("denseShape",e,t,n),getParamValue("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(getParamValue("inputIndices",e,t,n),getParamValue("inputShape",e,t,n),getParamValue("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":{const a=r.sparse.sparseSegmentMean(getParamValue("data",e,t,n),getParamValue("indices",e,t,n),getParamValue("segmentIds",e,t,n));return[a]}case"SparseSegmentSum":{const a=r.sparse.sparseSegmentSum(getParamValue("data",e,t,n),getParamValue("indices",e,t,n),getParamValue("segmentIds",e,t,n));return[a]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$3=(e,t,n,r=tfOps)=>{switch(e.op){case"FFT":{return[r.fft(getParamValue("x",e,t,n))]}case"IFFT":{return[r.ifft(getParamValue("x",e,t,n))]}case"RFFT":{return[r.rfft(getParamValue("x",e,t,n))]}case"IRFFT":{return[r.irfft(getParamValue("x",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$2=(e,t,n,r=tfOps)=>{switch(e.op){case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(getParamValue("data",e,t,n),getParamValue("dataSplits",e,t,n),getParamValue("separator",e,t,n),getParamValue("nGramWidths",e,t,n),getParamValue("leftPad",e,t,n),getParamValue("rightPad",e,t,n),getParamValue("padWidth",e,t,n),getParamValue("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(getParamValue("input",e,t,n),getParamValue("delimiter",e,t,n),getParamValue("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":{const a=r.string.stringToHashBucketFast(getParamValue("input",e,t,n),getParamValue("numBuckets",e,t,n));return[a]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const executeOp$1=(e,t,n,r=tfOps)=>{switch(e.op){case"Cast":{return[r.cast(getParamValue("x",e,t,n),getParamValue("dtype",e,t,n))]}case"ExpandDims":{const a=getParamValue("axis",e,t,n);return[r.expandDims(getParamValue("x",e,t,n),a)]}case"Squeeze":{const a=getParamValue("axis",e,t,n);return[r.squeeze(getParamValue("x",e,t,n),a)]}case"Reshape":{return[r.reshape(getParamValue("x",e,t,n),getParamValue("shape",e,t,n))]}case"MirrorPad":{return[r.mirrorPad(getParamValue("x",e,t,n),getParamValue("padding",e,t,n),getParamValue("mode",e,t,n))]}case"PadV2":case"Pad":{return[r.pad(getParamValue("x",e,t,n),getParamValue("padding",e,t,n),getParamValue("constantValue",e,t,n))]}case"SpaceToBatchND":{const a=getParamValue("blockShape",e,t,n);const s=getParamValue("paddings",e,t,n);return[r.spaceToBatchND(getParamValue("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=getParamValue("blockShape",e,t,n);const s=getParamValue("crops",e,t,n);return[r.batchToSpaceND(getParamValue("x",e,t,n),a,s)]}case"DepthToSpace":{const a=getParamValue("blockSize",e,t,n);const s=getParamValue("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(getParamValue("x",e,t,n),a,s)]}case"BroadcastTo":{return[r.broadcastTo(getParamValue("x",e,t,n),getParamValue("shape",e,t,n))]}case"BroadcastArgs":{return[r.broadcastArgs(getParamValue("s0",e,t,n),getParamValue("s1",e,t,n))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function executeOp(e,t,n,r,a=tidy){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>executeOp$j(e,t,n)));case"basic_math":return a((()=>executeOp$i(e,t,n)));case"control":return executeOp$h(e,t,n);case"convolution":return a((()=>executeOp$g(e,t,n)));case"creation":return a((()=>executeOp$f(e,t,n)));case"dynamic":return executeOp$e(e,t,n);case"evaluation":return a((()=>executeOp$d(e,t,n)));case"image":return a((()=>executeOp$a(e,t,n)));case"graph":return a((()=>executeOp$c(e,t,n)));case"logical":return a((()=>executeOp$9(e,t,n)));case"matrices":return a((()=>executeOp$8(e,t,n)));case"normalization":return a((()=>executeOp$7(e,t,n)));case"reduction":return a((()=>executeOp$6(e,t,n)));case"slice_join":return a((()=>executeOp$5(e,t,n)));case"sparse":return a((()=>executeOp$4(e,t,n)));case"spectral":return a((()=>executeOp$3(e,t,n)));case"string":return a((()=>executeOp$2(e,t,n)));case"transformation":return a((()=>executeOp$1(e,t,n)));case"hash_table":return executeOp$b(e,t,n,r);case"custom":const s=getRegisteredOp(e.op);if(s&&s.customExecutor){return s.customExecutor(new NodeValueImpl(e,t,n))}else{throw TypeError(`Custom op ${e.op} is not registered.`)}default:throw TypeError(`Unknown op '${e.op}'. File an issue at `+`https://github.com/tensorflow/tfjs/issues so we can add it`+`, or register a custom execution with tf.registerOp()`)}})(e,t,n);if(isPromise(s)){return s.then((e=>[].concat(e)))}return[].concat(s)}class ExecutionContext{constructor(e={},t={},n={},r={}){this.weightMap=e;this.tensorArrayMap=t;this.tensorListMap=n;this.functionMap=r;this.rootContext={id:0,frameName:"",iterationId:0};this.contexts=[this.rootContext];this.lastId=0;this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){if(this.contexts!==e){this.contexts=e;this.generateCurrentContextIds()}}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push("");this._currentContextIds=e}contextIdforContexts(e){return e?e.map((e=>e.id===0&&e.iterationId===0?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){if(this.contexts){this.lastId++;this.contexts=this.contexts.slice();this.contexts.push(this.newFrame(this.lastId,e));this._currentContextIds.unshift(this.contextIdforContexts(this.contexts))}}exitFrame(){if(this.contexts&&this.contexts.length>1){this.contexts=this.contexts.slice();this.contexts.splice(-1);this.currentContextIds.shift()}else{throw new Error("Cannot exit frame, the context is empty")}}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice();this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1;e.id=this.lastId;this.contexts.splice(-1,1,e);this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else{throw new Error("Cannot increase frame iteration, the context is empty")}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap){this.tensorArrayMap[t].clearAndClose(e)}for(const t in this.tensorListMap){this.tensorListMap[t].clearAndClose(e)}}}function getExecutionSubgraph(e,t,n,r){const a=new Set;const s=[];let o=null;let i=null;const u=new Set;const l=Object.keys(e).map((e=>parseNodeName(e)[0]));let c=[];if(r!=null){c=r.map((e=>parseNodeName(e.name)[0]))}const p=[...t];while(p.length>0){const e=p.pop();if(isControlFlow(e)||isDynamicShape(e)||isHashTable(e)){if(o==null){o=e;i=o.children.map((e=>e.name)).filter((e=>a.has(e)))}}a.add(e.name);if(n[e.name]!=null){continue}if(l.indexOf(e.name)!==-1){continue}if(c.indexOf(e.name)!==-1){continue}if(e.inputs.length===0){s.push(e.name);continue}e.inputs.forEach((e=>{if(u.has(e.name)){return}u.add(e.name);p.push(e)}))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}function getNodesInTopologicalOrder(e,t,n){const{usedNodes:r,inputs:a}=n;const s=[];const o=Object.keys(a).map((e=>parseNodeName(e)[0])).map((t=>e.nodes[t]));const i=e.initNodes;o.forEach((e=>{if(r.has(e.name)){s.push(e)}}));e.weights.forEach((e=>{if(r.has(e.name)){s.push(e)}}));if(i!=null){i.forEach((e=>{if(r.has(e.name)){s.push(e)}}))}const u=new Set;const l=[];while(s.length>0){const e=s.pop();u.add(e.name);if(!t[e.name]){l.push(e)}e.children.forEach((e=>{if(!u.has(e.name)&&r.has(e.name)&&e.inputs.every((e=>u.has(e.name)))){s.push(e)}}))}return l}const CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"];const DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];const HASH_TABLE_OPS=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function isControlFlow(e){return CONTROL_FLOW_OPS.indexOf(e.op)>=0}function isDynamicShape(e){return DYNAMIC_SHAPE_OPS.indexOf(e.op)>=0}function isHashTable(e){return HASH_TABLE_OPS.indexOf(e.op)>=0}class GraphExecutor{constructor(e,t){this.graph=e;this.parent=t;this.compiledMap=new Map;this._weightMap={};this.SEPERATOR=",";this._functions={};this._functionExecutorMap={};this.intermediateTensors={};this.keepTensorForDebug=false;this._outputs=e.outputs;this._inputs=e.inputs;this._initNodes=e.initNodes;this._signature=e.signature;this._functions=e.functions;if(e.functions!=null){Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new GraphExecutor(e.functions[t],this)}))}}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t);this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams["shape"]?e.attrParams["shape"].value:undefined,dtype:e.attrParams["dtype"]?e.attrParams["dtype"].value:undefined})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams["shape"]?e.attrParams["shape"].value:undefined,dtype:e.attrParams["dtype"]?e.attrParams["dtype"].value:undefined})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>{e[t]=this._functions[t].signature;return e}),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort();const r=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){const n=getExecutionSubgraph(e,t,this.weightMap,this._initNodes);const{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(a!=null){throw new Error(`This execution contains the node '${a.name}', which has `+`the dynamic op '${a.op}'. Please use `+`model.executeAsync() instead. Alternatively, to avoid the `+`dynamic ops, specify the inputs [${s}]`)}if(r.length>0){const n=t.map((e=>e.name));const a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs `+`[${a}]. Missing the following inputs: [${r}]`)}return getNodesInTopologicalOrder(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e);this.checkInputShapeAndType(e);t=this.mapOutputs(t);this.checkOutputs(t);const r=n.map((e=>this.graph.nodes[parseNodeName(e)[0]]));const a=t.map((e=>parseNodeName(e)[0]));let s=a.map((e=>this.graph.nodes[e]));this.resetIntermediateTensors();if(s.length===0){s=this._outputs}const o=this.getCompilationKey(r,s);let i=this.compiledMap.get(o);if(i==null){i=this.compile(e,s);this.compiledMap.set(o,i)}const u={};const l={};return tidy((()=>{const n=new ExecutionContext(this.weightMap,u,l,this.functionExecutorMap);const r=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,a]=parseNodeName(t);const s=[];s[a]=e[t];r[n]=s}));const s=this.getFrozenTensorIds(r);const o={};for(let e=0;e<i.length;e++){const t=i[e];if(!r[t.name]){const e=executeOp(t,r,n,this._resourceManager);if(isPromise(e)){throw new Error(`The execution of the op '${t.op}' returned a promise. `+`Please use model.executeAsync() instead.`)}r[t.name]=e;this.checkTensorForDisposal(t.name,t,r,n,s,a,o)}}if(this.parent==null){n.dispose(s)}return t.map((e=>getTensor(e,r,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){if(t.category==="control"||s.indexOf(e)!==-1){return}n[e].forEach((e=>{if(e!=null){o[e.id]=(o[e.id]||0)+t.children.length}}));t.inputs.forEach((e=>{if(e.category!=="control"){const s=getTensorsForCurrentContenxt(e.name,n,r);if(s!=null){s.forEach((e=>{if(e&&!e.kept&&!a.has(e.id)){const n=o[e.id];if(n===1){if(!this.keepTensorForDebug){e.dispose()}else{const[n,a]=getNodeNameAndIndex(t.name,r);if(this.intermediateTensors[n]){this.intermediateTensors[n][a]=e}else{this.intermediateTensors[n]=[];this.intermediateTensors[n][a]=e}}delete o[e.id]}else if(n!=null){o[e.id]--}}}))}}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){if(!this.intermediateTensors){return}Object.keys(this.intermediateTensors).forEach((e=>this.intermediateTensors[e].forEach((e=>e.dispose()))));this.disposeTensorsMap()}disposeTensorsMap(){if(!this.tensorsMap){return}Object.keys(this.tensorsMap).forEach((e=>{const t=this.tensorsMap[e];t.forEach((e=>{if(e&&!e.kept&&!e.isDisposed&&!this.keepIds.has(e.id)){e.dispose()}}))}))}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(const e in this.intermediateTensors){this.intermediateTensors[e].forEach((e=>e.dispose()));delete this.intermediateTensors[e]}}async _executeAsync(e,t,n=false,r={},a={}){if(!n){e=this.mapInputs(e);this.checkInputs(e);this.checkInputShapeAndType(e);t=this.mapOutputs(t);this.checkOutputs(t)}try{this.keepTensorForDebug=env().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){console.warn(e.message)}this.resetIntermediateTensors();const s=new ExecutionContext(this.weightMap,r,a,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,s,t,n);const o=t.map((e=>getTensor(e,this.tensorsMap,s)));const i=o.map((e=>e.id));const u=Object.keys(e).map((t=>e[t].id));this.keepIds=new Set([...i,...u,...this.weightIds]);if(!this.keepTensorForDebug){this.disposeTensorsMap()}if(this.parent==null){s.dispose(this.keepIds)}return o}async executeFunctionAsync(e,t,n){const r=e.reduce(((e,t,n)=>{e[this.inputs[n].name]=t;return e}),{});return this._executeAsync(r,this.outputNodes,true,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e);const s=a.map((e=>this.graph.nodes[parseNodeName(e)[0]]));const o=n.map((e=>parseNodeName(e)[0]));let i=o.map((e=>this.graph.nodes[e]));if(i.length===0){i=this._outputs}const{usedNodes:u,missingInputs:l,dynamicNode:c,syncInputs:p}=getExecutionSubgraph(e,i,this.weightMap,this._initNodes);const m=[...s,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext})));const d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=parseNodeName(t);const a=[];a[r]=e[t];d[n]=a}));const h={};const f=this.getFrozenTensorIds(d);const g={};while(m.length>0){const e=this.processStack(s,m,t,d,g,f,o,h,u);await Promise.all(e)}if(c==null&&!r){console.warn(`This model execution did not contain any nodes with control flow `+`or dynamic output shapes. You can use model.execute() instead.`)}const y=i.filter((e=>!isControlFlow(e)&&!getTensor(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";if(c!=null){e=`Alternatively, to avoid the dynamic ops, use model.execute() `+`and specify the inputs [${p}]`}throw new Error(`Cannot compute the outputs [${y}] from the provided `+`inputs [${a}]. Consider providing the following inputs: `+`[${l}]. ${e}`)}return d}processStack(e,t,n,r,a,s,o,i,u){const l=[];while(t.length>0){const e=t.pop();n.currentContext=e.contexts;let c="";if(e.node.op==="Enter"&&getParamValue("isConstant",e.node,r,n)){[c]=getNodeNameAndIndex(e.node.name,n)}if(r[e.node.name]==null){const p=executeOp(e.node,r,n,this._resourceManager);if(!c){[c]=getNodeNameAndIndex(e.node.name,n)}const m=n.currentContext;if(isPromise(p)){l.push(p.then((l=>{r[c]=l;n.currentContext=m;this.checkTensorForDisposal(c,e.node,r,n,s,o,i);this.processChildNodes(e.node,t,n,r,a,u);return l})))}else{r[c]=p;this.checkTensorForDisposal(c,e.node,r,n,s,o,i);this.processChildNodes(e.node,t,n,r,a,u)}}else{this.processChildNodes(e.node,t,n,r,a,u)}}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach((e=>{const[o]=getNodeNameAndIndex(e.name,n);if(a[o]||!s.has(e.name)){return}if(e.op==="Merge"){if(e.inputNames.some((e=>!!getTensor(e,r,n)))){a[o]=true;t.push({contexts:n.currentContext,node:e})}}else if(e.inputNames.every((e=>!!getTensor(e,r,n)))){a[o]=true;t.push({contexts:n.currentContext,node:e})}}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t];const[r]=parseNodeName(t);const a=this.graph.nodes[r];if(a.attrParams["shape"]&&a.attrParams["shape"].value){const e=a.attrParams["shape"].value;const t=e.length===n.shape.length&&n.shape.every(((t,n)=>e[n]===-1||e[n]===t));assert(t,(()=>`The shape of dict['${a.name}'] provided in `+`model.execute(dict) must be [${e}], but was `+`[${n.shape}]`))}if(a.attrParams["dtype"]&&a.attrParams["dtype"].value){assert(n.dtype===a.attrParams["dtype"].value,(()=>`The dtype of dict['${a.name}'] provided in `+`model.execute(dict) must be `+`${a.attrParams["dtype"].value}, but was ${n.dtype}`))}}))}mapInputs(e){const t={};for(const n in e){if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){const r=this._signature.inputs[n];t[r.name]=e[n]}else{t[n]=e[n]}}return t}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=parseNodeName(e);return this.graph.nodes[t]==null}));if(t.length>0){throw new Error(`The dict provided in model.execute(dict) has `+`keys: [${t}] that are not part of graph`)}}mapOutputs(e){return e.map((e=>{if(this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[e]!=null){const t=this._signature.outputs[e];return t.name}return e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=parseNodeName(e);if(!this.graph.nodes[t]){throw new Error(`The output '${e}' is not found in the graph`)}}))}}class ResourceManager{constructor(e={},t={}){this.hashTableNameToHandle=e;this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle;this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap){this.hashTableMap[e].clearAndClose();delete this.hashTableMap[e]}for(const e in this.hashTableNameToHandle){this.hashTableNameToHandle[e].dispose();delete this.hashTableNameToHandle[e]}}}class GraphModel{constructor(e,t={},n=io){this.modelUrl=e;this.loadOptions=t;this.version="n/a";this.io=n;if(t==null){this.loadOptions={}}this.resourceManager=new ResourceManager}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}findIOHandler(){const e=this.modelUrl;if(e.load!=null){this.handler=e}else if(this.loadOptions.requestInit!=null){this.handler=this.io.browserHTTPRequest(e,this.loadOptions)}else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0){t.push(this.io.browserHTTPRequest(e,this.loadOptions))}else if(t.length>1){throw new Error(`Found more than one (${t.length}) load handlers for `+`URL '${[e]}'`)}this.handler=t[0]}}load(){this.findIOHandler();if(this.handler.load==null){throw new Error("Cannot proceed with model loading because the IOHandler provided "+"does not have the `load` method implemented.")}const e=this.handler.load();if(isPromise(e)){return e.then((e=>this.loadSync(e)))}return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){const e=this.artifacts.userDefinedMetadata;if(e.signature!=null){n=e.signature}if(e.structuredOutputKeys!=null){this.structuredOutputKeys=e.structuredOutputKeys}}this.signature=n;this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const r=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(t,this.signature));this.executor.weightMap=this.convertTensorMapToTensorsMap(r);this.executor.resourceManager=this.resourceManager;if(e.modelInitializer!=null&&e.modelInitializer.node!=null){const t=OperationMapper.Instance.transformGraph(e.modelInitializer);this.initializer=new GraphExecutor(t);this.initializer.weightMap=this.executor.weightMap;this.initializer.resourceManager=this.resourceManager;this.initializer.executeAsync({},[])}return true}async save(e,t){if(typeof e==="string"){const t=this.io.getSaveHandlers(e);if(t.length===0){throw new Error(`Cannot find any save handlers for URL '${e}'`)}else if(t.length>1){throw new Error(`Found more than one (${t.length}) save handlers for `+`URL '${e}'`)}e=t[0]}if(e.save==null){throw new Error("GraphModel.save() cannot proceed because the IOHandler "+"provided does not have the `save` attribute defined.")}return e.save(this.artifacts)}predict(e,t){const n=this.execute(e,this.outputNodes);if(this.structuredOutputKeys){const e=n instanceof Tensor?[n]:n;const t={};e.forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e));return t}return n}normalizeInputs(e){if(!(e instanceof Tensor)&&!Array.isArray(e)){return e}e=Array.isArray(e)?e:[e];if(e.length!==this.inputNodes.length){throw new Error("Input tensor count mismatch,"+`the graph model has ${this.inputNodes.length} placeholders, `+`while there are ${e.length} input tensors.`)}return this.inputNodes.reduce(((t,n,r)=>{t[n]=e[r];return t}),{})}normalizeOutputs(e){e=e||this.outputNodes;return!Array.isArray(e)?[e]:e}execute(e,t){e=this.normalizeInputs(e);t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e);t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>{t[n]=[e[n]];return t}),{})}dispose(){this.executor.dispose();if(this.initializer){this.initializer.dispose()}this.resourceManager.dispose()}}async function loadGraphModel(e,t={},n=io){if(e==null){throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url "+"or an IOHandler that loads the model")}if(t==null){t={}}if(t.fromTFHub&&typeof e==="string"){e=getTFHubUrl(e)}const r=new GraphModel(e,t,n);await r.load();return r}getGlobalTensorClass().prototype.pad=function(e,t){this.throwIfDisposed();return pad(this,e,t)};getGlobalTensorClass().prototype.where=function(e,t){this.throwIfDisposed();return where(e,this,t)};getGlobalTensorClass().prototype.mul=function(e){this.throwIfDisposed();return mul(this,e)};getGlobalTensorClass().prototype.dot=function(e){this.throwIfDisposed();return dot(this,e)};getGlobalTensorClass().prototype.add=function(e){this.throwIfDisposed();return add(this,e)};const contexts={};const WEBGL_ATTRIBUTES={alpha:false,antialias:false,premultipliedAlpha:false,preserveDrawingBuffer:false,depth:false,stencil:false,failIfMajorPerformanceCaveat:true};function setWebGLContext(e,t){contexts[e]=t}function getWebGLContext(e,t){if(!(e in contexts)||t!=null){const n=getWebGLRenderingContext(e,t);if(n!==null){contexts[e]=n}else{console.log("Could not get context for WebGL version",e);return null}}const n=contexts[e];if(n==null||n.isContextLost()){delete contexts[e];return getWebGLContext(e)}n.disable(n.DEPTH_TEST);n.disable(n.STENCIL_TEST);n.disable(n.BLEND);n.disable(n.DITHER);n.disable(n.POLYGON_OFFSET_FILL);n.disable(n.SAMPLE_COVERAGE);n.enable(n.SCISSOR_TEST);n.enable(n.CULL_FACE);n.cullFace(n.BACK);return contexts[e]}function createCanvas(e){if(typeof OffscreenCanvas!=="undefined"&&e===2){return new OffscreenCanvas(300,150)}else if(typeof document!=="undefined"){return document.createElement("canvas")}else{throw new Error("Cannot create a canvas in this context")}}function getWebGLRenderingContext(e,t){if(e!==1&&e!==2){throw new Error("Cannot get WebGL rendering context, WebGL is disabled.")}const n=t==null?createCanvas(e):t;n.addEventListener("webglcontextlost",(t=>{t.preventDefault();delete contexts[e]}),false);if(e===1){return n.getContext("webgl",WEBGL_ATTRIBUTES)||n.getContext("experimental-webgl",WEBGL_ATTRIBUTES)}return n.getContext("webgl2",WEBGL_ATTRIBUTES)}var PackingScheme;(function(e){e[e["DENSE"]=0]="DENSE";e[e["SHARED_BATCH"]=1]="SHARED_BATCH"})(PackingScheme||(PackingScheme={}));var TextureUsage;(function(e){e[e["RENDER"]=0]="RENDER";e[e["UPLOAD"]=1]="UPLOAD";e[e["PIXELS"]=2]="PIXELS";e[e["DOWNLOAD"]=3]="DOWNLOAD"})(TextureUsage||(TextureUsage={}));var PhysicalTextureType;(function(e){e[e["UNPACKED_FLOAT16"]=0]="UNPACKED_FLOAT16";e[e["UNPACKED_FLOAT32"]=1]="UNPACKED_FLOAT32";e[e["PACKED_4X1_UNSIGNED_BYTE"]=2]="PACKED_4X1_UNSIGNED_BYTE";e[e["PACKED_2X2_FLOAT32"]=3]="PACKED_2X2_FLOAT32";e[e["PACKED_2X2_FLOAT16"]=4]="PACKED_2X2_FLOAT16"})(PhysicalTextureType||(PhysicalTextureType={}));function getUnpackedMatrixTextureShapeWidthHeight(e,t){return[t,e]}function getDenseTexShape(e){const t=sizeFromShape(e);const n=Math.ceil(t/4);return sizeToSquarishShape(n)}function getPackedMatrixTextureShapeWidthHeight(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function getTextureConfig(e,t){const n=e;let r;let a;let s;let o;let i;let u;let l;let c;let p;let m;if(env().getNumber("WEBGL_VERSION")===2){r=n.R32F;a=n.R16F;s=n.RGBA16F;o=n.RGBA32F;i=n.RED;l=4;c=1;p=n.HALF_FLOAT;m=n.FLOAT;u=n.RGBA8}else{r=e.RGBA;a=e.RGBA;s=e.RGBA;o=n.RGBA;i=e.RGBA;l=4;c=4;p=t!=null?t.HALF_FLOAT_OES:null;m=e.FLOAT;u=e.RGBA}return{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:m}}function callAndCheck(e,t){const n=t();if(env().getBool("DEBUG")){checkWebGLError(e)}return n}function createVertexShader$1(e,t){const n=throwIfNull(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");callAndCheck(e,(()=>e.shaderSource(n,t)));callAndCheck(e,(()=>e.compileShader(n)));if(e.getShaderParameter(n,e.COMPILE_STATUS)===false){console.log(e.getShaderInfoLog(n));throw new Error("Failed to compile vertex shader.")}return n}function createFragmentShader(e,t){const n=throwIfNull(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");callAndCheck(e,(()=>e.shaderSource(n,t)));callAndCheck(e,(()=>e.compileShader(n)));if(env().get("ENGINE_COMPILE_ONLY")){return n}if(e.getShaderParameter(n,e.COMPILE_STATUS)===false){logShaderSourceAndInfoLog(t,e.getShaderInfoLog(n));throw new Error("Failed to compile fragment shader.")}return n}function createProgram(e){return throwIfNull(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}function linkProgram(e,t){callAndCheck(e,(()=>e.linkProgram(t)));if(env().get("ENGINE_COMPILE_ONLY")){return}if(e.getProgramParameter(t,e.LINK_STATUS)===false){console.log(e.getProgramInfoLog(t));throw new Error("Failed to link vertex and fragment shaders.")}}function createStaticVertexBuffer(e,t){const n=throwIfNull(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");callAndCheck(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n)));callAndCheck(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)));return n}function createStaticIndexBuffer(e,t){const n=throwIfNull(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");callAndCheck(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)));callAndCheck(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)));return n}function createTexture(e){return throwIfNull(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}function validateTextureSize(e,t){const n=env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>n||t>n){const r=`[${e}x${t}]`;const a=`[${n}x${n}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+a+".")}}function createFramebuffer(e){return throwIfNull(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);if(i===-1){return false}callAndCheck(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r)));callAndCheck(e,(()=>e.vertexAttribPointer(i,a,e.FLOAT,false,s,o)));callAndCheck(e,(()=>e.enableVertexAttribArray(i)));return true}function bindTextureUnit(e,t,n){validateTextureUnit(e,n);callAndCheck(e,(()=>e.activeTexture(e.TEXTURE0+n)));callAndCheck(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}function getProgramUniformLocation(e,t,n){return e.getUniformLocation(t,n)}function bindTextureToProgramUniformSampler(e,t,n,r){callAndCheck(e,(()=>bindTextureUnit(e,t,r)));callAndCheck(e,(()=>e.uniform1i(n,r)))}function bindColorTextureToFramebuffer(e,t,n){callAndCheck(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n)));callAndCheck(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function throwIfNull(e,t,n){const r=callAndCheck(e,(()=>t()));if(r==null){throw new Error(n)}return r}function validateTextureUnit(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1;const r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){const e=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${e}.`)}}function getBatchDim(e,t=2){return sizeFromShape(e.slice(0,e.length-t))}function getRowsCols(e){if(e.length===0){throw Error("Cannot get rows and columns of an empty shape array.")}return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function getShapeAs3D(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;if(!n){t=[getBatchDim(e),...getRowsCols(e)]}return t}function getTextureShapeFromLogicalShape(e,t=false){let n=env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t){n=n*2;e=e.map(((t,n)=>n>=e.length-2?nearestLargerEven(e[n]):e[n]));if(e.length===1){e=[2,e[0]]}}if(e.length!==2){const t=squeezeShape(e);e=t.newShape}let r=sizeFromShape(e);if(e.length<=1&&r<=n){return[1,r]}else if(e.length===2&&e[0]<=n&&e[1]<=n){return e}else if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n){return[e[0]*e[1],e[2]]}else if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n){return[e[0],e[1]*e[2]]}else if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n){return[e[0]*e[1]*e[2],e[3]]}else if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n){return[e[0],e[1]*e[2]*e[3]]}else{if(t){const t=getBatchDim(e);let n=2,a=2;if(e.length){[n,a]=getRowsCols(e)}r=t*(n/2)*(a/2);return sizeToSquarishShape(r).map((e=>e*2))}return sizeToSquarishShape(r)}}function isEven(e){return e%2===0}function isReshapeFree(e,t){e=e.slice(-2);t=t.slice(-2);if(arraysEqual(e,t)){return true}if(!e.length||!t.length){return true}if(e[0]===0||e[1]===0||t[0]===0||t[1]===0){return true}if(e.length!==t.length){const n=e.slice(-1)[0];const r=t.slice(-1)[0];if(n===r){return true}if(isEven(n)&&isEven(r)&&(e[0]===1||t[0]===1)){return true}}return e[1]===t[1]&&isEven(e[0])&&isEven(t[0])}let MAX_TEXTURE_SIZE;let MAX_TEXTURES_IN_SHADER;function getWebGLMaxTextureSize(e){if(MAX_TEXTURE_SIZE==null){const t=getWebGLContext(e);MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE)}return MAX_TEXTURE_SIZE}function getMaxTexturesInShader(e){if(MAX_TEXTURES_IN_SHADER==null){const t=getWebGLContext(e);MAX_TEXTURES_IN_SHADER=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,MAX_TEXTURES_IN_SHADER)}function hasExtension(e,t){const n=e.getExtension(t);return n!=null}function isWebGLVersionEnabled(e){try{const t=getWebGLContext(e);if(t!=null){return true}}catch(e){console.log("Error when getting WebGL context: ",e);return false}return false}function isCapableOfRenderingToFloatTexture(e){if(e===0){return false}const t=getWebGLContext(e);if(e===1){if(!hasExtension(t,"OES_texture_float")){return false}}else{if(!hasExtension(t,"EXT_color_buffer_float")){return false}}const n=createFloatTextureAndBindToFramebuffer(t);return n}function createFloatTextureAndBindToFramebuffer(e){const t=getTextureConfig(e);const n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);const r=1;const a=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,r,a,0,t.textureFormatFloat,t.textureTypeFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s);e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;e.bindTexture(e.TEXTURE_2D,null);e.bindFramebuffer(e.FRAMEBUFFER,null);e.deleteTexture(n);e.deleteFramebuffer(s);return o}function isWebGLFenceEnabled(e){if(e!==2){return false}const t=getWebGLContext(e);const n=t.fenceSync!=null;return n}const ENV=env();ENV.registerFlag("HAS_WEBGL",(()=>ENV.getNumber("WEBGL_VERSION")>0));ENV.registerFlag("WEBGL_VERSION",(()=>{if(isWebGLVersionEnabled(2)){return 2}else if(isWebGLVersionEnabled(1)){return 1}return 0}));ENV.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>false));ENV.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>ENV.get("WEBGL_VERSION")===2));ENV.registerFlag("WEBGL_CPU_FORWARD",(()=>true));ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>false));ENV.registerFlag("WEBGL_PACK",(()=>ENV.getBool("HAS_WEBGL")));ENV.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_CLIP",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_PACK_REDUCE",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_LAZILY_UNPACK",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_CONV_IM2COL",(()=>ENV.getBool("WEBGL_PACK")));ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>getWebGLMaxTextureSize(ENV.getNumber("WEBGL_VERSION"))));ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>getMaxTexturesInShader(ENV.getNumber("WEBGL_VERSION"))));ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=ENV.getNumber("WEBGL_VERSION");if(e===0){return 0}return getWebGLDisjointQueryTimerVersion(e)}));ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!isMobile()));ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>isCapableOfRenderingToFloatTexture(ENV.getNumber("WEBGL_VERSION"))));ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>ENV.getBool("WEBGL_FORCE_F16_TEXTURES")?false:ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")));ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>isDownloadFloatTextureEnabled(ENV.getNumber("WEBGL_VERSION"))));ENV.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>isWebGLFenceEnabled(ENV.getNumber("WEBGL_VERSION"))));ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>{const e=ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0}));ENV.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if(e<0&&e!==-1){throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never `+`delete) or at least 0, but got ${e}.`)}}));ENV.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>isMobile()?1:-1),(e=>{if(e<0&&e!==-1){throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never `+`manual flush) or at least 0, but got ${e}.`)}}));ENV.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128));ENV.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>false));ENV.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5));ENV.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128));function getGlslDifferences(){let e;let t;let n;let r;let a;let s;let o;let i;let u;let l;if(env().getNumber("WEBGL_VERSION")===2){e="#version 300 es";t="in";n="out";r="in";a="texture";s="outputColor";o="out vec4 outputColor;";i=`\n      bool isnan_custom(float val) {\n        uint floatToUint = floatBitsToUint(val);\n        return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n      }\n\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan_custom(val.x),\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n      }\n\n      #define isnan(value) isnan_custom(value)\n    `;u=``;l=`\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    `}else{e="";t="attribute";n="varying";r="varying";a="texture2D";s="gl_FragColor";o="";i=`\n      #define isnan(value) isnan_custom(value)\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n      }\n    `;u=`\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    `;l=`\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    `}return{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function getLogicalCoordinatesFromFlatIndex(e,t,n="index"){const r=computeStrides(t);return r.map(((t,a)=>{const s=`int ${e[a]} = ${n} / ${t}`;const o=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`;return`${s}; ${o};`})).join("")}function getOutputLogicalCoordinatesFromFlatIndexByUniform(e,t,n="index"){const r=computeStrides(t);return r.map(((t,a)=>{const s=`int ${e[a]} = ${n} / outShapeStrides[${a}]`;const o=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${s}; ${o};`})).join("")}function symbolicallyComputeStrides(e,t){const n=e.length;const r=e.map((e=>`${t}[${e}]`));const a=new Array(n-1);a[n-2]=r[n-1];for(let e=n-3;e>=0;--e){a[e]=`(${a[e+1]} * ${r[e+1]})`}return a}function getLogicalCoordinatesFromFlatIndexByUniform(e,t,n="index"){const r=e.map(((e,t)=>t));const a=symbolicallyComputeStrides(r,t);return a.map(((t,r)=>{const s=`int ${e[r]} = ${n} / ${a[r]}`;const o=r===a.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${a[r]}`:`index -= ${e[r]} * ${a[r]}`;return`${s}; ${o};`})).join("")}function getFlatIndexFrom3D(e){const t=computeStrides(e).map((e=>e.toString()));return`\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n  }\n`}function getFlatIndexFrom3DOutput(){return`\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n  }\n`}const ENCODE_FLOAT_SNIPPET=`\n  const float FLOAT_MAX = 1.70141184e38;\n  const float FLOAT_MIN = 1.17549435e-38;\n\n  lowp vec4 encode_float(highp float v) {\n    if (isnan(v)) {\n      return vec4(255, 255, 255, 255);\n    }\n\n    highp float av = abs(v);\n\n    if(av < FLOAT_MIN) {\n      return vec4(0.0, 0.0, 0.0, 0.0);\n    } else if(v > FLOAT_MAX) {\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n    } else if(v < -FLOAT_MAX) {\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n    }\n\n    highp vec4 c = vec4(0,0,0,0);\n\n    highp float e = floor(log2(av));\n    highp float m = exp2(fract(log2(av))) - 1.0;\n\n    c[2] = floor(128.0 * m);\n    m -= c[2] / 128.0;\n    c[1] = floor(32768.0 * m);\n    m -= c[1] / 32768.0;\n    c[0] = floor(8388608.0 * m);\n\n    highp float ebias = e + 127.0;\n    c[3] = floor(ebias / 2.0);\n    ebias -= c[3] * 2.0;\n    c[2] += floor(ebias) * 128.0;\n\n    c[3] += 128.0 * step(0.0, -v);\n\n    return c / 255.0;\n  }\n`;const{getBroadcastDims:getBroadcastDims}=backend_util;function makeShader(e,t,n){const r=[];e.forEach((e=>{const t=sizeFromShape(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform){r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`)}else{r.push(`uniform sampler2D ${e.name};`);r.push(`uniform int offset${e.name};`)}if(n.enableShapeUniforms){const{uniformShape:t}=getUniformInfoFromShape(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`);break}r.push(`uniform ivec2 ${e.name}TexShape;`)}}));if(n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push(`uniform int outShape;`);break;case 2:r.push(`uniform ivec2 outShape;`);r.push(`uniform int outShapeStrides;`);break;case 3:r.push(`uniform ivec3 outShape;`);r.push(`uniform ivec2 outShapeStrides;`);break;case 4:r.push(`uniform ivec4 outShape;`);r.push(`uniform ivec3 outShapeStrides;`);break}r.push(`uniform ivec2 outTexShape;`)}if(n.customUniforms){n.customUniforms.forEach((e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}))}const a=r.join("\n");const s=e.map((e=>getInputSamplingSnippet(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n");const o=t.texShape;const i=getGlslDifferences();const u=getFloatTextureSampleSnippet(i);let l;let c;let p=getShaderPrefix(i);if(t.isPacked){l=getPackedOutputSamplingSnippet(t.logicalShape,o,n.enableShapeUniforms);c=getFloatTextureSetRGBASnippet(i)}else{l=getOutputSamplingSnippet(t.logicalShape,o,n.enableShapeUniforms);c=getFloatTextureSetRSnippet(i)}if(n.packedInputs){p+=SHADER_PACKED_PREFIX}const m=[p,u,c,a,l,s,n.userCode].join("\n");return m}function getSamplerFromInInfo(e,t=false){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return getSamplerScalar(e,t);case 1:return getSampler1D(e,t);case 2:return getSampler2D(e,t);case 3:return getSampler3D(e,t);case 4:return getSampler4D(e,t);case 5:return getSampler5D(e);case 6:return getSampler6D(e);default:throw new Error(`${n.length}-D input sampling`+` is not yet supported`)}}function getPackedSamplerFromInInfo(e,t){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return getPackedSamplerScalar(e);case 1:return getPackedSampler1D(e,t);case 2:return getPackedSampler2D(e,t);case 3:return getPackedSampler3D(e,t);default:return getPackedSamplerND(e,t)}}function getInputSamplingSnippet(e,t,n=false,r){let a="";if(n){a+=getPackedSamplerFromInInfo(e,r)}else{a+=getSamplerFromInInfo(e,r)}const s=e.shapeInfo.logicalShape;const o=t.logicalShape;if(s.length<=o.length){if(n){a+=getPackedSamplerAtOutputCoords(e,t)}else{a+=getSamplerAtOutputCoords(e,t)}}return a}function getPackedOutputSamplingSnippet(e,t,n){switch(e.length){case 0:return getOutputScalarCoords();case 1:return getOutputPacked1DCoords(e,t,n);case 2:return getOutputPacked2DCoords(e,t,n);case 3:return getOutputPacked3DCoords(e,t,n);default:return getOutputPackedNDCoords(e,t,n)}}function getOutputSamplingSnippet(e,t,n){switch(e.length){case 0:return getOutputScalarCoords();case 1:return getOutput1DCoords(e,t,n);case 2:return getOutput2DCoords(e,t,n);case 3:return getOutput3DCoords(e,t,n);case 4:return getOutput4DCoords(e,t,n);case 5:return getOutput5DCoords(e,t);case 6:return getOutput6DCoords(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function getFloatTextureSampleSnippet(e){return`\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return ${e.texture2D}(textureSampler, uv).r;\n    }\n  `}function getFloatTextureSetRSnippet(e){return`\n    void setOutput(float val) {\n      ${e.output} = vec4(val, 0, 0, 0);\n    }\n  `}function getFloatTextureSetRGBASnippet(e){return`\n    void setOutput(vec4 val) {\n      ${e.output} = val;\n    }\n  `}function getShaderPrefix(e){const t=`${e.version}\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    ${e.varyingFs} vec2 resultUV;\n    ${e.defineOutput}\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    ${e.defineSpecialNaN}\n    ${e.defineSpecialInf}\n    ${e.defineRound}\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    ${SAMPLE_1D_SNIPPET}\n    ${SAMPLE_2D_SNIPPET}\n    ${SAMPLE_3D_SNIPPET}\n  `;return t}const SAMPLE_1D_SNIPPET=`\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n  int texelIndex = index / 2;\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;const SAMPLE_2D_SNIPPET=`\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n  int texNumC, int row, int col) {\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;const SAMPLE_3D_SNIPPET=`\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n    int texelsInBatch, int texelsInLogicalRow, int b,\n    int row, int col) {\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;const SHADER_PACKED_PREFIX=`\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n`;function getOutputPacked3DCoords(e,t,n){if(n){return`\n    ivec3 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n      int b = index / texelsInBatch;\n      index -= b * texelsInBatch;\n\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec3(b, r, c);\n    }\n  `}const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];const a=Math.ceil(e[2]/2);const s=a*Math.ceil(e[1]/2);return`\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${r[0]}, ${r[1]}));\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n      int b = index / ${s};\n      index -= b * ${s};\n\n      int r = 2 * (index / ${a});\n      int c = imod(index, ${a}) * 2;\n\n      return ivec3(b, r, c);\n    }\n  `}function getOutputPackedNDCoords(e,t,n){if(n){return`\n    ivec4 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n      int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n      int texelsInBatchN = texelsInBatch * outShape[1];\n\n      int b2 = index / texelsInBatchN;\n      index -= b2 * texelsInBatchN;\n\n      int b = index / texelsInBatch;\n      index -= b * texelsInBatch;\n\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec4(b2, b, r, c);\n    }\n  `}const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];const a=Math.ceil(e[e.length-1]/2);const s=a*Math.ceil(e[e.length-2]/2);let o=s;let i=``;let u="b, r, c";for(let t=2;t<e.length-1;t++){o*=e[e.length-t-1];i=`\n      int b${t} = index / ${o};\n      index -= b${t} * ${o};\n    `+i;u=`b${t}, `+u}return`\n    ivec${e.length} getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${r[0]}, ${r[1]}));\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n      ${i}\n\n      int b = index / ${s};\n      index -= b * ${s};\n\n      int r = 2 * (index / ${a});\n      int c = imod(index, ${a}) * 2;\n\n      return ivec${e.length}(${u});\n    }\n  `}function getOutputPacked2DCoords(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(arraysEqual(e,t)){if(n){return`\n      ivec2 getOutputCoords() {\n        ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n        return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n      }\n    `}return`\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n      }\n    `}const a=Math.ceil(e[1]/2);if(n){return`\n    ivec2 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec2(r, c);\n    }\n  `}return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${r[0]}, ${r[1]}));\n\n      int index = resTexRC.x * ${r[1]} + resTexRC.y;\n      int r = 2 * (index / ${a});\n      int c = imod(index, ${a}) * 2;\n\n      return ivec2(r, c);\n    }\n  `}function getOutput2DCoords(e,t,n){if(arraysEqual(e,t)){if(n){return`\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n      }\n    `}return`\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n      }\n    `}if(e[1]===1){if(n){return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(outTexShape[0], outTexShape[1]));\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    `}return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    `}if(e[0]===1){if(n){return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(outTexShape[0], outTexShape[1]));\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n        return ivec2(0, index);\n      }\n    `}return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(0, index);\n      }\n    `}if(n){return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(outTexShape[0], outTexShape[1]));\n      int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n      int r = index / outShape[1];\n      int c = index - r * outShape[1];\n      return ivec2(r, c);\n    }\n  `}return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      int r = index / ${e[1]};\n      int c = index - r * ${e[1]};\n      return ivec2(r, c);\n    }\n  `}function getFlatOffsetUniformName(e){return`offset${e}`}function getPackedSampler1D(e,t){const n=e.name;const r="get"+n.charAt(0).toUpperCase()+n.slice(1);const a=e.shapeInfo.texShape;const s=getGlslDifferences();if(t){return`\n    vec4 ${r}(int index) {\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n      vec2 uv = packedUVfrom1D(\n        packedTexShape[0], packedTexShape[1], index);\n      return ${s.texture2D}(${n}, uv);\n    }\n  `}const o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n    vec4 ${r}(int index) {\n      vec2 uv = packedUVfrom1D(\n        ${o[0]}, ${o[1]}, index);\n      return ${s.texture2D}(${n}, uv);\n    }\n  `}function getSampler1D(e,t){const n=e.name;const r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform){return`\n      float ${r}(int index) {\n        ${getUniformSampler(e)}\n      }\n    `}const a=e.shapeInfo.texShape;const s=a[0];const o=a[1];if(o===1&&s===1){return`\n      float ${r}(int index) {\n        return sampleTexture(${n}, halfCR);\n      }\n    `}const i=getFlatOffsetUniformName(n);if(o===1){if(t){return`\n      float ${r}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));\n        return sampleTexture(${n}, uv);\n      }\n    `}return`\n      float ${r}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `}if(s===1){if(t){return`\n      float ${r}(int index) {\n        vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);\n        return sampleTexture(${n}, uv);\n      }\n    `}return`\n      float ${r}(int index) {\n        vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);\n        return sampleTexture(${n}, uv);\n      }\n    `}if(t){return`\n    float ${r}(int index) {\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});\n      return sampleTexture(${n}, uv);\n    }\n  `}return`\n    float ${r}(int index) {\n      vec2 uv = uvFromFlat(${s}, ${o}, index + ${i});\n      return sampleTexture(${n}, uv);\n    }\n  `}function getPackedSampler2D(e,t){const n=e.shapeInfo.logicalShape;const r=e.name;const a="get"+r.charAt(0).toUpperCase()+r.slice(1);const s=e.shapeInfo.texShape;const o=s[0];const i=s[1];const u=getGlslDifferences();if(s!=null&&arraysEqual(n,s)){if(t){return`\n      vec4 ${a}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n\n        return ${u.texture2D}(${r}, uv);\n      }\n    `}return`\n      vec4 ${a}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);\n\n        return ${u.texture2D}(${r}, uv);\n      }\n    `}if(t){return`\n    vec4 ${a}(int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n      return ${u.texture2D}(${r}, uv);\n    }\n  `}const l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];const c=Math.ceil(n[1]/2);return`\n    vec4 ${a}(int row, int col) {\n      vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);\n      return ${u.texture2D}(${r}, uv);\n    }\n  `}function getSampler2D(e,t){const n=e.shapeInfo.logicalShape;const r=e.name;const a="get"+r.charAt(0).toUpperCase()+r.slice(1);const s=e.shapeInfo.texShape;if(s!=null&&arraysEqual(n,s)){if(t){return`\n      float ${a}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n        return sampleTexture(${r}, uv);\n      }\n    `}const e=s[0];const n=s[1];return`\n    float ${a}(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}.0, ${e}.0);\n      return sampleTexture(${r}, uv);\n    }\n  `}const{newShape:o,keptDims:i}=squeezeShape(n);const u=o;if(u.length<n.length){const n=squeezeInputInfo(e,u);const r=["row","col"];return`\n      ${getSamplerFromInInfo(n,t)}\n      float ${a}(int row, int col) {\n        return ${a}(${getSqueezedParams(r,i)});\n      }\n    `}if(e.shapeInfo.isUniform){return`\n      float ${a}(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n        ${getUniformSampler(e)}\n      }\n    `}const l=s[0];const c=s[1];const p=getFlatOffsetUniformName(r);if(c===1){if(t){return`\n      float ${a}(int row, int col) {\n        float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n        vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\n        return sampleTexture(${r}, uv);\n      }\n    `}return`\n    float ${a}(int row, int col) {\n      float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\n      return sampleTexture(${r}, uv);\n    }\n  `}if(l===1){if(t){return`\n      float ${a}(int row, int col) {\n        float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n        vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\n        return sampleTexture(${r}, uv);\n      }\n    `}return`\n    float ${a}(int row, int col) {\n      float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n      vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n      return sampleTexture(${r}, uv);\n    }\n  `}if(t){return`\n      float ${a}(int row, int col) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ${r}Shape[1] + col + ${p};\n        vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n        return sampleTexture(${r}, uv);\n      }\n    `}return`\n  float ${a}(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * ${n[1]} + col + ${p};\n    vec2 uv = uvFromFlat(${l}, ${c}, index);\n    return sampleTexture(${r}, uv);\n  }\n`}function getPackedSampler3D(e,t){const n=e.shapeInfo.logicalShape;const r=e.name;const a="get"+r.charAt(0).toUpperCase()+r.slice(1);const s=e.shapeInfo.texShape;const o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(n[0]===1){const r=n.slice(1);const s=[1,2];const o=squeezeInputInfo(e,r);const i=["b","row","col"];return`\n        ${getPackedSamplerFromInInfo(o,t)}\n        vec4 ${a}(int b, int row, int col) {\n          return ${a}(${getSqueezedParams(i,s)});\n        }\n      `}const i=getGlslDifferences();if(t){return`\n    vec4 ${a}(int b, int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom3D(\n        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n      return ${i.texture2D}(${r}, uv);\n    }\n  `}const u=o[0];const l=o[1];const c=Math.ceil(n[2]/2);const p=c*Math.ceil(n[1]/2);return`\n    vec4 ${a}(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        ${u}, ${l}, ${p}, ${c}, b, row, col);\n      return ${i.texture2D}(${r}, uv);\n    }\n  `}function getSampler3D(e,t){const n=e.shapeInfo.logicalShape;const r=e.name;const a="get"+r.charAt(0).toUpperCase()+r.slice(1);const s=n[1]*n[2];const o=n[2];const{newShape:i,keptDims:u}=squeezeShape(n);const l=i;if(l.length<n.length){const n=squeezeInputInfo(e,l);const r=["row","col","depth"];return`\n        ${getSamplerFromInInfo(n,t)}\n        float ${a}(int row, int col, int depth) {\n          return ${a}(${getSqueezedParams(r,u)});\n        }\n      `}if(e.shapeInfo.isUniform){return`\n      float ${a}(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3(${s}, ${o}, 1)));\n        ${getUniformSampler(e)}\n      }\n    `}const c=e.shapeInfo.texShape;const p=c[0];const m=c[1];const d=e.shapeInfo.flatOffset;if(m===s&&d==null){if(t){return`\n      float ${a}(int row, int col, int depth) {\n        int stride1 = ${r}Shape[2];\n        float texR = float(row);\n        float texC = dot(vec2(col, depth), vec2(stride1, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${r}TexShape[1], ${r}TexShape[0]);\n        return sampleTexture(${r}, uv);\n      }\n    `}return`\n        float ${a}(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2(${o}, 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2(${m}.0, ${p}.0);\n          return sampleTexture(${r}, uv);\n        }\n      `}if(m===o&&d==null){if(t){return`\n      float ${a}(int row, int col, int depth) {\n        float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\n        float texC = float(depth);\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n        return sampleTexture(${r}, uv);\n      }\n    `}return`\n    float ${a}(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${p}.0);\n      return sampleTexture(${r}, uv);\n    }\n  `}const h=getFlatOffsetUniformName(r);if(t){return`\n    float ${a}(int row, int col, int depth) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int stride0 = ${r}Shape[1] * ${r}Shape[2];\n      int stride1 = ${r}Shape[2];\n      int index = row * ${s} + col * ${o} + depth + ${h};\n      vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n      return sampleTexture(${r}, uv);\n    }\n    `}return`\n      float ${a}(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ${s} + col * ${o} + depth + ${h};\n        vec2 uv = uvFromFlat(${p}, ${m}, index);\n        return sampleTexture(${r}, uv);\n      }\n  `}function getPackedSamplerND(e,t){const n=e.name;const r="get"+n.charAt(0).toUpperCase()+n.slice(1);const a=getGlslDifferences();if(t){return`\n    vec4 ${r}(int b2, int b, int row, int col) {\n      int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n      texelsInBatch *= ${n}Shape[1];\n      index = b2 * texelsInBatch + index;\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n      int texR = index / packedTexShape[1];\n      int texC = index - texR * packedTexShape[1];\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${a.texture2D}(${n}, uv);\n    }\n  `}const s=e.shapeInfo.logicalShape;const o=s.length;const i=e.shapeInfo.texShape;const u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];const l=u[0];const c=u[1];const p=Math.ceil(s[o-1]/2);let m=p*Math.ceil(s[o-2]/2);let d=`int b, int row, int col`;let h=`b * ${m} + (row / 2) * ${p} + (col / 2)`;for(let e=2;e<o-1;e++){d=`int b${e}, `+d;m*=s[o-e-1];h=`b${e} * ${m} + `+h}return`\n    vec4 ${r}(${d}) {\n      int index = ${h};\n      int texR = index / ${c};\n      int texC = index - texR * ${c};\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\n      return ${a.texture2D}(${n}, uv);\n    }\n  `}function getPackedSamplerAtOutputCoords(e,t){const n=e.name;const r=n.charAt(0).toUpperCase()+n.slice(1);const a="get"+r+"AtOutCoords";const s=e.shapeInfo.logicalShape.length;const o=t.logicalShape.length;const i=getBroadcastDims(e.shapeInfo.logicalShape,t.logicalShape);const u=getCoordsDataType(o);const l=o-s;let c;const p=["x","y","z","w","u","v"];if(s===0){c=""}else if(o<2&&i.length>=1){c="coords = 0;"}else{c=i.map((e=>`coords.${p[e+l]} = 0;`)).join("\n")}let m="";if(o<2&&s>0){m="coords"}else{m=e.shapeInfo.logicalShape.map(((e,t)=>`coords.${p[t+l]}`)).join(", ")}let d=`return outputValue;`;const h=sizeFromShape(e.shapeInfo.logicalShape);const f=h===1;const g=sizeFromShape(t.logicalShape);const y=g===1;if(s===1&&!f&&!y){d=`\n      return vec4(outputValue.xy, outputValue.xy);\n    `}else if(f&&!y){if(o===1){d=`\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      `}else{d=`\n        return vec4(outputValue.x);\n      `}}else if(i.length){const e=s-2;const t=s-1;if(i.indexOf(e)>-1&&i.indexOf(t)>-1){d=`return vec4(outputValue.x);`}else if(i.indexOf(e)>-1){d=`return vec4(outputValue.x, outputValue.y, `+`outputValue.x, outputValue.y);`}else if(i.indexOf(t)>-1){d=`return vec4(outputValue.xx, outputValue.zz);`}}return`\n    vec4 ${a}() {\n      ${u} coords = getOutputCoords();\n      ${c}\n      vec4 outputValue = get${r}(${m});\n      ${d}\n    }\n  `}function getSamplerAtOutputCoords(e,t){const n=e.name;const r=n.charAt(0).toUpperCase()+n.slice(1);const a="get"+r+"AtOutCoords";const s=t.texShape;const o=e.shapeInfo.texShape;const i=e.shapeInfo.logicalShape.length;const u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===u&&e.shapeInfo.flatOffset==null&&arraysEqual(o,s)){return`\n      float ${a}() {\n        return sampleTexture(${n}, resultUV);\n      }\n    `}const l=getCoordsDataType(u);const c=getBroadcastDims(e.shapeInfo.logicalShape,t.logicalShape);const p=u-i;let m;const d=["x","y","z","w","u","v"];if(i===0){m=""}else if(u<2&&c.length>=1){m="coords = 0;"}else{m=c.map((e=>`coords.${d[e+p]} = 0;`)).join("\n")}let h="";if(u<2&&i>0){h="coords"}else{h=e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+p]}`)).join(", ")}return`\n    float ${a}() {\n      ${l} coords = getOutputCoords();\n      ${m}\n      return get${r}(${h});\n    }\n  `}function getCoordsDataType(e){if(e<=1){return"int"}else if(e===2){return"ivec2"}else if(e===3){return"ivec3"}else if(e===4){return"ivec4"}else if(e===5){return"ivec5"}else if(e===6){return"ivec6"}else{throw Error(`GPU for rank ${e} is not yet supported`)}}function getUniformInfoFromShape(e,t,n){const{newShape:r,keptDims:a}=squeezeShape(t);const s=t.length;const o=e&&s===3&&t[0]===1;const i=o?t.slice(1):r;const u=!e&&s>1&&!arraysEqual(t,n)&&r.length<s||o;const l=u?i:t;return{useSqueezeShape:u,uniformShape:l,keptDims:a}}function squeezeInputInfo(e,t){const n=JSON.parse(JSON.stringify(e));n.shapeInfo.logicalShape=t;return n}function getSqueezedParams(e,t){return t.map((t=>e[t])).join(", ")}function compileProgram(e,t,n,r){const a=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:e.isUniform?false:e.texData.isPacked,flatOffset:null};if(e.texData!=null&&e.texData.slice!=null&&e.texData.slice.flatOffset>0){r.flatOffset=e.texData.slice.flatOffset}return{name:t.variableNames[n],shapeInfo:r}}));const s=a.map((e=>e.shapeInfo));const o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:false,isPacked:r.texData.isPacked,flatOffset:null};const i=makeShader(a,o,t);const u=createFragmentShader(e.gl,i);const l=e.createProgram(u);if(!env().get("ENGINE_COMPILE_ONLY")){return Object.assign({program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},getUniformLocations(e,t,l))}else{return{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}}}function getUniformLocations(e,t,n){const r={};const a={};const s={};const o=[];let i;let u;let l;let c=null;let p=null;p=e.getUniformLocation(n,"NAN",false);if(env().getNumber("WEBGL_VERSION")===1){c=e.getUniformLocation(n,"INFINITY",false)}const m=false;for(let o=0;o<t.variableNames.length;o++){const i=t.variableNames[o];r[i]=e.getUniformLocation(n,i,m);r[`offset${i}`]=e.getUniformLocation(n,`offset${i}`,m);if(t.enableShapeUniforms){a[`${i}Shape`]=e.getUniformLocation(n,`${i}Shape`,m);s[`${i}TexShape`]=e.getUniformLocation(n,`${i}TexShape`,m)}}if(t.enableShapeUniforms){i=e.getUniformLocation(n,"outShape",m);l=e.getUniformLocation(n,"outShapeStrides",m);u=e.getUniformLocation(n,"outTexShape",m)}if(t.customUniforms){t.customUniforms.forEach(((t,r)=>{o[r]=e.getUniformLocation(n,t.name,m)}))}return{uniformLocations:r,customUniformLocations:o,infLoc:c,nanLoc:p,inShapesLocations:a,inTexShapesLocations:s,outShapeLocation:i,outShapeStridesLocation:l,outTexShapeLocation:u}}function validateBinaryAndProgram(e,t){if(e.length!==t.length){throw Error(`Binary was compiled with ${e.length} inputs, but `+`was executed with ${t.length} inputs`)}e.forEach(((e,n)=>{const r=e.logicalShape;const a=t[n];const s=a.shape;if(!arraysEqual(r,s)){throw Error(`Binary was compiled with different shapes than `+`the current args. Shapes ${r} and ${s} must match`)}if(e.isUniform&&a.isUniform){return}const o=e.texShape;const i=a.isUniform?null:a.texData.texShape;if(!arraysEqual(o,i)){throw Error(`Binary was compiled with different texture shapes than the`+` current args. Shape ${o} and ${i} must match`)}}))}function runProgram(e,t,n,r,a){if(!t.program.enableShapeUniforms){validateBinaryAndProgram(t.inShapeInfos,n);validateBinaryAndProgram([t.outShapeInfo],[r])}const s=r.texData.texture;const o=r.texData.texShape;if(r.texData.isPacked){e.setOutputPackedMatrixTexture(s.texture,o[0],o[1])}else{e.setOutputMatrixTexture(s.texture,o[0],o[1])}e.setProgram(t.webGLProgram);if(env().getNumber("WEBGL_VERSION")===1){if(t.infLoc!==null){e.gl.uniform1f(t.infLoc,Infinity)}}if(t.nanLoc!==null){e.gl.uniform1f(t.nanLoc,NaN)}n.forEach(((n,r)=>{const a=t.program.variableNames[r];const s=t.uniformLocations[a];const o=t.uniformLocations[`offset${a}`];const i=t.inShapesLocations[`${a}Shape`];const u=t.inTexShapesLocations[`${a}TexShape`];if(i){const{uniformShape:r}=getUniformInfoFromShape(t.program.packedInputs,n.shape,n.texData.texShape);switch(r.length){case 1:e.gl.uniform1iv(i,new Int32Array(r));break;case 2:e.gl.uniform2iv(i,new Int32Array(r));break;case 3:e.gl.uniform3iv(i,new Int32Array(r));break;case 4:e.gl.uniform4iv(i,new Int32Array(r));break}}if(u){e.gl.uniform2i(u,n.texData.texShape[0],n.texData.texShape[1])}if(s==null){return}if(n.isUniform){if(sizeFromShape(n.shape)<2){e.gl.uniform1f(s,n.uniformValues[0])}else{let t=n.uniformValues;if(!(t instanceof Float32Array)){t=new Float32Array(t)}e.gl.uniform1fv(s,t)}return}if(n.texData.slice!=null&&o!=null){e.gl.uniform1i(o,n.texData.slice.flatOffset)}e.setInputMatrixTexture(n.texData.texture.texture,s,r)}));const i=t.outShapeLocation;if(i){switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape));break}}if(t.outShapeStridesLocation){const n=computeStrides(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n));break}}if(t.outTexShapeLocation){e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1])}if(t.program.customUniforms&&a){t.program.customUniforms.forEach(((n,r)=>{const s=t.customUniformLocations[r];const o=a[r];if(n.type==="float"){e.gl.uniform1fv(s,o)}else if(n.type==="vec2"){e.gl.uniform2fv(s,o)}else if(n.type==="vec3"){e.gl.uniform3fv(s,o)}else if(n.type==="vec4"){e.gl.uniform4fv(s,o)}else if(n.type==="int"){e.gl.uniform1iv(s,o)}else if(n.type==="ivec2"){e.gl.uniform2iv(s,o)}else if(n.type==="ivec3"){e.gl.uniform3iv(s,o)}else if(n.type==="ivec4"){e.gl.uniform4iv(s,o)}else{throw Error(`uniform type ${n.type} is not supported yet.`)}}))}e.executeProgram()}function makeShaderKey(e,t,n){let r="";t.concat(n).forEach((t=>{const a=t.texData!=null&&t.texData.slice!=null&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const s=t.texData.texShape;const{useSqueezeShape:o,uniformShape:i,keptDims:u}=getUniformInfoFromShape(e.packedInputs,t.shape,s);let l="",c="",p="";if(i.length===1&&e.packedInputs){const e=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(i.length===2&&!e.packedInputs){c=`${i[0]>1}_${i[1]>1}`}else if(i.length>2&&!e.packedInputs){const e=computeStrides(i);p=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}const m=t.shape.length;const d=i.length===2&&arraysEqual(t.shape,s);const h=sizeFromShape(t.shape)===1;const f=getBroadcastDims$1(t.shape,n.shape);const g=!e.packedInputs&&m===n.shape.length&&arraysEqual(s,n.texData.texShape);const y=e.packedInputs||i.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${m}_${g}_${o?u:""}_${i.length}_${h}_${f}_${d}_${l}_${c}_${p}_${y}_${a}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${a}`}}));const a=e.userCode;let s=e.constructor.name;s+="_"+r+"_"+a+`${env().getNumber("WEBGL_VERSION")}`;return s}function useShapeUniforms(e){return env().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class DecodeMatrixProgram{constructor(e){this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;this.outPackingScheme=PackingScheme.DENSE;this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=getGlslDifferences();this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?getOutputLogicalCoordinatesFromFlatIndexByUniform(["r","c","d"],e):getLogicalCoordinatesFromFlatIndex(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getA(rc.x, rc.y, rc.z);\n        }\n\n        ${t.output} = result;\n      }\n    `}}class DecodeMatrixPackedProgram{constructor(e){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outPackingScheme=PackingScheme.DENSE;this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=getGlslDifferences();this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?getOutputLogicalCoordinatesFromFlatIndexByUniform(["r","c","d"],e):getLogicalCoordinatesFromFlatIndex(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n        }\n\n        ${t.output} = result;\n      }\n    `}}class EncodeFloatProgram{constructor(e){this.variableNames=["A"];this.outTexUsage=TextureUsage.DOWNLOAD;const t=getGlslDifferences();this.outputShape=e;this.userCode=`\n      ${ENCODE_FLOAT_SNIPPET}\n\n      void main() {\n        float x = getAAtOutCoords();\n        ${t.output} = encode_float(x);\n      }\n    `}}class EncodeFloatPackedProgram{constructor(e){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=false;this.outTexUsage=TextureUsage.DOWNLOAD;const t=getGlslDifferences();this.outputShape=e;this.userCode=`\n      ${ENCODE_FLOAT_SNIPPET}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        ${t.output} = encode_float(x);\n      }\n    `}}class EncodeMatrixProgram{constructor(e,t=false){this.variableNames=["A"];this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=getGlslDifferences();this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);let r=`result`;if(t){r=`floor(result * 255. + 0.5)`}this.userCode=`\n      ${this.enableShapeUniforms?getFlatIndexFrom3DOutput():getFlatIndexFrom3D(e)}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        int flatIndex = getFlatIndex(coords);\n        int offset = imod(flatIndex, 4);\n\n        flatIndex = idiv(flatIndex, 4, 1.);\n\n        int r = flatIndex / texShape[1];\n        int c = imod(flatIndex, texShape[1]);\n        vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n        vec4 values = ${n.texture2D}(A, uv);\n\n        float result;\n\n        if(offset == 0) {\n          result = values[0];\n        } else if(offset == 1) {\n          result = values[1];\n        } else if(offset == 2) {\n          result = values[2];\n        } else {\n          result = values[3];\n        }\n\n        ${n.output} = vec4(${r}, 0., 0., 0.);\n      }\n    `}}class EncodeMatrixPackedProgram{constructor(e,t=false){this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=getGlslDifferences();this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);let r="";let a="result";if(t){a="floor(result * 255. + 0.5)"}for(let t=0;t<=1;t++){for(let a=0;a<=1;a++){const s=t*2+a;r+=`\n          localCoords = coords;\n          if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n          localCoords[2] += ${a};\n          if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n            localCoords[1] += ${t};\n\n            flatIndex = getFlatIndex(localCoords);\n            offset = imod(flatIndex, 4);\n\n            flatIndex = idiv(flatIndex, 4, 1.);\n\n            int r = flatIndex / texShape[1];\n            int c = imod(flatIndex, texShape[1]);\n            vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n            values = ${n.texture2D}(A, uv);\n\n            if (offset == 0) {\n              result[${s}] = values[0];\n            } else if (offset == 1) {\n              result[${s}] = values[1];\n            } else if (offset == 2) {\n              result[${s}] = values[2];\n            } else {\n              result[${s}] = values[3];\n            }\n          }\n        }\n        `}}this.userCode=`\n        ${this.enableShapeUniforms?getFlatIndexFrom3DOutput():getFlatIndexFrom3D(e)}\n\n        void main() {\n          ivec3 coords = getOutputCoords();\n\n          vec4 result = vec4(0.);\n          int flatIndex, r, c, offset;\n          ivec3 localCoords;\n          vec2 uv;\n          vec4 values;\n\n          ${r}\n\n          ${n.output} = ${a};\n        }\n    `}}function createVertexShader(e){const t=getGlslDifferences();const n=`${t.version}\n    precision highp float;\n    ${t.attribute} vec3 clipSpacePos;\n    ${t.attribute} vec2 uv;\n    ${t.varyingVs} vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }`;return createVertexShader$1(e,n)}function createVertexBuffer(e){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return createStaticVertexBuffer(e,t)}function createIndexBuffer(e){const t=new Uint16Array([0,1,2,2,1,3]);return createStaticIndexBuffer(e,t)}function createAndConfigureTexture(e,t,n,r,a,s){validateTextureSize(t,n);const o=createTexture(e);const i=e.TEXTURE_2D;callAndCheck(e,(()=>e.bindTexture(i,o)));callAndCheck(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)));callAndCheck(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)));callAndCheck(e,(()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)));callAndCheck(e,(()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)));if(env().getNumber("WEBGL_VERSION")===1){callAndCheck(e,(()=>e.texImage2D(i,0,r,t,n,0,a,s,null)))}else{callAndCheck(e,(()=>e.texStorage2D(i,1,r,t,n)))}callAndCheck(e,(()=>e.bindTexture(e.TEXTURE_2D,null)));return{texture:o,texShape:[n,t]}}function getInternalFormatForFloat32MatrixTexture(e){return e.internalFormatFloat}function createFloat32MatrixTexture(e,t,n,r){const[a,s]=getUnpackedMatrixTextureShapeWidthHeight(t,n);return createAndConfigureTexture(e,a,s,getInternalFormatForFloat32MatrixTexture(r),r.textureFormatFloat,e.FLOAT)}function getInternalFormatForPackedMatrixTexture(e){return e.internalFormatPackedFloat}function createPackedMatrixTexture(e,t,n,r){const[a,s]=getPackedMatrixTextureShapeWidthHeight(t,n);return createAndConfigureTexture(e,a,s,getInternalFormatForPackedMatrixTexture(r),e.RGBA,e.FLOAT)}function bindVertexProgramAttributeStreams(e,t,n){const r=0;const a=3*4;const s=3*4+2*4;callAndCheck(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n)));const o=bindVertexBufferToProgramAttribute(e,t,"clipSpacePos",n,3,s,r);return o&&bindVertexBufferToProgramAttribute(e,t,"uv",n,2,s,a)}function uploadDenseMatrixToTexture(e,t,n,r,a,s){callAndCheck(e,(()=>e.bindTexture(e.TEXTURE_2D,t)));let o,i,u;if(a instanceof Uint8Array){o=new Uint8Array(n*r*4);i=e.UNSIGNED_BYTE;u=e.RGBA}else{o=new Float32Array(n*r*4);i=e.FLOAT;u=s.internalFormatPackedFloat}o.set(a);if(env().getNumber("WEBGL_VERSION")===2){callAndCheck(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)))}else{callAndCheck(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o)))}callAndCheck(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function createBufferFromOutputTexture(e,t,n,r){const a=e.createBuffer();callAndCheck(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=4;const o=4;const i=s*o*t*n;callAndCheck(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)));callAndCheck(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)));callAndCheck(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)));return a}function downloadFloat32MatrixFromBuffer(e,t,n){const r=e;const a=new Float32Array(n);r.bindBuffer(r.PIXEL_PACK_BUFFER,t);r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a);r.bindBuffer(r.PIXEL_PACK_BUFFER,null);return a}class GPGPUContext{constructor(e){this.outputTexture=null;this.program=null;this.disposed=false;this.vertexAttrsAreBound=false;this.itemsToPoll=[];const t=env().getNumber("WEBGL_VERSION");if(e!=null){this.gl=e;setWebGLContext(t,e)}else{this.gl=getWebGLContext(t)}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile");if(env().getNumber("WEBGL_VERSION")===1){const e="OES_texture_float";const t="OES_texture_half_float";this.textureFloatExtension=getExtensionOrThrow(this.gl,e);if(hasExtension(this.gl,t)){this.textureHalfFloatExtension=getExtensionOrThrow(this.gl,t)}else if(env().get("WEBGL_FORCE_F16_TEXTURES")){throw new Error("GL context does not support half float textures, yet the "+"environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}this.colorBufferFloatExtension=this.gl.getExtension(n);if(hasExtension(this.gl,r)){this.colorBufferHalfFloatExtension=getExtensionOrThrow(this.gl,r)}else if(env().get("WEBGL_FORCE_F16_TEXTURES")){throw new Error("GL context does not support color renderable half floats, yet "+"the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}}else{n="EXT_color_buffer_float";if(hasExtension(this.gl,n)){this.colorBufferFloatExtension=this.gl.getExtension(n)}else if(hasExtension(this.gl,r)){this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}else{throw new Error("GL context does not support color renderable floats")}}this.vertexBuffer=createVertexBuffer(this.gl);this.indexBuffer=createIndexBuffer(this.gl);this.framebuffer=createFramebuffer(this.gl);this.textureConfig=getTextureConfig(this.gl,this.textureHalfFloatExtension)}get debug(){return env().getBool("DEBUG")}dispose(){if(this.disposed){return}if(this.program!=null){console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram."+" This is probably a resource leak, delete the program with "+"GPGPUContext.deleteProgram before disposing.")}if(this.outputTexture!=null){console.warn("Disposing a GPGPUContext that still has a bound output matrix "+"texture.  This is probably a resource leak, delete the output "+"matrix texture with GPGPUContext.deleteMatrixTexture before "+"disposing.")}const e=this.gl;callAndCheck(e,(()=>e.finish()));callAndCheck(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null)));callAndCheck(e,(()=>e.deleteFramebuffer(this.framebuffer)));callAndCheck(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null)));callAndCheck(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)));callAndCheck(e,(()=>e.deleteBuffer(this.indexBuffer)));this.disposed=true}createFloat32MatrixTexture(e,t){this.throwIfDisposed();return createFloat32MatrixTexture(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){this.throwIfDisposed();return createFloat16MatrixTexture(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){this.throwIfDisposed();return createUnsignedBytesMatrixTexture(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed();uploadPixelDataToTexture(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed();uploadDenseMatrixToTexture(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){this.throwIfDisposed();return createFloat16PackedMatrixTexture(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){this.throwIfDisposed();return createPackedMatrixTexture(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed();if(this.outputTexture===e){unbindColorTextureFromFramebuffer(this.gl,this.framebuffer);this.outputTexture=null}callAndCheck(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>downloadByteEncodedFloatMatrixFromOutputTexture(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return downloadPackedMatrixFromBuffer(this.gl,e,t,n,r,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return downloadFloat32MatrixFromBuffer(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=createBufferFromOutputTexture(this.gl,t,n,this.textureConfig);this.unbindTextureToFrameBuffer();return r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t;let n;if(env().getBool("WEBGL_FENCE_API_ENABLED")){const r=e;const a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush();n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED};t=a}else if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0){t=this.beginQuery();this.endQuery();n=()=>this.isQueryAvailable(t,env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}else{n=()=>true}return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>downloadMatrixFromPackedOutputTexture(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;if(this.vertexShader==null){this.vertexShader=createVertexShader(t)}const n=createProgram(t);callAndCheck(t,(()=>t.attachShader(n,this.vertexShader)));callAndCheck(t,(()=>t.attachShader(n,e)));linkProgram(t,n);if(this.debug){validateProgram(t,n)}if(!this.vertexAttrsAreBound){this.setProgram(n);this.vertexAttrsAreBound=bindVertexProgramAttributeStreams(t,this.program,this.vertexBuffer)}return n}deleteProgram(e){this.throwIfDisposed();if(e===this.program){this.program=null}if(e!=null){callAndCheck(this.gl,(()=>this.gl.deleteProgram(e)))}}setProgram(e){this.throwIfDisposed();this.program=e;if(this.program!=null&&this.debug){validateProgram(this.gl,this.program)}callAndCheck(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=true){this.throwIfDisposed();if(n){return getProgramUniformLocationOrThrow(this.gl,e,t)}else{return getProgramUniformLocation(this.gl,e,t)}}getAttributeLocation(e,t){this.throwIfDisposed();return callAndCheck(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){this.throwIfDisposed();return this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed();this.throwIfNoProgram();bindTextureToProgramUniformSampler(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=getPackedMatrixTextureShapeWidthHeight(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){if(this.program!=null){validateProgram(this.gl,this.program)}validateFramebuffer(this.gl)}executeProgram(){this.throwIfDisposed();this.throwIfNoProgram();const e=this.gl;if(this.debug){this.debugValidate()}callAndCheck(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed();callAndCheck(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){if(this.disjointQueryTimerExtension==null){this.disjointQueryTimerExtension=getExtensionOrThrow(this.gl,env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")}return this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const e=this.gl;const t=this.getQueryTimerExtensionWebGL2();const n=e.createQuery();e.beginQuery(t.TIME_ELAPSED_EXT,n);return n}const e=this.getQueryTimerExtensionWebGL1();const t=e.createQueryEXT();e.beginQueryEXT(e.TIME_ELAPSED_EXT,t);return t}endQuery(){if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const e=this.gl;const t=this.getQueryTimerExtensionWebGL2();e.endQuery(t.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){await repeatedTry((()=>this.disposed||this.isQueryAvailable(e,env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))));return this.getQueryTime(e,env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0){return null}if(t===2){const t=this.gl;const n=t.getQueryParameter(e,t.QUERY_RESULT);return n/1e6}else{const t=this.getQueryTimerExtensionWebGL1();const n=t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT);return n/1e6}}isQueryAvailable(e,t){if(t===0){return true}if(t===2){const t=this.gl;const n=this.getQueryTimerExtensionWebGL2();const r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);if(this.disjoint==null){this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)}return r&&!this.disjoint}else{const t=this.getQueryTimerExtensionWebGL1();const n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);if(this.disjoint==null){this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)}return n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=linearSearchLastTrue(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t});if(this.itemsToPoll.length>1){return}repeatedTry((()=>{this.pollItems();return this.itemsToPoll.length===0}))}bindTextureToFrameBuffer(e){this.throwIfDisposed();bindColorTextureToFramebuffer(this.gl,e,this.framebuffer);if(this.debug){validateFramebuffer(this.gl)}}unbindTextureToFrameBuffer(){if(this.outputTexture!=null){bindColorTextureToFramebuffer(this.gl,this.outputTexture,this.framebuffer);if(this.debug){validateFramebuffer(this.gl)}}else{unbindColorTextureFromFramebuffer(this.gl,this.framebuffer)}}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();this.unbindTextureToFrameBuffer();return n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;bindColorTextureToFramebuffer(r,e,this.framebuffer);if(this.debug){validateFramebuffer(r)}this.outputTexture=e;callAndCheck(r,(()=>r.viewport(0,0,t,n)));callAndCheck(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed();callAndCheck(this.gl,(()=>this.gl.scissor(e,t,n,r)))}throwIfDisposed(){if(this.disposed){throw new Error("Attempted to use disposed GPGPUContext.")}}throwIfNoProgram(){if(this.program==null){throw new Error("No GPU program is currently set.")}}}function linearSearchLastTrue(e){let t=0;for(;t<e.length;++t){const n=e[t]();if(!n){break}}return t-1}function createSimpleBinaryKernelImpl(e){return(t,n,r,a,s)=>{const o=assertAndGetBroadcastShape(t,n);const i=o.length;const u=computeStrides(o);const l=sizeFromShape(o);const c=getTypedArrayFromDType(s,l);const p=t.length;const m=n.length;const d=computeStrides(t);const h=computeStrides(n);const f=getBroadcastDims$1(t,o);const g=getBroadcastDims$1(n,o);if(f.length+g.length===0){for(let t=0;t<c.length;++t){c[t]=e(r[t%r.length],a[t%a.length])}}else{for(let t=0;t<c.length;++t){const n=indexToLoc(t,i,u);const s=n.slice(-p);f.forEach((e=>s[e]=0));const o=locToIndex(s,p,d);const l=n.slice(-m);g.forEach((e=>l[e]=0));const y=locToIndex(l,m,h);c[t]=e(r[o],a[y])}}return[c,o]}}const addImpl=createSimpleBinaryKernelImpl(((e,t)=>e+t));function bincountImpl(e,t,n,r,a){const s=sizeFromShape(r);const o=makeZerosTypedArray(a,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0){throw new Error("Input x must be non-negative!")}if(r>=a){continue}if(s>0){o[r]+=t[n]}else{o[r]+=1}}return o}function createSimpleUnaryImpl(e){return(t,n,r)=>{const a=getTypedArrayFromDType(n,t.length);for(let n=0;n<t.length;++n){a[n]=e(t[n],r)}return a}}const ceilImpl=createSimpleUnaryImpl((e=>Math.ceil(e)));function concatImpl$1(e,t,n,r){const a=getArrayFromDType(n,sizeFromShape(t));if(r&&n!=="string"){let t=0;e.forEach((e=>{const n=sizeFromShape(e.shape);a.set(e.vals,t);t+=n}))}else{let r=0;e.forEach((e=>{const s=n==="string"?fromUint8ToStringArray(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const i=n*t[1]+r;for(let t=0;t<e.shape[1];++t){a[i+t]=s[o++]}}r+=e.shape[1]}))}return a}const equalImpl=createSimpleBinaryKernelImpl(((e,t)=>e===t?1:0));const expImpl=createSimpleUnaryImpl((e=>Math.exp(e)));const expm1Impl=createSimpleUnaryImpl((e=>Math.expm1(e)));const floorImpl=createSimpleUnaryImpl((e=>Math.floor(e)));function gatherV2Impl(e,t,n){const r=buffer(n,e.dtype);for(let n=0;n<r.size;++n){const a=r.indexToLoc(n);const s=a.slice();const o=s[0];const i=s[2];const u=t.locToIndex([o,i]);s[2]=t.values[u];const l=e.locToIndex(s);if(0<=l&&l<e.values.length){r.values[n]=e.values[l]}}return r}const greaterImpl=createSimpleBinaryKernelImpl(((e,t)=>e>t?1:0));const greaterEqualImpl=createSimpleBinaryKernelImpl(((e,t)=>e>=t?1:0));const lessImpl=createSimpleBinaryKernelImpl(((e,t)=>e<t?1:0));const lessEqualImpl=createSimpleBinaryKernelImpl(((e,t)=>e<=t?1:0));const logImpl=createSimpleUnaryImpl((e=>Math.log(e)));function maxImpl(e,t,n,r){const a=getTypedArrayFromDType(r,sizeFromShape(n));for(let n=0;n<a.length;++n){const r=n*t;let s=e[r];for(let n=0;n<t;++n){const t=e[r+n];if(Number.isNaN(t)||t>s){s=t}}a[n]=s}return a}const maximumImpl=createSimpleBinaryKernelImpl(((e,t)=>Math.max(e,t)));const minimumImpl=createSimpleBinaryKernelImpl(((e,t)=>Math.min(e,t)));const multiplyImpl=createSimpleBinaryKernelImpl(((e,t)=>e*t));function negImpl(e,t,n){const r=createScalarValue(-1,n);return multiplyImpl([],t,r,e,n)}const notEqualImpl=createSimpleBinaryKernelImpl(((e,t)=>e!==t?1:0));function transposeImpl$1(e,t,n,r,a){const s=t.length;const o=sizeFromShape(t);const i=computeStrides(t);const u=computeStrides(a);const l=getTypedArrayFromDType(n,sizeFromShape(a));for(let t=0;t<o;++t){const n=indexToLoc(t,s,i);const a=new Array(n.length);for(let e=0;e<a.length;e++){a[e]=n[r[e]]}const o=locToIndex(a,s,u);l[o]=e[t]}return l}function prodImpl(e,t,n,r){const[a,s]=computeOutAndReduceShapes(e,r);const o=upcastType(t,"int32");const i=makeZerosTypedArray(sizeFromShape(a),o);const u=sizeFromShape(s);for(let e=0;e<i.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e){r*=n[t+e]}i[e]=r}return{outVals:i,outShape:a,outDtype:o}}function rangeImpl(e,t,n,r){const a=e===t;const s=e<t&&n<0;const o=t<e&&n>1;if(a||s||o){return makeZerosTypedArray(0,r)}const i=Math.abs(Math.ceil((t-e)/n));const u=makeZerosTypedArray(i,r);if(t<e&&n===1){n=-1}u[0]=e;for(let e=1;e<u.length;e++){u[e]=u[e-1]+n}return u}const rsqrtImpl=createSimpleUnaryImpl((e=>1/Math.sqrt(e)));function scatterImpl(e,t,n,r,a,s,o,i,u,l){const c=[r/a,a];const p=e.values;const m=t.values;if(r===0){return buffer(n,t.dtype)}const d=buffer(c,t.dtype);if(typeof u==="string"){d.values.fill(u)}else if(typeof u==="number"){d.values.fill(u)}else if(typeof u==="boolean"){d.values.fill(+u)}for(let e=0;e<s;e++){const s=[];let u=0;for(let t=0;t<o;t++){const n=p[e*o+t];s.push(n);u+=n*i[t]}if(u<0||u>=r/a){throw new Error(`Invalid indices: ${s} does not index into ${n}`)}for(let n=0;n<a;n++){if(l){d.values[u*a+n]+=m[e*a+n]}else{d.values[u*a+n]=t.rank===0?m[0]:m[e*a+n]}}}return d}const sigmoidImpl=createSimpleUnaryImpl((e=>1/(1+Math.exp(-e))));function sliceImpl(e,t,n,r,a){const s=isSliceContinous(r,t,n);const o=sizeFromShape(n);const i=computeStrides(r);if(s){const n=computeFlatOffset(t,i);if(a==="string"){return e.slice(n,n+o)}return e.subarray(n,n+o)}const u=a==="string"?fromUint8ToStringArray(e):e;const l=buffer(r,a,u);const c=buffer(n,a);for(let e=0;e<c.size;++e){const n=c.indexToLoc(e);const r=n.map(((e,n)=>e+t[n]));c.set(l.get(...r),...n)}if(a==="string"){return fromStringArrayToUint8(c.values)}return c.values}const sqrtImpl=createSimpleUnaryImpl((e=>Math.sqrt(e)));const squaredDifferenceImpl=createSimpleBinaryKernelImpl(((e,t)=>{const n=e-t;return n*n}));const subImpl=createSimpleBinaryKernelImpl(((e,t)=>e-t));var shared=Object.freeze({__proto__:null,simpleAbsImpl:()=>{},addImpl:addImpl,bincountImpl:bincountImpl,bincountReduceImpl:()=>{},ceilImpl:ceilImpl,concatImpl:concatImpl$1,equalImpl:equalImpl,expImpl:expImpl,expm1Impl:expm1Impl,floorImpl:floorImpl,gatherNdImpl:()=>{},gatherV2Impl:gatherV2Impl,greaterImpl:greaterImpl,greaterEqualImpl:greaterEqualImpl,lessImpl:lessImpl,lessEqualImpl:lessEqualImpl,linSpaceImpl:()=>{},logImpl:logImpl,maxImpl:maxImpl,maximumImpl:maximumImpl,minimumImpl:minimumImpl,multiplyImpl:multiplyImpl,negImpl:negImpl,notEqualImpl:notEqualImpl,prodImpl:prodImpl,rangeImpl:rangeImpl,rsqrtImpl:rsqrtImpl,scatterImpl:scatterImpl,sigmoidImpl:sigmoidImpl,sliceImpl:sliceImpl,sparseFillEmptyRowsImpl:()=>{},sparseReshapeImpl:()=>{},sparseSegmentReductionImpl:()=>{},sqrtImpl:sqrtImpl,squaredDifferenceImpl:squaredDifferenceImpl,stridedSliceImpl:()=>{},stringNGramsImpl:()=>{},stringSplitImpl:()=>{},stringToHashBucketFastImpl:()=>{},subImpl:subImpl,tileImpl:()=>{},topKImpl:()=>{},transposeImpl:transposeImpl$1,uniqueImpl:()=>{}});const{addImpl:addImplCPU,bincountImpl:bincountImplCPU,bincountReduceImpl:bincountReduceImplCPU,ceilImpl:ceilImplCPU,concatImpl:concatImplCPU,equalImpl:equalImplCPU,expImpl:expImplCPU,expm1Impl:expm1ImplCPU,floorImpl:floorImplCPU,gatherNdImpl:gatherNdImplCPU,gatherV2Impl:gatherV2ImplCPU,greaterImpl:greaterImplCPU,greaterEqualImpl:greaterEqualImplCPU,lessImpl:lessImplCPU,lessEqualImpl:lessEqualImplCPU,linSpaceImpl:linSpaceImplCPU,logImpl:logImplCPU,maxImpl:maxImplCPU,maximumImpl:maximumImplCPU,minimumImpl:minimumImplCPU,multiplyImpl:multiplyImplCPU,negImpl:negImplCPU,notEqualImpl:notEqualImplCPU,prodImpl:prodImplCPU,rangeImpl:rangeImplCPU,rsqrtImpl:rsqrtImplCPU,scatterImpl:scatterImplCPU,sigmoidImpl:sigmoidImplCPU,simpleAbsImpl:simpleAbsImplCPU,sliceImpl:sliceImplCPU,sparseFillEmptyRowsImpl:sparseFillEmptyRowsImplCPU,sparseReshapeImpl:sparseReshapeImplCPU,sparseSegmentReductionImpl:sparseSegmentReductionImplCPU,sqrtImpl:sqrtImplCPU,stridedSliceImpl:stridedSliceImplCPU,stringNGramsImpl:stringNGramsImplCPU,stringSplitImpl:stringSplitImplCPU,stringToHashBucketFastImpl:stringToHashBucketFastImplCPU,subImpl:subImplCPU,tileImpl:tileImplCPU,topKImpl:topKImplCPU,transposeImpl:transposeImplCPU,uniqueImpl:uniqueImplCPU}=shared;function getVecChannels(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function getChannels(e,t){if(t===1){return[e]}return getVecChannels(e,t)}function getSourceCoords$1(e,t){if(e===1){return"rc"}let n="";for(let r=0;r<e;r++){n+=t[r];if(r<e-1){n+=","}}return n}class PackProgram{constructor(e){this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;this.outputShape=e;this.rank=e.length;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);if(this.rank===0){this.userCode=`\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      `}else{const e=getChannels("rc",this.rank);const t=getCoordsDataType(this.rank);const n=this.getOutOfBoundsCondition(e);const r=this.getSetup(e);const a=this.getOutput(e);this.userCode=`\n        void main() {\n          ${t} rc = getOutputCoords();\n\n          if(${n}) {\n            setOutput(vec4(0));\n          } else {\n            ${r}\n\n            setOutput(vec4(${a}));\n          }\n        }\n      `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++){for(let r=0;r<=1;r++){let a=`${n===0?"r":"rp1"}, ${r===0?"c":"cp1"}`;for(let t=2;t<this.rank;t++){a=`${e[e.length-1-t]},`+a}t.push(a)}}return t}getOutOfBoundsCondition(e){if(this.rank===1){return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`}let t="";for(let n=this.rank-2;n<this.rank;n++){t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`;if(n<this.rank-1){t+="||"}}return t}getSetup(e){if(this.rank===1){return""}const t=e.slice(-2);const n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1];const r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n      int r = ${t[0]};\n      int c = ${t[1]};\n      int rp1 = r + 1;\n      int cp1 = c + 1;\n\n      bool cEdge = cp1 >= ${n};\n      bool rEdge = rp1 >= ${r};\n    `}getOutput(e){const t=this.getSourceCoordsArr(e);if(this.rank===1){const e=this.enableShapeUniforms?"outShape":this.outputShape[0];return`getA(rc), (rc + 1 >= ${e} ? 0. : getA(rc + 1)), 0, 0`}return`getA(${t[0]}),\n            cEdge ? 0. : getA(${t[1]}),\n            rEdge ? 0. : getA(${t[2]}),\n            rEdge || cEdge ? 0. : getA(${t[3]})`}}class ReshapePackedProgram{constructor(e,t){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.customUniforms=[{name:"inputShape",type:"ivec3"}];this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);let n=``;for(let e=0;e<4;e++){let t=`thisRC = rc;`;if(e%2===1){t+=`thisRC.z += 1;`}if(e>1){t+=`thisRC.y += 1;`}n+=`\n        ${t}\n        ${e>0?`if(thisRC.y < rows && thisRC.z < cols){`:""}\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result[${e}] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        ${e>0?"}":""}\n      `}this.userCode=`\n      ${getReshapedInputCoords(t,this.enableShapeUniforms)}\n      ${this.enableShapeUniforms?getFlatIndexFrom3DOutput():getFlatIndexFrom3D(e)}\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n        int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n        ${n}\n\n        setOutput(result);\n      }\n    `}}function getReshapedInputCoords(e,t){const n=t?getLogicalCoordinatesFromFlatIndexByUniform(["r","c","d"],"inputShape"):getLogicalCoordinatesFromFlatIndex(["r","c","d"],e);return`\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      ${n}\n      return ivec3(r, c, d);\n    }\n  `}class TextureManager{constructor(e){this.gpgpu=e;this.numUsedTextures=0;this.numFreeTextures=0;this._numBytesAllocated=0;this._numBytesFree=0;this.freeTextures={};this.logEnabled=false;this.usedTextures={}}acquireTexture(e,t,n){const r=getPhysicalFromLogicalTextureType(t,n);const a=getKeyFromTextureShape(e,r,n);if(!(a in this.freeTextures)){this.freeTextures[a]=[]}if(!(a in this.usedTextures)){this.usedTextures[a]=[]}const s=computeBytes(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--;this.numUsedTextures++;this._numBytesFree-=s;this.log();const e=this.freeTextures[a].shift();this.usedTextures[a].push(e);return e}let o;if(r===PhysicalTextureType.PACKED_2X2_FLOAT32){o=this.gpgpu.createPackedMatrixTexture(e[0],e[1])}else if(r===PhysicalTextureType.PACKED_2X2_FLOAT16){o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1])}else if(r===PhysicalTextureType.UNPACKED_FLOAT32){o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1])}else if(r===PhysicalTextureType.UNPACKED_FLOAT16){o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1])}else if(r===PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE){o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])}this.usedTextures[a].push(o);this.numUsedTextures++;this._numBytesAllocated+=s;this.log();return o}releaseTexture(e,t,n,r){if(this.freeTextures==null){return}const a=getPhysicalFromLogicalTextureType(n,r);const s=getKeyFromTextureShape(t,a,r);if(!(s in this.freeTextures)){this.freeTextures[s]=[]}const o=computeBytes(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r);const i=env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");if(i!==-1&&this._numBytesAllocated>i){this.gpgpu.deleteMatrixTexture(e.texture);this._numBytesAllocated-=o}else{this.freeTextures[s].push(e);this.numFreeTextures++;this._numBytesFree+=o}this.numUsedTextures--;const u=this.usedTextures[s];const l=u.indexOf(e);if(l<0){throw new Error("Cannot release a texture that was never provided by this "+"texture manager")}u.splice(l,1);this.log()}log(){if(!this.logEnabled){return}const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`);console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null){return}for(const e in this.freeTextures){this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}))}for(const e in this.usedTextures){this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}))}this.freeTextures=null;this.usedTextures=null;this.numUsedTextures=0;this.numFreeTextures=0;this._numBytesAllocated=0;this._numBytesFree=0}}function numBytesForInternalFormat(e,t){const n=e;if(t===n.R32F){return 4}else if(t===n.R16F){return 2}else if(t===n.RGBA32F){return 16}else if(t===e.RGBA){return 16}else if(t===n.RGBA16F){return 8}else if(t===n.RGBA8){return 4}throw new Error(`Unknown internal format ${t}`)}function computeBytes(e,t,n,r,a){const s=internalFormatForPhysicalTexType(t,r);let o;if(a){const[t,n]=getPackedMatrixTextureShapeWidthHeight(e[0],e[1]);o=t*n}else{const[t,n]=getUnpackedMatrixTextureShapeWidthHeight(e[0],e[1]);o=t*n}const i=numBytesForInternalFormat(n,s);return o*i}function internalFormatForPhysicalTexType(e,t){switch(e){case PhysicalTextureType.PACKED_2X2_FLOAT32:return getInternalFormatForPackedMatrixTexture(t);case PhysicalTextureType.PACKED_2X2_FLOAT16:return getInternalFormatForFloat16PackedMatrixTexture(t);case PhysicalTextureType.UNPACKED_FLOAT32:return getInternalFormatForFloat32MatrixTexture(t);case PhysicalTextureType.UNPACKED_FLOAT16:return getInternalFormatForFloat16MatrixTexture(t);case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:return getInternalFormatForUnsignedBytesMatrixTexture(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function getPhysicalTextureForRendering(e){if(env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")){if(e){return PhysicalTextureType.PACKED_2X2_FLOAT32}return PhysicalTextureType.UNPACKED_FLOAT32}if(e){return PhysicalTextureType.PACKED_2X2_FLOAT16}return PhysicalTextureType.UNPACKED_FLOAT16}function getPhysicalFromLogicalTextureType(e,t){if(e===TextureUsage.UPLOAD){return PhysicalTextureType.PACKED_2X2_FLOAT32}else if(e===TextureUsage.RENDER||e==null){return getPhysicalTextureForRendering(t)}else if(e===TextureUsage.DOWNLOAD||e===TextureUsage.PIXELS){return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE}throw new Error(`Unknown logical texture type ${e}`)}function getKeyFromTextureShape(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class UnaryOpProgram{constructor(e,t){this.variableNames=["A"];this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);this.userCode=`\n      float unaryOperation(float x) {\n        ${t}\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}const CHECK_NAN_SNIPPET$1=`if (isnan(x)) return x;`;const LINEAR$1=`return x;`;const ABS=`return abs(x);`;const ELU$1=`return (x >= 0.0) ? x : (exp(x) - 1.0);`;const RELU$2=CHECK_NAN_SNIPPET$1+`\n  return (x < 0.0) ? 0.0 : x;\n`;const RELU6$1=CHECK_NAN_SNIPPET$1+`\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n`;const CLONE="return x;";const SIGMOID$2=`return 1.0 / (1.0 + exp(-1.0 * x));`;const LINEAR=`return x;`;const ELU=`\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n`;const RELU$1=`\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n`;const RELU6=`\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n`;const SIGMOID$1=`return 1.0 / (1.0 + exp(-1.0 * x));`;class UnaryOpPackedProgram{constructor(e,t){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);this.userCode=`\n      vec4 unaryOperation(vec4 x) {\n        ${t}\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}class UnpackProgram{constructor(e){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=false;this.outputShape=e;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);const t=e.length;const n=getChannels("rc",t);const r=getCoordsDataType(t);const a=getSourceCoords$1(t,n);const s=n.slice(-2);const o=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`\n      void main() {\n        ${r} rc = getOutputCoords();\n        vec4 packedInput = getA(${a});\n\n        setOutput(getChannel(packedInput, ${o}));\n      }\n    `}}const EPSILON_FLOAT32=1e-7;const EPSILON_FLOAT16=1e-4;const binaryCaches={};function getBinaryCache(e){if(e in binaryCaches){return binaryCaches[e]}binaryCaches[e]={};return binaryCaches[e]}const CPU_HANDOFF_SIZE_THRESHOLD=env().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");const BEFORE_PAGING_CONSTANT=600;function numMBBeforeWarning(){if(env().global.screen==null){return 1024}return env().global.screen.height*env().global.screen.width*window.devicePixelRatio*BEFORE_PAGING_CONSTANT/1024/1024}class MathBackendWebGL extends KernelBackend{constructor(e){super();this.pendingRead=new WeakMap;this.pendingDisposal=new WeakSet;this.dataRefCount=new WeakMap;this.numBytesInGPU=0;this.uploadWaitMs=0;this.downloadWaitMs=0;this.lastGlFlushTime=0;this.warnedAboutMemory=false;this.pendingDeletes=0;this.disposed=false;if(!env().getBool("HAS_WEBGL")){throw new Error("WebGL is not supported on this device")}let t;if(e!=null){if(e instanceof GPGPUContext){t=e}else{const n=getWebGLContext(env().getNumber("WEBGL_VERSION"),e);t=new GPGPUContext(n)}this.binaryCache={};this.gpgpuCreatedLocally=false}else{const e=getWebGLContext(env().getNumber("WEBGL_VERSION"));t=new GPGPUContext(e);this.binaryCache=getBinaryCache(env().getNumber("WEBGL_VERSION"));this.gpgpuCreatedLocally=true}this.gpgpu=t;this.canvas=this.gpgpu.gl.canvas;this.textureManager=new TextureManager(this.gpgpu);this.numMBBeforeWarning=numMBBeforeWarning();this.texData=new DataStorage(this,engine())}nextDataId(){return MathBackendWebGL.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if(env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||env().getBool("DEBUG")){this.checkNumericalProblems(e)}if(n==="complex64"&&e!=null){throw new Error(`Cannot write to a complex64 dtype. `+`Please use tf.complex(real, imag).`)}const r={id:this.nextDataId()};this.texData.set(r,{shape:t,dtype:n,values:e,usage:TextureUsage.UPLOAD,refCount:1});return r}refCount(e){if(this.texData.has(e)){const t=this.texData.get(e);return t.refCount}return 0}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,r,a){if(env().getBool("DEBUG")){this.checkNumericalProblems(t)}if(r==="complex64"){throw new Error(`Cannot write to a complex64 dtype. `+`Please use tf.complex(real, imag).`)}this.texData.set(e,{shape:n,dtype:r,values:t,usage:TextureUsage.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e);const{values:n,dtype:r,complexTensorInfos:a,slice:s,shape:o,isPacked:i}=t;if(s!=null){let t;if(i){t=new UnaryOpPackedProgram(o,CLONE)}else{t=new UnaryOpProgram(o,CLONE)}const n=this.runWebGLProgram(t,[{dataId:e,shape:o,dtype:r}],r);const a=this.readSync(n.dataId);this.disposeIntermediateTensorInfo(n);return a}if(n!=null){return this.convertAndCacheOnCPU(e)}if(r==="string"){return n}const u=this.activeTimers!=null;let l;if(u){l=now()}let c;if(r==="complex64"){const e=this.readSync(a.real.dataId);const t=this.readSync(a.imag.dataId);c=mergeRealAndImagArrays(e,t)}else{c=this.getValuesFromTexture(e)}if(u){this.downloadWaitMs+=now()-l}return this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e);const{values:n,shape:r,slice:a,dtype:s,complexTensorInfos:o,isPacked:i}=t;if(a!=null){let t;if(i){t=new UnaryOpPackedProgram(r,CLONE)}else{t=new UnaryOpProgram(r,CLONE)}const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s);const a=this.read(n.dataId);this.disposeIntermediateTensorInfo(n);return a}if(n!=null){return this.convertAndCacheOnCPU(e)}if(env().getBool("DEBUG")){if(!env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&env().getNumber("WEBGL_VERSION")===2){throw new Error(`tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and `+`WEBGL_VERSION=2 not yet supported.`)}}let u=null;let l;if(s!=="complex64"&&env().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);u=this.gpgpu.createBufferFromTexture(t.texture.texture,...getDenseTexShape(r))}this.pendingRead.set(e,[]);if(s!=="complex64"){await this.gpgpu.createAndWaitForFence()}let c;if(s==="complex64"){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);const t=e[0];const n=e[1];c=mergeRealAndImagArrays(t,n)}else if(u==null){c=this.getValuesFromTexture(e)}else{const e=sizeFromShape(r);c=this.gpgpu.downloadFloat32MatrixFromBuffer(u,e)}if(l!=null){this.disposeIntermediateTensorInfo(l)}if(u!=null){const e=this.gpgpu.gl;callAndCheck(e,(()=>e.deleteBuffer(u)))}const p=this.convertAndCacheOnCPU(e,c);const m=this.pendingRead.get(e);this.pendingRead.delete(e);m.forEach((e=>e(p)));if(this.pendingDisposal.has(e)){this.pendingDisposal.delete(e);if(this.disposeData(e)){engine().removeDataId(e,this)}this.pendingDeletes--}return p}readToGPU(e,t={}){const n=this.texData.get(e);const{values:r,shape:a,slice:s,dtype:o,isPacked:i,texture:u}=n;if(o==="complex64"){throw new Error("Does not support reading texture for complex64 dtype.")}if(s!=null){let n;if(i){n=new UnaryOpPackedProgram(a,CLONE)}else{n=new UnaryOpProgram(a,CLONE)}const r=this.runWebGLProgram(n,[{dataId:e,shape:a,dtype:o}],o);const s=this.readToGPU(r,t);this.disposeIntermediateTensorInfo(r);return s}if(u==null){if(r!=null){throw new Error("Data is not on GPU but on CPU.")}else{throw new Error("There is no data on GPU or CPU.")}}const l=this.decode(e,t.customTexShape);const c=engine().makeTensorFromTensorInfo(l);const p=this.texData.get(l.dataId);return Object.assign({tensorRef:c},p.texture)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string"){try{const n=t.map((e=>decodeString(e)));return buffer(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}}return buffer(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e==null){return}for(let t=0;t<e.length;t++){const n=e[t];if(!canBeRepresented(n)){if(env().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")){throw Error(`The value ${n} cannot be represented with your `+`current settings. Consider enabling float32 rendering: `+`'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`)}throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e);const a=sizeFromShape(t);if(env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e);const r=this.texData.get(n.dataId);const s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...getDenseTexShape(t)).subarray(0,a);this.disposeIntermediateTensorInfo(n);return s}const s=env().getBool("WEBGL_PACK")&&r===true;const o=s?getShapeAs3D(t):t;const i=s?new EncodeFloatPackedProgram(o):new EncodeFloatProgram(o);const u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32");const l=this.texData.get(u.dataId);const c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);this.disposeIntermediateTensorInfo(u);return c}timerAvailable(){return env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers;const n=[];let r=false;if(this.programTimersStack==null){this.programTimersStack=n;r=true}else{this.activeTimers.push(n)}this.activeTimers=n;e();const a=flatten(this.activeTimers.map((e=>e.query))).filter((e=>e!=null));const s=flatten(this.activeTimers.map((e=>e.name))).filter((e=>e!=null));this.activeTimers=t;if(r){this.programTimersStack=null}const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o["kernelMs"]=sum$2(e);o["getExtraProfileInfo"]=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else{o["kernelMs"]={error:"WebGL query timers are not supported in this environment."}}this.uploadWaitMs=0;this.downloadWaitMs=0;return o})()}memory(){return{unreliable:false,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){return this.gpgpu.beginQuery()}return{startMs:now(),endMs:null}}endTimer(e){if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){this.gpgpu.endQuery();return e}e.endMs=now();return e}async getQueryTime(e){if(env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){return this.gpgpu.waitForQueryAndGetTime(e)}const t=e;return t.endMs-t.startMs}disposeData(e,t=false){if(this.pendingDisposal.has(e)){return false}if(!this.texData.has(e)){return true}if(t){this.texData.get(e).refCount=0}else{this.texData.get(e).refCount--}if(!t&&this.texData.get(e).refCount>0){return false}if(this.pendingRead.has(e)){this.pendingDisposal.add(e);this.pendingDeletes++;return false}this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);if(n!=null){this.disposeData(n.real.dataId,t);this.disposeData(n.imag.dataId,t)}this.texData.delete(e);return true}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e);const i=o&&o.origDataId||e;const u=this.dataRefCount.get(i);if(u>1){this.dataRefCount.set(i,u-1)}else{this.dataRefCount.delete(i);if(t!=null){this.numBytesInGPU-=this.computeBytes(r,n);this.textureManager.releaseTexture(t,r,a,s)}}const l=this.texData.get(e);l.texture=null;l.texShape=null;l.isPacked=false;l.slice=null}getTexture(e){this.uploadToGPU(e);return this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=CPU_HANDOFF_SIZE_THRESHOLD){return env().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>this.texData.get(e.dataId).texture==null&&sizeFromShape(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){warn("tf.where() in webgl locks the UI thread. "+"Call tf.whereAsync() instead");const t=e.dataSync();return whereImpl(e.shape,t)}packedUnaryOp(e,t,n){const r=new UnaryOpPackedProgram(e.shape,t);const a=this.compileAndRun(r,[e],n);return engine().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const t=simpleAbsImplCPU(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(e,ABS,e.dtype)}const t=new UnaryOpProgram(e.shape,ABS);const n=this.compileAndRun(t,[e]);return engine().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&isString(n[0])){const a=n.map((e=>encodeString(e)));r=this.write(a,e,t)}else{r=this.write(n,e,t)}this.texData.get(r).usage=null;return{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return engine().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new UnpackProgram(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new PackProgram(e.shape);const n=true;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){const n=[getBatchDim(e.shape),...getRowsCols(e.shape)];const r={dtype:e.dtype,shape:n,dataId:e.dataId};const a=[getBatchDim(t),...getRowsCols(t)];const s=new ReshapePackedProgram(a,n);const o=true;const i=[n];const u=this.runWebGLProgram(s,[r],e.dtype,i,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}decode(e,t){const n=this.texData.get(e);const{isPacked:r,shape:a,dtype:s}=n;if(t!=null){const e=sizeFromShape(a);const n=t[0]*t[1]*4;assert(e<=n,(()=>"customTexShape is too small. "+"Row * Column * 4 should be equal or larger than the "+"size of the tensor data."))}const o=getShapeAs3D(a);let i;if(r){i=new DecodeMatrixPackedProgram(o)}else{i=new DecodeMatrixProgram(o)}const u=true;const l=[t!=null?t:getDenseTexShape(o)];const c=this.runWebGLProgram(i,[{shape:o,dtype:s,dataId:e}],s,l,u,t);return{dtype:s,shape:a,dataId:c.dataId}}runWebGLProgram(e,t,n,r,a=false,s){const o=this.makeTensorInfo(e.outputShape,n);const i=this.texData.get(o.dataId);if(e.packedOutput){i.isPacked=true}if(e.outPackingScheme===PackingScheme.DENSE){const t=s!=null?s:getDenseTexShape(e.outputShape);i.texShape=t.map((e=>e*2))}if(e.outTexUsage!=null){i.usage=e.outTexUsage}if(sizeFromShape(o.shape)===0){i.values=getTypedArrayFromDType(o.dtype,0);return o}const u=[];const l=t.map((t=>{if(t.dtype==="complex64"){throw new Error(`GPGPUProgram does not support complex64 input. For complex64 `+`dtypes, please separate the program into real and imaginary `+`parts.`)}let n=this.texData.get(t.dataId);if(n.texture==null){if(!e.packedInputs&&sizeFromShape(t.shape)<=env().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM")){return{shape:t.shape,texData:null,isUniform:true,uniformValues:n.values}}if(e.packedInputs){n.isPacked=true;n.shape=t.shape}}this.uploadToGPU(t.dataId);if(!!n.isPacked!==!!e.packedInputs){t=n.isPacked?this.unpackTensor(t):this.packTensor(t);u.push(t);n=this.texData.get(t.dataId)}else if(n.isPacked&&!isReshapeFree(n.shape,t.shape)){const e=t;const r=t.shape;t.shape=n.shape;t=this.packedReshape(t,r);u.push(t);n=this.texData.get(t.dataId);e.shape=r}return{shape:t.shape,texData:n,isUniform:false}}));this.uploadToGPU(o.dataId);const c={shape:o.shape,texData:i,isUniform:false};const p=makeShaderKey(e,l,c);const m=this.getAndSaveBinary(p,(()=>compileProgram(this.gpgpu,e,l,c)));const d=this.activeTimers!=null;let h;if(d){h=this.startTimer()}if(!env().get("ENGINE_COMPILE_ONLY")){runProgram(this.gpgpu,m,l,c,r)}u.forEach((e=>this.disposeIntermediateTensorInfo(e)));if(d){h=this.endTimer(h);this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)})}const f=env().get("WEBGL_FLUSH_THRESHOLD");if(f>0){const e=now();if(e-this.lastGlFlushTime>f){this.gpgpu.gl.flush();this.lastGlFlushTime=e}}if(!env().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&a===false){const e=this.unpackTensor(o);this.disposeIntermediateTensorInfo(o);return e}return o}compileAndRun(e,t,n,r,a=false){n=n||t[0].dtype;const s=this.runWebGLProgram(e,t,n,r,a);return s}getAndSaveBinary(e,t){if(!(e in this.binaryCache)){this.binaryCache[e]=t()}return this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(this.disposed){return}if(!env().getBool("IS_TEST")){const e=Object.keys(this.binaryCache);e.forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);delete this.binaryCache[e]}))}this.textureManager.dispose();if(this.canvas!=null&&(typeof HTMLCanvasElement!=="undefined"&&this.canvas instanceof HTMLCanvasElement)){this.canvas.remove()}else{this.canvas=null}if(this.gpgpuCreatedLocally){this.gpgpu.program=null;this.gpgpu.dispose()}this.disposed=true}floatPrecision(){if(this.floatPrecisionValue==null){this.floatPrecisionValue=tidy((()=>{if(!env().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=env().getBool("DEBUG");env().set("DEBUG",false);const t=this.abs(scalar(1e-8)).dataSync()[0];env().set("DEBUG",e);if(t>0){return 32}}return 16}))}return this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?EPSILON_FLOAT32:EPSILON_FLOAT16}uploadToGPU(e){const t=this.texData.get(e);const{shape:n,dtype:r,values:a,texture:s,usage:o,isPacked:i}=t;if(s!=null){return}const u=this.activeTimers!=null;let l;if(u){l=now()}let c=t.texShape;if(c==null){c=getTextureShapeFromLogicalShape(n,i);t.texShape=c}if(a!=null){const e=getShapeAs3D(n);let s;let o=c[1],p=c[0];const m=a instanceof Uint8Array||a instanceof Uint8ClampedArray;if(i||!m){[o,p]=getPackedMatrixTextureShapeWidthHeight(c[0],c[1])}if(i){s=new EncodeMatrixPackedProgram(e,m)}else{s=new EncodeMatrixProgram(e,m)}const d=m?[p,o]:c;const h=this.makeTensorInfo(d,r);const f=this.texData.get(h.dataId);if(m){f.usage=TextureUsage.PIXELS}else{f.usage=TextureUsage.UPLOAD}f.texShape=d;this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(h.dataId),o,p,a);const g=[[p,o]];const y=true;const x=this.runWebGLProgram(s,[h],r,g,y);const T=this.texData.get(x.dataId);t.texShape=T.texShape;t.isPacked=T.isPacked;t.usage=T.usage;if(!env().get("ENGINE_COMPILE_ONLY")){t.texture=T.texture;t.values=null;this.texData.delete(x.dataId)}else{this.disposeData(x.dataId)}this.disposeIntermediateTensorInfo(h);if(u){this.uploadWaitMs+=now()-l}}else{const e=this.acquireTexture(c,o,r,i);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e);const{dtype:r}=n;this.releaseGPUData(e);if(t!=null){n.values=float32ToTypedArray(t,r)}return n.values}acquireTexture(e,t,n,r){this.numBytesInGPU+=this.computeBytes(e,n);if(!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=true;console.warn(`High memory usage in GPU: ${e} MB, `+`most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*bytesPerElement(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache)){this.checkCompletion_(e)}}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache)){e.push(this.checkCompletionAsync_(t))}return Promise.all(e)}else{for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t);e(true)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}}async checkCompletionAsync_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)){return this.checkCompletion_(e)}else{await nextFrame();return this.checkCompletionAsync_(e)}}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===false){console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram));if(this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===false){logShaderSourceAndInfoLog(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader));throw new Error("Failed to compile fragment shader.")}throw new Error("Failed to link vertex and fragment shaders.")}return true}getUniformLocations(){for(const[,e]of Object.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,inShapesLocations:s,inTexShapesLocations:o,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:l}=getUniformLocations(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t;e.customUniformLocations=n;e.infLoc=r;e.nanLoc=a;e.inShapesLocations=s;e.inTexShapesLocations=o;e.outShapeLocation=i;e.outShapeStridesLocation=u;e.outTexShapeLocation=l}}}MathBackendWebGL.nextDataId=0;function float32ToTypedArray(e,t){if(t==="float32"||t==="complex64"){return e}else if(t==="int32"||t==="bool"){const n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t){n[t]=Math.round(e[t])}return n}else{throw new Error(`Unknown dtype ${t}`)}}if(isBrowser()){registerBackend("webgl",(()=>new MathBackendWebGL),2)}class BinaryOpProgram{constructor(e,t,n){this.variableNames=["A","B"];this.outputShape=assertAndGetBroadcastShape(t,n);this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);this.userCode=`\n      float binaryOperation(float a, float b) {\n        ${e}\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    `}}const CHECK_NAN_SNIPPET=`\n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n`;class BinaryOpPackedProgram{constructor(e,t,n,r=false){this.variableNames=["A","B"];this.supportsBroadcasting=true;this.packedInputs=true;this.packedOutput=true;this.outputShape=assertAndGetBroadcastShape(t,n);const a=this.outputShape.length;this.enableShapeUniforms=useShapeUniforms(a);let s="";if(r){if(a===0||sizeFromShape(this.outputShape)===1){s=`\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        `}else{const e=getCoordsDataType(a);s=`\n          ${e} coords = getOutputCoords();\n        `;if(a===1){if(this.enableShapeUniforms){s+=`\n            result.y = (coords + 1) >= outShape ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          `}else{s+=`\n            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          `}}else{const e=getChannels("coords",a);if(this.enableShapeUniforms){s+=`\n            bool nextRowOutOfBounds =\n              (${e[a-2]} + 1) >= outShape[${a} - 2];\n            bool nextColOutOfBounds =\n              (${e[a-1]} + 1) >= outShape[${a} - 1];\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          `}else{s+=`\n            bool nextRowOutOfBounds =\n              (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n            bool nextColOutOfBounds =\n              (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          `}}}}this.userCode=`\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        ${e}\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        ${s}\n\n        setOutput(result);\n      }\n    `}}function identity(e){const{inputs:t,backend:n}=e;const{x:r}=t;n.incRef(r.dataId);return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const identityConfig={kernelName:Identity,backendName:"webgl",kernelFunc:identity};function complex(e){const{inputs:t,backend:n}=e;const{real:r,imag:a}=t;const s=n.makeTensorInfo(r.shape,"complex64");const o=n.texData.get(s.dataId);const i=identity({inputs:{x:r},backend:n});const u=identity({inputs:{x:a},backend:n});o.complexTensorInfos={real:i,imag:u};return s}const LEAKYRELU=`return (a < 0.) ? b * a : a;`;const LEAKYRELU_PACKED=`\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;const PRELU=`return (a < 0.) ? b * a : a;`;const PRELU_PACKED=`\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;const CHECK_NAN_SNIPPET_UNARY=`if (isnan(x)) return x;`;function unaryKernelFunc({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:o}=a;const i=s;const u=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){const e=i.texData.get(o.dataId);const t=n(e.values,u);return i.makeTensorInfo(o.shape,u,t)}const l=env().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null;let c;if(l){c=new UnaryOpPackedProgram(o.shape,t)}else{c=new UnaryOpProgram(o.shape,e)}return i.runWebGLProgram(c,[o],u)}}function binaryKernelFunc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=false,supportsComplex:r=false,cpuKernelImpl:a,dtype:s}){return({inputs:o,backend:i})=>{const{a:u,b:l}=o;const c=i;if(r&&u.dtype==="complex64"){const t=c.texData.get(u.dataId);const n=c.texData.get(l.dataId);const[r,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,r]=t;const a={dataId:n.dataId,dtype:n.dtype,shape:u.shape};const s={dataId:r.dataId,dtype:r.dtype,shape:l.shape};const o=new BinaryOpProgram(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],upcastType(n.dtype,r.dtype))}));const s=complex({inputs:{real:r,imag:a},backend:c});c.disposeIntermediateTensorInfo(r);c.disposeIntermediateTensorInfo(a);return s}const p=s||upcastType(u.dtype,l.dtype);if((u.dtype==="string"||l.dtype==="string"||c.shouldExecuteOnCPU([u,l]))&&a!=null){const e=c.texData.get(u.dataId).values;const t=c.texData.get(l.dataId).values;const n=u.dtype==="string"?fromUint8ToStringArray(e):e;const r=u.dtype==="string"?fromUint8ToStringArray(t):t;const[s,o]=a(u.shape,l.shape,n,r,p);const i=c.makeTensorInfo(o,p);const m=c.texData.get(i.dataId);m.values=s;return i}const m=env().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let d;if(m){d=new BinaryOpPackedProgram(t,u.shape,l.shape,n)}else{d=new BinaryOpProgram(e,u.shape,l.shape)}return c.runWebGLProgram(d,[u,l],p)}}function mapActivationToShaderProgram(e,t=false){if(e==="linear"){if(t){return LINEAR}return LINEAR$1}else if(e==="relu"){if(t){return RELU$1}return RELU$2}else if(e==="elu"){if(t){return ELU}return ELU$1}else if(e==="relu6"){if(t){return RELU6}return RELU6$1}else if(e==="prelu"){if(t){return PRELU_PACKED}return PRELU}else if(e==="leakyrelu"){if(t){return LEAKYRELU_PACKED}return LEAKYRELU}else if(e==="sigmoid"){if(t){return SIGMOID$1}return SIGMOID$2}throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const ADD="return a + b;";const addKernelFunc=binaryKernelFunc({opSnippet:ADD,packedOpSnippet:ADD,supportsComplex:true,cpuKernelImpl:addImplCPU});const addConfig={kernelName:Add,backendName:"webgl",kernelFunc:addKernelFunc};class MeanProgram{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const o=Math.floor(n/4)*4;const i=n%4;let u=`sumValue += dot(values, ones);`;if(t!=null){const e=1/t;u=`sumValue += dot(values * ${isInt(e)?e.toPrecision(2):e}, ones);`}let l="";if(a%n>0){l=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return 0.0;\n        }\n      `}this.userCode=`\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${l}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ${o}; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${u}\n        }\n\n        int inIdx = inOffset + ${o};\n        if (${i===1}) {\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n          ${u}\n        } else if (${i===2}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1), 0.0, 0.0);\n\n          ${u}\n        } else if (${i===3}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2), 0.0);\n\n          ${u}\n        }\n        setOutput(sumValue);\n      }\n    `}}class ReduceProgram{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let o="0.0";let i=``;if(t==="prod"){o="1.0"}else if(t==="min"){o="1.0 / 1e-20";i=`min`}else if(t==="max"){o="-1.0 / 1e-20";i=`max`}let u=`${t}(${t}(${t}(`+"minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";if(t==="sum"){u=`sumValue`}else if(t==="prod"){u=`prodValue`}else if(t==="all"){u=`allValue`}else if(t==="any"){u=`anyValue`}const l=Math.floor(n/4)*4;const c=n%4;let p=`\n      if (${t==="sum"}) {\n        sumValue += dot(values, ones);\n      } else if (${t==="prod"}) {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = ${i}(values, minMaxValue);\n        if (${t==="min"} || ${t==="max"}) {\n          minMaxValue = ${i}(values, minMaxValue);\n          bvec4 isNaN = isnan(values);\n          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n            minMaxValue = vec4(NAN);\n          }\n        }\n      }\n    `;let m=`vec4`;if(t==="all"){o="1.0";p=`\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      `;m=`bvec4`}else if(t==="any"){o="0.0";p=`\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      `;m=`bvec4`}let d="";if(a%n>0){d=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return initializationValue;\n        }\n      `}this.userCode=`\n      const float initializationValue = ${o};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${d}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        vec4 minMaxValue = vec4(${o});\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < ${l}; i += 4) {\n          int inIdx = inOffset + i;\n          ${m} values = ${m}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${p}\n        }\n\n        int inIdx = inOffset + ${l};\n        if (${c===1}) {\n          ${m} values = ${m}(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          ${p}\n        } else if (${c===2}) {\n          ${m} values = ${m}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          ${p}\n        } else if (${c===3}) {\n          ${m} values = ${m}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          ${p}\n        }\n        setOutput(${u});\n      }\n    `}}function getReductionStages(e){const t=[];while(t.length===0||t[t.length-1].outSize!==1){const n=t.length?t[t.length-1].outSize:e[1];const r=computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function reduce(e,t,n,r){const a=getReductionStages(e.shape);let s=e;for(let o=0;o<a.length;o++){const{inSize:i,windowSize:u,outSize:l}=a[o];let c;let p;if(n==="mean"){c=o===0?new MeanProgram({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new MeanProgram({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l})}else{c=new ReduceProgram({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},n)}p=s;s=r.runWebGLProgram(c,[s],t);if(p.dataId!==e.dataId){r.disposeIntermediateTensorInfo(p)}}return s}function packedReshape(e,t,n){const r=[getBatchDim(e.shape),...getRowsCols(e.shape)];const a={dtype:e.dtype,shape:r,dataId:e.dataId};const s=[getBatchDim(t),...getRowsCols(t)];const o=new ReshapePackedProgram(s,r);const i=true;const u=[r];const l=n.runWebGLProgram(o,[a],e.dtype,u,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function reshape(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{shape:s}=r;const o=n;const i=sizeFromShape(a.shape);const u=inferFromImplicitShape(s,i);const l=sizeFromShape(u);assert(i===l,(()=>`The new shape (${u}) has ${l} elements and the old `+`shape (${a.shape}) has ${i} elements. The new shape and old `+`shape must have the same number of elements.`));const c=o.texData.get(a.dataId);if(c.isPacked&&!isReshapeFree(a.shape,u)&&!(c.texture!==null&&isReshapeFree(c.shape,u))){return packedReshape(a,u,o)}o.incRef(a.dataId);return{dataId:a.dataId,shape:u,dtype:a.dtype}}const reshapeConfig={kernelName:Reshape,backendName:"webgl",kernelFunc:reshape};class TransposeProgram{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++){n[r]=e[t[r]]}this.outputShape=n;this.rank=n.length;const r=getCoordsDataType(this.rank);const a=getSwitchedCoords(t);this.userCode=`\n    void main() {\n      ${r} resRC = getOutputCoords();\n      setOutput(getA(${a}));\n    }\n    `}}function getSwitchedCoords(e){const t=e.length;if(t>6){throw Error(`Transpose for rank ${t} is not yet supported`)}const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"];const r=new Array(t);for(let t=0;t<e.length;t++){r[e[t]]=n[t]}return r.join()}class TransposePackedProgram{constructor(e,t){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;const n=new Array(e.length);for(let r=0;r<n.length;r++){n[r]=e[t[r]]}this.outputShape=n;this.rank=n.length;if(this.rank>6){throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`)}const r=getCoordsDataType(this.rank);const a=getVecChannels("rc",this.rank);const s=new Array(this.rank);for(let e=0;e<t.length;e++){s[t[e]]=a[e]}const o=`vec2(${s.slice(-2).join()})`;const i=`++${a[this.rank-1]} < ${n[this.rank-1]}`;const u=`getChannel(getA(${s.join()}), ${o})`;this.userCode=`\n    void main() {\n      ${r} rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = ${u};\n      if(${i}) {\n        result[1] = ${u};\n      }\n      --${a[this.rank-1]};\n      if(++${a[this.rank-2]} < ${n[this.rank-2]}) {\n        result[2] = ${u};\n        if(${i}) {\n          result[3] = ${u};\n        }\n      }\n      setOutput(result);\n    }\n    `}}function transposeImpl(e,t,n){const r=env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new TransposePackedProgram(e.shape,t):new TransposeProgram(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function sumImpl(e,t,n,r){const a=t;const s=e.shape.length;const o=parseAxisParam(a,e.shape);let i=o;const u=getAxesPermutation(i,s);const l=u!=null;let c=e;if(l){c=transposeImpl(e,u,r);i=getInnerMostAxes(i.length,s)}assertAxesAreInnerMostDims("sum",i,s);const[p,m]=computeOutAndReduceShapes(c.shape,i);let d=p;if(n){d=expandShapeToKeepDim(p,o)}const h=sizeFromShape(m);const f=sizeFromShape(e.shape);const g=f/h;const y=reshape({inputs:{x:c},attrs:{shape:[g,h]},backend:r});const x=sumOutType(e.dtype);const T=reduce(y,x,"sum",r);const E=reshape({inputs:{x:T},attrs:{shape:d},backend:r});r.disposeIntermediateTensorInfo(y);r.disposeIntermediateTensorInfo(T);if(l){r.disposeIntermediateTensorInfo(c)}return E}function sum(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{axis:s,keepDims:o}=r;return sumImpl(a,s,o,n)}const sumConfig={kernelName:Sum,backendName:"webgl",kernelFunc:sum};const POW=`\n  if(a < 0.0 && floor(b) < b){\n    return NAN;\n  }\n  if (b == 0.0) {\n    return 1.0;\n  }\n  return (round(mod(b, 2.0)) != 1) ?\n      pow(abs(a), b) : sign(a) * pow(abs(a), b);\n`;const POW_PACKED=`\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n  vec4 result = multiplier * pow(abs(a), b);\n\n  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n  bvec4 isExpZero = equal(b, vec4(0.0));\n  result.r = isExpZero.r ? 1.0 : result.r;\n  result.g = isExpZero.g ? 1.0 : result.g;\n  result.b = isExpZero.b ? 1.0 : result.b;\n  result.a = isExpZero.a ? 1.0 : result.a;\n\n  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n  `+CHECK_NAN_SNIPPET+`\n  return result;\n`;const pow=binaryKernelFunc({opSnippet:POW,packedOpSnippet:POW_PACKED});const powConfig={kernelName:Pow,backendName:"webgl",kernelFunc:pow};class ConcatProgram{constructor(e){this.outputShape=[];this.outputShape=computeOutShape$1(e,1);this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++){t[n]=t[n-1]+e[n][1]}const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}) `+`setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length;const a=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${a}));`);this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        ${n.join("\n        ")}\n      }\n    `}}class ConcatPackedProgram{constructor(e,t){this.packedInputs=true;this.packedOutput=true;this.outputShape=[];this.outputShape=computeOutShape$1(e,t);const n=this.outputShape;const r=n.length;const a=getCoordsDataType(r);const s=getChannels("coords",r);const o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map(((e,t)=>`T${t}`));const i=new Array(e.length-1);i[0]=e[0][t];for(let n=1;n<i.length;n++){i[n]=i[n-1]+e[n][t]}const u=o[t];const l=o.slice(-2);const c=o.join();let p=`if (${u} < ${i[0]}) {\n        return getChannel(\n            getT0(${c}), vec2(${l.join()}));\n        }`;for(let e=1;e<i.length;e++){const t=i[e-1];p+=`\n        if (${u} < ${i[e]}  && ${u} >= ${i[e-1]}) {\n          return getChannel(\n            getT${e}(${shiftedChannels(o,u,t)}),\n            vec2(${shiftedChannels(l,u,t)}));\n        }`}const m=i.length;const d=i[i.length-1];p+=`\n        return getChannel(\n          getT${m}(${shiftedChannels(o,u,d)}),\n          vec2(${shiftedChannels(l,u,d)}));`;this.userCode=`\n      float getValue(${o.map((e=>"int "+e))}) {\n        ${p}\n      }\n\n      void main() {\n        ${a} coords = getOutputCoords();\n        vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n        ${s[r-1]} = ${s[r-1]} + 1;\n        if (${s[r-1]} < ${n[r-1]}) {\n          result.g = getValue(${s});\n        }\n\n        ${s[r-2]} = ${s[r-2]} + 1;\n        if (${s[r-2]} < ${n[r-2]}) {\n          result.a = getValue(${s});\n        }\n\n        ${s[r-1]} = ${s[r-1]} - 1;\n        if (${s[r-2]} < ${n[r-2]} &&\n            ${s[r-1]} < ${n[r-1]}) {\n          result.b = getValue(${s});\n        }\n        setOutput(result);\n      }\n    `}}function shiftedChannels(e,t,n){const r=e.indexOf(t);const a=e.map(((e,t)=>{if(t===r){return`${e} - ${n}`}else{return e}}));return a.join()}function real(e){const{inputs:t,backend:n}=e;const{input:r}=t;const a=n.texData.get(r.dataId);return identity({inputs:{x:a.complexTensorInfos.real},backend:n})}function concatImpl(e,t,n){const r=e[0].dtype;if(r==="complex64"){const r=e.map((e=>real({inputs:{input:e},backend:n})));const a=e.map((e=>imag({inputs:{input:e},backend:n})));const s=concatImpl(r,t,n);const o=concatImpl(a,t,n);const i=complex({inputs:{real:s,imag:o},backend:n});r.forEach((e=>n.disposeIntermediateTensorInfo(e)));a.forEach((e=>n.disposeIntermediateTensorInfo(e)));n.disposeIntermediateTensorInfo(s);n.disposeIntermediateTensorInfo(o);return i}let a=n.shouldExecuteOnCPU(e);if(r==="string"){a=true}if(a){const a=e.map((e=>{const r=sizeFromShape(e.shape.slice(t));const a=[-1,r];return reshape({inputs:{x:e},backend:n,attrs:{shape:a}})}));const s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));const o=computeOutShape$1(a.map((e=>e.shape)),1);const i=a[0].shape[0]===1;const u=concatImplCPU(s,o,r,i);const l=computeOutShape$1(e.map((e=>e.shape)),t);const c=n.makeTensorInfo(l,r,u);a.forEach((e=>n.disposeIntermediateTensorInfo(e)));return c}const s=env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(e.length>s){const r=[];for(let a=0;a<e.length;a+=s){const o=e.slice(a,a+s);r.push(concatImpl(o,t,n))}const a=concatImpl(r,t,n);for(const e of r){n.disposeIntermediateTensorInfo(e)}return a}if(env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const a=new ConcatPackedProgram(e.map((e=>e.shape)),t);return n.runWebGLProgram(a,e,r)}const{tensors2D:o,outShape:i}=computeTensors2D(e,t,n);const u=new ConcatProgram(o.map((e=>e.shape)));const l=n.runWebGLProgram(u,o,r);o.forEach((e=>n.disposeIntermediateTensorInfo(e)));const c=reshape({inputs:{x:l},attrs:{shape:i},backend:n});n.disposeIntermediateTensorInfo(l);return c}function concat(e){const{inputs:t,backend:n,attrs:r}=e;const{axis:a}=r;const s=parseAxisParam(a,t[0].shape)[0];const o=computeOutShape$1(t.map((e=>e.shape)),s);if(sizeFromShape(o)===0){return n.makeTensorInfo(o,t[0].dtype,[])}const i=t.filter((e=>sizeFromShape(e.shape)>0));if(i.length===1){return identity({inputs:{x:i[0]},backend:n})}const u=i.map((e=>e.shape));assertParamsConsistent(u,s);return concatImpl(i,s,n)}const concatConfig={kernelName:Concat,backendName:"webgl",kernelFunc:concat};function expandDims(e){const{inputs:t,attrs:n,backend:r}=e;const{dim:a}=n;const{input:s}=t;const o=s.shape.length;const i=s.shape.slice();let u=a;if(a<0){assert(-(o+1)<=a,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`));u=o+a+1}i.splice(u,0,1);return reshape({inputs:{x:s},backend:r,attrs:{shape:i}})}function pack(e){const{inputs:t,backend:n,attrs:r}=e;const{axis:a}=r;if(t.length===1){return expandDims({inputs:{input:t[0]},backend:n,attrs:{dim:a}})}const s=t[0].shape;const o=t[0].dtype;t.forEach((e=>{assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes");assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[];const u=t.map((e=>{const t=expandDims({inputs:{input:e},backend:n,attrs:{dim:a}});i.push(t);return t}));const l=concat({inputs:u,backend:n,attrs:{axis:a}});i.forEach((e=>n.disposeIntermediateTensorInfo(e)));return l}const packConfig={kernelName:Pack,backendName:"webgl",kernelFunc:pack};const NOT_EQUAL=`return float(a != b);`;const notEqual=binaryKernelFunc({opSnippet:NOT_EQUAL,cpuKernelImpl:notEqualImplCPU,dtype:"bool"});function cast(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{dtype:s}=r;if(s==="complex64"){if(a.dtype==="complex64"){return identity({inputs:{x:a},backend:n})}const e=zeros$1(a.shape);const t=cast({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});const r=complex({inputs:{real:t,imag:e},backend:n});e.dispose();n.disposeIntermediateTensorInfo(t);return r}if(a.dtype==="complex64"){const e=real({inputs:{input:a},backend:n});const t=cast({inputs:{x:e},backend:n,attrs:{dtype:s}});n.disposeIntermediateTensorInfo(e);return t}if(!hasEncodingLoss(a.dtype,s)){const e=identity({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}if(s==="int32"){return int(a,n)}if(s==="bool"){const e=n.makeTensorInfo([],"bool",getTypedArrayFromDType("bool",1));const t={a:a,b:e};const r=notEqual({inputs:t,backend:n});n.disposeIntermediateTensorInfo(e);return r}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}const castConfig={kernelName:Cast,backendName:"webgl",kernelFunc:cast};const RELU=CHECK_NAN_SNIPPET$1+`\n  return (x < 0.0) ? 0.0 : x;\n`;const RELU_PACKED=`\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n`;const relu=unaryKernelFunc({opSnippet:RELU,packedOpSnippet:RELU_PACKED});const reluConfig={kernelName:Relu,backendName:"webgl",kernelFunc:relu};function meanImpl(e,t,n,r){const a=sizeFromShape(t);const s=sizeFromShape(e.shape);const o=s/a;const i=reshape({inputs:{x:e},attrs:{shape:[o,a]},backend:r});const u=reduce(i,"float32","mean",r);const l=reshape({inputs:{x:u},attrs:{shape:n},backend:r});r.disposeIntermediateTensorInfo(i);r.disposeIntermediateTensorInfo(u);return l}const meanConfig={kernelName:Mean,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e;const{keepDims:a,axis:s}=t;const o=n;const i=r.shape.length;const u=parseAxisParam(s,r.shape);let l=u;const c=getAxesPermutation(l,i);const p=c!=null;const m=o.shouldExecuteOnCPU([r]);const d=[];let h=r;if(p){if(m){const e=o.texData.get(h.dataId);const t=e.values;const n=new Array(i);for(let e=0;e<n.length;e++){n[e]=r.shape[c[e]]}const a=transposeImplCPU(t,r.shape,r.dtype,c,n);h=o.makeTensorInfo(n,r.dtype);const s=o.texData.get(h.dataId);s.values=a}else{h=transposeImpl(r,c,o)}d.push(h);l=getInnerMostAxes(l.length,i)}assertAxesAreInnerMostDims("sum",l,i);const[f,g]=computeOutAndReduceShapes(h.shape,l);let y=f;if(a){y=expandShapeToKeepDim(f,u)}const x=meanImpl(h,g,y,o);for(const e of d){o.disposeIntermediateTensorInfo(e)}return x}};function prod(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{axis:s,keepDims:o}=r;const i=a.shape.length;const u=[];const l=parseAxisParam(s,a.shape);let c=l;const p=getAxesPermutation(c,i);let m=a;if(p!=null){m=transpose({inputs:{x:a},backend:n,attrs:{perm:p}});c=getInnerMostAxes(c.length,i);u.push(m)}assertAxesAreInnerMostDims("prod",c,i);let d;if(n.shouldExecuteOnCPU([m])){const e=n.texData.get(m.dataId).values;const{outVals:t,outShape:r,outDtype:a}=prodImplCPU(m.shape,m.dtype,e,c);d=n.makeTensorInfo(r,a,t)}else{const[e,t]=computeOutAndReduceShapes(m.shape,c);const r=sizeFromShape(t);const s=reshape({inputs:{x:m},backend:n,attrs:{shape:[-1,r]}});const o=sumOutType(a.dtype);const i=reduce(s,o,"prod",n);d=reshape({inputs:{x:i},backend:n,attrs:{shape:e}});u.push(s);u.push(i)}if(o){u.push(d);const e=expandShapeToKeepDim(d.shape,l);d=reshape({inputs:{x:d},backend:n,attrs:{shape:e}})}u.forEach((e=>n.disposeIntermediateTensorInfo(e)));return d}const prodConfig={kernelName:Prod,backendName:"webgl",kernelFunc:prod};class PadProgram{constructor(e,t,n){this.variableNames=["x"];this.customUniforms=[{name:"value",type:"float"}];this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length;const a=getCoordsDataType(r);const s=t.map((e=>e[0])).join(",");const o=t.map(((t,n)=>t[0]+e[n])).join(",");const i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`\n        int start = ${s};\n        int end = ${o};\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(value);\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      `;return}this.userCode=`\n      ${a} start = ${a}(${s});\n      ${a} end = ${a}(${o});\n\n      void main() {\n        ${a} outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(value);\n        } else {\n          ${a} coords = outC - start;\n          setOutput(getX(${i}));\n        }\n      }\n    `}}class PadPackedProgram{constructor(e,t,n){this.variableNames=["x"];this.packedInputs=true;this.packedOutput=true;this.customUniforms=[{name:"value",type:"float"}];this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length;const a=getCoordsDataType(r);const s=t.map((e=>e[0])).join(",");const o=t.map(((t,n)=>t[0]+e[n])).join(",");const i=getChannels("rc",r);const u=getChannels("source",r);const l=`${i[r-1]} < ${this.outputShape[r-1]}`;const c=r===1?"source":`vec2(${u.slice(-2).join()})`;const p=[`${a} rc = outputLoc;`,`${i[r-1]} += 1;\n       if(${l}) {\n      `,r===1?"":`}\n       rc = outputLoc;\n       ${i[r-2]} += 1;\n       if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":`  ${i[r-1]} += 1;\n         if(${l}) {`];const m=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=r===1?2:4;e<t;e++){d+=`\n        ${p[e]}\n        if (${m}) {\n          result[${e}] = float(value);\n        } else {\n          ${a} source = rc - start;\n          result[${e}] = getChannel(getX(${u.join()}), ${c});\n        }\n      `}d+=r===1?`} `:`}}`;this.userCode=`\n      const ${a} start = ${a}(${s});\n      const ${a} end = ${a}(${o});\n\n      void main() {\n        ${a} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${d}\n        setOutput(result);\n      }\n    `}}const padV2=e=>{const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{paddings:s,constantValue:o}=r;if(sizeFromShape(a.shape)===0){const e=s.map(((e,t)=>e[0]+a.shape[t]+e[1]));return fill({backend:n,attrs:{shape:e,value:o,dtype:a.dtype}})}const i=env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new PadPackedProgram(a.shape,s,o):new PadProgram(a.shape,s,o);const u=[[o]];return n.runWebGLProgram(i,[a],a.dtype,u)};const padV2Config={kernelName:PadV2,backendName:"webgl",kernelFunc:padV2};class SliceProgram{constructor(e){this.variableNames=["source"];this.outputShape=e;this.rank=e.length;const t=getCoordsDataType(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=getCoords(this.rank);let r;const a=e.map(((e,t)=>`sourceLoc.${coords[t]} = start[${t}] + coords.${coords[t]};`));r=`\n        ${t} sourceLoc;\n        ${t} coords = getOutputCoords();\n        ${a.join("\n")}\n      `;this.userCode=`\n      void main() {\n        ${r}\n        setOutput(getSource(${n}));\n      }\n    `}}const coords=["x","y","z","w","u","v"];function getCoords(e){if(e===1){return"sourceLoc"}else if(e<=6){return coords.slice(0,e).map((e=>"sourceLoc."+e)).join(",")}else{throw Error(`Slicing for rank ${e} is not yet supported`)}}class SlicePackedProgram{constructor(e){this.variableNames=["source"];this.packedInputs=true;this.packedOutput=true;this.outputShape=e;this.rank=e.length;this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=getCoordsDataType(this.rank);const n=getChannels("coords",this.rank);const r=getChannels("sourceLoc",this.rank);const a=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`;const s=`getChannel(getSource(${r.join()}), ${a})`;const o=`\n      result.x = ${s};\n      if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n        ++${r[this.rank-1]};\n        result.y = ${s};\n        --${r[this.rank-1]};\n      }\n    `;const i=this.rank===1?"":`\n      --${n[this.rank-1]};\n      if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n        ++${r[this.rank-2]};\n        result.z = ${s};\n        if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n          ++${r[this.rank-1]};\n          result.w = ${s};\n        }\n      }\n    `;const u=this.rank<=4?`sourceLoc = coords +\n            ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n      void main() {\n        ${t} coords = getOutputCoords();\n        ${t} sourceLoc;\n        ${u}\n        vec4 result = vec4(0.);\n        ${o}\n        ${i}\n        setOutput(result);\n      }\n    `}}function slice(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a}=t;const{begin:s,size:o}=r;const[i,u]=parseSliceParams(a,s,o);assertParamsValid(a,i,u);if(sizeFromShape(u)===0){return n.makeTensorInfo(u,a.dtype,[])}if(n.shouldExecuteOnCPU([a])||a.dtype==="string"){const e=n.texData.get(a.dataId);const t=sliceImplCPU(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId);const c=isSliceContinous(a.shape,i,u);if(l||!c){const e=env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new SlicePackedProgram(u):new SliceProgram(u);const t=[i];return n.runWebGLProgram(e,[a],a.dtype,t)}n.uploadToGPU(a.dataId);return shallowSlice(a,i,u,n)}function unpack(e){const{inputs:t,backend:n,attrs:r}=e;const{value:a}=t;let{axis:s}=r;if(s<0){s+=a.shape.length}const o=a;const i=o.shape.length;const u=a.shape[s];const l=new Array(i-1);let c=0;for(let e=0;e<i;e++){if(e!==s){l[c++]=o.shape[e]}}const p=[];const m=new Array(i).fill(0);const d=o.shape.slice();d[s]=1;const h=new Array(u);for(let e=0;e<h.length;e++){m[s]=e;const t=slice({inputs:{x:o},backend:n,attrs:{begin:m,size:d}});const r=reshape({inputs:{x:t},backend:n,attrs:{shape:l}});h[e]=r;p.push(t)}p.forEach((e=>n.disposeIntermediateTensorInfo(e)));return h}const unpackConfig={kernelName:Unpack,backendName:"webgl",kernelFunc:unpack};const IS_FINITE=`return float(!isnan(x) && !isinf(x));`;const isFinite$1=unaryKernelFunc({opSnippet:IS_FINITE,dtype:"bool"});const isFiniteConfig={kernelName:IsFinite,backendName:"webgl",kernelFunc:isFinite$1};class SelectProgram{constructor(e,t,n){this.variableNames=["c","a","b"];this.outputShape=t;let r;let a;if(n>4){throw Error(`Where for rank ${n} is not yet supported`)}if(n===1){a=`resRC`;r=`resRC`}else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"];const s=[];const o=[];for(let r=0;r<t.length;r++){o.push(`${n[r]}`);if(r<e){s.push(`${n[r]}`)}}r=s.join();a=o.join()}const s=getCoordsDataType(n);this.userCode=`\n      void main() {\n        ${s} resRC = getOutputCoords();\n        float cVal = getC(${r});\n        if (cVal >= 1.0) {\n          setOutput(getA(${a}));\n        } else {\n          setOutput(getB(${a}));\n        }\n      }\n    `}}function service_min_select(e){const{inputs:t,backend:n}=e;const{condition:r,t:a,e:s}=t;const o=new SelectProgram(r.shape.length,a.shape,a.shape.length);return n.runWebGLProgram(o,[r,a,s],upcastType(a.dtype,s.dtype))}const selectConfig={kernelName:Select,backendName:"webgl",kernelFunc:service_min_select};const COMPLEX_MULTIPLY={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class BinaryOpComplexProgram{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"];this.outputShape=assertAndGetBroadcastShape(t,n);this.userCode=`\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        ${e}\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    `}}const MUL="return a * b;";function multiply(e){const{inputs:t,backend:n}=e;const{a:r,b:a}=t;const s=upcastType(r.dtype,a.dtype);if(r.dtype==="complex64"){const e=n.texData.get(r.dataId);const t=n.texData.get(a.dataId);const s=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL,r.shape,a.shape);const o=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG,r.shape,a.shape);const i=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:a.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:a.shape}];const u=n.runWebGLProgram(s,i,"float32");const l=n.runWebGLProgram(o,i,"float32");const c=complex({inputs:{real:u,imag:l},backend:n});n.disposeIntermediateTensorInfo(u);n.disposeIntermediateTensorInfo(l);return c}if(n.shouldExecuteOnCPU([r,a])){const e=n.texData.get(r.dataId);const t=n.texData.get(a.dataId);const[o,i]=multiplyImplCPU(r.shape,a.shape,e.values,t.values,s);const u=n.makeTensorInfo(i,s);const l=n.texData.get(u.dataId);l.values=o;return u}let o;if(env().getBool("WEBGL_PACK_BINARY_OPERATIONS")){o=new BinaryOpPackedProgram(MUL,r.shape,a.shape)}else{o=new BinaryOpProgram(MUL,r.shape,a.shape)}return n.runWebGLProgram(o,[r,a],s)}const multiplyConfig={kernelName:Multiply,backendName:"webgl",kernelFunc:multiply};class MatMulPackedProgram{constructor(e,t,n,r=false,a=false,s=false,o=null,i=false,u=false){this.variableNames=["matrixA","matrixB"];this.packedInputs=true;this.packedOutput=true;this.outputShape=n;this.enableShapeUniforms=useShapeUniforms(this.outputShape.length);const l=r?e[1]:e[2];const c=Math.ceil(l/2);const p=r?"i * 2, rc.y":"rc.y, i * 2";const m=a?"rc.z, i * 2":"i * 2, rc.z";const d=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"];const h=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let f="",g="";if(o){if(i){f=`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${o}\n        }`}else if(u){f=`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${o}\n        }`}else{f=`vec4 activation(vec4 x) {\n          ${o}\n        }`}g=`result = activation(result);`}const y=s?"result += getBiasAtOutCoords();":"";if(s){this.variableNames.push("bias")}if(i){this.variableNames.push("preluActivationWeights")}if(u){this.variableNames.push("leakyreluAlpha")}let x="rc.x";let T="rc.x";if(e[0]<t[0]){x=`int(min(float(rc.x), ${e[0]-1}.))`}else if(t[0]<e[0]){T=`int(min(float(rc.x), ${t[0]-1}.))`}this.userCode=`\n      ${f}\n      // Don't use uniform for sharedDimensionPacked for performance.\n      const float sharedDimension = ${c}.0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < ${c}; i++) {\n          int batchA = ${x};\n          int batchB = ${T};\n          vec4 a = getMatrixA(batchA, ${p});\n          vec4 b = getMatrixB(batchB, ${m});\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += (${d[0]} * ${h[0]});\n          result += (${d[1]} * ${h[1]});\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        ${y}\n\n        ${g}\n\n        setOutput(result);\n      }\n    `}}const MATMUL_SHARED_DIM_THRESHOLD=1e3;function batchMatMulImpl({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:u=null}){const l=e.shape.length;const c=t.shape.length;const p=n?e.shape[l-2]:e.shape[l-1];const m=r?t.shape[c-1]:t.shape[c-2];const d=n?e.shape[l-1]:e.shape[l-2];const h=r?t.shape[c-2]:t.shape[c-1];const f=e.shape.slice(0,-2);const g=t.shape.slice(0,-2);const y=sizeFromShape(f);const x=sizeFromShape(g);const T=assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2));const E=T.concat([d,h]);assert(p===m,(()=>`Error in matMul: inner shapes (${p}) and (`+`${m}) of Tensors with shapes ${e.shape} and `+`${t.shape} and transposeA=${n}`+` and transposeB=${r} must match.`));const b=n?[y,p,d]:[y,d,p];const N=r?[x,h,m]:[x,m,h];const S=reshape({inputs:{x:e},backend:a,attrs:{shape:b}});const _=reshape({inputs:{x:t},backend:a,attrs:{shape:N}});const I=[S,_];const v=Math.max(y,x);const P=n?S.shape[1]:S.shape[2];const w=s!=null;const A=o!=null;const O=u==="leakyrelu";const $=u!=null?mapActivationToShaderProgram(u,true):null;const k=w||A||O||$!=null;let C;if((d===1||h===1)&&P>MATMUL_SHARED_DIM_THRESHOLD&&k===false){let e=S;let t=_;if(n){e=transpose({inputs:{x:S},backend:a,attrs:{perm:[0,2,1]}});I.push(e)}if(r){t=transpose({inputs:{x:_},backend:a,attrs:{perm:[0,2,1]}});I.push(t)}const s=h!==1;const o=h===1;let i=e;if(s){i=reshape({inputs:{x:e},backend:a,attrs:{shape:[v,P,1]}});I.push(i)}const u=h===1?2:1;let l=t;if(o){l=reshape({inputs:{x:t},backend:a,attrs:{shape:[v,1,P]}});I.push(l)}const c=multiply({inputs:{a:i,b:l},backend:a});C=sum({inputs:{x:c},backend:a,attrs:{axis:u,keepDims:true}});I.push(c)}else{const u=upcastType(e.dtype,t.dtype);const l=new MatMulPackedProgram(b,N,[v,d,h],n,r,w,$,A,O);const c=[S,_];if(s!=null){c.push(s)}if(A){c.push(o)}if(O){const e=a.makeTensorInfo([],"float32",createScalarValue(i,"float32"));c.push(e);I.push(e)}C=a.runWebGLProgram(l,c,u)}const R=reshape({inputs:{x:C},backend:a,attrs:{shape:E}});I.push(C);for(const e of I){a.disposeIntermediateTensorInfo(e)}return R}function batchMatMul(e){const{inputs:t,backend:n,attrs:r}=e;const{a:a,b:s}=t;const{transposeA:o,transposeB:i}=r;return batchMatMulImpl({a:a,b:s,transposeA:o,transposeB:i,backend:n})}const batchMatMulConfig={kernelName:BatchMatMul,backendName:"webgl",kernelFunc:batchMatMul};class GatherProgram{constructor(e,t){this.variableNames=["A","indices"];this.outputShape=t;this.rank=t.length;const n=getCoordsDataType(this.rank);const r=getSourceCoords(e);this.userCode=`\n      void main() {\n        ${n} resRC = getOutputCoords();\n        int index = int(getIndices(resRC.x, resRC.z));\n        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n        setOutput(inBounds * getA(${r}));\n      }\n    `}}function getSourceCoords(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"];const r=[];for(let t=0;t<e.length;t++){if(t===2){r.push("index")}else{r.push(`${n[t]}`)}}return r.join()}function gatherV2(e){const{inputs:t,backend:n,attrs:r}=e;const{x:a,indices:s}=t;const{axis:o,batchDims:i}=r;const u=parseAxisParam(o,a.shape)[0];if(env().get("DEBUG")){const e=n.readSync(s.dataId);const t=a.shape[u];for(let n=0;n<e.length;++n){const r=e[n];assert(r<=t-1&&r>=0,(()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`))}}const l=collectGatherOpShapeInfo(a,s,u,i);const c=sizeFromShape(s.shape);const p=[];const m=reshape({inputs:{x:a},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}});const d=reshape({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,c/l.batchSize]}});p.push(m);p.push(d);const h=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([a,s])||a.dtype==="string"){const e=n.bufferSync(d);const t=n.bufferSync(m);const r=gatherV2ImplCPU(t,e,h);p.forEach((e=>n.disposeIntermediateTensorInfo(e)));return n.makeTensorInfo(l.outputShape,r.dtype,r.values)}const f=new GatherProgram(m.shape,h);const g=n.runWebGLProgram(f,[m,d],m.dtype);p.push(g);const y=reshape({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});p.forEach((e=>n.disposeIntermediateTensorInfo(e)));return y}const gatherV2Config={kernelName:GatherV2,backendName:"webgl",kernelFunc:gatherV2};const SIGMOID=CHECK_NAN_SNIPPET_UNARY+`\n  return 1.0 / (1.0 + exp(-1.0 * x));\n`;const SIGMOID_PACKED=`\n  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n`;const sigmoid=unaryKernelFunc({opSnippet:SIGMOID,packedOpSnippet:SIGMOID_PACKED,cpuKernelImpl:sigmoidImplCPU});const sigmoidConfig={kernelName:Sigmoid,backendName:"webgl",kernelFunc:sigmoid};function _fusedMatMul(e){const{inputs:t,backend:n,attrs:r}=e;const{a:a,b:s,bias:o,preluActivationWeights:i}=t;const{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=r;return batchMatMulImpl({a:a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}const _fusedMatMulConfig={kernelName:_FusedMatMul,backendName:"webgl",kernelFunc:_fusedMatMul};for(let e of[addConfig,sumConfig,powConfig,packConfig,castConfig,reluConfig,meanConfig,prodConfig,padV2Config,unpackConfig,reshapeConfig,isFiniteConfig,identityConfig,selectConfig,multiplyConfig,batchMatMulConfig,gatherV2Config,concatConfig,sigmoidConfig,_fusedMatMulConfig])registerKernel(e);var tfjs=Object.freeze({__proto__:null,cast:cast$1,enableProdMode:enableProdMode,env:env,loadGraphModel:loadGraphModel,oneHot:oneHot,stack:stack,sum:sum$1,tensor:tensor,tidy:tidy,unstack:unstack,zeros:zeros$1});const WHITESPACE_PATTERN=/\s+/g;const PUNCTUATION_PATTERN=/[\xA0!"\\'()*,-./:;?&[\]^_`{|}~“”]/g;const RGB_PATTERN=/rgb\((\d+), (\d+), (\d+)\)/;const RGBA_PATTERN=/rgba\((\d+), (\d+), (\d+), (\d+)\)/;const ORIGIN_PATTERN=/(\d*?\.?\d*)px (\d*?\.?\d*)px/;const PIXEL_PATTERN=/(\d*?\.?\d*)px/;const DOT_PATTERN=/\./g;const BRACKETS_PATTERN=/^\[|\]$/g;const SLASH_PATTERN=/\//g;const WORD_INDEX=Object.fromEntries([..." abcdefghijklmnopqrstuvwxyz1234567890:;/?!=+.,()[]-`*_|~"].map(((e,t)=>[e,t+1])));class FeatureNormalizer{constructor(e){this.normalizers=[];e.forEach((e=>{if(Array.isArray(e)){let[t,n]=e;this.normalizers.push(new t(n))}else{this.normalizers.push(new e)}}))}normalize(e,t){this.normalizers.forEach((n=>{e=n.normalize(e,t)}));return e}}class StringNormalizer{normalize(e){throw new Error("Not implemented.")}}class Lowercase extends StringNormalizer{normalize(e){return e.toLowerCase()}}class StripWhitespace extends StringNormalizer{normalize(e){return e.trim()}}class CollapseWhitespace extends StringNormalizer{normalize(e){return e.replace(WHITESPACE_PATTERN," ")}}class StripAndCollapseWhitespace extends StringNormalizer{normalize(e){return e.replace(WHITESPACE_PATTERN," ").trim()}}class RemovePunctuation extends StringNormalizer{normalize(e){return e.replace(PUNCTUATION_PATTERN,"")}}class ReplacePunctuation extends StringNormalizer{normalize(e){return e.replace(PUNCTUATION_PATTERN," ")}}class ReplaceStr extends StringNormalizer{constructor(e){super();this.pairs=e}normalize(e){if(e){this.pairs.forEach((t=>{e=e.split(t[0]).join(t[1])}))}return e}}class LastCSSClassNormalizer extends StringNormalizer{normalize(e){return e.split(" ").pop()}}class VectorNormalizer{normalize(e){throw new Error("Not implemented.")}}class FloatNormalizer extends VectorNormalizer{normalize(e){return[parseFloat(e)||0]}}class SequenceNormalizer extends VectorNormalizer{constructor(e){super();this.maxLen=e}normalize(e){let t=[...e.toLowerCase()].slice(-this.maxLen).map((e=>e in WORD_INDEX?WORD_INDEX[e]:1));return t.length>=this.maxLen?t:t.concat(new Array(this.maxLen-t.length).fill(0))}}class OneHotVectorNormalizer extends VectorNormalizer{constructor(e){super();const t=e.length;this.empty=new Array(t).fill(0);let n=0;this.categoryMap=e.reduce(((e,t)=>{let r=[...this.empty];r[n++]=1;e[t]=r;return e}),{})}normalize(e){return this.categoryMap[e]||this.empty}}class FontSizeNormalizer extends VectorNormalizer{normalize(e){return[parseFloat(e)||0]}}class ColorNormalizer extends VectorNormalizer{constructor(e){super();this.maxLen=e}normalize(e){let t=[0,0,0,0];const n=e.match(RGB_PATTERN);if(n){n.shift();t=n.map((e=>parseFloat(e)||0));t.push(0)}else{const n=e.match(RGBA_PATTERN);if(n){n.shift();t=n.map((e=>parseFloat(e)||0))}}return t.slice(0,this.maxLen)}}class PixelNormalizer extends VectorNormalizer{normalize(e){const t=e.match(PIXEL_PATTERN);if(t)return[parseFloat(t[1])||0];return[0]}}class OriginNormalizer extends VectorNormalizer{normalize(e){const t=e.match(ORIGIN_PATTERN);if(t){t.shift();return t.map((e=>parseFloat(e)||0))}return[0,0]}}class NodeChildrenLenNormalizer{normalize(e){if(Array.isArray(e))return[e.length];return[0]}}const URL_MARKERS=["http","data","blob","ftp:"];class MetaURLPartsNormalizer{normalize(e,t){if(!e)return[0,0,0,0,0,0,0,0,0];const n=1;const r=URL_MARKERS.includes(e.slice(0,4).toLowerCase())?1:0;if(!r)return[n,r,0,0,e.length,0,0,0,0];let a;try{a=new URL(e)}catch(t){return[n,r,0,0,e.length,0,0,0,0]}const s=a.hostname.includes(t["domain"])?0:1;const o=a.username+a.password+a.hostname+(a.port?a.port:"");const i=a.pathname==="/"?"":a.pathname;const u=Array.from(a.searchParams);const l=o.length;const c=i.length;const p=u.flat().join("").length;const m=o?a.hostname.split(".").length:0;const d=i.split("/").filter(Boolean).length;const h=u.length;return[n,r,s,l,c,p,m,d,h]}}class URLPartsNormalizer{constructor(e){this.maxLen=e;this.maxPartsLen=this.maxLen/3;this.replacePunctuation=new ReplacePunctuation}normalize(e,t){let n;const r=URL_MARKERS.includes(e.slice(0,4).toLowerCase())?1:0;if(!r)return e.substring(0,this.maxLen).trim();try{n=new URL(e)}catch(t){return e.substring(0,this.maxLen).trim()}const a=n.hostname.replace(BRACKETS_PATTERN,"");const s=[n.username,n.password,a.replace(DOT_PATTERN," "),n.port].filter(Boolean).join(" ").slice(0,this.maxPartsLen).trim();const o=n.pathname.replace(SLASH_PATTERN," ").slice(0,2*this.maxPartsLen-s.length).trim();const i=n.search.substring(1).split("&").map((e=>e.split("=")[0].trim())).join(" ").slice(0,3*this.maxPartsLen-s.length-o.length).trim();return[[s,o].join(" ").trim(),i].join(" ").trim()}}class MetaContentNormalizer{normalize(e,t){let n=0;let r=0;if(e){n=e.length;r=e.split(" ").length}return[n,r]}}class FeaturePreProcessor{constructor(e){this.preprocesors=[];for(let t of e)this.preprocesors.push(new t)}process(e,t){this.preprocesors.forEach((t=>e=t.process(e)));return e}}class EmptyPreProcessor{process(e,t){if(!e)return new Map;return e}}class CSSSelectorPreProcessor{process(e,t){if(!e||!(typeof e==="string"||e instanceof String))return new Map;return e.split(";").reduce(((e,t)=>{const[n,r]=t.split(":");if(n&&r&&!(n in e))e[n.trim()]=r.trim();return e}),{})}}function createFeatureGroups(e){let t=[];let n=[];for(let t of e)t.groupName=Object.keys(t)[2];for(let r of e){if(r.scope==="graph"&&r.include)t.push(new FeatureGroup(r.groupName,r[r.groupName]));else if(r.scope==="node"&&r.include)n.push(new FeatureGroup(r.groupName,r[r.groupName]))}return[n,t]}const Preprocessor2Class={empty:EmptyPreProcessor,css_selector:CSSSelectorPreProcessor};const Normalizers2Class={lower:Lowercase,strip_whitespace:StripWhitespace,collapse_whitespace:CollapseWhitespace,strip_and_collapse_whitespace:StripAndCollapseWhitespace,remove_punctuation:RemovePunctuation,replace_punctuation:ReplacePunctuation,sequence:SequenceNormalizer,one_hot_vector:OneHotVectorNormalizer,font_size:FontSizeNormalizer,color:ColorNormalizer,pixel:PixelNormalizer,origin:OriginNormalizer,children_len:NodeChildrenLenNormalizer,replace_str:ReplaceStr,meta_url:MetaURLPartsNormalizer,url_parts:URLPartsNormalizer,meta_content:MetaContentNormalizer,css_class:LastCSSClassNormalizer,float:FloatNormalizer};const splitWithEmpty=(e,t)=>{const n=e.split(t);if(n[0]===""&&n.length===1)return[];return n};class Feature{constructor(e,t){this.name=e;this.dim=t.dim;this.altNames=splitWithEmpty(e,"^");this.path=[];if(t.path)this.path=splitWithEmpty(t.path,"^");let n=[];if(!Object.prototype.hasOwnProperty.call(t,"normalizers")){n.push(Normalizers2Class.empty)}else{for(const e in t.normalizers){const r=t.normalizers[e];if(typeof r==="string"||r instanceof String){n.push(Normalizers2Class[r])}else if(typeof r==="object"&&r!==null){const e=Object.keys(r)[0];n.push([Normalizers2Class[e],Object.values(r[e])[0]])}}}this.normalizer=new FeatureNormalizer(n)}getName(e){if(this.altNames&&Object.keys(e).length>0){for(let t of this.altNames){if(t in e)return t}}return this.name}extractValues(e,t){let n=e;this.path.forEach((e=>{if(e in n)n=n[e]}));const r=this.getName(n);const a=r in n?n[r]:"";const s=this.normalizer.normalize(a||"",t);if(s.length!==this.dim)throw new Error("Feature dimensionality mismatch");return s}}class FeatureGroup{constructor(e,t){this.name=e;this.path=splitWithEmpty(t.path,"/");this.prep=this.initPreprocessing(t);this.features=this.initFeatures(t.features)}initPreprocessing(e){let t=[];if(!Object.prototype.hasOwnProperty.call(e,"prep")){t.push(Preprocessor2Class.empty)}else{for(let n of e.prep)t.push(Preprocessor2Class[n])}return new FeaturePreProcessor(t)}initFeatures(e){let t=[];for(const n of e){const e=Object.keys(n)[0];const r=n[e];if(!Object.prototype.hasOwnProperty.call(r,"names")){t.push(new Feature(e,r));continue}for(const e of r.names)t.push(new Feature(e,r))}return t}extractValues(e,t){let n=e;this.path.forEach((e=>{if(e in n)n=n[e]}));n=this.prep.process(n,t);if(typeof n!=="object"||Array.isArray(n)||n===null){throw new Error(`path ${this.path}, value ${n}, expected ${typeof{}}, got ${n}`)}let r=[];this.features.forEach((e=>r.push(...e.extractValues(n,t))));return r}}const URL_DATA_ATTRS=["src","href","xlink:href"];const zeros=(e,t,n=0)=>Array.from(new Array(t),(t=>Array(e).fill(n)));const get=(e,t,n)=>t in e?e[t]:n;class Graph{constructor(e){this.numNodes=0;this.root=e["obj"]["graph"];this.domain=e["obj"]["domain"];this.graphAttributes={domain:e["obj"]["domain"]};this.featureGroups=e["nodeFeatureGroups"];this.graphFeatureGroups=e["graphFeatureGroups"];this.cutoff=e["cutoff"]}getData(){this.setNodeAttributes();let e=zeros(this.numNodes,this.numNodes);let t=[];let n=[];let r=[[this.root,{}]];let a=this.cutoff;while(r.length&&--a>=0){let n;let[a,s]=r.pop();this._updateFeatures(a,this.featureGroups,t);if(s&&Object.keys(s).length>0)this._updateEdges(a,s,e);[s,n]=[a,a["children"]];for(let e=n.length-1;e>=0;e--)r.push([n[e],s])}this._updateFeatures(this.graphAttributes,this.graphFeatureGroups,n);return this._formatData(e,t,n)}setNodeAttributes(){let e=[[this.root,{}]];let t=this.cutoff;while(e.length&&--t>=0){let t;let[n,r]=e.pop();this._setNodeAttributes(n,r);[r,t]=[n,n["children"]];for(let n=t.length-1;n>=0;n--)e.push([t[n],r])}}_setNodeAttributes(e,t){e["node_id"]=this.numNodes++;e["dom"]=this.domain;e["parent_id"]=get(t,"node_id",0);e["siblings"]=get(t,"children",[]).length;e["level"]=get(t,"level",-1)+1;let n=get(e,"attributes",{});let r=get(t,"attributes",{});URL_DATA_ATTRS.forEach((a=>{let s=`${a}_level`;if(this._hasAttribute(a,n)){e["attributes"][s]=0}else if(this._hasAttribute(a,r)){e["attributes"][a]=r[a];e["attributes"][s]=r[s]+1;if("requestType"in t)e["requestType"]=t["requestType"]}}))}_hasAttribute(e,t){return e in t&&t[e]}_updateFeatures(e,t,n){let r=[];t.forEach((t=>r.push(...t.extractValues(e,{domain:this.domain}).map((e=>Math.round(e*100)/100||0)))));n.push(r)}_updateEdges(e,t,n){n[t["node_id"]][e["node_id"]]=1;n[e["node_id"]][t["node_id"]]=1}_formatData(e,t,n){if(e.length>t.length)this._cutEdges(e,t.length);if(this.graphFeatureGroups.length>0)return[e,t,n];return[e,t]}_cutEdges(e,t){e=e.slice(0,t);e.forEach(((e,n,r)=>{r[n]=e.slice(0,t)}))}}class ML{constructor(e){this.tfjs=e;this._preprocessingFunctions=new Map([["cast",e.cast],["stack",e.stack],["unstack",e.unstack],["localPooling",this._localPoolingMap.bind(this)],["padAdjacency",this._padTensorAdjacency.bind(this)],["padFeatures",this._padTensorFeatures.bind(this)]])}_padTensorAdjacency(e,t){return e.pad([[0,0],[0,t-e.shape[1]],[0,t-e.shape[2]]])}_localPoolingMap(e){return e.map((e=>this._localPooling(e)))}_localPooling(e){let t=e.add(this.tfjs.eye(e.shape[0]));let n=this.tfjs.pow(this.tfjs.sum(t,1),-.5);n=n.where(this.tfjs.isFinite(n),this.tfjs.zeros(n.shape));let r=n.mul(this.tfjs.eye(t.shape[0]));let a=r.dot(t).dot(r);return a}_padTensorFeatures(e,t){return e.pad([[0,0],[0,t-e.shape[1]],[0,0]])}createTensors(e,t){let[n,r]=e;let a=[{data:[n],preprocess:[{funcName:"padAdjacency",args:t}]},{data:[r],preprocess:[{funcName:"padFeatures",args:t}]}];let s=this.tfjs.tidy((()=>a.map((e=>{let t=this.tfjs.tensor(e.data);if(e.preprocess){for(let n of e.preprocess){t=this._preprocessingFunctions.get(n.funcName)(t,n.args)}}return t}))));return s}}const DEFAULT_GRAPH_CUTOFF=500;async function preprocessGraph(e,t,n="."){return new Promise(((r,a)=>{if(!e||!t)return a();let s=e.config;let o=s.cutoff||e.topology.graphml.nodes||DEFAULT_GRAPH_CUTOFF;let[i,u]=createFeatureGroups(s);let l={nodeFeatureGroups:i,graphFeatureGroups:u,obj:{domain:n,graph:t},cutoff:o};let c=new Graph(l);let p=c.getData();r(p)}))}async function predict(e,t,n,r){return new Promise(((a,s)=>{if(!n||!e||!t||!r)return s();let o=n.config;let i=o.cutoff||n.topology.graphml.nodes||DEFAULT_GRAPH_CUTOFF;let u=new ML(e);let l=u.createTensors(r,i);let c=t.execute(l);c.data().then((e=>{a(e)})).catch((e=>{s(e)})).finally((()=>{c.dispose();for(let e of l)e.dispose()}))}))}async function digestPrediction(e){return new Promise(((t,n)=>{e=Array.from(e);if(!e||!Array.isArray(e)||!e.some((e=>e>0))||e.length<2)return n();let r=e.reduce(((e,t)=>e+t),0);e=e.map((e=>e/r));t(e[1]>e[0])}))}async function loadBundledModel(e,t){if(!t)return Promise.reject("model not found");return e.loadGraphModel({load(){let e={modelTopology:t.topology.modelTopology||{},signature:t.topology.signature||{},weightsManifest:t.topology.weightsManifest||[],weightSpecs:t.topology.weightsManifest.map((e=>e.weights))[0]||[],weightData:concatWeights(t.weights.map((e=>Uint8Array.from(atob(e.shard),(e=>e.charCodeAt(0))))))||[]};return e}})}function concatWeights(e){let t=0;e.forEach((e=>{t+=e.byteLength}));let n=new Uint8Array(t);let r=0;e.forEach((e=>{n.set(new Uint8Array(e),r);r+=e.byteLength}));return n.buffer}let modelDataCache;let deviceDataCache;function parsePrediction(e){try{let{rawPrediction:t,prediction:n}=e;return{...t&&typeof t==="object"?{confidenceScore:Array.from(t)}:[],...typeof n==="boolean"?{classLabel:n?"ad":"non-ad"}:{}}}catch(e){}}function parseInputs(e){let t;try{let{bundle:n,preprocessedGraph:r,settings:a,debug:s}=e||{};let{reportConfig:o}=n||{};let{featureReportProbability:i}=a&&a.featureReportProbability?a:o||{};if(!s&&(a.telemetryOptOut||!i||isNaN(i)||i<=Math.random()))return Promise.resolve();if(!r||!Array.isArray(r)||r.length<2)return Promise.resolve();for(let e of r){if(!Array.isArray(e)||!e.length||!Array.isArray(e[0])||!e[0].length||isNaN(e[0][0]))return Promise.resolve()}let u;if(n&&n.topology&&n.topology.graphml&&n.topology.graphml.nodes)u=n.topology.graphml.nodes;t=[compressAdjacencyMatrix(r[0],u),compressFeatureMatrix(r[1])];return gzipAndBase64Encode(t)}catch(e){if(t&&Array.isArray(t))return Promise.resolve(t);return Promise.resolve()}}function parseProfilingData(e){try{let{modelColdStart:t,modelBootupTime:n,preprocessingTime:r,inferenceTime:a,digestTime:s,startTime:o}=e;return{...typeof t==="boolean"?{modelColdStart:t}:{},...!isNaN(n)&&!isNaN(o)?{modelBootupTime:n-o}:{},...!isNaN(r)&&!isNaN(n)?{preprocessingTime:r-n}:{},...!isNaN(a)&&!isNaN(r)?{inferenceTime:a-r}:{},...!isNaN(s)&&!isNaN(a)?{predictionDigestionTime:s-a}:{}}}catch(e){}}function parseModelMetadata(e){try{let{modelName:t,bundle:n}=e||{};if(modelDataCache&&modelDataCache.has(t))return modelDataCache.get(t);let r={...t&&typeof t==="string"?{modelName:t.split("-").slice(0,-1).join("-")||t}:{},...t&&typeof t==="string"&&t.includes("-")?{modelVersion:t.split("-").slice(-1).join("")}:{},...n&&n.weights&&Array.isArray(n.weights)&&n.weights[0]&&n.weights[0].shard?{modelSize:n.weights[0].shard.length}:{}};if(!modelDataCache)modelDataCache=new Map;modelDataCache.set(t,r);return r}catch(e){}}function parseDeviceData(){try{if(deviceDataCache)return deviceDataCache;let e=detectPlatformType();let t=detectBrowser();let n=detectBrowserVersion();let r=detectOsInformation();let a=detectLanguage();let s=detectAvailableMemory();return deviceDataCache={...e?{type:e}:{},...t?{browserName:t}:{},...n?{browserVersion:n}:{},...r?{OSInformation:r}:{},...a?{language:a}:{},...s?{availableMemory:s}:{}}}catch(e){}}function parseWebsiteMetadata(e){let{sender:t}=e||{};if(!t||!t.tab||!t.tab.id||!chrome||!chrome.tabs)return Promise.resolve();return new Promise((e=>{try{chrome.tabs.get(t.tab.id,(t=>{if(chrome.runtime.lastError||!t||!t.url)return e();let n=new URL(t.url);e({url:n.origin+n.pathname,domainName:n.hostname})}))}catch(t){e()}}))}function detectOs(){try{let{userAgent:e}=navigator||{};if(!e)return;switch(true){case/Android/.test(e):return"Android";case/Windows/.test(e):return"Windows";case/Mac OS X/.test(e):return"Mac";case/Linux/.test(e):return"Linux"}}catch(e){}}function detectOsVersion(){try{let{userAgent:e}=navigator||{};if(!e)return;let t=detectOs();let n;if(t==="Android")n="Android";else if(t==="Windows")n=/Phone/.test(e)?/Windows Phone (?:OS )?/:"Windows NT";else if(t==="Mac")n="Mac OS X ";if(n){let t=e.split(n)[1].trim().split(/[^\w.]/)[0];return t.split(/[._]/).slice(0,3).join(".")}}catch(e){}}function detectOsInformation(){try{let e=detectOs();let t=detectOsVersion();let n;if(e){n=e;if(t)n+=` ${t}`}return n}catch(e){}}function detectPlatformType(){try{let e=chrome&&chrome.runtime&&chrome.runtime.getManifest?chrome.runtime.getManifest():null;if(e&&e.short_name){switch(e.short_name){case"Adblock":return"Adblock";case"Adblock Plus":return"Adblock Plus";default:return"Extension"}}let t=detectOs();if(t==="Android")return"Mobile"}catch(e){}}function detectBrowser(){try{let{userAgent:e}=navigator||{};if(!e)return;switch(true){case e.includes("Chrome")&&!e.includes("Chromium")&&!e.includes("OPR")&&!e.includes("Edge")&&!e.includes("Edg")&&!e.includes("SamsungBrowser"):return"Chrome";case e.includes("Firefox")&&!e.includes("Seamonkey"):return"Firefox";case e.includes("OPR"):return"Opera";case(e.includes("Edg")||e.includes("Edge"))&&e.includes("Chrome"):return"Edge"}}catch(e){}}function detectBrowserVersion(){try{let{userAgent:e}=navigator||{};if(!e)return;let t=detectBrowser();let n;if(t){if(t==="Opera")t="opera|opr";if(t==="Edge")t="edge|edg";n=e.match(new RegExp(`(${t}(?=\\/))\\/?\\s*(\\d[^\\s|$]*)`,"i"))}if(!n&&!n.length>=2&&!n[2])n=e.match(/(edge|edg|opr|opera|chrome|firefox|version(?=\/))\/?\s*(\d[^\s|$]*)/i);if(n&&n[2])return n[2]}catch(e){}}function detectLanguage(){let{language:e}=navigator||{};if(e)return e}function detectAvailableMemory(){if(window&&window.performance&&window.performance.memory&&window.performance.memory.totalJSHeapSize)return window.performance.memory.totalJSHeapSize}function compressAdjacencyMatrix(e,t){try{if(!Array.isArray(e)||!e.length||!Array.isArray(e[0])||!e[0].length)return;if(t){for(let n of e)n.push(...new Array(Math.max(0,t-n.length)).fill(0))}return e.map((e=>e.reduce(((e,t)=>{if(e.length&&Math.sign(e[e.length-1])===Math.sign(t-.5))e[e.length-1]+=Math.sign(t-.5);else e.push(Math.sign(t-.5));return e}),[])))}catch(e){}}function compressFeatureMatrix(e){try{if(!Array.isArray(e)||!e.length||!Array.isArray(e[0])||!e[0].length)return;return e.map((e=>e.reduce(((e,t)=>{if(t)e.push(t);else if(e[e.length-1]<0)e[e.length-1]-=1;else e.push(-1);return e}),[])))}catch(e){}}function gzipAndBase64Encode(e){try{if(!Array.isArray(e)||e.length!==2||!Array.isArray(e[0])||!e[0].length||!Array.isArray(e[0][0])||!e[0][0].length||!Array.isArray(e[1][0])||!e[1][0].length)return Promise.resolve();if(typeof CompressionStream==="undefined")return Promise.resolve(e);let t=new ReadableStream({start:t=>t.enqueue((new TextEncoder).encode(JSON.stringify(e))),pull:e=>e.close()});let n=t.pipeThrough(new CompressionStream("gzip"));return new Response(n).arrayBuffer().then((e=>btoa(new Uint8Array(e).reduce(((e,t)=>e+String.fromCharCode(t)),"")))).catch((()=>Promise.resolve(e)))}catch(t){return Promise.resolve(e)}}const QUEUE_DIGESTION_INTERVAL=1e3;const MAX_SEND_ATTEMPT=3;let reportQueue;let debug$1=false;let digestInterval;function queueReport(e){try{let{bundle:t,settings:n,sender:r}=e||{};let{reportConfig:a}=t||{};let{reportProbability:s}=n&&n.reportProbability?n:a||{};let o=!!(r&&r.tab&&r.tab.incognito);if(debug$1!==e.debug)debug$1=e.debug;if(!debug$1&&(n.telemetryOptOut||o&&!n.privateBrowsingTelemetry||!s||isNaN(s)||s<=Math.random()))return Promise.resolve(e);debugOut$1("Queueing report with raw data",false,e);if(!reportQueue)reportQueue=new Set;reportQueue.add(e);if(!digestInterval)digestInterval=setTimeout(digestQueue,QUEUE_DIGESTION_INTERVAL)}catch(e){debugOut$1(`Queueing report failed with "${e}"`,true)}return Promise.resolve(e)}function digestQueue(e=false){try{if(!reportQueue||!reportQueue.size){digestInterval=0;return}let[e]=reportQueue;reportQueue.delete(e);if(!e||["bundle","modelName","prediction","preprocessedGraph"].some((t=>!(t in e)||!e.bundle.reportConfig||!e.bundle.reportConfig.reportURL)))return debugOut$1("Reporting queue digestion failed due to corrupt data",true);let{reportURL:t,reportBearerToken:n}=e.bundle.reportConfig;generateTelemetryData(e).then((e=>sendReport(e,t,n).then((()=>debugOut$1("Report successfully sent:",false,e))))).catch((t=>{e.failedCounter=(e.failedCounter||0)+1;(t instanceof Response?t.text():Promise.resolve(t)).then((t=>debugOut$1(`Sending report failed ${e.failedCounter} times with error "${t}" for`,true,e)));if(e.failedCounter<MAX_SEND_ATTEMPT){debugOut$1("Attempting to resend",false,e);reportQueue.add(e)}else{debugOut$1(`Abandoning report after ${e.failedCounter} retries`,true,e)}})).then((()=>{digestInterval=setTimeout(digestQueue,QUEUE_DIGESTION_INTERVAL)}))}catch(t){if(e){reportQueue.clear();digestInterval=0}else{digestInterval=setTimeout((()=>digestQueue(true)),QUEUE_DIGESTION_INTERVAL)}debugOut$1(`Reporting queue digestion failed with "${t}"`,true)}}async function generateTelemetryData(e){try{if(typeof e!=="object")return Promise.reject();let t=parsePrediction(e);let n=parseProfilingData(e);let r=parseModelMetadata(e);let a=parseDeviceData();let s=await parseWebsiteMetadata(e);let o=await parseInputs(e);return{payload:{timestamp:Date.now(),...t?{prediction:t}:{},...n?{profilingData:n}:{},...r?{modelMetadata:r}:{},...a?{device:a}:{},...s?{websiteMetadata:s}:{},...o?{inputs:o}:{}}}}catch(e){debugOut$1(`Report data calculation failed with "${e}"`,true);return Promise.reject()}}function sendReport(e,t,n){try{debugOut$1("Sending report",false,e);if(!e||typeof e!=="object"||typeof t!=="string"||!t.trim()||n&&typeof n!=="string")return Promise.reject("Missing data");return fetch(t,{method:"POST",headers:{Accept:"*/*",...n?{Authorization:`Bearer ${n}`}:{},"Content-Type":"application/json"},body:JSON.stringify(e)}).then((e=>!e||!e.ok?Promise.reject(e):e))}catch(e){return Promise.reject(e)}}function debugOut$1(e,t=false,...n){if(debug$1){console.log("%cTELDBG ♥ %c| %s%c |","color:cyan",t?"color:red":"color:inherit",e,"color:inherit",...n)}}const MESSAGE_PREFIX="ML:";const MESSAGE_PREPARE_SUFFIX="prepare";const MESSAGE_INFERENCE_SUFFIX="inference";const errors={UNKNOWN_REQUEST:1,MISSING_REQUEST_DATA:2,UNKNOWN_MODEL:3,MISSING_INFERENCE_DATA:4,INFERENCE_FAILED:5,MODEL_INSTANTIATION_FAILED:6,MISSING_ENVIRONMENTAL_SUPPORT:7};let models=new Map;let debug=false;let databaseRef;let performedMaintenance=false;let settings={};const DATABASE_NAME="ml";const TABLE_NAME="data";const BACKEND_URL="https://easylist-downloads.adblockplus.org/models/";const BACKEND_TIMEOUT=1e4;const BACKEND_RETRIES=1;const MODEL_TTL=2592e6;const MODEL_DELETION_TIMEOUT=1e3;const MAINTENANCE_INTERVAL=864e5;const MAINTENANCE_DATABASE_KEY="conf_maintenance_time";const WEBGL_SUPPORT=checkWebGlSupport();enableProdMode();env().set("WEBGL_USE_SHAPES_UNIFORMS",true);function setOptions(e){if(!e||typeof e!=="object")return;settings=Object.assign(settings,e)}function messageListener(e,t,n){if(e&&typeof e.type==="string"&&e.type.startsWith(MESSAGE_PREFIX)){digestMessage(e,t).then(n).catch(n);return true}return false}function digestMessage(e,t){if(!e)return Promise.reject({type:e.type,error:errors.MISSING_REQUEST_DATA});let n=(e.model||"").replace([/[^a-zA-Z0-9._-]/g,""]);if(!e.type||!n||e.type===MESSAGE_PREFIX+MESSAGE_INFERENCE_SUFFIX&&!e.graph)return Promise.reject({type:e.type,error:errors.MISSING_REQUEST_DATA});if(e.debug)debug=true;debugOut("Digesting request",false,e);if(typeof indexedDB==="undefined"){debugOut("Request aborted due to missing database support",true);return Promise.reject({type:e.type,error:errors.MISSING_ENVIRONMENTAL_SUPPORT})}if(!WEBGL_SUPPORT){debugOut("Request aborted due to missing WebGL support",true);return Promise.reject({type:e.type,error:errors.MISSING_ENVIRONMENTAL_SUPPORT})}if(!performedMaintenance){maintenance();performedMaintenance=true}if(e.type===MESSAGE_PREFIX+MESSAGE_PREPARE_SUFFIX){return digestPrepare(n).then((t=>({type:e.type,config:t.config,cutoff:t.topology.graphml.nodes}))).catch((()=>Promise.reject({type:e.type,error:errors.MODEL_INSTANTIATION_FAILED})))}else if(e.type===MESSAGE_PREFIX+MESSAGE_INFERENCE_SUFFIX){return digestInference(n,e.graph).then((e=>queueReport({...e,sender:t}))).then((t=>({type:e.type,prediction:t.prediction}))).catch((()=>Promise.reject({type:e.type,error:errors.INFERENCE_FAILED})))}return Promise.reject({type:e.type,error:errors.UNKNOWN_REQUEST})}function digestPrepare(e){return getModelInstance(e).then((e=>e.bundle)).catch((()=>{deleteModelLocal(e);return Promise.reject("Model corrupted")}))}function digestInference(e,t){debugOut(`Running inference: ${e}`,false,t);let n={debug:debug,modelName:e,settings:settings,modelColdStart:!models.has(e),startTime:Date.now()};return getModelInstance(e).then((e=>Promise.all([e.instance,e.bundle]))).then((([e,r])=>{n.bundle=r;n.modelBootupTime=Date.now();return preprocessGraph(r,t,".").then((t=>{n.preprocessingTime=Date.now();n.preprocessedGraph=t;return predict(tfjs,e,r,t)})).then((e=>{n.inferenceTime=Date.now();n.rawPrediction=e;return digestPrediction(e)})).then((e=>{n.digestTime=Date.now();n.prediction=e;return n}))})).catch((()=>{deleteModelLocal(e);return Promise.reject("Model corrupted")}))}function getModelInstance(e){if(!e)return Promise.reject("No model name provided");if(!models.has(e)){let t=getModel(e);let n=t.then(loadModel);t.catch((()=>{}));n.catch((()=>{}));models.set(e,{bundle:t,instance:n})}let t=models.get(e);if(!t.bundle||!t.instance){models.delete(e);return Promise.reject("Model corrupted")}return Promise.resolve(t)}function loadModel(e){return loadBundledModel(tfjs,e)}function getModel(e){return fetchModelLocal(e).catch(fetchModelRemote.bind(this,e,BACKEND_RETRIES))}function fetchModelLocal(e){if(typeof indexedDB==="undefined")return Promise.reject("No IndexedDB support");return databaseTransaction({action:"get",key:e}).then((t=>{if(!t.config||!t.topology||!t.weights){databaseTransaction({action:"del",key:e}).catch((e=>debugOut(`Warning: can't remove corrupted model (${e})`,true)));return Promise.reject("model corrupted")}storeModelLocal(e,t).catch((e=>debugOut(`Warning: can't update existing model (${e})`,true)));debugOut(`Loaded model from database: ${e}`);return t}))}function deleteModelLocal(e){if(typeof indexedDB==="undefined")return Promise.reject("No IndexedDB support");if(models.has(e)){debugOut(`Removing model from memory: ${e}`);models.delete(e)}debugOut(`Removing model from database: ${e}`);return databaseTransaction({action:"del",key:e})}function storeModelLocal(e,t){if(typeof indexedDB==="undefined")return Promise.reject("No IndexedDB support");return databaseTransaction({action:"put",key:e,data:{...t,dt:Date.now()}})}function fetchModelRemote(e,t){debugOut(`Attempting to fetch ${e} from remote`);let n=new AbortController;let r=setTimeout(n.abort,BACKEND_TIMEOUT);if(isNaN(t))t=BACKEND_RETRIES;return fetch(`${BACKEND_URL}${e}.json`,{signal:n.signal}).then((e=>e.json())).then((t=>{if(!t.config||!t.topology||!t.weights)return Promise.reject("model corrupted");debugOut(`Loaded model from remote: ${e}`);debugOut(`Storing model in database: ${e}`);return storeModelLocal(e,t).catch((e=>Promise.resolve(t)))})).catch((n=>{if(t>0)return fetchModelRemote(e,--t);debugOut(`Failed to fetch ${e} from remote: offline`,true);return Promise.reject(n)})).finally((()=>clearTimeout(r)))}function maintenance(){databaseTransaction({action:"get",key:MAINTENANCE_DATABASE_KEY}).then((e=>{if(isNaN(e)||Date.now()-e>MAINTENANCE_INTERVAL){cleanUpDatabase();return databaseTransaction({action:"put",key:MAINTENANCE_DATABASE_KEY,data:Date.now()})}})).catch((e=>debugOut(`Warning: maintenance failed (${e})`,true)))}function cleanUpDatabase(){debugOut("Cleaning up database");databaseTransaction({action:"keys"}).then((e=>{e.forEach(((e,t)=>{if(!e||e.startsWith("conf"))return;setTimeout((()=>{databaseTransaction({action:"get",key:e}).then((t=>{if(t&&!isNaN(t.dt)&&Date.now()-t.dt>MODEL_TTL)return deleteModelLocal(e)})).catch((t=>debugOut(`Warning: database cleanup for ${e} failed (${t})`,true)))}),MODEL_DELETION_TIMEOUT*t)}))})).catch((e=>debugOut(`Warning: database cleanup failed (${e})`,true)))}function databaseTransaction(e){if(!e.action||e.action!=="keys"&&!e.key||e.action==="put"&&!e.data)return Promise.reject("Missing database transaction options/data.");if(typeof indexedDB==="undefined")return Promise.reject("No IndexedDB support");return openDatabase().then((t=>{let n=t.transaction(TABLE_NAME,"readwrite");let r=n.objectStore(TABLE_NAME);let a;if(e.action==="get")a=r.get(e.key);else if(e.action==="put")a=r.put(e.data,e.key);else if(e.action==="del")a=r.delete(e.key);else if(e.action==="keys")a=r.getAllKeys();else return Promise.reject("Database transaction request not recognized");return new Promise(((t,r)=>{n.onerror=r;a.onerror=r;a.onsuccess=()=>{if(e.action==="put")t(e.data);else if(e.action==="get")t(a.result);else if(e.action==="del")t();else if(e.action==="keys")t(a.result);else r("Database transaction request not recognized")}}))}))}function openDatabase(){if(typeof indexedDB==="undefined")return Promise.reject("No IndexedDB support");if(!databaseRef){databaseRef=new Promise(((e,t)=>{let n=indexedDB.open(DATABASE_NAME,1);n.onsuccess=()=>e(n.result);n.onerror=t;n.onupgradeneeded=()=>n.result.createObjectStore(TABLE_NAME)}))}return databaseRef}function checkWebGlSupport(){if(typeof OffscreenCanvas==="undefined")return false;let e=new OffscreenCanvas(0,0);try{if(e.getContext("webgl2"))return true}catch(e){}return false}function debugOut(e,t=false,...n){if(debug){console.log("%cMLDBG ♥ %c| %s%c |","color:cyan",t?"color:red":"color:inherit",e,"color:inherit",...n)}}

// EXTERNAL MODULE: ./adblockpluschrome/lib/prefs.js
var prefs = __webpack_require__(968);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/contentFiltering.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module contentFiltering */







function updateMlTelemetryOptout()
{
  setOptions({
    privateBrowsingTelemetry: false,
    telemetryOptOut: prefs.Prefs.get("data_collection_opt_out")
  });
}

async function start()
{
  await prefs.Prefs.untilLoaded;

  ewe_api.snippets.setLibrary({
    injectedCode: main,
    isolatedCode: ml
  });

  updateMlTelemetryOptout();
  prefs.Prefs.on("data_collection_opt_out", updateMlTelemetryOptout);
  browser.runtime.onMessage.addListener(messageListener);
}

// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/port.js
var port = __webpack_require__(305);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/debug.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */



let lastError = null;

function safeToString(value)
{
  try
  {
    return String(value);
  }
  catch (e)
  {
    return "<string conversion error>";
  }
}

function debug_start()
{
  self.addEventListener("error", event =>
  {
    lastError = safeToString(event.error);
  });

  self.addEventListener("unhandledrejection", event =>
  {
    lastError = safeToString(event.reason);
  });

  let consoleError = console.error;
  console.error = function error(...args)
  {
    lastError = args.map(safeToString).join(" ");
    consoleError.apply(this, args);
  };

  port.port.on("debug.getLastError", () =>
  {
    let error = lastError;
    lastError = null;
    return error;
  });
}

// EXTERNAL MODULE: ./adblockpluschrome/lib/messaging/events.js
var events = __webpack_require__(370);
// EXTERNAL MODULE: ./src/core/api/background/index.ts + 1 modules
var api_background = __webpack_require__(12);
// EXTERNAL MODULE: ./src/version/shared/version.ts
var version = __webpack_require__(3);
// EXTERNAL MODULE: ./adblockpluschrome/lib/storage/tab-session.js
var tab_session = __webpack_require__(658);
// EXTERNAL MODULE: ./src/info/background/index.ts + 1 modules
var info_background = __webpack_require__(463);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/devtools.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module devtools */










const reloadStateByPage = new tab_session/* TabSessionStorage */.H("devtools:reloadState");

async function onBlockableItem(emit, blockableItem)
{
  const {filter} = blockableItem;

  let subscriptions = [];
  if (filter)
  {
    subscriptions = await ewe_api.subscriptions.getForFilter(filter.text);
    subscriptions = subscriptions
      .filter(subscription => subscription.enabled)
      .map(api_background/* toSerializableSubscription */.Bp);
  }

  emit(
    (0,api_background/* toSerializableBlockableItem */.UV)(blockableItem),
    (filter) ? (0,api_background/* toSerializableFilter */.iw)(filter) : null,
    subscriptions
  );
}

function onPageFrame(emit, details)
{
  void reloadStateByPage.transaction(async() =>
  {
    const {tabId} = details;
    const reloadState = await reloadStateByPage.get(tabId);

    // Clear the devtools panel and reload the inspected tab without caching
    // when a new request is issued. However, make sure that we don't end up
    // in an infinite recursion if we already triggered a reload.
    if (reloadState === "reloading")
    {
      await reloadStateByPage.delete(tabId);
      return;
    }

    emit("requests", "reset");

    // We can't repeat the request if it isn't a GET request. The browser would
    // prompt the user to confirm reloading the page, and POST requests are
    // known to cause issues on many websites if repeated.
    if (details.method === "GET")
      await reloadStateByPage.set(tabId, "needsReload");
  });
}

function onPageLoad(page)
{
  void reloadStateByPage.transaction(async() =>
  {
    const reloadState = await reloadStateByPage.get(page.id);

    // Reloading the tab is the only way that allows bypassing all caches, in
    // order to see all requests in the devtools panel. Reloading must not be
    // performed before the tab changes to "loading", otherwise it will load the
    // previous URL.
    if (reloadState === "needsReload")
    {
      await reloadStateByPage.set(page.id, "reloading");
      browser.tabs.reload(page.id, {bypassCache: true});
    }
  });
}

function devtools_start()
{
  /**
   * Returns true if our devtools panel is supported by the browser.
   *
   * @event "devtools.supported"
   * @returns {boolean}
   */
  port.port.on("devtools.supported", (message, sender) =>
    info_background.info.platform == "chromium" ||
  info_background.info.application == "firefox" &&
  (0,version/* compareVersions */.n)(info_background.info.applicationVersion, "54") >= 0
  );

  (0,events/* installHandler */.a)("requests", null, (emit, action, targetTabId) =>
  {
    switch (action)
    {
      case "hits":
        const blockableItemsOptions = {
          filterType: "all",
          includeElementHiding: true,
          includeUnmatched: true,
          tabId: targetTabId
        };
        const localOnBlockableItem = onBlockableItem.bind(null, emit);

        ewe_api.reporting.onBlockableItem.addListener(
          localOnBlockableItem,
          blockableItemsOptions
        );
        return () =>
        {
          ewe_api.reporting.onBlockableItem.removeListener(
            localOnBlockableItem,
            blockableItemsOptions
          );
        };
      case "reset":
        const localOnPageFrame = onPageFrame.bind(null, emit);
        const localOnPageLoad = onPageLoad.bind(null, emit);

        browser.webRequest.onBeforeRequest.addListener(
          localOnPageFrame,
          {
            urls: ["http://*/*", "https://*/*"],
            types: ["main_frame"],
            tabId: targetTabId
          }
        );
        ext.pages.onLoading.addListener(localOnPageLoad);

        return () =>
        {
          browser.webRequest.onBeforeRequest.removeListener(localOnPageFrame);
          ext.pages.onLoading.removeListener(localOnPageLoad);
        };
    }
  });
}


// EXTERNAL MODULE: ./adblockpluschrome/lib/filterConfiguration.js + 1 modules
var filterConfiguration = __webpack_require__(311);
// EXTERNAL MODULE: ./src/id/background/index.ts + 3 modules
var id_background = __webpack_require__(153);
// EXTERNAL MODULE: ./src/premium/background/index.ts + 1 modules
var premium_background = __webpack_require__(282);
;// CONCATENATED MODULE: ./adblockpluschrome/lib/messageResponder.js
/*
 * This file is part of Adblock Plus <https://adblockplus.org/>,
 * Copyright (C) 2006-present eyeo GmbH
 *
 * Adblock Plus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Adblock Plus 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 Adblock Plus.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @module messageResponder */









function forward(type, message, sender)
{
  return port.port._onMessage(Object.assign({}, message, {type}), sender);
}

/**
 * Opens given UI page or switches to it, if it's already open
 *
 * @param {string} pathname - UI page path name
 */
async function openUiPage(pathname)
{
  const tabs = await browser.tabs.query({});
  for (const tab of tabs)
  {
    const url = new URL(tab.url);
    if (pathname !== url.pathname)
      continue;

    void browser.tabs.update(tab.id, {active: true});
    return;
  }

  void browser.tabs.create({
    url: browser.runtime.getURL(pathname)
  });
}

function messageResponder_start()
{
  /**
   * @deprecated Please send the "filters.getTypes" message instead.
   *
   * @event "types.get"
   */
  port.port.on("types.get",
          (message, sender) => forward("filters.getTypes", message, sender));

  /**
   * @deprecated Please send the "options.open" message instead.
   *
   * @event "app.open"
   */
  port.port.on("app.open", async(message, sender) =>
  {
    switch (message.what)
    {
      case "options":
        await forward("options.open", message, sender);
        break;
      case "premium-onboarding":
        await openUiPage("premium-onboarding.html");
        break;
    }

    if (message.replaceTab)
      void browser.tabs.remove(sender.page.id);
  });

  /**
   * @deprecated Please send the "subscriptions.getInitIssues",
   *             "prefs.getDocLink", "subscriptions.getRecommendations",
   *             "devtools.supported" or "info.get" messages, or call the
   *             browser.tabs.getCurrent(), browser.i18n.getUILanguage(),
   *             browser.i18n.getMessage("@@bidi_dir") APIs instead.
   *
   * @event "app.get"
   */
  port.port.on("app.get", async(message, sender) =>
  {
    if (message.what == "localeInfo")
    {
      return {
        locale: browser.i18n.getUILanguage(),
        bidiDir: browser.i18n.getMessage("@@bidi_dir")
      };
    }

    if (message.what == "acceptableAdsUrl")
      return ewe_api.subscriptions.ACCEPTABLE_ADS_URL;

    if (message.what == "acceptableAdsPrivacyUrl")
      return ewe_api.subscriptions.ACCEPTABLE_ADS_PRIVACY_URL;

    if (message.what == "senderId")
      return sender.page.id;

    if (message.what == "ctalink")
    {
      const ctaLinkNameToPrefsMap = new Map([
        ["premium-manage", "premium_manage_page_url"],
        ["premium-upgrade", "premium_upgrade_page_url"]
      ]);

      const {link: ctaLinkName, queryParams} = message;
      const prefsUrlKey = ctaLinkNameToPrefsMap.get(ctaLinkName);
      let url = prefs.Prefs[prefsUrlKey];

      const linkPlaceholders = [
        ["LANG", () => browser.i18n.getUILanguage().replace("-", "_")],
        ["ADDON_NAME", () => info_background.info.addonName],
        ["ADDON_VERSION", () => info_background.info.addonVersion],
        ["APPLICATION_NAME", () => info_background.info.application],
        ["APPLICATION_VERSION", () => info_background.info.applicationVersion],
        ["PLATFORM_NAME", () => info_background.info.platform],
        ["PLATFORM_VERSION", () => info_background.info.platformVersion],
        ["LICENSE_CODE", () => prefs.Prefs.get("premium_license").code],
        ["SOURCE", () => queryParams.source]
      ];

      for (const [key, getValue] of linkPlaceholders)
        url = url.replace(`%${key}%`, encodeURIComponent(getValue()));

      return url;
    }

    if (message.what == "doclink")
      return forward("prefs.getDocLink", message, sender);

    if (message.what == "recommendations")
      return forward("subscriptions.getRecommendations", message, sender);

    if (message.what == "features")
    {
      let devToolsPanel = await forward("devtools.supported", message, sender);
      return {devToolsPanel};
    }

    if (message.what == "os")
    {
      let platformInfo = await browser.runtime.getPlatformInfo();
      return platformInfo.os;
    }

    return info_background.info[message.what];
  });

  /**
   * @typedef {object} infoGetResult
   * @property {string} addonName
   *   The extension's name, e.g. "adblockpluschrome".
   * @property {string} addonVersion
   *   The extension's version, e.g. "3.6.3".
   * @property {string} application
   *   The browser's name, e.g. "chrome".
   * @property {string} applicationVersion
   *   The browser's version, e.g. "77.0.3865.90".
   * @property {string} platform
   *   The browser platform, e.g. "chromium".
   * @property {string} platformVersion
   *   The browser platform's version, e.g. "77.0.3865.90".
   */

  /**
   * Returns the browser platform information.
   *
   * @event "info.get"
   * @returns {infoGetResult}
   */
  port.port.on("info.get", (message, sender) => info_background.info);

  /**
   * @typedef {object} injectionInfo
   * @property {boolean} isPremium
   *   Whether premium is activated
   * @property {string} addonVersion
   *   The extension's version, e.g. "3.6.3".
   * @property {string} id
   *   The installation id
   */

  /**
   * Returns the information to be injected on product websites.
   *
   * @event "info.getInjectionInfo"
   * @returns {injectionInfo}
   */
  port.port.on("info.getInjectionInfo", async() =>
  {
    const {isActive: isPremium} = (0,premium_background/* getPremiumState */.rh)();
    const version = info_background.info.addonVersion;
    const id = await (0,id_background/* getInstallationId */.l)();

    return {isPremium, version, id};
  });
}

// EXTERNAL MODULE: ./adblockpluschrome/lib/stats.js
var stats = __webpack_require__(774);
// EXTERNAL MODULE: ./adblockpluschrome/lib/subscriptionInit.js + 13 modules
var subscriptionInit = __webpack_require__(821);
// EXTERNAL MODULE: ./adblockpluschrome/lib/uninstall.js
var uninstall = __webpack_require__(581);
// EXTERNAL MODULE: ./lib/init.js
var init = __webpack_require__(997);
// EXTERNAL MODULE: ./lib/recommendLanguage.js
var recommendLanguage = __webpack_require__(398);
// EXTERNAL MODULE: ./adblockpluschrome/lib/allowlisting.js
var allowlisting = __webpack_require__(320);
;// CONCATENATED MODULE: ./src/allowlisting/background/public-api.ts




async function onAllowlisting(domain) {
    if (premium_background/* getPremiumState */.rh().isActive)
        return;
    await (0,allowlisting/* allowlist */.fm)({
        hostname: domain,
        origin: "web"
    });
}
async function removeWebAllowlistingFilters() {
    const allowlistingFilters = (await ewe_api.filters.getUserFilters()).filter((filter) => filter.type === "allowing");
    const allowlistingFiltersWithMetadata = await Promise.all(allowlistingFilters.map(async (filter) => {
        const metadata = await ewe_api.filters.getMetadata(filter.text);
        return { filter, metadata };
    }));
    const webAllowlistingFilters = allowlistingFiltersWithMetadata
        .filter(({ metadata }) => metadata && metadata.origin === "web")
        .map(({ filter }) => filter);
    await ewe_api.filters.remove(webAllowlistingFilters.map((filter) => filter.text));
}
async function public_api_start() {
    const authorizedKeys = prefs.Prefs.get("allowlisting_authorizedKeys");
    void ewe_api.allowlisting.setAuthorizedKeys(authorizedKeys);
    ewe_api.allowlisting.setAllowlistingCallback(onAllowlisting);
    await prefs.Prefs.untilLoaded;
    if (premium_background/* getPremiumState */.rh().isActive) {
        void removeWebAllowlistingFilters();
    }
    premium_background/* emitter.on */.uY.on("activated", async () => {
        void ewe_api.allowlisting.setAuthorizedKeys([]);
        void removeWebAllowlistingFilters();
    });
    premium_background/* emitter.on */.uY.on("deactivated", () => {
        void ewe_api.allowlisting.setAuthorizedKeys(authorizedKeys);
    });
}

;// CONCATENATED MODULE: ./src/allowlisting/background/index.ts


;// CONCATENATED MODULE: ./src/bypass/background/bypass.ts



const algorithm = {
    name: "RSASSA-PKCS1-v1_5",
    modulusLength: 4096,
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: { name: "SHA-512" }
};
const signatureExpiration = 60 * 60 * 1000;
function base64ToArrayBuffer(str) {
    const decodedData = atob(str);
    return Uint8Array.from(decodedData, (c) => c.charCodeAt(0));
}
function getAllowData(domain, timestamp) {
    const str = `${domain},${timestamp}`;
    return new TextEncoder().encode(str);
}
async function getKey(key) {
    const abKey = base64ToArrayBuffer(key);
    const importedKey = await crypto.subtle.importKey("spki", abKey, algorithm, false, ["verify"]);
    return importedKey;
}
async function handleGetAuthPayloadMessage(message, sender) {
    if (!isPremiumGetAuthPayloadMessage(message)) {
        return null;
    }
    if (!(0,premium_background/* getPremiumState */.rh)().isActive) {
        return null;
    }
    const { signature, timestamp } = message;
    const validTimestamp = verifyTimestamp(timestamp);
    if (!validTimestamp) {
        return null;
    }
    const domain = sender.page.url.hostname;
    const validSignature = await verifySignature(domain, timestamp, signature);
    if (!validSignature) {
        return null;
    }
    const payload = (0,premium_background/* getAuthPayload */.p2)();
    if (!payload) {
        return null;
    }
    return payload;
}
function isPremiumGetAuthPayloadMessage(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "signature" in candidate &&
        "timestamp" in candidate);
}
async function verifySignature(domain, timestamp, signature) {
    if (typeof signature !== "string") {
        return false;
    }
    const data = getAllowData(domain, timestamp);
    const abSignature = base64ToArrayBuffer(signature);
    const authorizedKeys = prefs.Prefs.get("bypass_authorizedKeys");
    const promisedValidations = authorizedKeys.map(async (key) => {
        return await verifySignatureWithKey(data, abSignature, key);
    });
    const validations = await Promise.all(promisedValidations);
    return validations.some((isValid) => isValid);
}
async function verifySignatureWithKey(data, signature, pubKey) {
    return await crypto.subtle.verify(algorithm, await getKey(pubKey), signature, data);
}
function verifyTimestamp(timestamp) {
    if (typeof timestamp !== "number" || Number.isNaN(timestamp)) {
        return false;
    }
    const timeDiff = Date.now() - timestamp;
    return timeDiff < signatureExpiration;
}
function bypass_start() {
    port.port.on("premium.getAuthPayload", handleGetAuthPayloadMessage);
    ext.addTrustedMessageTypes(null, ["premium.getAuthPayload"]);
}

;// CONCATENATED MODULE: ./src/bypass/background/index.ts



// EXTERNAL MODULE: ./adblockpluschrome/lib/storage/session.js
var session = __webpack_require__(137);
// EXTERNAL MODULE: ./src/core/url/shared/url.ts
var url = __webpack_require__(88);
;// CONCATENATED MODULE: ./src/composer/background/composer.ts








const activeDialogKey = "activeDialog";
const composer_session = new session.SessionStorage("filterComposer");
const readyActivePages = new tab_session/* TabSessionStorage */.H("filterComposer:readyActivePages");
let showingContextMenu = false;
function isValidString(s) {
    return s && s.indexOf("\0") === -1;
}
function escapeChar(chr) {
    const code = chr.charCodeAt(0);
    if (code <= 0x1f || code === 0x7f || /[\d{}]/.test(chr)) {
        return "\\" + code.toString(16) + " ";
    }
    return "\\" + chr;
}
function escapeCSS(s) {
    return s.replace(/^[\d-]|[^\w\-\u0080-\uFFFF]/g, escapeChar);
}
function quoteCSS(value) {
    return '"' + value.replace(/["\\{}\x00-\x1F\x7F]/g, escapeChar) + '"';
}
async function composeFilters(details) {
    const { page, frame } = details;
    const filters = [];
    const selectors = [];
    const isFrameAllowlisted = await ewe_api.filters.isResourceAllowlisted(frame.url, "document", page.id, frame.id);
    if (!isFrameAllowlisted) {
        const docDomain = (0,url/* extractHostFromFrame */.I8)(frame);
        if (details.url) {
            let type;
            switch (details.tagName) {
                case "img":
                case "input":
                    type = "image";
                    break;
                case "audio":
                case "video":
                    type = "media";
                    break;
                case "frame":
                case "iframe":
                    type = "subdocument";
                    break;
                case "object":
                case "embed":
                    type = "object";
                    break;
            }
            const isAllowlisted = await ewe_api.filters.isResourceAllowlisted(details.url, type, page.id, frame.id);
            if (!isAllowlisted) {
                let filterText = details.url.replace(/^[\w-]+:\/+(?:www\.)?/, "||");
                const isSpecificAllowlisted = await ewe_api.filters.isResourceAllowlisted(details.url, "genericblock", page.id, frame.id);
                if (isSpecificAllowlisted) {
                    filterText += "$domain=" + docDomain;
                }
                if (!filters.includes(filterText)) {
                    filters.push(filterText);
                }
            }
        }
        const elementAllowlistingFilters = await ewe_api.filters.getAllowingFilters(page.id, {
            frameId: frame.id,
            types: ["elemhide"]
        });
        const isElementAllowlisted = elementAllowlistingFilters.length > 0;
        if (filters.length === 0 && !isElementAllowlisted) {
            if (isValidString(details.id)) {
                selectors.push("#" + escapeCSS(details.id));
            }
            const classes = details.classes.filter(isValidString);
            if (classes.length > 0) {
                selectors.push(classes.map((c) => "." + escapeCSS(c)).join(""));
            }
            if (isValidString(details.src)) {
                selectors.push(escapeCSS(details.tagName) + "[src=" + quoteCSS(details.src) + "]");
            }
            if (isValidString(details.style) &&
                selectors.length === 0 &&
                filters.length === 0) {
                selectors.push(escapeCSS(details.tagName) + "[style=" + quoteCSS(details.style) + "]");
            }
            for (const selector of selectors) {
                filters.push(docDomain.replace(/^www\./, "") + "##" + selector);
            }
        }
    }
    return { filters, selectors };
}
async function handleOpenDialogMessage(message, sender) {
    const activeDialog = await composer_session.get(activeDialogKey);
    if (activeDialog) {
        void browser.tabs.remove(activeDialog.tab.id);
        void browser.tabs.sendMessage(activeDialog.sender.id, {
            type: "composer.content.dialogClosed",
            popupId: activeDialog.tab.id
        });
    }
    const dialogWindow = await browser.windows.create({
        url: browser.runtime.getURL("composer.html"),
        left: 50,
        top: 50,
        width: 600,
        height: 300,
        type: "popup"
    });
    const [dialogTab] = dialogWindow.tabs;
    await composer_session.set(activeDialogKey, {
        filters: message.filters,
        highlights: message.highlights,
        initAttempt: 0,
        sender: {
            id: sender.page.id
        },
        status: null,
        tab: {
            id: dialogTab.id,
            status: dialogTab.status
        },
        window: {
            id: dialogWindow.id,
            width: dialogWindow.width
        }
    });
    if (dialogTab.status !== "complete") {
        return;
    }
    await doInit();
}
async function doInit() {
    const activeDialog = await composer_session.get(activeDialogKey);
    await browser.tabs.sendMessage(activeDialog.sender.id, {
        type: "composer.content.dialogOpened",
        popupId: activeDialog.tab.id
    });
    activeDialog.initAttempt += 1;
    await composer_session.set(activeDialogKey, activeDialog);
    if (activeDialog.initAttempt > 30) {
        return;
    }
    try {
        const response = await browser.tabs.sendMessage(activeDialog.tab.id, {
            type: "composer.dialog.init",
            sender: activeDialog.sender.id,
            filters: activeDialog.filters,
            highlights: activeDialog.highlights
        });
        if (!response) {
            throw new Error();
        }
        if (info_background.info.application === "firefox") {
            await browser.windows.update(activeDialog.window.id, {
                width: activeDialog.window.width + 2
            });
        }
    }
    catch (e) {
        setTimeout(() => {
            void doInit();
        }, 100);
    }
}
async function onTabRemoved(removedTabId) {
    const activeDialog = await composer_session.get(activeDialogKey);
    if (!activeDialog) {
        return;
    }
    if (removedTabId === activeDialog.tab.id) {
        void browser.tabs.sendMessage(activeDialog.sender.id, {
            type: "composer.content.dialogClosed",
            popupId: activeDialog.tab.id
        });
    }
    else if (removedTabId === activeDialog.sender.id) {
        void browser.tabs.sendMessage(activeDialog.tab.id, {
            type: "composer.dialog.close"
        });
    }
    else {
        return;
    }
    await composer_session.delete(activeDialogKey);
}
async function onTabUpdated(tabId, changeInfo) {
    const activeDialog = await composer_session.get(activeDialogKey);
    if (!activeDialog || tabId !== activeDialog.tab.id) {
        return;
    }
    if (activeDialog.status === "complete" || changeInfo.status !== "complete") {
        return;
    }
    activeDialog.status = changeInfo.status;
    await composer_session.set(activeDialogKey, activeDialog);
    await doInit();
}
async function handleGetFiltersMessage(message, sender) {
    return await composeFilters({
        tagName: message.tagName,
        id: message.id,
        src: message.src,
        style: message.style,
        classes: message.classes,
        url: message.url,
        page: sender.page,
        frame: sender.frame
    });
}
function handleForwardMessage(msg, sender) {
    let targetPage;
    if (msg.targetPageId) {
        targetPage = ext.getPage(msg.targetPageId);
    }
    else {
        targetPage = sender.page;
    }
    if (targetPage) {
        msg.payload.sender = sender.page.id;
        return browser.tabs.sendMessage(targetPage.id, msg.payload);
    }
}
function composer_reset(page) {
    void browser.tabs
        .sendMessage(page.id, { type: "composer.content.finished" })
        .catch(() => { });
}
function handleContextMenuClicked(itemInfo, tab) {
    if (itemInfo.menuItemId === "block_element") {
        void browser.tabs.sendMessage(tab.id, {
            type: "composer.content.contextMenuClicked"
        });
    }
}
async function showOrHideContextMenu(activePage) {
    if (!("contextMenus" in browser)) {
        return;
    }
    const shouldShowContextMenu = prefs.Prefs.shouldShowBlockElementMenu &&
        (await readyActivePages.get(activePage.id));
    if (shouldShowContextMenu && !showingContextMenu) {
        void browser.contextMenus.create({
            id: "block_element",
            title: browser.i18n.getMessage("block_element"),
            contexts: ["image", "video", "audio"]
        });
        showingContextMenu = true;
    }
    else if (!shouldShowContextMenu && showingContextMenu) {
        void browser.contextMenus.remove("block_element");
        showingContextMenu = false;
    }
}
async function updateContextMenu(updatedPage) {
    const tabs = await browser.tabs.query({
        active: true,
        lastFocusedWindow: true
    });
    if (tabs.length > 0 && (!updatedPage || updatedPage.id === tabs[0].id)) {
        await showOrHideContextMenu(updatedPage || new ext.Page(tabs[0]));
    }
}
function handleFocusChanged(windowId) {
    if (windowId !== browser.windows.WINDOW_ID_NONE) {
        void updateContextMenu();
    }
}
function handleAllowlistingStateChanged(page, isAllowlisted) {
    void readyActivePages.transaction(async () => {
        if (await readyActivePages.has(page.id)) {
            await readyActivePages.set(page.id, !isAllowlisted);
            void updateContextMenu(page);
        }
    });
}
async function handleIsPageReadyMessage(message) {
    return await readyActivePages.has(message.pageId);
}
async function initializeReadyState(page) {
    const isAllowlisted = await ewe_api.filters.isResourceAllowlisted(page.url, "document", page.id);
    await readyActivePages.set(page.id, !isAllowlisted);
    void updateContextMenu(page);
}
async function handleReadyMessage(message, sender) {
    await initializeReadyState(sender.page);
}
async function handlePageLoaded(page) {
    try {
        const state = await browser.tabs.sendMessage(page.id, {
            type: "composer.content.getState"
        });
        if (!state) {
            return;
        }
        await initializeReadyState(page);
    }
    catch (ex) {
    }
}
function composer_start() {
    browser.tabs.onRemoved.addListener(onTabRemoved);
    browser.tabs.onUpdated.addListener(onTabUpdated);
    port.port.on("composer.forward", handleForwardMessage);
    port.port.on("composer.getFilters", handleGetFiltersMessage);
    port.port.on("composer.isPageReady", handleIsPageReadyMessage);
    port.port.on("composer.openDialog", handleOpenDialogMessage);
    port.port.on("composer.ready", handleReadyMessage);
    ext.pages.onLoading.addListener(composer_reset);
    if ("contextMenus" in browser) {
        browser.contextMenus.onClicked.addListener(handleContextMenuClicked);
    }
    browser.tabs.onActivated.addListener((activeInfo) => {
        void showOrHideContextMenu(new ext.Page({ id: activeInfo.tabId }));
    });
    if ("windows" in browser) {
        browser.windows.onFocusChanged.addListener(handleFocusChanged);
    }
    allowlisting/* allowlistingState.addListener */._o.addListener("changed", handleAllowlistingStateChanged);
    prefs.Prefs.on("shouldShowBlockElementMenu", updateContextMenu);
    ext.pages.onLoaded.addListener(handlePageLoaded);
    ext.addTrustedMessageTypes(null, [
        "composer.content.clearPreviousRightClickEvent",
        "composer.content.finished",
        "composer.dialog.close",
        "composer.forward",
        "composer.getFilters",
        "composer.openDialog",
        "composer.ready"
    ]);
}

;// CONCATENATED MODULE: ./src/composer/background/index.ts


// EXTERNAL MODULE: ./src/ipm/background/index.ts + 3 modules
var ipm_background = __webpack_require__(386);
// EXTERNAL MODULE: ./node_modules/webextension-polyfill/dist/browser-polyfill.js
var browser_polyfill = __webpack_require__(935);
;// CONCATENATED MODULE: ./src/new-tab/background/middleware/new-tab.types.ts
var CreationMethod;
(function (CreationMethod) {
    CreationMethod["default"] = "default";
    CreationMethod["force"] = "force";
})(CreationMethod || (CreationMethod = {}));
const defaultCreationMethod = CreationMethod.default;

;// CONCATENATED MODULE: ./src/new-tab/background/middleware/new-tab.ts



const paramDefinitionList = [
    {
        name: "url",
        validate: ipm_background/* isSafeUrl */.w6
    },
    {
        name: "license_state_list",
        validate: ipm_background/* isValidLicenseStateList */.Bi
    },
    {
        name: "method",
        validate: (param) => typeof param === "undefined" ||
            (typeof param === "string" &&
                Object.values(CreationMethod)
                    .map((method) => String(method))
                    .includes(param))
    }
];
function isNewTabCommand(command) {
    const validationErrors = (0,ipm_background/* validateParams */.uU)(command, paramDefinitionList);
    if (validationErrors.length === 0) {
        return true;
    }
    background/* error */.vU("[new-tab]: Invalid parameters received:", validationErrors.join(" "));
    return false;
}
function isNewTabBehavior(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "target" in candidate &&
        "method" in candidate);
}
function getBehavior(command) {
    var _a;
    if (!isNewTabCommand(command)) {
        return null;
    }
    const method = typeof command.method === "undefined"
        ? defaultCreationMethod
        : CreationMethod[command.method];
    return {
        target: command.url,
        licenseStateList: (_a = command.license_state_list) !== null && _a !== void 0 ? _a : ipm_background/* defaultLicenseState */.CD,
        method
    };
}
function getContent() {
    return {};
}
function setNewTabCommandHandler(handler) {
    (0,ipm_background/* setCommandActor */.yA)(ipm_background/* CommandName.createTab */.G7.createTab, {
        getBehavior,
        getContent,
        handleCommand: handler,
        isValidCommand: isNewTabCommand
    });
}

;// CONCATENATED MODULE: ./src/new-tab/background/middleware/index.ts



;// CONCATENATED MODULE: ./src/new-tab/background/tab-manager.types.ts
var ListenerType;
(function (ListenerType) {
    ListenerType["create"] = "create";
    ListenerType["update"] = "update";
    ListenerType["remove"] = "remove";
})(ListenerType || (ListenerType = {}));
var CreationSuccess;
(function (CreationSuccess) {
    CreationSuccess["created"] = "tab_created";
    CreationSuccess["loaded"] = "tab_loaded";
})(CreationSuccess || (CreationSuccess = {}));
var CreationError;
(function (CreationError) {
    CreationError["invalidBehavior"] = "error_no_behavior";
    CreationError["licenseStateMismatch"] = "license_state_no_match";
    CreationError["invalidURL"] = "error_no_url";
    CreationError["tabCreationError"] = "tab_creation_error";
})(CreationError || (CreationError = {}));
var CreationRejection;
(function (CreationRejection) {
    CreationRejection["admin"] = "newtab_admin";
})(CreationRejection || (CreationRejection = {}));

;// CONCATENATED MODULE: ./src/new-tab/background/tab-manager.ts





const listenerMap = new Map();
const tabIds = new Set();
const newTabUpdateListeners = new Map();
function registerEvent(ipmId, name) {
    void (0,ipm_background/* recordEvent */.Ny)(ipmId, ipm_background/* CommandName.createTab */.G7.createTab, name);
}
function onNewTabUpdated(ipmId, tabId, changeInfo, tab) {
    if (changeInfo.status !== "complete" || tab === null || tabId !== tab.id) {
        return;
    }
    registerEvent(ipmId, CreationSuccess.loaded);
    const listener = newTabUpdateListeners.get(ipmId);
    if (typeof listener === "undefined") {
        return;
    }
    newTabUpdateListeners.delete(ipmId);
    browser_polyfill.tabs.onUpdated.removeListener(listener);
}
async function openNewTab(ipmId) {
    background/* debug */.fF("[new-tab]: openNewTab");
    removeListeners(ipmId);
    listenerMap.delete(ipmId);
    tabIds.clear();
    const behavior = (0,ipm_background/* getBehavior */.J)(ipmId);
    if (!isNewTabBehavior(behavior)) {
        background/* debug */.fF("[new-tab]: Invalid command behavior.");
        registerEvent(ipmId, CreationError.invalidBehavior);
        (0,ipm_background/* dismissCommand */._E)(ipmId);
        return;
    }
    if (!(await (0,ipm_background/* doesLicenseStateMatch */.a9)(behavior))) {
        background/* debug */.fF("[new-tab]: License state mismatch.");
        registerEvent(ipmId, CreationError.licenseStateMismatch);
        (0,ipm_background/* dismissCommand */._E)(ipmId);
        return;
    }
    const targetUrl = (0,ipm_background/* createSafeOriginUrl */.qX)(behavior.target);
    if (targetUrl === null) {
        background/* debug */.fF("[new-tab]: Invalid target URL.");
        registerEvent(ipmId, CreationError.invalidURL);
        (0,ipm_background/* dismissCommand */._E)(ipmId);
        return;
    }
    const updateListener = onNewTabUpdated.bind(null, ipmId);
    newTabUpdateListeners.set(ipmId, updateListener);
    browser_polyfill.tabs.onUpdated.addListener(updateListener);
    const tab = await browser_polyfill.tabs.create({ url: targetUrl }).catch((error) => {
        background/* error */.vU("[new-tab]: create tab error", error);
        return null;
    });
    if (tab === null) {
        registerEvent(ipmId, CreationError.tabCreationError);
        return;
    }
    registerEvent(ipmId, CreationSuccess.created);
    (0,ipm_background/* dismissCommand */._E)(ipmId);
}
function onTabCreated(ipmId, tab) {
    if (tab.url === "about:newtab") {
        void openNewTab(ipmId);
        return;
    }
    if (typeof tab.id !== "number") {
        return;
    }
    tabIds.add(tab.id);
}
function tab_manager_onTabUpdated(ipmId, tabId, changeInfo, tab) {
    if (!tabIds.has(tabId) || changeInfo.status !== "complete") {
        return;
    }
    tabIds.delete(tabId);
    if (typeof tab.url !== "string") {
        return;
    }
    if (/^https?:/.test(tab.url)) {
        return;
    }
    void openNewTab(ipmId);
}
function tab_manager_onTabRemoved(tabId) {
    tabIds.delete(tabId);
}
function createListeners(ipmId) {
    return {
        [ListenerType.create]: onTabCreated.bind(null, ipmId),
        [ListenerType.update]: tab_manager_onTabUpdated.bind(null, ipmId),
        [ListenerType.remove]: tab_manager_onTabRemoved.bind(null)
    };
}
function removeListeners(ipmId) {
    const listeners = listenerMap.get(ipmId);
    if (typeof listeners === "undefined") {
        return;
    }
    browser_polyfill.tabs.onCreated.removeListener(listeners[ListenerType.create]);
    browser_polyfill.tabs.onUpdated.removeListener(listeners[ListenerType.update]);
    browser_polyfill.tabs.onRemoved.removeListener(listeners[ListenerType.remove]);
}
async function handleCommand(ipmId) {
    background/* debug */.fF("[new-tab]: tab manager handleCommand", ipmId);
    if (navigator.webdriver) {
        return;
    }
    const { installType } = await browser_polyfill.management.getSelf();
    if (installType === "admin") {
        registerEvent(ipmId, CreationRejection.admin);
        (0,ipm_background/* dismissCommand */._E)(ipmId);
        return;
    }
    const behavior = (0,ipm_background/* getBehavior */.J)(ipmId);
    if (!isNewTabBehavior(behavior)) {
        background/* debug */.fF("[new-tab]: Invalid command behavior.");
        registerEvent(ipmId, CreationError.invalidBehavior);
        (0,ipm_background/* dismissCommand */._E)(ipmId);
        return;
    }
    if (behavior.method === CreationMethod.force) {
        void openNewTab(ipmId);
        return;
    }
    const listeners = createListeners(ipmId);
    listenerMap.set(ipmId, listeners);
    browser_polyfill.tabs.onCreated.addListener(listeners[ListenerType.create]);
    browser_polyfill.tabs.onUpdated.addListener(listeners[ListenerType.update]);
    browser_polyfill.tabs.onRemoved.addListener(listeners[ListenerType.remove]);
}
async function tab_manager_start() {
    background/* debug */.fF("[new-tab]: tab manager start");
    setNewTabCommandHandler(handleCommand);
}

;// CONCATENATED MODULE: ./src/new-tab/background/index.ts


// EXTERNAL MODULE: ./adblockpluschrome/lib/events.js
var lib_events = __webpack_require__(491);
;// CONCATENATED MODULE: ./src/i18n/background/locale.ts
function getLocaleInfo() {
    return {
        locale: browser.i18n.getUILanguage(),
        readingDirection: browser.i18n.getMessage("@@bidi_dir")
    };
}

// EXTERNAL MODULE: ./src/core/api/shared/api.ts
var api = __webpack_require__(808);
;// CONCATENATED MODULE: ./src/onpage-dialog/shared/messages.ts
function isPingMessage(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "displayDuration" in candidate &&
        "type" in candidate);
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/dialog.ts
function isDialog(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "behavior" in candidate &&
        "content" in candidate);
}
function isDialogBehavior(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "displayDuration" in candidate &&
        "target" in candidate &&
        "timing" in candidate);
}
function isDialogContent(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "body" in candidate &&
        "button" in candidate &&
        "title" in candidate);
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/timing.types.ts
var Timing;
(function (Timing) {
    Timing["afterWebAllowlisting"] = "after_web_allowlisting";
    Timing["immediate"] = "immediate";
    Timing["revisitWebAllowlisted"] = "revisit_web_allowlisted_site";
    Timing["afterNavigation"] = "after_navigation";
})(Timing || (Timing = {}));

;// CONCATENATED MODULE: ./src/onpage-dialog/background/middleware/ipm-onpage-dialog.ts



const ipm_onpage_dialog_paramDefinitionList = [
    {
        name: "timing",
        validate: (param) => typeof param === "undefined" ||
            param === Timing.afterWebAllowlisting ||
            param === Timing.revisitWebAllowlisted ||
            param === Timing.afterNavigation
    },
    {
        name: "display_duration",
        validate: (param) => typeof param === "undefined" ||
            (typeof param === "number" && param >= 0 && param <= 20)
    },
    {
        name: "sub_title",
        validate: ipm_background/* isNotEmpty */.UE
    },
    {
        name: "upper_body",
        validate: ipm_background/* isNotEmpty */.UE
    },
    {
        name: "button_label",
        validate: ipm_background/* isNotEmpty */.UE
    },
    {
        name: "button_target",
        validate: ipm_background/* isSafeUrl */.w6
    },
    {
        name: "domain_list",
        validate: ipm_background/* isValidDomainList */.h8
    },
    {
        name: "license_state_list",
        validate: ipm_background/* isValidLicenseStateList */.Bi
    }
];
function ipm_onpage_dialog_getBehavior(command) {
    var _a;
    if (!isDialogCommand(command)) {
        return null;
    }
    return {
        displayDuration: typeof command.display_duration === "number"
            ? command.display_duration
            : 5,
        target: command.button_target,
        timing: command.timing,
        domainList: command.domain_list,
        licenseStateList: (_a = command.license_state_list) !== null && _a !== void 0 ? _a : ipm_background/* defaultLicenseState */.CD
    };
}
function ipm_onpage_dialog_getContent(command) {
    if (!isDialogCommand(command)) {
        return null;
    }
    return {
        body: typeof command.lower_body === "string"
            ? [command.upper_body, command.lower_body]
            : [command.upper_body],
        button: command.button_label,
        title: command.sub_title
    };
}
function isDialogCommand(command) {
    const validationErrors = (0,ipm_background/* validateParams */.uU)(command, ipm_onpage_dialog_paramDefinitionList);
    if (validationErrors.length === 0) {
        return true;
    }
    background/* error */.vU("[onpage-dialog]: Invalid parameters received:", validationErrors.join(" "));
    return false;
}
function setDialogCommandHandler(handler) {
    (0,ipm_background/* setCommandActor */.yA)(ipm_background/* CommandName.createOnPageDialog */.G7.createOnPageDialog, {
        getBehavior: ipm_onpage_dialog_getBehavior,
        getContent: ipm_onpage_dialog_getContent,
        handleCommand: handler,
        isValidCommand: isDialogCommand
    });
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/middleware/index.ts



;// CONCATENATED MODULE: ./src/onpage-dialog/background/stats.ts

const statsStorageKey = "onpage_dialog_command_stats";
function clearStats(dialogId) {
    const statsStorage = prefs.Prefs.get(statsStorageKey);
    delete statsStorage[dialogId];
    void prefs.Prefs.set(statsStorageKey, statsStorage);
}
function getStats(dialogId) {
    const storage = prefs.Prefs.get(statsStorageKey);
    const storedStats = storage[dialogId];
    if (isStats(storedStats)) {
        return storedStats;
    }
    const initialStats = {
        displayCount: 0,
        lastDisplayTime: 0
    };
    setStats(dialogId, initialStats);
    return initialStats;
}
function isStats(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "displayCount" in candidate &&
        "lastDisplayTime" in candidate);
}
function setStats(dialogId, stats) {
    const storage = prefs.Prefs.get(statsStorageKey);
    storage[dialogId] = stats;
    void prefs.Prefs.set(statsStorageKey, storage);
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/tab-manager.types.ts
var DialogEventType;
(function (DialogEventType) {
    DialogEventType["buttonClicked"] = "dialog_button_clicked";
    DialogEventType["closed"] = "dialog_closed";
    DialogEventType["ignored"] = "dialog_ignored";
    DialogEventType["injected"] = "dialog_injected";
})(DialogEventType || (DialogEventType = {}));
var ShowOnpageDialogResult;
(function (ShowOnpageDialogResult) {
    ShowOnpageDialogResult[ShowOnpageDialogResult["ignored"] = 0] = "ignored";
    ShowOnpageDialogResult[ShowOnpageDialogResult["rejected"] = 1] = "rejected";
    ShowOnpageDialogResult[ShowOnpageDialogResult["shown"] = 2] = "shown";
})(ShowOnpageDialogResult || (ShowOnpageDialogResult = {}));

;// CONCATENATED MODULE: ./src/polyfills/background/polyfill.ts
function isFilterMetadata(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "created" in candidate &&
        "origin" in candidate);
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/timing.ts






const configsStorageKey = "onpage_dialog_timing_configurations";
const knownConfigs = new Map();
async function getAllowlistingTime(tabId) {
    const allowlistingFilterTexts = await ewe_api.filters.getAllowingFilters(tabId);
    if (allowlistingFilterTexts.length === 0) {
        return null;
    }
    for (const filterText of allowlistingFilterTexts) {
        const metadata = await ewe_api.filters.getMetadata(filterText);
        if (!isFilterMetadata(metadata)) {
            continue;
        }
        if (metadata.origin !== "web") {
            continue;
        }
        return metadata.created;
    }
    return null;
}
function isTiming(candidate) {
    return (typeof candidate === "string" &&
        Object.values(Timing).includes(candidate));
}
function isTimingConfiguration(candidate) {
    return (candidate !== null &&
        typeof candidate === "object" &&
        "cooldownDuration" in candidate &&
        "maxDisplayCount" in candidate);
}
function isWithin(timestamp, minutes) {
    return timestamp < Date.now() - minutes * 60 * 1000;
}
function initializeConfigs() {
    const configs = prefs.Prefs.get(configsStorageKey);
    for (const [timing, config] of Object.entries(configs)) {
        if (!isTiming(timing) || !isTimingConfiguration(config)) {
            background/* warn */.ZK("[onpage-dialog] Unknown timing configuration", timing);
            continue;
        }
        knownConfigs.set(timing, config);
    }
    background/* debug */.fF("[onpage-dialog]: Known timing configurations", knownConfigs);
}
function shouldBeDismissed(dialog, stats) {
    if (typeof stats !== "object") {
        return false;
    }
    const config = knownConfigs.get(dialog.behavior.timing);
    if (typeof config !== "object") {
        background/* debug */.fF("[onpage-dialog]: Unknown timing");
        return true;
    }
    if (config.maxDisplayCount === 0) {
        return false;
    }
    background/* debug */.fF("[onpage-dialog]: Display count", `${stats.displayCount}/${config.maxDisplayCount}`);
    return stats.displayCount >= config.maxDisplayCount;
}
async function shouldBeShownForAfterWebAllowlisting(timing, tab, stats) {
    var _a;
    const tabId = (_a = tab.id) !== null && _a !== void 0 ? _a : browser.tabs.TAB_ID_NONE;
    const config = knownConfigs.get(timing);
    if (typeof config !== "object") {
        background/* debug */.fF("[onpage-dialog]: Unknown timing");
        return false;
    }
    const allowlistingTime = await getAllowlistingTime(tabId);
    if (allowlistingTime === null) {
        background/* debug */.fF("[onpage-dialog]: Not allowlisted");
        return false;
    }
    if (typeof config.maxAllowlistingDelay === "number" &&
        isWithin(allowlistingTime, config.maxAllowlistingDelay)) {
        background/* debug */.fF("[onpage-dialog]: Allowlisted too long ago");
        return false;
    }
    if (typeof config.minAllowlistingDelay === "number" &&
        !isWithin(allowlistingTime, config.minAllowlistingDelay)) {
        background/* debug */.fF("[onpage-dialog]: Allowlisted too recently");
        return false;
    }
    if (!isWithin(stats.lastDisplayTime, config.cooldownDuration * 60)) {
        background/* debug */.fF("[onpage-dialog]: Dialog shown too recently");
        return false;
    }
    return true;
}
async function shouldBeShown(tab, dialog, stats) {
    var _a;
    const { domainList, timing } = dialog.behavior;
    if (shouldBeDismissed(dialog, stats)) {
        background/* debug */.fF("[onpage-dialog]: No more dialogs to show for command");
        return false;
    }
    const isWebAllowlistingRelated = [
        Timing.afterWebAllowlisting,
        Timing.revisitWebAllowlisted
    ].includes(timing);
    if (isWebAllowlistingRelated &&
        !(await shouldBeShownForAfterWebAllowlisting(timing, tab, stats))) {
        return false;
    }
    return (0,url/* isActiveOnDomain */.Nm)((_a = tab.url) !== null && _a !== void 0 ? _a : "", domainList);
}
async function timing_start() {
    await prefs.Prefs.untilLoaded;
    initializeConfigs();
    prefs.Prefs.on(configsStorageKey, () => {
        initializeConfigs();
    });
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/tab-manager.ts















const assignedDialogs = new tab_session/* TabSessionStorage */.H("onpage-dialog:dialogs");
const eventEmitter = new lib_events/* EventEmitter */.v();
const unassignedDialogs = new Map();
async function removeDialog(tabId) {
    background/* debug */.fF("[onpage-dialog]: Remove dialog");
    const dialog = await assignedDialogs.get(tabId);
    if (!isDialog(dialog)) {
        return;
    }
    try {
        const message = { type: "onpage-dialog.hide" };
        await sendMessage(tabId, message);
        await assignedDialogs.delete(tabId);
    }
    catch (ex) {
    }
    const stats = getStats(dialog.id);
    if (!shouldBeDismissed(dialog, stats)) {
        background/* debug */.fF("[onpage-dialog]: Keep dialog active");
        return;
    }
    dismissDialog(dialog);
    clearStats(dialog.id);
}
function dismissDialog(dialog) {
    background/* debug */.fF("[onpage-dialog]: Dismiss dialog");
    unassignedDialogs.delete(dialog.id);
    if (typeof dialog.ipmId === "string") {
        (0,ipm_background/* dismissCommand */._E)(dialog.ipmId);
    }
}
async function forwardMessage(message, sender) {
    if (!(0,api/* isMessage */.c)(message)) {
        return;
    }
    return await sendMessage(sender.page.id, message);
}
async function handleCloseMessage(message, sender) {
    const dialog = await assignedDialogs.get(sender.page.id);
    if (!isDialog(dialog)) {
        return;
    }
    void removeDialog(sender.page.id);
    recordDialogEvent(dialog, DialogEventType.closed);
}
async function handleContinueMessage(message, sender) {
    const dialog = await assignedDialogs.get(sender.page.id);
    if (!isDialog(dialog)) {
        return;
    }
    const safeTargetUrl = (0,ipm_background/* createSafeOriginUrl */.qX)(dialog.behavior.target);
    if (safeTargetUrl === null) {
        return;
    }
    void browser.tabs.create({ url: safeTargetUrl });
    void removeDialog(sender.page.id);
    recordDialogEvent(dialog, DialogEventType.buttonClicked);
}
async function handleDialogCommand(ipmId) {
    if (typeof ipmId !== "string") {
        return;
    }
    const behavior = (0,ipm_background/* getBehavior */.J)(ipmId);
    if (!isDialogBehavior(behavior)) {
        return;
    }
    const content = (0,ipm_background/* getContent */.L5)(ipmId);
    if (!isDialogContent(content)) {
        return;
    }
    const dialog = { behavior, content, id: ipmId, ipmId };
    unassignedDialogs.set(dialog.id, dialog);
}
async function handleGetMessage(message, sender) {
    const dialog = await assignedDialogs.get(sender.page.id);
    if (!isDialog(dialog)) {
        return null;
    }
    return {
        content: dialog.content,
        localeInfo: getLocaleInfo()
    };
}
async function handlePingMessage(message, sender) {
    if (!isPingMessage(message)) {
        return;
    }
    const dialog = await assignedDialogs.get(sender.page.id);
    if (!isDialog(dialog)) {
        return;
    }
    if (dialog.behavior.displayDuration === 0 ||
        message.displayDuration < dialog.behavior.displayDuration) {
        return;
    }
    void removeDialog(sender.page.id);
    recordDialogEvent(dialog, DialogEventType.ignored);
}
function handleTabRemovedEvent(data) {
    const { tabId, value: dialog } = data;
    if (!isDialog(dialog)) {
        return;
    }
    void removeDialog(tabId);
    recordDialogEvent(dialog, DialogEventType.ignored);
}
async function handleTabsUpdatedEvent(tabId, changeInfo, tab) {
    if (unassignedDialogs.size === 0) {
        background/* debug */.fF("[onpage-dialog]: No command");
        return;
    }
    if (changeInfo.status !== "complete" ||
        tab.incognito ||
        typeof tab.url !== "string" ||
        !/^https?:/.test(tab.url)) {
        return;
    }
    for (const dialog of unassignedDialogs.values()) {
        if (!(await (0,ipm_background/* doesLicenseStateMatch */.a9)(dialog.behavior))) {
            background/* debug */.fF("[onpage-dialog]: License has mismatch");
            dismissDialog(dialog);
            continue;
        }
        const result = await showOnpageDialog(tabId, tab, dialog);
        if (result === ShowOnpageDialogResult.rejected) {
            dismissDialog(dialog);
        }
    }
}
function recordDialogEvent(dialog, eventType) {
    eventEmitter.emit(eventType, dialog);
    if (typeof dialog.ipmId === "string") {
        void (0,ipm_background/* recordEvent */.Ny)(dialog.ipmId, ipm_background/* CommandName.createOnPageDialog */.G7.createOnPageDialog, eventType);
    }
}
async function sendMessage(tabId, message) {
    return await browser.tabs.sendMessage(tabId, message, { frameId: 0 });
}
async function shouldBeIgnored() {
    const ignoredCategories = await ewe_api.notifications.getIgnoredCategories();
    return ignoredCategories.includes("*");
}
async function showOnpageDialog(tabId, tab, dialog) {
    if (await shouldBeIgnored()) {
        background/* debug */.fF("[onpage-dialog]: User ignores notifications");
        return ShowOnpageDialogResult.rejected;
    }
    if (await assignedDialogs.has(tabId)) {
        background/* debug */.fF("[onpage-dialog]: Tab already contains dialog");
        return ShowOnpageDialogResult.rejected;
    }
    const stats = getStats(dialog.id);
    if (!(await shouldBeShown(tab, dialog, stats))) {
        background/* debug */.fF("[onpage-dialog]: Don't show");
        return ShowOnpageDialogResult.ignored;
    }
    background/* debug */.fF("[onpage-dialog]: Show dialog");
    await assignedDialogs.set(tabId, dialog);
    setStats(dialog.id, {
        displayCount: stats.displayCount + 1,
        lastDisplayTime: Date.now()
    });
    await addDialog(tabId);
    recordDialogEvent(dialog, DialogEventType.injected);
    return ShowOnpageDialogResult.shown;
}
async function addDialog(tabId) {
    if (browser.scripting) {
        await browser.scripting.insertCSS({
            files: ["skin/onpage-dialog.css"],
            origin: "USER",
            target: { tabId }
        });
    }
    else {
        await browser.tabs.insertCSS(tabId, {
            cssOrigin: "user",
            file: "/skin/onpage-dialog.css"
        });
    }
    await browser.tabs.sendMessage(tabId, {
        type: "onpage-dialog.show",
        platform: info_background.info.platform
    });
}
async function background_tab_manager_start() {
    await timing_start();
    port.port.on("onpage-dialog.close", handleCloseMessage);
    port.port.on("onpage-dialog.continue", handleContinueMessage);
    port.port.on("onpage-dialog.get", handleGetMessage);
    port.port.on("onpage-dialog.ping", handlePingMessage);
    port.port.on("onpage-dialog.resize", forwardMessage);
    ext.addTrustedMessageTypes(null, [
        "onpage-dialog.continue",
        "onpage-dialog.close",
        "onpage-dialog.get",
        "onpage-dialog.ping",
        "onpage-dialog.resize"
    ]);
    assignedDialogs.on("tab-removed", handleTabRemovedEvent);
    browser.tabs.onUpdated.addListener(handleTabsUpdatedEvent);
    setDialogCommandHandler(handleDialogCommand);
}

;// CONCATENATED MODULE: ./src/onpage-dialog/background/index.ts





;// CONCATENATED MODULE: ./src/premium-onboarding/background/onboarding.ts

function onboarding_start() {
    ext.addTrustedMessageTypes(prefs.Prefs.get("premium_onboarding_trigger_origin"), [
        "app.open"
    ]);
}

;// CONCATENATED MODULE: ./src/premium-onboarding/background/index.ts


;// CONCATENATED MODULE: ./src/premium-subscriptions/shared/premium-subscriptions.ts
const premiumTypes = new Set(["annoyances", "cookies-premium"]);

;// CONCATENATED MODULE: ./src/premium-subscriptions/shared/index.ts


;// CONCATENATED MODULE: ./src/premium-subscriptions/background/premium-subscriptions.ts




async function getPremiumSubscriptions() {
    return ewe_api.subscriptions.getRecommendations()
        .filter(({ type }) => premiumTypes.has(type));
}
async function addOptoutPremiumSubscriptions() {
    const subscriptions = await getPremiumSubscriptions();
    for (const subscription of subscriptions) {
        if (!(await ewe_api.subscriptions.has(subscription.url)) &&
            subscription.type === "annoyances") {
            await (0,filterConfiguration/* addSubscription */.VF)(subscription);
            break;
        }
    }
}
async function removePremiumSubscriptions() {
    const subscriptions = await getPremiumSubscriptions();
    for (const subscription of subscriptions) {
        if (await ewe_api.subscriptions.has(subscription.url)) {
            await ewe_api.subscriptions.remove(subscription.url);
        }
    }
}
function premium_subscriptions_start() {
    premium_background/* emitter.on */.uY.on("deactivated", () => {
        void removePremiumSubscriptions();
    });
    premium_background/* emitter.on */.uY.on("activated", () => {
        void addOptoutPremiumSubscriptions();
    });
}

;// CONCATENATED MODULE: ./src/premium-subscriptions/background/index.ts


// EXTERNAL MODULE: ./src/testing/ready-state/background/index.ts + 2 modules
var ready_state_background = __webpack_require__(351);
;// CONCATENATED MODULE: ./src/yt-wall-detection/shared/detection.ts
const isEnabled = false;

;// CONCATENATED MODULE: ./src/yt-wall-detection/shared/detection.types.ts
const detectedMessageType = "yt-wall-detection.detected";

;// CONCATENATED MODULE: ./src/yt-wall-detection/background/detection.ts




const dialogId = "yt-wall-detection";
const dialogInteractedStorageKey = "ytWallDetection_dialog_interacted";
function handleDialogInteraction(dialog) {
    if (dialog.id !== dialogId) {
        return;
    }
    void prefs.Prefs.set(dialogInteractedStorageKey, true);
}
function handleDetectedMessage(message, sender) {
    if (typeof sender.tab !== "object" || typeof sender.tab.id !== "number") {
        return;
    }
    showDialog(sender.tab.id, sender.tab);
}
function showDialog(tabId, tab) {
    if (prefs.Prefs.get(dialogInteractedStorageKey) === true) {
        return;
    }
    void showOnpageDialog(tabId, tab, {
        behavior: {
            displayDuration: 0,
            target: prefs.Prefs.get("ytWallDetection_dialog_url"),
            timing: Timing.immediate
        },
        content: {
            body: [browser.i18n.getMessage("ytWallDetection_dialog_body")],
            button: browser.i18n.getMessage("ytWallDetection_dialog_button"),
            title: browser.i18n.getMessage("ytWallDetection_dialog_title")
        },
        id: dialogId
    });
}
function detection_start() {
    if (!isEnabled) {
        return;
    }
    eventEmitter.on(DialogEventType.buttonClicked, handleDialogInteraction);
    eventEmitter.on(DialogEventType.closed, handleDialogInteraction);
    port.port.on(detectedMessageType, handleDetectedMessage);
    ext.addTrustedMessageTypes("https://youtube.com", [detectedMessageType]);
    ext.addTrustedMessageTypes("https://www.youtube.com", [detectedMessageType]);
}

;// CONCATENATED MODULE: ./src/yt-wall-detection/background/index.ts


;// CONCATENATED MODULE: ./src/info-injector/shared/info-injector.types.ts
const injectionOrigins = [
    "https://adblockplus.org",
    "https://accounts.adblockplus.org",
    "https://new.adblockplus.org",
    "https://welcome.adblockplus.org",
    "https://getadblock.com",
    "https://vpn.getadblock.com"
];

;// CONCATENATED MODULE: ./src/info-injector/background/info-injector.ts

function info_injector_start() {
    injectionOrigins.forEach((origin) => {
        ext.addTrustedMessageTypes(origin, ["info.getInjectionInfo"]);
    });
}

;// CONCATENATED MODULE: ./src/bootstrap/background/bootstrap.entry.ts























async function bootstrap() {
    (0,tab_session/* start */.B)();
    devtools_start();
    debug_start();
    void (0,ipm_background/* start */.BL)().catch(background/* error */.vU);
    (0,ready_state_background/* start */.BL)();
    (0,filterConfiguration/* start */.BL)();
    (0,stats.start)();
    void (0,subscriptionInit.start)();
    (0,init/* start */.B)();
    void (0,recommendLanguage/* start */.B)();
    composer_start();
    (0,uninstall.start)();
    void start();
    messageResponder_start();
    void public_api_start().catch(background/* error */.vU);
    bypass_start();
    void background_tab_manager_start().catch(background/* error */.vU);
    void tab_manager_start().catch(background/* error */.vU);
    onboarding_start();
    premium_subscriptions_start();
    detection_start();
    info_injector_start();
}
void bootstrap();

})();

/******/ })()
;