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

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

"use strict";

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

// UNUSED EXPORTS: addSecretArrayProvider, blockWebsiteProvider, cacheKeys, checkoutSecretsStateProvider, commonCacheProvider, favIconsProvider, foldersProvider, lastFetchedSecretsProvider, lastFetchedWinADSecretsProvider, selectionHistoryProvider, sitesProvider, ssoSecretsProvider, ssoUrlsProvider, urlTemplatesProvider, windowsAdminCenterItemProvider

// EXTERNAL MODULE: ./src/scripts/core/storage.js
var storage = __webpack_require__(988);
;// CONCATENATED MODULE: ./src/scripts/cache/local-storage-provider.js


const localStorageProvider = {
  async get(key) {
    return this.load(key);
  },
  async load(key) {
    return new Promise((resolve) => {
      const name = (key.name || key); // for common cache keys
      const defaultValue = (key.default ?? []);
      storage/* default */.A.get(name, (items) => {
        const value = (items[name] === undefined) ? defaultValue : items[name];
        resolve(value);
      });
    });
  },
  async set(key, value) {
    const obj = {};
    const name = (key.name || key);
    obj[name] = value;
    return new Promise((resolve) => {
      storage/* default */.A.set(obj, () => {
        resolve(true);
      });
    });
  },
};
/* harmony default export */ const local_storage_provider = (localStorageProvider);

;// CONCATENATED MODULE: ./src/scripts/cache/fav-icon-provider.js


const key = "favIcons";

const favIconsProvider = {
  async load() {
    return local_storage_provider.get(key);
  },
  set(value) {
    local_storage_provider.set(key, value);
  },
  async getAll() {
    return this.load();
  },
  async getByHost(host) {
    const items = await this.load();
    return this.find(items, host);
  },
  async add(host, iconUrl) {
    const items = await this.load();
    const existingItem = this.find(items, host);
    if (!existingItem) {
      items.push({ host, iconUrl });
      this.set(items);
    }
    return items;
  },
  async find(items, host) {
    return items.find((x) => x.host.toLowerCase() === host.toLowerCase());
  },
  clear() {
    this.set([]);
  },
};

/* harmony default export */ const fav_icon_provider = ((/* unused pure expression or super */ null && (favIconsProvider)));

// EXTERNAL MODULE: ./src/scripts/handlers/current-context.js
var current_context = __webpack_require__(208);
;// CONCATENATED MODULE: ./src/scripts/cache/folders-provider.js



const folders_provider_key = "folders";
let lastCached = null;
// storing folders to local storage, as there could be thousands of folders
const foldersProvider = {
  async get() {
    const result = await this.load();
    return result.filter((x) => x.folderName.toLowerCase() !== "personal folders");
  },
  load() {
    return local_storage_provider.get(this.getKey());
  },
  set(value) {
    local_storage_provider.set(this.getKey(), value);
    lastCached = Date.now();
    lastCached = Date.now();
  },
  clear() {
    this.set([]);
    lastCached = null;
  },
  getKey() {
    return current_context/* default */.A.getContextKey(folders_provider_key);
  },
  getLastCached() {
    return lastCached;
  }
};

/* harmony default export */ const folders_provider = ((/* unused pure expression or super */ null && (foldersProvider)));

// EXTERNAL MODULE: ./src/scripts/cache/session-storage-provider.js
var session_storage_provider = __webpack_require__(576);
;// CONCATENATED MODULE: ./src/scripts/cache/sites-provider.js



const sites_provider_key = "sites";

const sitesProvider = {
  async get() {
    return session_storage_provider/* default */.A.get(sites_provider_key);
  },
  set(value) {
    session_storage_provider/* default */.A.set(sites_provider_key, value);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(sites_provider_key);
  },
};

/* harmony default export */ const sites_provider = ((/* unused pure expression or super */ null && (sitesProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/last-fetched-secrets-provider.js



const last_fetched_secrets_provider_key = "lastFetchedSecrets";
const lastFetchedSecretsProvider = {

  async load() {
    return local_storage_provider.get(this.getKey());
  },
  async set(value) {
    local_storage_provider.set(this.getKey(), value);
  },
  async get() {
    return this.load();
  },
  async getByHost(host) {
    const items = await this.load();
    return this.find(items, host);
  },
  async addAll(hostEntries) {
    if (hostEntries.length === 0) return;
    const items = await this.load();
    let finalItems = [...items];
    hostEntries.forEach((hostEntry) => {
      finalItems = [...this.exclude(finalItems, hostEntry.host), hostEntry];
    });
    await this.set(finalItems);
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    const excludedItems = this.exclude(items, item.host);
    excludedItems.push(item);
    await this.set(excludedItems);
  },
  async addSecret(host, secret) {
    const items = await this.load();
    const existingItem = this.find(items, host);
    if (existingItem) {
      existingItem.Secrets.push(secret);
    } else {
      // url missing here
      items.push({
        host,
        Secrets: [secret],
      });
    }
    await this.set(items);
  },
  async findBySecretId(secretId) {
    const items = await this.load();
    return items.find((s) => s.Secrets && s.Secrets.find((k) => k.id === secretId));
  },
  async removeBySecretId(secretId) {
    let items = await this.load();
    items = items.map((s) => {
      s.Secrets = s.Secrets.filter((k) => k.id !== secretId);
      return s;
    });
    await this.set(items);
  },

  find(items, host) {
    return items.find((x) => x.host.toLowerCase() === host.toLowerCase());
  },
  exclude(items, host) {
    return items.filter((x) => x.host.toLowerCase() !== host.toLowerCase());
  },
  async removeByHost(host) {
    let items = await this.load();
    items = items.filter((x) => x.host.toLowerCase() !== host.toLowerCase());
    await this.set(items);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(last_fetched_secrets_provider_key);
  },

};

/* harmony default export */ const last_fetched_secrets_provider = ((/* unused pure expression or super */ null && (lastFetchedSecretsProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/selection-history-provider.js



const selection_history_provider_key = "selectionHistory";

const selectionHistoryProvider = {
  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    const excludedItems = this.exclude(items, item);
    excludedItems.push(item);
    this.set(excludedItems);
  },
  async get() {
    return this.load();
  },

  exclude(items, item) {
    return items.filter((x) => x.tabid !== item.tabid);
  },
  async remove(tabid) {
    let items = await this.load();
    if (!items?.filter) return;
    items = items.filter((item) => item.tabid !== tabid);
    this.set(items);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(selection_history_provider_key);
  },
};
/* harmony default export */ const selection_history_provider = ((/* unused pure expression or super */ null && (selectionHistoryProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/checkout-secrets-state-provider.js



const checkout_secrets_state_provider_key = "checkoutSecretsState";

const checkoutSecretsStateProvider = {
  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    const excludedItems = this.exclude(items, item);
    excludedItems.push(item);
    this.set(excludedItems);
  },
  async get() {
    return this.load();
  },
  async getByID(secretId) {
    const items = await this.load();
    return items.find((s) => s.id === secretId);
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  exclude(items, item) {
    return items.filter((x) => x.id !== item.id);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(checkout_secrets_state_provider_key);
  },
};
/* harmony default export */ const checkout_secrets_state_provider = ((/* unused pure expression or super */ null && (checkoutSecretsStateProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/block-website-provider.js


const block_website_provider_key = "BlockWebSite";

const blockWebsiteProvider = {
  async get() {
    return local_storage_provider.get(this.getKey());
  },
  set(value) {
    local_storage_provider.set(block_website_provider_key, value);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return block_website_provider_key;
  },
};

/* harmony default export */ const block_website_provider = ((/* unused pure expression or super */ null && (blockWebsiteProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/settings-provider.js


const settings_provider_key = "Settings";

const settingsProvider = {
  async get() {
    return local_storage_provider.get(settings_provider_key);
  },
};

/* harmony default export */ const settings_provider = (settingsProvider);

;// CONCATENATED MODULE: ./src/scripts/cache/add-secret-array-provider.js

let memoryCache = []; // Store secrets in memory

const addSecretArrayProvider = {
 
  // Load the secrets from memory cache instead of sessionStorage
  async load() {
    return memoryCache;
  },
  async set(value) {
    memoryCache = value;
  },
  async get() {
    return this.load();
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    items.push(item);
    this.set(items);
  },
  async findByTabId(tabId) {
    const items = await this.load();
    return this.find(items, tabId);
  },
  clear() {
    this.set([]);
  },
  find(items, tabId) {
    return items.find((x) => x.tabid === tabId);
  },
  async removeByTabId(tabId) {
    if (!tabId) return;
    const items = await this.load();
    const result = items.filter((t) => t.tabid !== tabId);
    this.set(result);
  },
};

/* harmony default export */ const add_secret_array_provider = ((/* unused pure expression or super */ null && (addSecretArrayProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/sso-secret-provider.js



const sso_secret_provider_key = "ssoSecrets";

const ssoSecretsProvider = {
  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    if (!items.find((x) => x.id === item.id)) { // Check if item with same id already exists
      items.push(item);
      this.set(items);
    }
  },
  async get() {
    return this.load();
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(sso_secret_provider_key);
  },
};
/* harmony default export */ const sso_secret_provider = ((/* unused pure expression or super */ null && (ssoSecretsProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/last-fetched-winAD-secrets.provider.js



const last_fetched_winAD_secrets_provider_key = "lastFetchedWinADSecrets";
const lastFetchedWinADSecretsProvider = {

  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  async get() {
    return this.load();
  },
  async getByName(name) {
    const items = await this.load();
    return this.find(items, name);
  },
  async add(name, secrets) {
    if (!secrets) return;
    const items = await this.exclude(name);
    items.push({ name, secrets });
    this.set(items);
  },
  async exclude(name) {
    if (!name) return [];
    const items = await this.load();
    const filteredItems = items.filter((x) => x.name !== name);
    this.set(filteredItems);
    return filteredItems;
  },
  find(items, name) {
    return items.find((x) => x.name.toLowerCase() === name.toLowerCase());
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(last_fetched_winAD_secrets_provider_key);
  },

};

/* harmony default export */ const last_fetched_winAD_secrets_provider = ((/* unused pure expression or super */ null && (lastFetchedWinADSecretsProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/sso-urls-provider.js



const sso_urls_provider_key = "ssoUrls";

const ssoUrlsProvider = {
  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  async get() {
    return this.load();
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(sso_urls_provider_key);
  },
};

/* harmony default export */ const sso_urls_provider = ((/* unused pure expression or super */ null && (ssoUrlsProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/windows-admin-center-item-provider.js



const windows_admin_center_item_provider_key = "windowsAdminCenterItem";
const windowsAdminCenterItemProvider = {

  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  async get() {
    return this.load();
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    items.push(item);
    this.set(items);
  },
  async findByTabId(tabId) {
    const items = await this.load();
    return items.find((s) => s.tabId === tabId);
  },
  async removeByTabId(tabId) {
    const items = await this.load();
    const filteredItems = items.filter((x) => x.tabId !== tabId);
    this.set(filteredItems);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(windows_admin_center_item_provider_key);
  },

};

/* harmony default export */ const windows_admin_center_item_provider = ((/* unused pure expression or super */ null && (windowsAdminCenterItemProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/url-templates-provider.js



const url_templates_provider_key = "urlTemplates";
const urlTemplatesProvider = {

  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  async get() {
    return this.load();
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  clear() {
    this.set([]);
  },
  getKey() {
    return current_context/* default */.A.getContextKey(url_templates_provider_key);
  },

};

/* harmony default export */ const url_templates_provider = ((/* unused pure expression or super */ null && (urlTemplatesProvider)));

;// CONCATENATED MODULE: ./src/scripts/cache/common-cache-provider.js


const commonCacheProvider = {
  async get(key) {
    return session_storage_provider/* default */.A.get(key);
  },
  async set(key, value) {
    return session_storage_provider/* default */.A.set(key, value);
  },
  clear(key) {
    this.set(key, []);
  }
};

/* harmony default export */ const common_cache_provider = ((/* unused pure expression or super */ null && (commonCacheProvider)));

// EXTERNAL MODULE: ./src/scripts/utils/constants.js
var constants = __webpack_require__(482);
;// CONCATENATED MODULE: ./src/scripts/cache/cache-keys.js


const cacheKeys = {
  token: {
    name: "token",
    default: {}
  },
  launchedSecret:
  {
    name: "secret",
    default: {}
  },
  twoStepSecret: {
    name: "twoStepSecret",
    default: {}
  },
  webLauncherData:
  {
    name: "webLauncherData",
    default: {}
  },
  serverType: {
    name: "serverType",
    default: constants.SERVER_TYPE.SS
  },
  samlTabId: {
    name: "samlTabId",
    default: 0
  },
  ssLoginTabId: {
    name: "samlTabId",
    default: 0
  },
  ssLoginWindowId: {
    name: "ssLoginWindowId",
    default: 0,
  },
  lastFocusedTabId:
  {
    name: "lastFocusedTabId",
    default: 0
  },
  platformTabId:
  {
    name: "platformTabId",
    default: 0
  },
  loggedInURLType:
  {
    name: "loggedInURLType",
    default: {}
  },
};

/* harmony default export */ const cache_keys = ((/* unused pure expression or super */ null && (cacheKeys)));

;// CONCATENATED MODULE: ./src/scripts/cache/index.js




















/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(666);
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_core_ext__WEBPACK_IMPORTED_MODULE_0__);


let storage = (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().storage).session || (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().storage).local;
const sessionStorageProvider = {
  async get(key) {
    return this.load(key);
  },
  async load(key) {
    return new Promise((resolve) => {
      const name = (key.name || key); // for common cache keys
      const defaultValue = (key.default ?? []);
      storage.get(name, (items) => {
        const value = (items[name] === undefined) ? defaultValue : items[name];
        resolve(value);
      });
    });
  },
  async set(key, value) {
    const obj = {};
    const name = (key.name || key);
    obj[name] = value;
    return new Promise((resolve) => {
      storage.set(obj, () => {
        resolve(true);
      });
    });
  },
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (sessionStorageProvider);


/***/ }),

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

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  kP: () => (/* binding */ getSecretState),
  OS: () => (/* binding */ handleLaunchSecret),
  aA: () => (/* binding */ handleSecretState),
  rW: () => (/* binding */ sendKeystrokes)
});

// UNUSED EXPORTS: addBackgroundImage, addComment, addEventToBtns, addFontFace, addNewSecretPopup, applyDialogSettings, applyMappings, attachDropEvent, attachHandleSubmit, attachMutation, attachOnDrag, attachOnGeneratePassword, attachOnSecretClickEvent, attachSecretUrlClick, attachWindowResize, calculateWindowWidthHeight, checkExactMatch, checkIfSSLoggedIn, chooseTemplateClick, confirmAndLaunch, createAddSecretPopup, createHostElement, createWPFParent, displaySecrets, domLoaded, fillGeneratedPassword, findLoginButton, formElements, getAddNewSecretTemplateFieldsMarkup, getAppropriateParent, getConfirmDialogMarkup, getElementByXpath, getIframeId, getMFAChallenge, getMappedValue, getPathTo, getSiteIconUrl, getTicketSystem, getUsernameField, handleOtp, handleSubmit, handleTicketSystem, hideShowPWD, isOtpOnPage, isPasswordOnPage, isValidForm, loadAddSecretForm, markRequiredFields, markUsername, mousedownCallback, onAddSecretClick, onCancelChooseTemplate, onCancelSaveSecret, onCommentSaved, onInpuDrop, onMouseMove, onSaveSecret, onSecretNameInput, onSecurityWarningAccepted, onSecurityWarningRejected, onTemplateChange, openIframeDialog, openSecretPopup, openSecretPopupOnIframe, pageLoad, passwordSet, placeDelineaIcon, processFormElements, readAndSendSAMLToken, reassignPwd, reassignUsername, recordingMouseMove, rememberSelection, removeContainer, removeDelineaIcon, removeDropEvent, removeFlag, removeFont, removeSecretDivIcon, removeUserPWDEvents, resizeInput, saveNewSecret, secretUrlOnClick, sendSAMLToken, setAllUserNamePassword, setDefaultFolderAndSiteValues, setDefaultTemplateValue, setDefaultTicketName, setDefaultUrlValue, setFavIcon, setFolders, setMessageListner, setSites, setTemplates, setTemplatesNFolders, setUrls, setUserNamePWD, setUserNameValue, showAddSecretForm, showConfirmDialog, showContainer, showCopyToClipBoardMsg, showErrorPop, showMFAChallenge, showMultipleUrlOnPopup, showRecordingIcon, showRequireCommentPop, showRequireMFA, showSecret, showSecretPopupOnDemand, skipWPFMutations, templateTextChange, toggleChooseTemplateButton, toggleFavIcon, triggerSecretNameInputEvent, validateSecretFields

// EXTERNAL MODULE: ./src/scripts/core/ext.js
var core_ext = __webpack_require__(666);
var ext_default = /*#__PURE__*/__webpack_require__.n(core_ext);
// EXTERNAL MODULE: ./src/scripts/core/storage.js
var storage = __webpack_require__(988);
// EXTERNAL MODULE: ./src/scripts/utils/common.js
var common = __webpack_require__(942);
// EXTERNAL MODULE: ./src/scripts/utils/constants.js
var constants = __webpack_require__(482);
// EXTERNAL MODULE: ./src/scripts/utils/errors.js
var errors = __webpack_require__(600);
// EXTERNAL MODULE: ./src/scripts/helpers/url-helpers.js
var url_helpers = __webpack_require__(714);
// EXTERNAL MODULE: ./src/scripts/helpers/visibility-helpers.js
var visibility_helpers = __webpack_require__(511);
;// CONCATENATED MODULE: ./node_modules/dompurify/dist/purify.es.mjs
/*! @license DOMPurify 3.2.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.3/LICENSE */

const {
  entries,
  setPrototypeOf,
  isFrozen,
  getPrototypeOf,
  getOwnPropertyDescriptor
} = Object;
let {
  freeze,
  seal,
  create
} = Object; // eslint-disable-line import/no-mutable-exports
let {
  apply,
  construct
} = typeof Reflect !== 'undefined' && Reflect;
if (!freeze) {
  freeze = function freeze(x) {
    return x;
  };
}
if (!seal) {
  seal = function seal(x) {
    return x;
  };
}
if (!apply) {
  apply = function apply(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  };
}
if (!construct) {
  construct = function construct(Func, args) {
    return new Func(...args);
  };
}
const arrayForEach = unapply(Array.prototype.forEach);
const arrayPop = unapply(Array.prototype.pop);
const arrayPush = unapply(Array.prototype.push);
const stringToLowerCase = unapply(String.prototype.toLowerCase);
const stringToString = unapply(String.prototype.toString);
const stringMatch = unapply(String.prototype.match);
const stringReplace = unapply(String.prototype.replace);
const stringIndexOf = unapply(String.prototype.indexOf);
const stringTrim = unapply(String.prototype.trim);
const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
const regExpTest = unapply(RegExp.prototype.test);
const typeErrorCreate = unconstruct(TypeError);
/**
 * Creates a new function that calls the given function with a specified thisArg and arguments.
 *
 * @param func - The function to be wrapped and called.
 * @returns A new function that calls the given function with a specified thisArg and arguments.
 */
function unapply(func) {
  return function (thisArg) {
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return apply(func, thisArg, args);
  };
}
/**
 * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
 *
 * @param func - The constructor function to be wrapped and called.
 * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
 */
function unconstruct(func) {
  return function () {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return construct(func, args);
  };
}
/**
 * Add properties to a lookup table
 *
 * @param set - The set to which elements will be added.
 * @param array - The array containing elements to be added to the set.
 * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
 * @returns The modified set with added elements.
 */
function addToSet(set, array) {
  let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
  if (setPrototypeOf) {
    // Make 'in' and truthy checks like Boolean(set.constructor)
    // independent of any properties defined on Object.prototype.
    // Prevent prototype setters from intercepting set as a this value.
    setPrototypeOf(set, null);
  }
  let l = array.length;
  while (l--) {
    let element = array[l];
    if (typeof element === 'string') {
      const lcElement = transformCaseFunc(element);
      if (lcElement !== element) {
        // Config presets (e.g. tags.js, attrs.js) are immutable.
        if (!isFrozen(array)) {
          array[l] = lcElement;
        }
        element = lcElement;
      }
    }
    set[element] = true;
  }
  return set;
}
/**
 * Clean up an array to harden against CSPP
 *
 * @param array - The array to be cleaned.
 * @returns The cleaned version of the array
 */
function cleanArray(array) {
  for (let index = 0; index < array.length; index++) {
    const isPropertyExist = objectHasOwnProperty(array, index);
    if (!isPropertyExist) {
      array[index] = null;
    }
  }
  return array;
}
/**
 * Shallow clone an object
 *
 * @param object - The object to be cloned.
 * @returns A new object that copies the original.
 */
function clone(object) {
  const newObject = create(null);
  for (const [property, value] of entries(object)) {
    const isPropertyExist = objectHasOwnProperty(object, property);
    if (isPropertyExist) {
      if (Array.isArray(value)) {
        newObject[property] = cleanArray(value);
      } else if (value && typeof value === 'object' && value.constructor === Object) {
        newObject[property] = clone(value);
      } else {
        newObject[property] = value;
      }
    }
  }
  return newObject;
}
/**
 * This method automatically checks if the prop is function or getter and behaves accordingly.
 *
 * @param object - The object to look up the getter function in its prototype chain.
 * @param prop - The property name for which to find the getter function.
 * @returns The getter function found in the prototype chain or a fallback function.
 */
function lookupGetter(object, prop) {
  while (object !== null) {
    const desc = getOwnPropertyDescriptor(object, prop);
    if (desc) {
      if (desc.get) {
        return unapply(desc.get);
      }
      if (typeof desc.value === 'function') {
        return unapply(desc.value);
      }
    }
    object = getPrototypeOf(object);
  }
  function fallbackValue() {
    return null;
  }
  return fallbackValue;
}

const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
// List of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace
// checks properly in case one wants to add them to
// allow-list.
const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
// Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default.
const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
const purify_es_text = freeze(['#text']);

const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);

// eslint-disable-next-line unicorn/better-regex
const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
const TMPLIT_EXPR = seal(/\$\{[\w\W]*}/gm); // eslint-disable-line unicorn/better-regex
const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
);
const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
);
const DOCTYPE_NAME = seal(/^html$/i);
const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);

var EXPRESSIONS = /*#__PURE__*/Object.freeze({
  __proto__: null,
  ARIA_ATTR: ARIA_ATTR,
  ATTR_WHITESPACE: ATTR_WHITESPACE,
  CUSTOM_ELEMENT: CUSTOM_ELEMENT,
  DATA_ATTR: DATA_ATTR,
  DOCTYPE_NAME: DOCTYPE_NAME,
  ERB_EXPR: ERB_EXPR,
  IS_ALLOWED_URI: IS_ALLOWED_URI,
  IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
  MUSTACHE_EXPR: MUSTACHE_EXPR,
  TMPLIT_EXPR: TMPLIT_EXPR
});

/* eslint-disable @typescript-eslint/indent */
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
const NODE_TYPE = {
  element: 1,
  attribute: 2,
  text: 3,
  cdataSection: 4,
  entityReference: 5,
  // Deprecated
  entityNode: 6,
  // Deprecated
  progressingInstruction: 7,
  comment: 8,
  document: 9,
  documentType: 10,
  documentFragment: 11,
  notation: 12 // Deprecated
};
const getGlobal = function getGlobal() {
  return typeof window === 'undefined' ? null : window;
};
/**
 * Creates a no-op policy for internal use only.
 * Don't export this function outside this module!
 * @param trustedTypes The policy factory.
 * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
 * @return The policy created (or null, if Trusted Types
 * are not supported or creating the policy failed).
 */
const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
  if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
    return null;
  }
  // Allow the callers to control the unique policy name
  // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
  // Policy creation with duplicate names throws in Trusted Types.
  let suffix = null;
  const ATTR_NAME = 'data-tt-policy-suffix';
  if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
    suffix = purifyHostElement.getAttribute(ATTR_NAME);
  }
  const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML(html) {
        return html;
      },
      createScriptURL(scriptUrl) {
        return scriptUrl;
      }
    });
  } catch (_) {
    // Policy creation failed (most likely another DOMPurify script has
    // already run). Skip creating the policy, as this will only cause errors
    // if TT are enforced.
    console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
    return null;
  }
};
const _createHooksMap = function _createHooksMap() {
  return {
    afterSanitizeAttributes: [],
    afterSanitizeElements: [],
    afterSanitizeShadowDOM: [],
    beforeSanitizeAttributes: [],
    beforeSanitizeElements: [],
    beforeSanitizeShadowDOM: [],
    uponSanitizeAttribute: [],
    uponSanitizeElement: [],
    uponSanitizeShadowNode: []
  };
};
function createDOMPurify() {
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  const DOMPurify = root => createDOMPurify(root);
  DOMPurify.version = '3.2.3';
  DOMPurify.removed = [];
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document) {
    // Not running in a browser, provide a factory function
    // so that you can pass your own Window
    DOMPurify.isSupported = false;
    return DOMPurify;
  }
  let {
    document
  } = window;
  const originalDocument = document;
  const currentScript = originalDocument.currentScript;
  const {
    DocumentFragment,
    HTMLTemplateElement,
    Node,
    Element,
    NodeFilter,
    NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
    HTMLFormElement,
    DOMParser,
    trustedTypes
  } = window;
  const ElementPrototype = Element.prototype;
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  const remove = lookupGetter(ElementPrototype, 'remove');
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  // As per issue #47, the web-components registry is inherited by a
  // new document created via createHTMLDocument. As per the spec
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
  // a new empty registry is used when creating a template contents owner
  // document, so we use that as our parent document to ensure nothing
  // is inherited.
  if (typeof HTMLTemplateElement === 'function') {
    const template = document.createElement('template');
    if (template.content && template.content.ownerDocument) {
      document = template.content.ownerDocument;
    }
  }
  let trustedTypesPolicy;
  let emptyHTML = '';
  const {
    implementation,
    createNodeIterator,
    createDocumentFragment,
    getElementsByTagName
  } = document;
  const {
    importNode
  } = originalDocument;
  let hooks = _createHooksMap();
  /**
   * Expose whether this browser supports running the full DOMPurify.
   */
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
  const {
    MUSTACHE_EXPR,
    ERB_EXPR,
    TMPLIT_EXPR,
    DATA_ATTR,
    ARIA_ATTR,
    IS_SCRIPT_OR_DATA,
    ATTR_WHITESPACE,
    CUSTOM_ELEMENT
  } = EXPRESSIONS;
  let {
    IS_ALLOWED_URI: IS_ALLOWED_URI$1
  } = EXPRESSIONS;
  /**
   * We consider the elements and attributes below to be safe. Ideally
   * don't add any new ones but feel free to remove unwanted ones.
   */
  /* allowed element names */
  let ALLOWED_TAGS = null;
  const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...purify_es_text]);
  /* Allowed attribute names */
  let ALLOWED_ATTR = null;
  const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
  /*
   * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
   * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
   * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
   * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
   */
  let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
    tagNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    attributeNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    allowCustomizedBuiltInElements: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: false
    }
  }));
  /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
  let FORBID_TAGS = null;
  /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
  let FORBID_ATTR = null;
  /* Decide if ARIA attributes are okay */
  let ALLOW_ARIA_ATTR = true;
  /* Decide if custom data attributes are okay */
  let ALLOW_DATA_ATTR = true;
  /* Decide if unknown protocols are okay */
  let ALLOW_UNKNOWN_PROTOCOLS = false;
  /* Decide if self-closing tags in attributes are allowed.
   * Usually removed due to a mXSS issue in jQuery 3.0 */
  let ALLOW_SELF_CLOSE_IN_ATTR = true;
  /* Output should be safe for common template engines.
   * This means, DOMPurify removes data attributes, mustaches and ERB
   */
  let SAFE_FOR_TEMPLATES = false;
  /* Output should be safe even for XML used within HTML and alike.
   * This means, DOMPurify removes comments when containing risky content.
   */
  let SAFE_FOR_XML = true;
  /* Decide if document with <html>... should be returned */
  let WHOLE_DOCUMENT = false;
  /* Track whether config is already set on this instance of DOMPurify. */
  let SET_CONFIG = false;
  /* Decide if all elements (e.g. style, script) must be children of
   * document.body. By default, browsers might move them to document.head */
  let FORCE_BODY = false;
  /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
   * string (or a TrustedHTML object if Trusted Types are supported).
   * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
   */
  let RETURN_DOM = false;
  /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
   * string  (or a TrustedHTML object if Trusted Types are supported) */
  let RETURN_DOM_FRAGMENT = false;
  /* Try to return a Trusted Type object instead of a string, return a string in
   * case Trusted Types are not supported  */
  let RETURN_TRUSTED_TYPE = false;
  /* Output should be free from DOM clobbering attacks?
   * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
   */
  let SANITIZE_DOM = true;
  /* Achieve full DOM Clobbering protection by isolating the namespace of named
   * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
   *
   * HTML/DOM spec rules that enable DOM Clobbering:
   *   - Named Access on Window (§7.3.3)
   *   - DOM Tree Accessors (§3.1.5)
   *   - Form Element Parent-Child Relations (§4.10.3)
   *   - Iframe srcdoc / Nested WindowProxies (§4.8.5)
   *   - HTMLCollection (§4.2.10.2)
   *
   * Namespace isolation is implemented by prefixing `id` and `name` attributes
   * with a constant string, i.e., `user-content-`
   */
  let SANITIZE_NAMED_PROPS = false;
  const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
  /* Keep element content when removing element? */
  let KEEP_CONTENT = true;
  /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
   * of importing it into a new Document and returning a sanitized copy */
  let IN_PLACE = false;
  /* Allow usage of profiles like html, svg and mathMl */
  let USE_PROFILES = {};
  /* Tags to ignore content of when KEEP_CONTENT is true */
  let FORBID_CONTENTS = null;
  const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
  /* Tags that are safe for data: URIs */
  let DATA_URI_TAGS = null;
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
  /* Attributes safe for values like "javascript:" */
  let URI_SAFE_ATTRIBUTES = null;
  const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
  const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  /* Document namespace */
  let NAMESPACE = HTML_NAMESPACE;
  let IS_EMPTY_INPUT = false;
  /* Allowed XHTML+XML namespaces */
  let ALLOWED_NAMESPACES = null;
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
  let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
  let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
  // Certain elements are allowed in both SVG and HTML
  // namespace. We need to specify them explicitly
  // so that they don't get erroneously deleted from
  // HTML namespace.
  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
  /* Parsing of strict XHTML documents */
  let PARSER_MEDIA_TYPE = null;
  const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
  const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  let transformCaseFunc = null;
  /* Keep a reference to config to pass to hooks */
  let CONFIG = null;
  /* Ideally, do not touch anything below this line */
  /* ______________________________________________ */
  const formElement = document.createElement('form');
  const isRegexOrFunction = function isRegexOrFunction(testValue) {
    return testValue instanceof RegExp || testValue instanceof Function;
  };
  /**
   * _parseConfig
   *
   * @param cfg optional config literal
   */
  // eslint-disable-next-line complexity
  const _parseConfig = function _parseConfig() {
    let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (CONFIG && CONFIG === cfg) {
      return;
    }
    /* Shield configuration object from tampering */
    if (!cfg || typeof cfg !== 'object') {
      cfg = {};
    }
    /* Shield configuration object from prototype pollution */
    cfg = clone(cfg);
    PARSER_MEDIA_TYPE =
    // eslint-disable-next-line unicorn/prefer-includes
    SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
    // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
    transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
    /* Set configuration parameters */
    ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
    ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
    URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
    FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
    USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
    ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
    SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
    RETURN_DOM = cfg.RETURN_DOM || false; // Default false
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
    FORCE_BODY = cfg.FORCE_BODY || false; // Default false
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
    SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
    IN_PLACE = cfg.IN_PLACE || false; // Default false
    IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
    HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
    CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
      CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
    }
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }
    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }
    /* Parse profile info */
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, purify_es_text);
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html$1);
        addToSet(ALLOWED_ATTR, html);
      }
      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg$1);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl$1);
        addToSet(ALLOWED_ATTR, mathMl);
        addToSet(ALLOWED_ATTR, xml);
      }
    }
    /* Merge configuration parameters */
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone(ALLOWED_TAGS);
      }
      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
    }
    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone(ALLOWED_ATTR);
      }
      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
    }
    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
    }
    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone(FORBID_CONTENTS);
      }
      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
    }
    /* Add #text in case KEEP_CONTENT is set to true */
    if (KEEP_CONTENT) {
      ALLOWED_TAGS['#text'] = true;
    }
    /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
    }
    /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ['tbody']);
      delete FORBID_TAGS.tbody;
    }
    if (cfg.TRUSTED_TYPES_POLICY) {
      if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
      }
      if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
      }
      // Overwrite existing TrustedTypes policy.
      trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
      // Sign local variables required by `sanitize`.
      emptyHTML = trustedTypesPolicy.createHTML('');
    } else {
      // Uninitialized policy, attempt to initialize the internal dompurify policy.
      if (trustedTypesPolicy === undefined) {
        trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
      }
      // If creating the internal policy succeeded sign internal variables.
      if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
        emptyHTML = trustedTypesPolicy.createHTML('');
      }
    }
    // Prevent further manipulation of configuration.
    // Not available in IE8, Safari 5, etc.
    if (freeze) {
      freeze(cfg);
    }
    CONFIG = cfg;
  };
  /* Keep track of all possible SVG and MathML tags
   * so that we can perform the namespace checks
   * correctly. */
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
  /**
   * @param element a DOM element whose namespace is being checked
   * @returns Return false if the element has a
   *  namespace that a spec-compliant parser would never
   *  return. Return true otherwise.
   */
  const _checkValidNamespace = function _checkValidNamespace(element) {
    let parent = getParentNode(element);
    // In JSDOM, if we're inside shadow DOM, then parentNode
    // can be null. We just simulate parent in this case.
    if (!parent || !parent.tagName) {
      parent = {
        namespaceURI: NAMESPACE,
        tagName: 'template'
      };
    }
    const tagName = stringToLowerCase(element.tagName);
    const parentTagName = stringToLowerCase(parent.tagName);
    if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
      return false;
    }
    if (element.namespaceURI === SVG_NAMESPACE) {
      // The only way to switch from HTML namespace to SVG
      // is via <svg>. If it happens via any other tag, then
      // it should be killed.
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === 'svg';
      }
      // The only way to switch from MathML to SVG is via`
      // svg if parent is either <annotation-xml> or MathML
      // text integration points.
      if (parent.namespaceURI === MATHML_NAMESPACE) {
        return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }
      // We only allow elements that are defined in SVG
      // spec. All others are disallowed in SVG namespace.
      return Boolean(ALL_SVG_TAGS[tagName]);
    }
    if (element.namespaceURI === MATHML_NAMESPACE) {
      // The only way to switch from HTML namespace to MathML
      // is via <math>. If it happens via any other tag, then
      // it should be killed.
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === 'math';
      }
      // The only way to switch from SVG to MathML is via
      // <math> and HTML integration points
      if (parent.namespaceURI === SVG_NAMESPACE) {
        return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
      }
      // We only allow elements that are defined in MathML
      // spec. All others are disallowed in MathML namespace.
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }
    if (element.namespaceURI === HTML_NAMESPACE) {
      // The only way to switch from SVG to HTML is via
      // HTML integration points, and from MathML to HTML
      // is via MathML text integration points
      if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      // We disallow tags that are specific for MathML
      // or SVG and should never appear in HTML namespace
      return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
    }
    // For XHTML and XML documents that support custom namespaces
    if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
      return true;
    }
    // The code should never reach this place (this means
    // that the element somehow got namespace that is not
    // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
    // Return false just in case.
    return false;
  };
  /**
   * _forceRemove
   *
   * @param node a DOM node
   */
  const _forceRemove = function _forceRemove(node) {
    arrayPush(DOMPurify.removed, {
      element: node
    });
    try {
      // eslint-disable-next-line unicorn/prefer-dom-node-remove
      getParentNode(node).removeChild(node);
    } catch (_) {
      remove(node);
    }
  };
  /**
   * _removeAttribute
   *
   * @param name an Attribute name
   * @param element a DOM node
   */
  const _removeAttribute = function _removeAttribute(name, element) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: element.getAttributeNode(name),
        from: element
      });
    } catch (_) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: element
      });
    }
    element.removeAttribute(name);
    // We void attribute values for unremovable "is" attributes
    if (name === 'is') {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(element);
        } catch (_) {}
      } else {
        try {
          element.setAttribute(name, '');
        } catch (_) {}
      }
    }
  };
  /**
   * _initDocument
   *
   * @param dirty - a string of dirty markup
   * @return a DOM, filled with the dirty markup
   */
  const _initDocument = function _initDocument(dirty) {
    /* Create a HTML document */
    let doc = null;
    let leadingWhitespace = null;
    if (FORCE_BODY) {
      dirty = '<remove></remove>' + dirty;
    } else {
      /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
      const matches = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches && matches[0];
    }
    if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
      // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
      dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
    }
    const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    /*
     * Use the DOMParser API by default, fallback later if needs be
     * DOMParser not work for svg when has multiple root element.
     */
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
      } catch (_) {}
    }
    /* Use createHTMLDocument in case DOMParser is not available */
    if (!doc || !doc.documentElement) {
      doc = implementation.createDocument(NAMESPACE, 'template', null);
      try {
        doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
      } catch (_) {
        // Syntax error if dirtyPayload is invalid xml
      }
    }
    const body = doc.body || doc.documentElement;
    if (dirty && leadingWhitespace) {
      body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }
    /* Work on whole document or just its body */
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
    }
    return WHOLE_DOCUMENT ? doc.documentElement : body;
  };
  /**
   * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
   *
   * @param root The root element or node to start traversing on.
   * @return The created NodeIterator
   */
  const _createNodeIterator = function _createNodeIterator(root) {
    return createNodeIterator.call(root.ownerDocument || root, root,
    // eslint-disable-next-line no-bitwise
    NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
  };
  /**
   * _isClobbered
   *
   * @param element element to check for clobbering attacks
   * @return true if clobbered, false if safe
   */
  const _isClobbered = function _isClobbered(element) {
    return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
  };
  /**
   * Checks whether the given object is a DOM node.
   *
   * @param value object to check whether it's a DOM node
   * @return true is object is a DOM node
   */
  const _isNode = function _isNode(value) {
    return typeof Node === 'function' && value instanceof Node;
  };
  function _executeHooks(hooks, currentNode, data) {
    arrayForEach(hooks, hook => {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  }
  /**
   * _sanitizeElements
   *
   * @protect nodeName
   * @protect textContent
   * @protect removeChild
   * @param currentNode to check for permission to exist
   * @return true if node was killed, false if left alive
   */
  const _sanitizeElements = function _sanitizeElements(currentNode) {
    let content = null;
    /* Execute a hook if present */
    _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
    /* Check if element is clobbered or can clobber */
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    /* Now let's check the element's type and name */
    const tagName = transformCaseFunc(currentNode.nodeName);
    /* Execute a hook if present */
    _executeHooks(hooks.uponSanitizeElement, currentNode, {
      tagName,
      allowedTags: ALLOWED_TAGS
    });
    /* Detect mXSS attempts abusing namespace confusion */
    if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    /* Remove any occurrence of processing instructions */
    if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
      _forceRemove(currentNode);
      return true;
    }
    /* Remove any kind of possibly harmful comments */
    if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
      _forceRemove(currentNode);
      return true;
    }
    /* Remove element if anything forbids its presence */
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      /* Check if we have a custom element to handle */
      if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
          return false;
        }
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
          return false;
        }
      }
      /* Keep content except for bad-listed elements */
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        const parentNode = getParentNode(currentNode) || currentNode.parentNode;
        const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
        if (childNodes && parentNode) {
          const childCount = childNodes.length;
          for (let i = childCount - 1; i >= 0; --i) {
            const childClone = cloneNode(childNodes[i], true);
            childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
            parentNode.insertBefore(childClone, getNextSibling(currentNode));
          }
        }
      }
      _forceRemove(currentNode);
      return true;
    }
    /* Check whether element has a valid namespace */
    if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    /* Make sure that older browsers don't get fallback-tag mXSS */
    if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    /* Sanitize element content to be template-safe */
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
      /* Get the element's text content */
      content = currentNode.textContent;
      arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
        content = stringReplace(content, expr, ' ');
      });
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, {
          element: currentNode.cloneNode()
        });
        currentNode.textContent = content;
      }
    }
    /* Execute a hook if present */
    _executeHooks(hooks.afterSanitizeElements, currentNode, null);
    return false;
  };
  /**
   * _isValidAttribute
   *
   * @param lcTag Lowercase tag name of containing element.
   * @param lcName Lowercase attribute name.
   * @param value Attribute value.
   * @return Returns true if `value` is valid, otherwise false.
   */
  // eslint-disable-next-line complexity
  const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
    /* Make sure attribute cannot clobber */
    if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
      return false;
    }
    /* Allow valid data-* attributes: At least one character after "-"
        (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
        XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
        We don't need to check the value; it's always URI safe. */
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      if (
      // First condition does a very basic check if a) it's basically a valid custom element tagname AND
      // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
      // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
      _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) ||
      // Alternative, second condition checks if it's an `is`-attribute, AND
      // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
      lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
        return false;
      }
      /* Check value is safe. First, is attr inert? If so, is safe */
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
      return false;
    } else ;
    return true;
  };
  /**
   * _isBasicCustomElement
   * checks if at least one dash is included in tagName, and it's not the first char
   * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
   *
   * @param tagName name of the tag of the node to sanitize
   * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
   */
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
    return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
  };
  /**
   * _sanitizeAttributes
   *
   * @protect attributes
   * @protect nodeName
   * @protect removeAttribute
   * @protect setAttribute
   *
   * @param currentNode to sanitize
   */
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
    /* Execute a hook if present */
    _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
    const {
      attributes
    } = currentNode;
    /* Check if we have attributes; if not we might have a text node */
    if (!attributes || _isClobbered(currentNode)) {
      return;
    }
    const hookEvent = {
      attrName: '',
      attrValue: '',
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR,
      forceKeepAttr: undefined
    };
    let l = attributes.length;
    /* Go backwards over all attributes; safely remove bad ones */
    while (l--) {
      const attr = attributes[l];
      const {
        name,
        namespaceURI,
        value: attrValue
      } = attr;
      const lcName = transformCaseFunc(name);
      let value = name === 'value' ? attrValue : stringTrim(attrValue);
      /* Execute a hook if present */
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
      _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
      value = hookEvent.attrValue;
      /* Full DOM Clobbering protection via namespace isolation,
       * Prefix id and name attributes with `user-content-`
       */
      if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
        // Remove the attribute with this value
        _removeAttribute(name, currentNode);
        // Prefix the value and later re-create the attribute with the sanitized value
        value = SANITIZE_NAMED_PROPS_PREFIX + value;
      }
      /* Work around a security issue with comments inside attributes */
      if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      /* Did the hooks approve of the attribute? */
      if (hookEvent.forceKeepAttr) {
        continue;
      }
      /* Remove attribute */
      _removeAttribute(name, currentNode);
      /* Did the hooks approve of the attribute? */
      if (!hookEvent.keepAttr) {
        continue;
      }
      /* Work around a security issue in jQuery 3.0 */
      if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      /* Sanitize attribute content to be template-safe */
      if (SAFE_FOR_TEMPLATES) {
        arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
          value = stringReplace(value, expr, ' ');
        });
      }
      /* Is `value` valid for this attribute? */
      const lcTag = transformCaseFunc(currentNode.nodeName);
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }
      /* Handle attributes that require Trusted Types */
      if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
        if (namespaceURI) ; else {
          switch (trustedTypes.getAttributeType(lcTag, lcName)) {
            case 'TrustedHTML':
              {
                value = trustedTypesPolicy.createHTML(value);
                break;
              }
            case 'TrustedScriptURL':
              {
                value = trustedTypesPolicy.createScriptURL(value);
                break;
              }
          }
        }
      }
      /* Handle invalid data-* attribute set by try-catching it */
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name, value);
        } else {
          /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
          currentNode.setAttribute(name, value);
        }
        if (_isClobbered(currentNode)) {
          _forceRemove(currentNode);
        } else {
          arrayPop(DOMPurify.removed);
        }
      } catch (_) {}
    }
    /* Execute a hook if present */
    _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
  };
  /**
   * _sanitizeShadowDOM
   *
   * @param fragment to iterate over recursively
   */
  const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
    let shadowNode = null;
    const shadowIterator = _createNodeIterator(fragment);
    /* Execute a hook if present */
    _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
    while (shadowNode = shadowIterator.nextNode()) {
      /* Execute a hook if present */
      _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
      /* Sanitize tags and elements */
      _sanitizeElements(shadowNode);
      /* Check attributes next */
      _sanitizeAttributes(shadowNode);
      /* Deep shadow DOM detected */
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(shadowNode.content);
      }
    }
    /* Execute a hook if present */
    _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
  };
  // eslint-disable-next-line complexity
  DOMPurify.sanitize = function (dirty) {
    let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let body = null;
    let importedNode = null;
    let currentNode = null;
    let returnNode = null;
    /* Make sure we have a string to sanitize.
      DO NOT return early, as this will return the wrong type if
      the user has requested a DOM object rather than a string */
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = '<!-->';
    }
    /* Stringify, in case dirty is an object */
    if (typeof dirty !== 'string' && !_isNode(dirty)) {
      if (typeof dirty.toString === 'function') {
        dirty = dirty.toString();
        if (typeof dirty !== 'string') {
          throw typeErrorCreate('dirty is not a string, aborting');
        }
      } else {
        throw typeErrorCreate('toString is not a function');
      }
    }
    /* Return dirty HTML if DOMPurify cannot run */
    if (!DOMPurify.isSupported) {
      return dirty;
    }
    /* Assign config vars */
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }
    /* Clean up removed elements */
    DOMPurify.removed = [];
    /* Check if dirty is correctly typed for IN_PLACE */
    if (typeof dirty === 'string') {
      IN_PLACE = false;
    }
    if (IN_PLACE) {
      /* Do some early pre-sanitization to avoid unsafe root nodes */
      if (dirty.nodeName) {
        const tagName = transformCaseFunc(dirty.nodeName);
        if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
          throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
        }
      }
    } else if (dirty instanceof Node) {
      /* If dirty is a DOM element, append to an empty document to avoid
         elements being stripped by the parser */
      body = _initDocument('<!---->');
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
        /* Node is already a body, use as is */
        body = importedNode;
      } else if (importedNode.nodeName === 'HTML') {
        body = importedNode;
      } else {
        // eslint-disable-next-line unicorn/prefer-dom-node-append
        body.appendChild(importedNode);
      }
    } else {
      /* Exit directly if we have nothing to do */
      if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
      // eslint-disable-next-line unicorn/prefer-includes
      dirty.indexOf('<') === -1) {
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
      }
      /* Initialize the document to work on */
      body = _initDocument(dirty);
      /* Check we have a DOM node from the data */
      if (!body) {
        return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
      }
    }
    /* Remove first element node (ours) if FORCE_BODY is set */
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }
    /* Get node iterator */
    const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
    /* Now start iterating over the created document */
    while (currentNode = nodeIterator.nextNode()) {
      /* Sanitize tags and elements */
      _sanitizeElements(currentNode);
      /* Check attributes next */
      _sanitizeAttributes(currentNode);
      /* Shadow DOM detected, sanitize it */
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }
    }
    /* If we sanitized `dirty` in-place, return it. */
    if (IN_PLACE) {
      return dirty;
    }
    /* Return sanitized string or DOM */
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);
        while (body.firstChild) {
          // eslint-disable-next-line unicorn/prefer-dom-node-append
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }
      if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
        /*
          AdoptNode() is not used because internal state is not reset
          (e.g. the past names map of a HTMLFormElement), this is safe
          in theory but we would rather not risk another attack vector.
          The state that is cloned by importNode() is explicitly defined
          by the specs.
        */
        returnNode = importNode.call(originalDocument, returnNode, true);
      }
      return returnNode;
    }
    let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
    /* Serialize doctype if allowed */
    if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
      serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
    }
    /* Sanitize final string template-safe */
    if (SAFE_FOR_TEMPLATES) {
      arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
        serializedHTML = stringReplace(serializedHTML, expr, ' ');
      });
    }
    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };
  DOMPurify.setConfig = function () {
    let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    _parseConfig(cfg);
    SET_CONFIG = true;
  };
  DOMPurify.clearConfig = function () {
    CONFIG = null;
    SET_CONFIG = false;
  };
  DOMPurify.isValidAttribute = function (tag, attr, value) {
    /* Initialize shared config vars if necessary. */
    if (!CONFIG) {
      _parseConfig({});
    }
    const lcTag = transformCaseFunc(tag);
    const lcName = transformCaseFunc(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };
  DOMPurify.addHook = function (entryPoint, hookFunction) {
    if (typeof hookFunction !== 'function') {
      return;
    }
    arrayPush(hooks[entryPoint], hookFunction);
  };
  DOMPurify.removeHook = function (entryPoint) {
    return arrayPop(hooks[entryPoint]);
  };
  DOMPurify.removeHooks = function (entryPoint) {
    hooks[entryPoint] = [];
  };
  DOMPurify.removeAllHooks = function () {
    hooks = _createHooksMap();
  };
  return DOMPurify;
}
var purify = createDOMPurify();


//# sourceMappingURL=purify.es.mjs.map

;// CONCATENATED MODULE: ./src/scripts/utils/html.js


const sanitizeHtml = (str) => {
  return purify.sanitize(str, { ALLOWED_TAGS: [] });
};

;// CONCATENATED MODULE: ./src/scripts/helpers/match.js


const loginPageRegEx = /(login)|(signin)|(sign in)|(sign-in)|(sign_in)|(logon)|(signup)|(signup_form)|(auth)|(iamsuite)|(two-factor-form)/i;
const loginUrlPathRegex = /(oauth2)|(sso)|(saml)|(login)|(signin)/;
const MAX_INNERTEXT1_LENGTH = 100;
/**
 * Searches parents up to searchHeight to find nearby text
 * @param {HTMLInputElement} element element to evaluate
 * @param {number} searchHeight max number of steps up parent tree to search
 * @returns {string}
 */
function getInnerText(element, searchHeight = 5) {
  let el = element;
  for (let i = 0; i < searchHeight; i++) {
    const text = el?.innerText;
    if (text && text.length < MAX_INNERTEXT1_LENGTH) return text.toLowerCase();
    el = el?.parentElement;
  }
  return '';
}

/**
   * checkIfMatch
   * @param {*} elements
   * @return {array}
   */
function getBestMatch(elements) {
  const primaryUsernameRegEx = /(user id)|(userid)|(user name)|(username)|(user_name)|(txtuid)/;
  const secondaryUsernameRegEx = /(user)|(usr)|(agentid)|(utente)/;
  const emailRegEx = /(email)|(email address)|(email_address)/;
  const telRegEx =  /(?:\b|_)(?:tel|telephone|apple id|domain|onlineid)(?:\b|_)/i;
  const accountRegEx = /(account)|(accountid)|(account id)|(login)|(log in)/;
  const ignoreRegEx = /(search)|(authenticator)/;
  const arrayU1 = [];
  const arrayU2 = [];
  const arrayE = [];
  const arrayT = [];
  const arrayA = [];

  if (elements && elements.length !== undefined) {
    for (let x = 0; x < elements.length; x++) {
      const name = elements[x].name ? elements[x].name.toLowerCase() : '';
      const id = elements[x].id ? elements[x].id.toLowerCase() : '';
      const type = elements[x].type ? elements[x].type.toLowerCase() : '';
      const title = elements[x].title ? elements[x].title.toLowerCase() : '';
      const placeholder = elements[x].placeholder
        ? elements[x].placeholder.toLowerCase() : '';
      const innerTxt = getInnerText(elements[x]);
      const className = elements[x].className ? elements[x].className.toLowerCase() : '';
      const autocomplete = elements[x].autocomplete ? elements[x].autocomplete.toLowerCase() : '';

      if (name.match(ignoreRegEx)
        || id.match(ignoreRegEx)
        || title.match(ignoreRegEx)
        || placeholder.match(ignoreRegEx)
        || className.match(ignoreRegEx)) {
        continue;
      }
      if (name.match(primaryUsernameRegEx) || id.match(primaryUsernameRegEx)
        || title.match(primaryUsernameRegEx)
        || placeholder.match(primaryUsernameRegEx)
        || innerTxt.match(primaryUsernameRegEx)
        || autocomplete.match(primaryUsernameRegEx)) {
        arrayU1.push(elements[x]);
      } else if (name.match(secondaryUsernameRegEx)
        || id.match(secondaryUsernameRegEx)
        || title.match(secondaryUsernameRegEx)
        || placeholder.match(secondaryUsernameRegEx)
        || innerTxt.match(secondaryUsernameRegEx)) {
        arrayU2.push(elements[x]);
      } else if (name.match(emailRegEx) || id.match(emailRegEx)
        || title.match(emailRegEx) || placeholder.match(emailRegEx)
        || type.match(emailRegEx) || innerTxt.match(emailRegEx)) {
        arrayE.push(elements[x]);
      } else if (name.match(telRegEx) || id.match(telRegEx)
        || title.match(telRegEx) || placeholder.match(telRegEx)
        || type.match(telRegEx) || innerTxt.match(telRegEx)) {
        arrayT.push(elements[x]);
      } else if (name.match(accountRegEx) || id.match(accountRegEx)
        || title.match(accountRegEx) || placeholder.match(accountRegEx)
        || innerTxt.match(accountRegEx)) {
        arrayA.push(elements[x]);
      }
    }
  }

  return [...arrayU1, ...arrayU2, ...arrayE, ...arrayA, ...arrayT];
}

/**
 * getAllButtons
 * @param {*} container
 * @return {array}
 */
function getAllButtons(container) {
  if (!container) container = document;
  const selector = 'button[type="submit"], input[type="submit"], button, input[type="button"], input[type="image"], *[type="submit"], *[type="button"]';
  const btns = container.querySelectorAll(selector);
  const links = container.querySelectorAll('a, span');
  return [...btns, ...links];
}

/**
   * findSignIn
   * @param {*} btns
   * @return {array}
   */
function findSignIn(btns) {
  const matches = [];
  const loginButtonRegEx = /(log.?in|log.?in to$|sign.?in$|sign.?in to|sign.?on$|sign.?on to$|submit|continue$|go$|next$|inloggen|sign.?in)/;
  for (let k = 0; k < btns.length; k++) {
    const btnInnerText = btns[k].innerText || '';
    const btnId = btns[k].id || '';
    const btnValue = btns[k].value || '';
    if (btnInnerText.toLowerCase().match(loginButtonRegEx)
      || btnId.toLowerCase().match(loginButtonRegEx)
      || btnValue.toLowerCase().match(loginButtonRegEx)) {
      matches.push(btns[k]);
    }
  }
  return matches;
}

/**
   * checkIfLoginURL
   * @return {bool}
   */
function checkIfLoginURL() {
  try {
    if (window.location.hostname.match(loginPageRegEx)
      || window.location.pathname.match(loginUrlPathRegex)
      || window.location.hash.match(loginPageRegEx)) {
      return true;
    }
    if (window.location.hostname.match(loginPageRegEx)
      || window.location.pathname.match(loginUrlPathRegex)) {
      return true;
    }
    if (window.parent
      && (window.parent.location.hostname.toLowerCase().match(loginPageRegEx)
        || window.parent.location.pathname.toLowerCase().match(loginUrlPathRegex))) {
      return true;
    }
    return false;
  } catch {
    return false;
  }
}

/**
   * checkIfLoginForm
   * @param {*} form
   * @return {boolean}
   */
function checkIfLoginForm(form) {
  const name = form.getAttribute("name") ? form.getAttribute("name").toLowerCase() : '';
  const id = form.id ? form.id.toLowerCase() : '';
  let action = form.getAttribute('action');
  action = action ? action.toLowerCase() : '';
  const { classList } = form;
  if (name.match(loginPageRegEx)
    || id.match(loginPageRegEx)
    || action.match(loginPageRegEx)) {
    return true;
  }
  for (let i = 0; i < classList.length; i++) {
    if (classList[i].match(loginPageRegEx)) {
      return true;
    }
  }
  const formContent = form && form.innerText && form.innerText.toLowerCase();
  if (formContent && formContent.match(loginPageRegEx)) {
    return true;
  }
  return false;
}

function getBestOtpMatch(elements) {
  const primaryOTPRegEx = /(one-time-code)/;
  const secondaryOTPRegEx = /(?:\b|_)(?:otp|totp|pin code|otppin|mfa|mfaCode|authenticator|authentication|multifactor|passcode)(?:\b|_)/i;
  const ignoreRegEx = /(search)|(email)|(email address)|(email_address)|(telephone)|(apple id)|(domain)|(password)/;
  const arrayPrimary = [];
  const arrayOtp1 = [];

  if (elements && elements.length !== undefined) {
    for (let x = 0; x < elements.length; x++) {
      const formElement = elements[x].closest("form");
      const heading = formElement && formElement instanceof Element
        ? formElement.querySelector('h1, h2, h3')
        : null;
      let headingText = heading ? heading.textContent.trim() : '';
      // Check if the heading text does not match specific phrases
      if (headingText.includes("Verify with your password")) {
        return;
      }
      const forLabel = formElement && formElement instanceof Element
      ? formElement.querySelector('label')
      : null;
      let labelText = forLabel ? forLabel.textContent.trim() : '';

      const autocomplete = elements[x].getAttribute('autocomplete') ? elements[x].getAttribute('autocomplete').toLowerCase() : '';
      const name = elements[x].name ? elements[x].name.toLowerCase() : '';
      const id = elements[x].id ? elements[x].id.toLowerCase() : '';
      const title = elements[x].title ? elements[x].title.toLowerCase() : '';
      const placeholder = elements[x].placeholder
        ? elements[x].placeholder.toLowerCase() : '';
      const innerTxt = elements[x].innerText
        ? elements[x].innerText.toLowerCase() : '';

      if (name.match(ignoreRegEx)
        || id.match(ignoreRegEx)
        || title.match(ignoreRegEx)
        || placeholder.match(ignoreRegEx)) {
        continue;
      }
      if (autocomplete.match(primaryOTPRegEx)) {
        // Push only if not already added through autocomplete="one-time-code"
        if (!arrayPrimary.includes(elements[x])) {
          arrayPrimary.push(elements[x]);
        }
      }
      if (name.match(secondaryOTPRegEx)
        || id.match(secondaryOTPRegEx)
        || title.match(secondaryOTPRegEx)
        || placeholder.match(secondaryOTPRegEx)
        || innerTxt.match(secondaryOTPRegEx)) {
        // Push only if not already added through autocomplete="one-time-code"
        if (!arrayOtp1.includes(elements[x])) {
          arrayOtp1.push(elements[x]);
        }
      }
      if (labelText.includes('verification code')) {
        // Push only if not already added
        if ((0,visibility_helpers/* isElementVisible */.J9)(elements[x])) {
          if (!arrayOtp1.includes(elements[x])) {
            arrayOtp1.push(elements[x]);
          }
        }
      }
    }
  }
  return [...arrayPrimary, ...arrayOtp1];
}

function findForgotPasswordSignInLinks(btns) {
  const matches = [];
  const buttonforgotPasswordRegEx = /(log.?in|log.?in to$|sign.?in$|sign.?in to|sign.?on$|sign.?on to$|submit|continue$|go$|next$|inloggen|sign.?in)|(forgot\s*password)/;
  for (let k = 0; k < btns.length; k++) {
    const btnInnerText = btns[k].innerText || '';
    const btnId = btns[k].id || '';
    const btnValue = btns[k].value || '';
    if (btnInnerText.toLowerCase().match(buttonforgotPasswordRegEx)
      || btnId.toLowerCase().match(buttonforgotPasswordRegEx)
      || btnValue.toLowerCase().match(buttonforgotPasswordRegEx)) {
      matches.push(btns[k]);
    }
  }
  return matches;
}
function isLoginTitle() {
  if (document.title.match(loginPageRegEx)) return true;
  return false;
}

// Define a function to retrieve elements within a shadow DOM
function getInputFields(shadowRoot) {
  const inputs = shadowRoot.querySelectorAll('input');
  return inputs;
}

function traverseNestedShadowDOM(node, inputList = [], buttonList = [], shadoRootElements= []) {
  let inputs = inputList;
  let signInbuttonList = buttonList;
  let shadowRootElementList = shadoRootElements;
  if (node.shadowRoot) {
    shadowRootElementList.push(node.shadowRoot);
    // Access elements within the current shadow root
    const shadowRoot = node.shadowRoot;
    const elements = getInputFields(shadowRoot);
    const buttons = getAllButtons(shadowRoot);
    const signInButtons = findSignIn(buttons);
    inputs.push(...elements);
    signInbuttonList.push(...signInButtons);

    // Recursively traverse deeper shadow DOM
    traverseNestedShadowDOM(shadowRoot, inputs, signInbuttonList, shadowRootElementList);
  } else {
    // If there's no shadow root, check for child nodes
    node.childNodes.forEach(childNode => {
      if (childNode.tagName === 'IFRAME' || childNode.tagName === 'SCRIPT' || childNode.tagName === 'STYLE') { return; }
      if (childNode.nodeType === Node.ELEMENT_NODE) {
        // Recursively traverse child nodes
        traverseNestedShadowDOM(childNode, inputs, signInbuttonList, shadowRootElementList);
      }
    });
  }
  return { inputs, signInbuttonList, shadowRootElementList } ;
}

function getShadowDomElements(allInputs) {
  let allInputsArray = Array.from(allInputs); // Filter out hidden inputs
  let visibleInputs = allInputsArray.filter(input => input.type !== 'hidden');
  let inputs = [];
  let shouldReturn = false;
  if (visibleInputs.length !== 0) {
    for (let i = 0; i < visibleInputs.length; i++) {
      if ((0,visibility_helpers/* isElementVisible */.J9)(visibleInputs[i])) {
        // If any input is visible, set flag to true and exit the loop
        shouldReturn = true;
        break;
      }
    }
  }
  if(!shouldReturn && checkIfLoginURL()) {
    const body = document.querySelector('body');
    if(body) {
      const result = traverseNestedShadowDOM(body);
      inputs = result.inputs;
      let shadowPasswordField;
      let shadowUsername;
      for(let i=0; i<inputs.length; i++) {
        if (inputs[i].type.toLowerCase() === "password"
        && !inputs[i].classList.contains("Delinea_PWD")
        && !inputs[i].classList.contains("Delinea_OTP")
        ) {
          shadowPasswordField = inputs[i];
        }
      }
      const elements = getBestMatch(inputs);
      for(let i=0; i<elements.length; i++) {
        if((0,visibility_helpers/* isElementVisible */.J9)(elements[i])) {
          shadowUsername = elements[i];
          //markUsername(elements[i], shadowPasswordField?shadowPasswordField: null);
        }
      }
      //attachHandleSubmit(result.signInbuttonList);
      return { inputs, shadowUsername, shadowPasswordField, signInButtons: result.signInbuttonList, shadowRootElements: result.shadowRootElementList };
    };
  }
  return {inputs: [], shadowUsername: null, shadowPasswordField: null, signInButtons: [], shadowRootElements: [] };
}
;// CONCATENATED MODULE: ./src/scripts/handlers/wac-handler.js


/**
 * handleWACItemClick
 * @param {*} evt
 */
function handleWACItemClick(evt) {
  let linkText = evt && evt.target && evt.target.innerText;
  const regExp = /\(([^)]+)\)/;
  const matches = regExp.exec(linkText);
  linkText = linkText && linkText.split('[')[0].trim();
  ext_default().runtime.sendMessage({
    method: 'lastClickedItem',
    data: matches ? matches[1] : linkText,
  });
}

/**
   * handleWACConnectClick
   */
function handleWACConnectClick() {
  const chkWACConnect = document.querySelectorAll('div.sme-table-row-selected.sme-checked');
  if (chkWACConnect.length === 1) {
    const linkEle = chkWACConnect[0].querySelector('a.sme-link');
    if (linkEle) {
      linkEle.click();
    }
  }
}

/**
 * findServerLinks
 */
function findServerLinks() {
  const resources = document.querySelectorAll('a.sme-link');
  if (resources && resources.length > 0) {
    if (!document.getElementById('sme-splash')) {
      resources.forEach((button) => {
        button.addEventListener('click', handleWACItemClick);
      });
      const btnWACConnect = document.querySelectorAll('button.sme-icon-toolbox');
      if (btnWACConnect[0]) {
        btnWACConnect[0].addEventListener('click', handleWACConnectClick);
      }
    }
  }
}

const isWindowsAdminCenter = () => document.title.includes('Windows Admin Center')
         && document.querySelector('sme-root');

/**
 * checkIfWindowsAdminCenter
 * @param {settings} settings
 *
 */
function checkIfWindowsAdminCenter() {
  if (isWindowsAdminCenter()) {
    const observeMAC = new MutationObserver(() => {
      findServerLinks();
    });
    observeMAC.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: false,
    });
  }
}

;// CONCATENATED MODULE: ./src/scripts/helpers/position-helpers.js
/**
  * get the absolute position of the give element.
  * @param {document} e document.
  * @param {HTMLElement} t element .
  * @return {object} returns the coordinates.
  */
function getAbsolutePos(e, t) {
  let i = null;
  try {
    i = typeof t.getBoundingClientRect;
  } catch (e) {
    i = null;
  }
  if (!i || i === 'undefined') return null;
  try {
    const o = t.getBoundingClientRect();
    const a = void 0 === o.width ? o.right - o.left : o.width;
    const s = void 0 === o.height ? o.bottom - o.top : o.height;
    const l = e.body.getBoundingClientRect();
    const d = window.getComputedStyle(document.body);
    let clTop = 0;
    let clLeft = 0;
    if (d.position == 'relative' || d.position == 'fixed'
          || d.position == 'absolute') {
      clTop = o.top - l.top;
      clLeft = o.left - l.left;
    } else if (d.position == 'static') {
      clTop = o.top + document.documentElement.scrollTop;
      clLeft = o.left + document.documentElement.scrollLeft;
    }
    return {
      left: clLeft,
      top: clTop,
      width: a,
      height: s,
    };
  } catch (t) {

  }
}

/**
* returns the coordinates for the secret container.
* @param {HTMLElement} el the element whose icon image is clicked.
* @return {Object} the object of the coordinates.
*/
function getTopLeftForSecretDiv(el) {
  if (el) {
    let height = el.clientHeight;
    let width = el.clientWidth;
    const absoluteRect = getAbsolutePos(document, el);
    if (el.tagName.toLowerCase() === 'iframe') {
      height = 0;
      width = 0;
    }
    const top = Math.round(absoluteRect && absoluteRect.top + height);
    const left = Math.round(absoluteRect && absoluteRect.left);
    return {
      top,
      left,
      width,
    };
  }
}

/**
  * returns the coordinates for the Icon div.
  * @param {HTMLElement} el the element to whom icon image is being added.
  * @param {boolean} fieldItself passing field to get its top left
  * @return {Object} the object of the coordinates.
  */
function getTopLeftForIcon(el, fieldItself) {
  const height = el.clientHeight;
  const width = el.clientWidth;
  const imageHeight = 12;
  const absoluteRect = getAbsolutePos(document, el);
  const elstyle = window.getComputedStyle(el, null);
  let h = el.clientHeight
          - parseInt(elstyle && elstyle.getPropertyValue && elstyle.getPropertyValue('border-top-width'))
          - parseInt(elstyle && elstyle.getPropertyValue && elstyle.getPropertyValue('border-bottom-width'))
          - parseInt(elstyle && elstyle.getPropertyValue && elstyle.getPropertyValue('padding-bottom'))
          - parseInt(elstyle && elstyle.getPropertyValue && elstyle.getPropertyValue('padding-top'));
  if (h > imageHeight) {
    h -= ((h - imageHeight) / 2);
  }
  const top = Math.round(absoluteRect && absoluteRect.top + height / 2 - h / 2);
  let left = 0;
  if (fieldItself) {
    left = Math.round(absoluteRect && absoluteRect.left + width);
  } else {
    left = Math.round(absoluteRect && absoluteRect.left + width - 1 - (imageHeight * 1.8));
  }
  return {
    top,
    left,
    iconHeight: imageHeight,
    imageHeight,
    offsetHeight: el.offsetHeight,
    offsetWidth: el.offsetWidth,
  };
}

;// CONCATENATED MODULE: ./src/scripts/helpers/keyboard-shortkeys-helpers.js
/* eslint-disable no-use-before-define */
/**
  * Prevent parent event of the given input elements.
  * @param {HTMLElement} allInputs array of input elements.
*/
function preventShortcutKeys(container) {
  if (!container) return;
  const allInputs = container.querySelectorAll('input[type="text"], input[type="password"], textarea, input:not([type])');
  for (let i = 0; i < allInputs.length; i++) {
    allInputs[i].addEventListener('keydown', (evt) => {
      if (/^[\p{L}\p{N}]$/u.test(evt.key) && !evt.ctrlKey && !evt.altKey) {
        evt.preventDefault();
        evt.stopImmediatePropagation();
        evt.stopPropagation();
        setInputValue(evt.target, evt);
        evt.target.dispatchEvent(new Event('input'));
      }
    });
  }
}

/**
  * set the value to the given input element.
  * @param {HTMLElement} inputElement element.
  * @param {event} event.
*/
function setInputValue(inputElement, event) {
  const start = inputElement.selectionStart;
  const end = inputElement.selectionEnd;
  const currentValue = inputElement.value;
  const newValue = currentValue.substring(0, start) + event.key + currentValue.substring(end);
  inputElement.value = newValue;
  inputElement.setSelectionRange(start + 1, start + 1);
}

;// CONCATENATED MODULE: ./src/scripts/ui/auto-complete/auto-complete.js


/**
 * autocomplete
 * @param {*} inp 
 * @param {*} arr 
 * @param {*} shadowRoot 
 * @param {*} onItemClicked 
 * @param {*} itemTemplate 
 */
function autocomplete(inp, arr, shadowRoot, onItemClicked, itemTemplate) {
    /* the autocomplete function takes two arguments,
      the text field element and an array of possible autocompleted values:*/
    let currentFocus;
    const debouncedInputHandler = debounce(handleInput, 500);
    inp.addEventListener('input', debouncedInputHandler);


    function debounce(func, delay) {
        let timeoutId;

        return function () {
            const context = this;
            const args = [...arguments]; 

            clearTimeout(timeoutId);
            timeoutId = setTimeout(function () {
                func.apply(context, args);
            }, delay);
        };
    }
    /* execute a function presses a key on the keyboard:*/
    inp.addEventListener('keydown', function (e) {
        let x = document.getElementById(e.target.id + '-list');
        if (x) x = x.getElementsByTagName('div');
        if (e.keyCode == 40) {
            /* If the arrow DOWN key is pressed,
                  increase the currentFocus variable:*/
            currentFocus++;
            /* and and make the current item more visible:*/
            addActive(x);
        } else if (e.keyCode == 38) { // up
            /* If the arrow UP key is pressed,
                  decrease the currentFocus variable:*/
            currentFocus--;
            /* and and make the current item more visible:*/
            addActive(x);
        } else if (e.keyCode == 13) {
            /* If the ENTER key is pressed, prevent the form from being submitted,*/
            e.preventDefault();
            if (currentFocus > -1) {
                /* and simulate a click on the "active" item:*/
                if (x) x[currentFocus].click();
            }
        }
    });


    /* execute a function when someone writes in the text field:*/
    function handleInput(e) {
        let b; let i; const val = this.value;
        this.removeAttribute('selected-id');
        this.dispatchEvent(new Event('change'));
        /* close any already open lists of autocompleted values*/
        closeAllLists();
        // if (!val) {
        //     return false;
        // }
        currentFocus = -1;
        /* create a DIV element that will contain the items (values):*/
        const a = document.createElement('DIV');
        a.style.padding = '1em 0 1em 0';
        a.style.width = '300px';
        a.style.maxHeight = '125px';
        a.setAttribute('id', this.id + '-list');
        a.setAttribute('class', 'autocomplete-items');
        a.addEventListener('scroll', onScroll, { passive: true });
        /* append the DIV element as a child of the autocomplete container:*/
        this.parentNode.appendChild(a);
        const pageSize = 200;
        let startIndex = 0;
        let matchItems;
        if(val.trim() != '') {
            matchItems = arr.filter(x => x.name.toLowerCase().includes(val.toLowerCase()));
        } else {
            matchItems = arr;
        }
        loadList();

        function onScroll(evt) {
            const { scrollTop, scrollHeight, clientHeight, } = evt.target;
            if (scrollTop + clientHeight < scrollHeight - 100) return;
            loadList();
        }

        function loadList() {
            const pageItems = matchItems.slice(startIndex, startIndex + pageSize);
            startIndex += pageSize;
            /* for each item in the array...*/
            for (i = 0; i < pageItems.length; i++) {
                /* check if the item starts with the same letters as the text field value:*/
                // if (arr[i].name.substr(0, val.length).toUpperCase() == val.toUpperCase()) {
                /* create a DIV element for each matching element:*/
                b = document.createElement('DIV');
                /* make the matching letters bold:*/
                if(itemTemplate && itemTemplate.icon) {
                  b.innerHTML = itemTemplate.icon;
                }
                // b.innerHTML += '<strong>' + pageItems[i].name.substr(0, val.length) + '</strong>';
                // b.innerHTML += pageItems[i].name.substr(val.length);
                const textNode = document.createTextNode(pageItems[i].name);
                b.appendChild(textNode);
                
                /* insert a input field that will hold the current array item's value:*/
                b.innerHTML += `<input  type=\'hidden\' value=\'${(0,url_helpers/* urlEncode */.u4)(pageItems[i].name)}\'>`;
                b.innerHTML += '<input type=\'hidden\' value=\'' + pageItems[i].id + '\'>';
                /* execute a function when someone clicks on the item value (DIV element):*/
                b.addEventListener('click', function (e) {
                    inp.value = this.getElementsByTagName('input')[0].value;
                    inp.dispatchEvent(new Event('blur'));
                    /* insert the value for the autocomplete text field:*/
                    const id = this.getElementsByTagName('input')[1].value;
                    if (!id) {
                        inp.removeAttribute('selected-id');
                    } else {
                        inp.setAttribute('selected-id', id);
                    }
                    inp.value = this.innerText;
                    if(onItemClicked) {
                        onItemClicked();
                    }
                    /* close the list of autocompleted values,
                              (or any other open lists of autocompleted values:*/
                    closeAllLists();
                });
                a.appendChild(b);
                // }
            }
        }
    }




    /**
     * addActive
     * @param {*} x
     * @return {boolean}
     */
    function addActive(x) {
        /* a function to classify an item as "active":*/
        if (!x) return false;
        /* start by removing the "active" class on all items:*/
        removeActive(x);
        if (currentFocus >= x.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = (x.length - 1);
        /* add class "autocomplete-active":*/
        x[currentFocus].classList.add('autocomplete-active');
    }

    /**
     * removeActive
     * @param {*} x
     */
    function removeActive(x) {
        /* a function to remove the "active" class from all autocomplete items:*/
        for (let i = 0; i < x.length; i++) {
            x[i].classList.remove('autocomplete-active');
        }
    }

    /**
     * closeAllLists
     * @param {*} elmnt
     */
    function closeAllLists(elmnt) {
        let parent = shadowRoot || document;
       
        /* close all autocomplete lists in the document,
            except the one passed as an argument:*/
        const x = parent.querySelectorAll('.autocomplete-items');
        for (let i = 0; i < x.length; i++) {
            if (elmnt != x[i] && elmnt != inp) {
                x[i].parentNode.removeChild(x[i]);
            }
        }
    }
    /* execute a function when someone clicks in the document:*/
    document.addEventListener('click', function (e) {
        closeAllLists(e.target);
    });
}

// EXTERNAL MODULE: ./src/scripts/ui/timer/timer.js
var timer = __webpack_require__(691);
;// CONCATENATED MODULE: ./src/scripts/ui/kebab-menu/kebab-menu.js
/* eslint-disable no-plusplus */
/* eslint-disable no-use-before-define */





let shadowCopyElement;

function attachOnKebabOptionsClickEvent(request, shadowElement) {
  shadowCopyElement = shadowElement;
  const containers = Array.from(shadowCopyElement.querySelectorAll(".kebabMenu"));

  document.addEventListener("click", handleDocumentClick);

  containers.forEach((container, i) => {
    container.addEventListener("click", (evt) => {
      evt.stopPropagation();
      closeKebabOptions();
      const secretId = evt.currentTarget.id.split("-").pop();
      const skeletonElement = getKebabMenuSkeleton(evt);
      shadowCopyElement.appendChild(skeletonElement);
      getSecretState(secretId, (secretState) => {
        shadowCopyElement.removeChild(skeletonElement);
        handleSecretStateCallback(secretState, i, request, evt);
      });
    });
  });

  function handleSecretStateCallback(result, i, sender, evt) {
    if (!(result && result.id && result.secretState)) return;

    const kebabOptionsDiv = document.createElement("div");
    kebabOptionsDiv.className = "kebabOptions";

    kebabOptionsDiv.innerHTML = `
        <div class="kebabOption fillSecret" id="fillSecret-${result.id}">Fill Secret</div>
        <div class="kebabOption copyUsername" id="copyUsername-${result.id}">Copy Username</div>
        <div class="kebabOption copyPassword" id="copyPassword-${result.id}">Copy Password</div>
        ${result.actions && result.actions.includes("GenerateOneTimePassword") ? `<div class="kebabOption copyOtp" id="copyOtp-${result.id}">Copy OTP Code</div>` : ""}
      `;
    shadowCopyElement.appendChild(kebabOptionsDiv);
    attachFillSecretClickEvent(result);
    attachCloseKebabOnScrollEvent();
    attachCopyActionClickEvent(".copyUsername", result, sender);
    attachCopyActionClickEvent(".copyPassword", result, sender);
    attachCopyActionClickEvent(".copyOtp", result, sender);
    kebabOptionsDiv.style.top = `${evt.clientY}px`;
    kebabOptionsDiv.style.left = `${evt.clientX - 140}px`;
  }
}
function attachCloseKebabOnScrollEvent() {
  const scrollContainer = shadowCopyElement && shadowCopyElement.getElementById("thy-secret-container");
  if (scrollContainer) {
    scrollContainer.addEventListener("scroll", closeKebabOptions);
  }
  window.addEventListener("scroll", closeKebabOptions);
}

function detachCloseKebabOnScrollEvent() {
  const scrollContainer = shadowCopyElement && shadowCopyElement.getElementById("thy-secret-container");
  if (scrollContainer) {
    scrollContainer.removeEventListener("scroll", closeKebabOptions);
  }
  window.removeEventListener("scroll", closeKebabOptions);
}

function getKebabMenuSkeleton(evt) {
  const kebabOptionsDiv = document.createElement("div");
  kebabOptionsDiv.className = "kebabOptions";

  kebabOptionsDiv.innerHTML = `
      <div class="kebabOption"><div class="skeleton-line"></div></div>
      <div class="kebabOption"><div class="skeleton-line"></div></div>
      <div class="kebabOption"><div class="skeleton-line"></div></div>
    `;
  kebabOptionsDiv.style.top = `${evt.clientY}px`;
  kebabOptionsDiv.style.left = `${evt.clientX - 140}px`;
  return kebabOptionsDiv;
}

function attachFillSecretClickEvent(result) {
  const fillSecretContainers = shadowCopyElement.querySelectorAll(".fillSecret");
  fillSecretContainers.forEach((container) => {
    const secretId = container.id.split("-")[1];
    container.addEventListener("click", () => {
      getSecretState(secretId, handleLaunchSecret);
      const mainContainers = (0,common.$)("#WPF-shadow-root");
      if (mainContainers) {
        mainContainers.parentNode.removeChild(mainContainers);
      }
    });
  });
}

function attachCopyActionClickEvent(selector, result) {
  const copyActionContainers = shadowCopyElement.querySelectorAll(selector);
  copyActionContainers.forEach((container) => {
    container.addEventListener("click", (evt) => {
      if (selector === ".copyUsername") {
        container.innerText = "Copying...";
        evt.stopPropagation();
        result.secretListAction = constants.secretAction.copyUsername;
      } else if (selector === ".copyPassword") {
        evt.stopPropagation();
        container.innerText = "Copying...";
        result.secretListAction = constants.secretAction.copyPassword;
      } else {
        result.secretListAction = constants.secretAction.copyOtp;
      }
      if (result.secretState.toLowerCase() === constants.secretStates.none
        || result.secretState.toLowerCase() === constants.secretStates.requiresCheckout) {
        handleLaunchSecret({
          id: result.id,
          secretState: constants.secretStates.none,
          secretListAction: result.secretListAction,
        });
        return;
      }
      handleSecretState(result);
    });
  });
}

function closeKebabOptions() {
  detachCloseKebabOnScrollEvent();
  const openOptions = shadowCopyElement && shadowCopyElement.querySelector(".kebabOptions");
  if (openOptions) {
    shadowCopyElement.removeChild(openOptions);
  }
}

function handleDocumentClick() {
  closeKebabOptions();
}

;// CONCATENATED MODULE: ./src/scripts/handlers/login-mfe-handler.js
const login_mfe_handler_ext = __webpack_require__(666);

const loginMfeHandler = {

  checkLoginMfe() {
    const loginMfe = document.querySelector('login-mfe');

    if (loginMfe) {
      this.submitDeviceCode();
    }
  },

  submitDeviceCode() {
    const waitForSubmit = setInterval(() => {
      const button = document.getElementById('submit-device-code');
      if (button) {
        clearInterval(waitForSubmit);
        button.click();
      }
    }, 1000);
  },

};
/* harmony default export */ const login_mfe_handler = (loginMfeHandler);

// EXTERNAL MODULE: ./src/scripts/utils/domain-ext.js
var domain_ext = __webpack_require__(237);
;// CONCATENATED MODULE: ./src/scripts/ui/sorting/sorting-secret.js


const sortingSecrets = {
  cleanUrl(url) {
    try {
      // Prepend 'https://' if no valid protocol is present
      if (!/^https?:\/\//i.test(url)) {
        url = 'https://' + url; // Ensure URL has a valid protocol
      }

      const parsedUrl = new URL(url); // Create a URL object to parse the URL
      return `${parsedUrl.origin}${parsedUrl.pathname.replace(/\/+$/, '')}`; // Cleaned URL without trailing slashes
    } catch (error) {
      console.error("Invalid URL:", url, error); // Log any errors during parsing
      return null; // Return null if URL is invalid
    }
  },

  isExactMatch(url, currentUrl) {
    return this.cleanUrl(url) === this.cleanUrl(currentUrl);
  },

  isSubdomainMatch(url, currentUrl) {
    // Extract hostname from URLs
    const urlHostname = new URL(url).hostname;
    const currentHostname = new URL(currentUrl).hostname;

    // Check if currentUrl is a subdomain of url or vice versa
    return urlHostname === currentHostname ||
      currentHostname.endsWith('.' + urlHostname);
  },

  getUrlHierarchy(url) {
    // Split the URL into parts, filter out empty parts, build the hierarchy, and reverse it
    return url.split('/').filter(Boolean).map((_, i, parts) =>
      parts.slice(0, i + 1).join('/')
    ).reverse();
  },

  matchScore(secretPathLength, pagePathLength) {
    return 2 - ((pagePathLength - secretPathLength) / pagePathLength);
  },

  sortSecrets(secrets, currentUrl, exactMatchEnabled) {
    const cleanedCurrentUrl = this.cleanUrl(currentUrl); // Clean the current URL
    const buckets = { exactMatch: [], hostPath: [], host: [] };

    secrets.forEach(secret => {
      const secretUrls = secret.secretUrl.split(',')
        .filter(url => url !== '')
        .map(url => this.cleanUrl(url.trim()));

      let cleanedSecretUrl = null;

      // Only if there are multiple URLs, check for a match
      if (secretUrls.length > 0) {
        cleanedSecretUrl = secretUrls.find(url =>
          this.isExactMatch(url, cleanedCurrentUrl) ||
          this.isSubdomainMatch(url, cleanedCurrentUrl)
        ) || null;
      }

      // If there's no exact match, use the first cleaned URL as a fallback
      if (!cleanedSecretUrl && secretUrls.length > 0) {
        cleanedSecretUrl = secretUrls[0]; // Fallback to the first cleaned URL
      }
      if (cleanedSecretUrl) {
        const cleanedSecretUrlObject = new URL(cleanedSecretUrl);
        const secretPath = cleanedSecretUrlObject.pathname;
        const pagePath = new URL(currentUrl).pathname;
        // Step 2 Exact match logic
        if (this.isExactMatch(cleanedSecretUrl, cleanedCurrentUrl)) {
          const score = 2.0; // Define score directly here for exact match
          buckets.exactMatch.push({ ...secret, matchScore: score, cleanedSecretUrl });
        }
        // Step 3 If exact match enabled, discard this result
        else if (exactMatchEnabled) {
          return; // Skip to next secret
        }
        // Step 4 Host match logic
        else if (cleanedSecretUrlObject.hostname === new URL(currentUrl).hostname) {
          if (pagePath.startsWith(secretPath) && (pagePath[secretPath.length] === '/' || pagePath[secretPath.length] === '?')) {
            const secretPathLength = secretPath.split('/').filter(Boolean).length;
            const pagePathLength = pagePath.split('/').filter(Boolean).length;
            const score = this.matchScore(secretPathLength, pagePathLength);
            buckets.hostPath.push({ ...secret, matchScore: score, cleanedSecretUrl });
          } else {
            const score = 1.0; // Define score for host match
            buckets.host.push({ ...secret, matchScore: score, cleanedSecretUrl });
          }
        } else {
          // Step 5 Determine degree of match of the page URL host to the secret URL host
          const secretHostParts = cleanedSecretUrlObject.hostname.split('.');
          const pageHostParts = new URL(currentUrl).hostname.split('.');
          const Mwords = this.calculateMatchingWords(secretHostParts, pageHostParts);
          const matchScore = this.calculateHostMatchScore(Mwords, secretHostParts.length, pageHostParts.length);
          if (matchScore > 0) {
            buckets.host.push({ ...secret, matchScore, cleanedSecretUrl });
          }
        }
      }
    });
    // Step 6 Combine into final results
    const sortedResults = [
      ...buckets.exactMatch,
      ...buckets.hostPath,
      ...buckets.host,
    ].sort((a, b) => {
      if (b.matchScore !== a.matchScore) {
        return b.matchScore - a.matchScore;
      }
      if (a.isFavoriteSecret !== b.isFavoriteSecret) {
        return a.isFavoriteSecret ? -1 : 1;
      }
      return a.cleanedSecretUrl.localeCompare(b.cleanedSecretUrl);
    });

    return sortedResults;
  },

  calculateMatchingWords(secretHostParts, pageHostParts) {
    let Mwords = 0;
    for (let i = 1; i <= Math.min(secretHostParts.length, pageHostParts.length); i++) {
      if (secretHostParts[secretHostParts.length - i] === pageHostParts[pageHostParts.length - i]) {
        Mwords++;
      } else {
        break;
      }
    }
    return Mwords;
  },

  calculateHostMatchScore(Mwords, Lensecret, Lenpage) {
    return (Math.max(Mwords - 1, 1) / Math.max(Lenpage - 1, 1)) * (Math.max(Mwords - 1, 1) / Math.max(Lensecret - 1)) ** 2;
  },

  sortByMatchScore(a, b) {
    return b.matchScore - a.matchScore; // Higher scores come first
  },
  /**
   * highlighted the secret URL text that match with curent tab URL.
   * @param {string} secretURL secret url.
   * @param {string} currentURL current tab url
   */
  highlightMatches(secretURL, currentURL) {
    // Clean both URLs by removing the protocol and trailing slashes
    const cleanCurrentURL = currentURL.replace(/^https?:\/\//, '').replace(/\/$/, '');
    const cleanSecretURL = secretURL.replace(/^https?:\/\//, '').replace(/\/$/, '');

    // Extract current and secret domain or IP
    const currentParts = cleanCurrentURL.split('/');
    const secretParts = cleanSecretURL.split('/');

    const currentDomain = currentParts[0];
    const secretDomain = secretParts[0];

    // Function to get the main domain including multi-part TLDs
    function getMainDomain(domain) {
        const parts = domain.split('.');
        let mainDomain = '';
        let extExist = false;
        for (let index = parts.length - 1; index >= 0; index--) {
          const possibleTLD = `.${parts.slice(index).join('.')}`;
          const exist = domain_ext/* DOMAIN_EXT */.t.has(possibleTLD);
          if (exist) {
            extExist = true;
          } else if (!exist && extExist) {
            mainDomain = parts.slice(index).join('.');
            break;
          } else {
            break;
          }
        }

        return mainDomain || domain;
    }

    const currentMainDomain = getMainDomain(currentDomain);
    const secretMainDomain = getMainDomain(secretDomain);

    // Prepare highlighted output
    let highlightedOutput = '';

    // Highlight the IP address
    const ipRegex = new RegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]+)?$');
    ;
    if (ipRegex.test(secretDomain)) {
      if (currentDomain === secretDomain && cleanCurrentURL === cleanSecretURL) {
          // Exact IP match
          highlightedOutput = `<span class="highlight">${cleanSecretURL}</span>`;
      } else if (currentDomain === secretDomain) {
          // Same domain, highlight specific path from secretURL
          const secretPath = secretParts.slice(1).join('/') + '/'; // Include the path and ensure a trailing slash
        highlightedOutput = `<span class="highlight">${secretDomain}/${secretPath}</span>`;
      }
    } else if (this.isExactMatch(cleanCurrentURL, cleanSecretURL)) {
      highlightedOutput = `<span class="highlight">${cleanSecretURL}</span>`;
    } else if (currentDomain === secretDomain) {
      // If current URL is on the same domain but has a different path
      const pathSegments = secretParts.slice(1); // Exclude domain part
      const currentPathSegments = currentParts.slice(1);

      highlightedOutput = `<span class="highlight">${currentDomain}</span>`;

      pathSegments.forEach((segment, index) => {
        if (currentPathSegments[index] === segment) {
          highlightedOutput += `<span class="highlight">/${segment}</span>`;
        } else {
          highlightedOutput += `/${segment}`;
        }
      });
    } else if (currentMainDomain === secretMainDomain) {
        const secretDomainParts = secretDomain.split('.');
        const subDomain = secretDomainParts.slice(0, secretDomainParts.length - secretMainDomain.split('.').length).join('.');

      highlightedOutput = subDomain ? `${subDomain}.<span class="highlight">${secretMainDomain}</span>` : `<span class="highlight">${secretMainDomain}</span>`;
    }

    // Return the final output with the correct protocol or nothing if no highlighting
    if (highlightedOutput) {
        const protocol = secretURL.startsWith('https://')
            ? `https://${highlightedOutput}` : secretURL.startsWith('http://')
                ? `http://${highlightedOutput}` : highlightedOutput;

        return `<p>${protocol}</p>`;
    } else {
        return `<p>${secretURL}</p>`; // No highlighting, return secretURL
    }
  }
  };
  
  /* harmony default export */ const sorting_secret = (sortingSecrets);
  
// EXTERNAL MODULE: ./src/scripts/cache/index.js + 17 modules
var cache = __webpack_require__(845);
;// CONCATENATED MODULE: ./src/scripts/contentscript.js
/* eslint-disable no-plusplus */
/* eslint-disable no-use-before-define */





















let isPasswordVisible = false;
let gusername = "";
let gpswd = "";
let gurl = "";
let shadowElement;
let isLoggedin = false;
let Templates = [];
let Folders = [];
let Sites = [];
let username = "";
let contentscript_password = "";
let lastClickedElement;
let isCrossDomain = false;
let isSecretServer = false;
let isPlatformServer = false;
let Settings = {};
let urlExactMatchAvailable = false;
const targetUrl = window.location.origin + (window.location.pathname
  + window.location.hash).replace(/\/+/g, "/");
let isNewSecretAdded = false;
let webPasswordTemplate = null;
let personalFolder = null;
let isCspViolated = false;
let userFieldElement = null;
const elementNodes = [];
let favIconUrl = "";
let beingRecorded = false;
let observer = null;
const ignorePasswordFields = ["login-password-hp", "thyinput-Secretkey"];
let hideContextMenu = false;
let isMappingFound = false;
const windowLocation = (0,url_helpers/* appendPath */.mR)(window.location.href, "");
let serverType = "";
let debounceTimeout = 0;
let isMouseMoveEventAdded = false;
let isCurrentSSTabloggedIn = false;
let shadowRootDebounceTimeout = 0;
let shadowObserver = null;
let savePromptTimeout;

ext_default().runtime.sendMessage(
  { method: "checkIfSecretServer" },
  (response) => {
    if (response?.isSecretServer) {
      isSecretServer = true;
      serverType = response.serverType;
    }
  },
);

ext_default().runtime.sendMessage(
  { method: "checkIfPlatformServer" },
  (response) => {
    if (response?.isPlatform) {
      isPlatformServer = true;
      serverType = response.serverType;
    }
  },
);

ext_default().runtime.sendMessage(
  { method: "checkIfCurrentSSTabloggedIn" },
  (response) => {
    if (response?.isCurrentSSTabloggedIn) {
      isCurrentSSTabloggedIn = true;
    }
  },
);

window.addEventListener("hashchange", () => {
  removeDelineaIcon(false);
  ext_default().runtime.sendMessage(
    { method: "DoIExcluded" },
    (response) => {
      if (response && !response.excluded) {
        if (Settings && Settings.exactMatchUrl) {
          ext_default().runtime.sendMessage(
            { method: "checkExactMatch" },
            (response) => {
              if (response && response.urlExactMatchAvailable) {
                urlExactMatchAvailable = true;
              } else {
                urlExactMatchAvailable = false;
              }
              processFormElements();
            },
          );
        } else {
          processFormElements();
        }
      } else {
        removeDelineaIcon();
      }
    },
  );
}, false);

/**
  * remove containers
  * @param {element} shadowEle shadow element
  */
function getSiteIconUrl(shadowEle) {
  const urlList = [];

  if (!favIconUrl && document.head) {
    const faviconUrlList = document.head.querySelectorAll(`
        link[type*="image/x-icon"],
        link[rel*="apple-touch-icon"],
        link[rel*="icon"],
        link[rel*="shortcut icon"]`);

    for (let i = 0; i < faviconUrlList.length; i++) {
      if (faviconUrlList[i].href === constants.ICONS.RECORDING
        || faviconUrlList[i].href === document.baseURI
        || !faviconUrlList[i].href) {
        continue;
      }
      urlList.push(faviconUrlList[i].href);
    }

    // urlList.push(window.location.origin + '/favicon.ico');

    ext_default().runtime.sendMessage(
      { method: "getFavIcon", urls: urlList },
      (result) => {
        let siteImgUrl = "";
        if (result.success && result.success.length > 0) {
          siteImgUrl = result.success[0];
        } else {
          siteImgUrl = constants.ICONS.GLOBE;
        }
        if (!favIconUrl) {
          favIconUrl = siteImgUrl || constants.ICONS.GLOBE;
        }
        setFavIcon(shadowEle);
      },
    );
  } else {
    setFavIcon(shadowEle);
  }
}
/**
 * setFavIcon
 * @param {htmlElement} shadowEle
 */
function setFavIcon(shadowEle) {
  if (shadowEle) {
    const siteIconList = shadowEle.querySelectorAll(".siteImage");
    for (let i = 0; i < siteIconList.length; i++) {
      siteIconList[i].src = favIconUrl;
      siteIconList[i].onerror = () => {
        siteIconList[i].src = constants.ICONS.GLOBE;
      };
    }
  }
}

/**
    * Remove Delinea icon when logging out
    * @param {bool} removePopups
    */
function removeDelineaIcon(removePopups = true) {
  if (window !== window.parent && observer) {
    observer.disconnect();
  }
  if (pwdObserver) {
    pwdObserver.disconnect();
  }
  removeUserPWDEvents();
  if (removePopups) {
    removeContainer("WPF-permission-root");
    removeContainer("WPF-shadow-root");
    removeContainer("WPF-shadow-root-AddNewSecretPop");
    removeContainer("thy-wpf-confirm-dialog");
    clearSavePromptTimeout();
  }
}

/**
    * Remove remove user and password fields Event
    */
function removeUserPWDEvents() {
  const taggedUserFields = (0,common.$)(".Delinea_SS_UsernameField");
  const taggedPasswordFields = (0,common.$)(".Delinea_PWD");
  while (taggedUserFields.length > 0) {
    if (taggedPasswordFields.length > 0) {
      taggedUserFields[0].value = "";
    }
    taggedUserFields[0].removeEventListener("click", showSecret);
    taggedUserFields[0].removeEventListener("mousemove", onMouseMove);
    taggedUserFields[0].style.backgroundImage = "none";
    taggedUserFields[0].classList.remove("Delinea_SS_UsernameField");
  }
  while (taggedPasswordFields.length > 0) {
    taggedPasswordFields[0].value = "";
    taggedPasswordFields[0].classList.remove("Delinea_PWD");
  }
  timer/* default */.A.clearTimer();
  const taggedTotpdFields = (0,common.$)(".Delinea_OTP");
  while (taggedTotpdFields.length > 0) {
    taggedTotpdFields[0].classList.remove("Delinea_OTP");
  }
}

/**
    * remove containers
    * @param {string} id containerId
    */
function removeContainer(id) {
  const element = document.getElementById(id);
  if (element && element.remove) {
    element.remove();
  }
  removeDropEvent();
}

/**
    * creates shadow dom element.
    * @param {string} functionOnLinkLoad to call on link load
    * @return {bool}
    */
function createHostElement(functionOnLinkLoad) {
  const hostDiv = document.createElement("div");
  const link = document.createElement("link");
  link.href = ext_default().runtime.getURL("style.css");
  link.type = "text/css";
  link.rel = "stylesheet";
  if (functionOnLinkLoad) {
    link.addEventListener("load", functionOnLinkLoad);
  }
  hostDiv.style.boxShadow = "0 2px 4px 0 rgba(0, 0, 0, 0.5)";
  hostDiv.style.border = "solid 1px #a7adbc";
  hostDiv.style.backgroundColor = "#f3f4f7";
  hostDiv.style.position = "absolute";
  hostDiv.style.zIndex = "9999999999";
  hostDiv.style.display = "none";
  document.body.appendChild(hostDiv);
  hostDiv.attachShadow({ mode: "open" });
  hostDiv.shadowRoot.appendChild(link);
  return hostDiv;
}

/**
    * removes the secret div when clicked out side the div.
    * @param {event} e event object.
    */
function removeSecretDivIcon(e) {
  const container1 = (0,common.$)("#WPF-shadow-root");
  if (container1 && container1 != e.target
    && container1.contains(e.target) === false) {
    const templateContainer = shadowElement.getElementById("add-secret-container");
    if (templateContainer && templateContainer.style.display != "none") {
      return;
    }
    shadowElement = null;
    container1.remove();
  }
  if (window !== window.parent) {
    ext_default().runtime.sendMessage({
      method: "removeHostDiv",
    });
  }
}

/**
    * Created generic pop to show error message.
    * @param {string} message the text to display.f
    * @param {string} eventInfo the text to display.
    */
function showErrorPop(message, autoHide = true) {
  if (window !== window.parent) {
    return;
  }
  if (!message) {
    return;
  }
  if ((window.location.href.includes('chrome-extension://') || window.location.href.includes('moz-extension://') || window.location.href.includes('safari-web-extension://')) && window.location.href.includes('/popup.html')) {
    return;
  }

  if (document.head) {
    document.head.appendChild(addFontFace());
  }
  let hostDiv = (0,common.$)("#WPF-shadow-root");
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }
  hostDiv = createHostElement();
  hostDiv.setAttribute("id", "WPF-shadow-root");
  hostDiv.style.paddingBottom = "10px";
  hostDiv.style.width = "350px";
  shadowElement = hostDiv.shadowRoot;
  let element = shadowElement.getElementById("delinea-container");
  if (element && element.remove) {
    element.remove();
  }

  const iconUrl = ext_default().runtime.getURL("icons/delinea-logo.svg");
  element = document.createElement("div");
  element.setAttribute("id", "delinea-container");
  element.innerHTML = `
  <div id="delinea-inner-container" class="error-popup-container">
  <div class="div-error-popup">
  <div class="Sign-in-as error-popup-message">
  <div><img class="v_align_middle siteImage"> </div>
  <div id="spSigninas" class ="thycol2"> ${message}</div>
  </div>
  </div>
  </div>
  <div class="div-fields"><img class="site-logo" src="${iconUrl}"/>
  </div>`;
  element.style.minWidth = "350px";
  element.style.right = "0px";
  shadowElement.appendChild(element);
  hostDiv.style.top = "5px";
  hostDiv.style.right = "10px";
  hostDiv.style.display = "block";
  element.style.removeProperty("left");
  document.body.appendChild(hostDiv);
  getSiteIconUrl(shadowElement);
  if (!autoHide) return;
  setTimeout(() => {
    hostDiv.remove();
  }, 7000);
}

/**
    * Created generic pop to mfa message pop and button .
    * @param {string} message
    * @param {string} secretId
    */
function showRequireMFA(
  message,
  result,
) {
  if (window !== window.parent) {
    return;
  }
  let hostDiv = (0,common.$)("#WPF-shadow-root");
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }
  hostDiv = createHostElement();
  hostDiv.setAttribute("id", "WPF-shadow-root");
  hostDiv.style.paddingBottom = "10px";
  hostDiv.style.width = "350px";
  shadowElement = hostDiv.shadowRoot;
  let element = shadowElement.getElementById("delinea-container");
  if (element && element.remove) {
    element.remove();
  }

  element = document.createElement("div");
  element.setAttribute("id", "delinea-container");
  element.innerHTML = `<div id="delinea-inner-container" class="error-popup-container">
  <div class="div-error-popup">
    <div class="Sign-in-as error-popup-message">
      <div><img class="v_align_middle siteImage"> </div>
      <div id="spSigninas" class ="thycol2"> ${message}
      <p class="p-goToSite">
      <button id="btn-challenge">Challenge</button>
      </p>
      </div>
    </div>
  </div>
  </div>
  </div>`;

  element.style.minWidth = "350px";
  element.style.right = "0px";
  shadowElement.appendChild(element);
  hostDiv.style.top = "5px";
  hostDiv.style.right = "10px";
  hostDiv.style.display = "block";
  element.style.removeProperty("left");
  document.body.appendChild(hostDiv);
  shadowElement.getElementById("btn-challenge").addEventListener("click", () => {
    getMFAChallenge(result, handleLaunchSecret);
    if (hostDiv && hostDiv.remove) {
      hostDiv.remove();
    }
  });
}


function clearStorage(){
  const value = localStorage.getItem('msal.account.keys');
  const parsedArray = JSON.parse(value);
  const firstElement = parsedArray[0]; 
if (value !== null) {
  localStorage.removeItem(firstElement);
} else {
  console.log('Key does not exist');
}
}

/**
    * Created generic pop to require comment message pop and input .
    * @param {string} message the text to display.
    * @param {string} secretId
    * @param {string} state
    * @param {string}  records
    * @param {string} eventInfo
    */
function showRequireCommentPop(
  secretId,
  state,
  records,
  secretListAction,
) {
  const dropdownArrow = ext_default().runtime.getURL("icons/icons8-chevron-down-16.png");
  const secretServerLogo = ext_default().runtime.getURL("icons/secret-server-logo.svg");
  if (window !== window.parent) {
    return;
  }
  let hostDiv = (0,common.$)("#WPF-shadow-root");
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }
  hostDiv = createHostElement();
  hostDiv.setAttribute("id", "WPF-shadow-root");
  hostDiv.style.paddingBottom = "10px";
  hostDiv.style.width = "350px";
  shadowElement = hostDiv.shadowRoot;
  let element = shadowElement.getElementById("delinea-container");
  if (element && element.remove) {
    element.remove();
  }

  element = document.createElement("div");
  element.setAttribute("id", "delinea-container");
  element.innerHTML = `<div id="require-comment">
<div class="header">
<a href="#" class="cancel-secret-btn"  >
  <span id="cancel-comment-popup" class="save-cancel-text
   comment-req-btn-grp">Cancel</span>
</a>
<div class="save-popup">
  <a href="#" class="save-popup-btn ss-Add-secret-button"
  id="add-comment-to-secret">
    <span class="save-cancel-text comment-req-btn-grp">Continue</span>
  </a>
</div>
</div>
<div class="input-field input-label textarea-label">
<div >
  <img  class="secretserverlogo" src=${secretServerLogo}>
  <span style="vertical-align:middle" id="warning"></span>
</div>
<br/>
<div class="autocomplete-ticket">
<div id="ticketrequire">
  <div class="input-field input-label ticket">
  <label>Ticket System</label>
    <input id="ticket-system" name="ticket" class="input-box input-change">
    <img class="ticket-dropdown-arrow" id="ticket-dropdown-arrow" src=${dropdownArrow}>
      <ul id="ticket-auto-complete" class="hide">
      </ul>
</div>

  <div class="input-field input-label ticket">
  <label>Ticket Number <span id="lb-ticket" class="hide">*</span> </label>
  <input  class="input-box input-change" id="ticket-number">
  </div>
</div>
<label>Comment <span id="lb-comment" class="hide">*</span> </label>
<input class="comment_message_textarea input-change" id="comment">
</div>
</div>
</div>`;
  element.style.minWidth = "350px";
  element.style.right = "0px";
  shadowElement.appendChild(element);
  hostDiv.style.top = "5px";
  hostDiv.style.right = "10px";
  hostDiv.style.display = "block";
  element.style.removeProperty("left");
  document.body.appendChild(hostDiv);
  shadowElement.getElementById("add-comment-to-secret")
    .classList.add("disabled");
  shadowElement.getElementById("ticket-dropdown-arrow")
    .addEventListener("click", () => {
      shadowElement.getElementById("ticket-auto-complete")
        .classList.toggle("hide");
    });
  const warning = shadowElement.getElementById("warning");
  shadowElement.getElementById("comment").value = "";
  if (records && records.length > 0) {
    setDefaultTicketName(records);
    shadowElement.getElementById("ticket-number").value = "";
    warning.innerText = errors/* ERR */.s.TICKET_REQ;
  } else {
    warning.innerText = errors/* ERR */.s.COMMENT_REQ;
    shadowElement.getElementById("ticketrequire").classList.add("hide");
  }
  getSiteIconUrl(shadowElement);
  addEventToBtns(shadowElement, secretId, state, records, secretListAction);
  preventShortcutKeys(shadowElement);
}
/**
 * setDefaultTicketName
 * @param {*} records
 */
function setDefaultTicketName(records) {
  const ticketCtrl = shadowElement.getElementById("ticket-system");
  const ticketAutoComplete = shadowElement.getElementById("ticket-auto-complete");
  if (ticketCtrl) {
    if (records) {
      ticketCtrl.value = records[0].name;
      ticketCtrl.setAttribute("ticketSystemId", records[0].ticketSystemId);
      ticketCtrl.setAttribute("forceRequireTicketNumber", records[0].forceRequireTicketNumber);
      const defaultRecord = records[0];     
      updateTicketRequirementVisibility(defaultRecord.updateTicketRequirementVisibility);      
      if (records && records.length > 0) {
        records.forEach((item) => {
          const li = document.createElement("li");
          const span = document.createElement("span");
          li.append(span);
          span.innerText = item.name;
          span.addEventListener("click", (event) => {
            ticketCtrl.value = event.currentTarget.innerText;
            ticketCtrl.setAttribute("ticketSystemId", item.ticketSystemId);
            ticketCtrl.setAttribute("forceRequireTicketNumber", item.forceRequireTicketNumber);
            ticketCtrl.dispatchEvent(new Event("input"));
            ticketAutoComplete.classList.add("hide");
            shadowElement.getElementById("add-comment-to-secret")
              .classList.add("disabled");
              shadowElement.getElementById("comment").value = "";
              shadowElement.getElementById("ticket-number").value = "";      
            updateTicketRequirementVisibility(item.forceRequireTicketNumber);
          });
          ticketAutoComplete.appendChild(li);
        });
      }
    }
  }
}

function updateTicketRequirementVisibility(forceRequire) {
  const lbComment = shadowElement.getElementById("lb-comment");
  const lbTicket = shadowElement.getElementById("lb-ticket");
  if (forceRequire === 0) {
    lbComment.classList.remove("hide");
    lbTicket.classList.add("hide");
  } else if (forceRequire === 1) {
    lbComment.classList.remove("hide");
    lbTicket.classList.remove("hide");
  } else if (forceRequire === 3) {
    lbComment.classList.add("hide");
    lbTicket.classList.remove("hide");
  } else {
    lbComment.classList.add("hide");
    lbTicket.classList.add("hide");
  }
}

function addComment(secretId, data, state, handler) {
  ext_default().runtime.sendMessage({
    method: state.toLowerCase(),
    secretId,
    data,
    state,
  }, handler);
}

function onCommentSaved(result, secretId, action) {
  if (action === constants.secretAction.launch) {
    handleLaunchSecret({ id: secretId, secretState: constants.secretStates.none });
  } else {
    handleLaunchSecret({ id: secretId, secretState: constants.secretStates.none, action });
  }
}

/**
     * onSaveComment
     * @param {*} shadowElement
     * @param {*} id
     * @param {*} state
     * @param {*} records
     */
function addEventToBtns(shadowElement, id, state, records, secretListAction) {
  const secretId = id;
  if (shadowElement) {
    const btnAddComment = shadowElement.getElementById("add-comment-to-secret");
    btnAddComment.addEventListener("click", (e) => {
      e.preventDefault();
      const comment = shadowElement.getElementById("comment").value;
      const ticketSystemId = shadowElement.getElementById("ticket-system")
        .getAttribute("ticketSystemId");
      const ticketNumber = shadowElement.getElementById("ticket-number").value;
      const data = { comment, ticketSystemId, ticketNumber };
      const action = secretListAction || constants.secretAction.launch;

      addComment(
        secretId,
        data,
        state,
        (result) => onCommentSaved(result, secretId, action),
      );
      shadowElement.host.remove();
      shadowElement = null;
    }, false);
    const btnCancelComment = shadowElement.getElementById("cancel-comment-popup");
    btnCancelComment.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      shadowElement.host.remove();
      shadowElement = null;
    });
    shadowElement.querySelectorAll(".input-change").forEach((item) => {
      item.addEventListener("input", (evt) => {
        evt.preventDefault();
        const comment = shadowElement.getElementById("comment");
        const ticketSystemId = shadowElement.getElementById("ticket-system")
          .getAttribute("ticketSystemId");
        const ticketNumber = shadowElement.getElementById("ticket-number").value;
        const forceRequireTicketNumber = shadowElement.getElementById("ticket-system")
        .getAttribute("forceRequireTicketNumber");
        if (records && records.length > 0 && ticketSystemId) {
          
          if (forceRequireTicketNumber === "0" && comment.value.trim() !== "") { // Case 1: Only comment is required

            shadowElement.getElementById("add-comment-to-secret")
              .classList.remove("disabled");

          } else if (forceRequireTicketNumber === "1" && comment.value.trim() !== "" && ticketNumber) { // Case 2: Comment, and ticketNumber are required

            shadowElement.getElementById("add-comment-to-secret")
              .classList.remove("disabled");

          } else if (forceRequireTicketNumber === "2" && ((comment.value.trim() !== "") || (ticketNumber))) { // Case 3: Comment OR ticketNumber are required


            shadowElement.getElementById("add-comment-to-secret")
              .classList.remove("disabled");

          } else if (forceRequireTicketNumber === "3" && ticketNumber) { // Case 4: Only ticketNumber is required

            shadowElement.getElementById("add-comment-to-secret")
              .classList.remove("disabled");

          } else {
            shadowElement.getElementById("add-comment-to-secret")
              .classList.add("disabled");
          }
        } else if (comment.value.trim() !== "") {
          shadowElement.getElementById("add-comment-to-secret")
            .classList.remove("disabled");
        } else {
          shadowElement.getElementById("add-comment-to-secret")
            .classList.add("disabled");
        }
      }, false);
    });
  }
}

// Listen for the message even if not logged in.
window.addEventListener("message", (event) => {
  if (event.source !== window) {
    if (event.data.action === "SecurityWarningAccepted") {
      openSecretPopupOnIframe();
      return;
    }
    // Bug 489696: Added this condition to close
    // switch secret popup when clicked on cancel button
    if (event.data === "close-dialog") {
      removeContainer("WPF-shadow-root");
      return;
    }
    // Check for the action and relay the message
    if (event.data && event.data.action === "openSecretPopup") {
      if (window.parent === window) {
        // If in the top frame, handle the popup
        openSecretPopup(); 
        return;
      } else {
        // Forward the message to the next parent
        window.parent.postMessage(event.data, event.data.targetElementInfo.originPath);
      }
    }
  }
  if (window.parent !== window || event.source !== window) return;
  if (event.data) {
    if (event.data.action) {
      if (event.data.action === "LOGINSS_V2") {
        const appPath = event.data.appPath;  
        const originPath = new URL(appPath).origin;
        window.postMessage({
          action: "LOGIN_CAUGHT",
        }, originPath);
        confirmAndLaunch(event.data);
      }
    }
  }
}, false);

/**
   *
   * @param {*} data
   */
function confirmAndLaunch(data) {
  if (window.parent !== window) return;
  if (!(data && data.appPath)) return;
  if (!(0,url_helpers/* isUrl */.gU)(data.appPath)) return;
  if (window?.location?.href && window.location.href.indexOf(data.appPath) !== 0) return;

  ext_default().runtime.sendMessage({
    method: "login_tab",
    newUrl: data.secretUrl ? data.secretUrl : data.newUrl,
    tab: data.tab,
    secretId: data.secretId,
    appPath: data.appPath,
    Secrets: [],
  }, () => {});
}

/**
   * Open Secret popup list on Iframe
   * @param {*} ssUrl
   */
function openSecretPopupOnIframe() {
  storage/* default */.A.get("Settings", (theSettings) => {
    if (theSettings) {
      if (!theSettings.Settings.defaultPopupPosition) {
        const getThyIcon = (0,common.$)(".Delinea_SS_UsernameField");
        for (let i = 0; i < getThyIcon.length; i++) {
          if ((0,visibility_helpers/* isElementVisible */.J9)(getThyIcon[i])) {
            showSecret(getThyIcon[i], false);
          }
        }
      }
    }
  });
}

/**
   * openIframeDialog
   * @param {*} path
   * @param {*} settings
   * @return {iframe}
   */
function openIframeDialog(path, settings) {
  const hostDiv = createWPFParent(settings);
  const iframe = document.createElement("iframe");
  iframe.style.border = "0px";
  iframe.style.width = "100%";
  iframe.src = ext_default().runtime.getURL(path);
  hostDiv.appendChild(iframe);
  if (!(settings && settings.iframe && settings.iframe.height)) return iframe;
  iframe.style.height = `${settings.iframe.height}px`;
  return iframe;
}

/**
    * creates WPF parent div
    * @param {json} settings
    * @return {bool}
    */
function createWPFParent(settings) {
  let hostDiv = (0,common.$)("#WPF-shadow-root");
  if (hostDiv) {
    hostDiv.remove && hostDiv.remove();
  }

  hostDiv = document.createElement("div");
  hostDiv.style.boxShadow = "0 2px 4px 0 rgba(0, 0, 0, 0.5)";
  hostDiv.style.border = "solid 1px #a7adbc";
  hostDiv.style.backgroundColor = "#fff";
  hostDiv.style.position = "absolute";
  hostDiv.style.zIndex = "9999999999";
  hostDiv.style.top = "5px";
  hostDiv.style.right = "10px";
  hostDiv.setAttribute("id", "WPF-shadow-root");
  hostDiv.style.width = "350px";
  hostDiv.style.padding = "16px";
  hostDiv.style.paddingBottom = "0";
  applyDialogSettings(hostDiv, settings);
  document.body.appendChild(hostDiv);
  return hostDiv;
}

/**
   *
   * @param {*} hostDiv
   * @param {*} settings
   */
function applyDialogSettings(hostDiv, settings) {
  if (!(settings && settings.dialog)) return;

  if (settings.dialog.position === "center") {
    hostDiv.style.top = "0";
    hostDiv.style.left = "0";
    hostDiv.style.right = "0";
    hostDiv.style.bottom = "0";
    hostDiv.style.margin = "auto";
    hostDiv.style.height = "140px";
  }
  if (settings.dialog.width) {
    hostDiv.style.width = `${settings.dialog.width}px`;
  }
}

/**
   * checkIfSSLoggedIn
   * @param {string} ssUrl
   */
function checkIfSSLoggedIn(ssUrl) {
  if (!isLoggedin) {
    if (!windowLocation.includes("/loggedin.aspx?returnurl=")
      && !windowLocation.includes((0,url_helpers/* appendPath */.mR)(ssUrl, constants.SAML_URL))
      && window.parent === window) {
      let skipCookie = false;
      constants.REDIRCTION_URLS.forEach((e) => {
        if (windowLocation.includes((0,url_helpers/* appendPath */.mR)(ssUrl, e))) {
          skipCookie = true;
        }
      });
      ext_default().runtime.sendMessage({
        method: "checkIfSSLoggedIn",
        skipCookie,
        url: ssUrl,
      });
    }
  }
}

ext_default().runtime.onMessage.addListener(setMessageListner);
attachWindowResize();

/**
   * attachSecretUrlClick
   * @param {*} ssUrl
   */
function attachSecretUrlClick(configUrl) {
  const secretLinkObserver = new MutationObserver((mutations) => {
    let secretUrlLink = [];
    let parentDiv = [];
    let parentEle;
    let res;
    const secretRouteRegex = /\/secret(?:s)?\/(\d+)\/general/;
    const windowUrl = window && window.location && window.location.href.toLowerCase();
    if (windowUrl && (windowUrl.includes(`${configUrl}/app/#/secret`) || windowUrl.includes(`${configUrl}/view/vault/secrets`))) {
      res = window.location.href.match(secretRouteRegex);
      parentDiv = document.getElementsByClassName("layout-form-contents");
      if (parentDiv && parentDiv.length > 0) {
        parentEle = parentDiv[0];
        secretUrlLink = parentEle.querySelectorAll("[target = '_blank']");
      }
    }
    if (res || (windowUrl && (windowUrl.includes(`${configUrl}/app/#/secrets/all`) || windowUrl.includes(`${configUrl}/view/vault/secrets`)))) {
      const secretPathLink = getElementByXpath("//div[contains(@class, \"thy-preview-panel-header\")]/div/a");
      parentDiv = getElementByXpath("//div[contains(@class, \"thy-preivew-panel-content\")]");
      if (parentDiv) {
        const previewLinks = parentDiv.querySelectorAll("[target = '_blank']");
        if (previewLinks.length > 0) {
          secretUrlLink = [...secretUrlLink, ...previewLinks];
        }
        if (secretPathLink && (secretUrlLink.length > 0)) {
          const secretPath = new URL(secretPathLink.href);
          res = secretPath.hash.match(secretRouteRegex);
        }
      }
    }
    if ((secretUrlLink.length > 0) && res && res.length === 2) {
      for (let i = 0; i < secretUrlLink.length; i++) {
        if (!secretUrlLink[i].secretId) {
          const secretUrl = secretUrlLink[i].href;
          secretUrlLink[i].secretId = res[1];
          secretUrlLink[i].secretUrl = secretUrl;
          secretUrlLink[i].addEventListener("click", secretUrlOnClick);
        }
      }
    }
  });
  if (!document.body) return;
  secretLinkObserver.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: false,
  });
}

/**
 *secretUrlOnClick
 * @param {*} evt
 */
function secretUrlOnClick(evt) {
  evt.preventDefault();
  ext_default().runtime.sendMessage({
    method: "login_tab",
    newUrl: evt.target.text,
    secretId: evt.target.secretId,
    appPath: evt.target.baseURI,
  });
}
/**
  * getElementByXpath
  * @param {*} path
  * @return {htmlElement}
  */
function getElementByXpath(path) {
  try {
    return document.evaluate(
      path,
      document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null,
    ).singleNodeValue;
  } catch (e) {
    return null;
  }
}
/**
    * mouse down call back for contextmenu
    * @param {string} event
    */
function mousedownCallback(event) {
  if (!isLoggedin || hideContextMenu) {
    return;
  }
  if (event.button == 2) {
    const clickedElement = event.target;
    let isPassword = false;
    lastClickedElement = null;
    const inputTypes = ["password", "text", "email", "tel", "number"];
    if (clickedElement && clickedElement.type
      && inputTypes.includes(clickedElement.type.toLowerCase())) {
      lastClickedElement = clickedElement;
      isPassword = (clickedElement.type.toLowerCase() === "password");
    }
    const xPath = getPathTo(event.target);
    ext_default().runtime.sendMessage({
      method: "lastClickedElement",
      isPassword,
      isSecretServer,
      isPlatformServer,
      isCurrentSSTabloggedIn,
      xPath,
      referrer: document.referrer,
    });
  }
}

/**
    * read and send token generated by secret server
    *  to background script to login
    */
function readAndSendSAMLToken() {
  if (!isLoggedin && windowLocation.endsWith("/alreadyloggedin.aspx")) {
    ext_default().runtime.sendMessage({
      method: "SSLoggedIn",
    });

    const tokenEle = document.getElementById("TokenBlobField");
    const oldTokenEle = document.getElementById("TokenField");
    if ((tokenEle && tokenEle.value !== "")
      || (oldTokenEle && oldTokenEle.value !== "")) {
      let sTokenEle = "";
      let soldTokenEle = "";
      if (tokenEle) {
        sTokenEle = tokenEle.value;
      }
      if (oldTokenEle) {
        soldTokenEle = oldTokenEle.value;
      }
      sendSAMLToken(sTokenEle, soldTokenEle);
    } else if ((0,common.$)("#GetTokenButton")) {
      (0,common.$)("#GetTokenButton").click();
    }
  } else if (!isLoggedin
    && (windowLocation.includes("/passwordexpired.aspx")
      || windowLocation.includes(constants.LICENSES_URL))) {
    setTimeout(() => {
      const hideNav = document.getElementsByClassName("hideMenuIcon");
      if (hideNav && hideNav.length > 0) {
        hideNav[0].click();
      }
    }, 100);
  }
}

/**
 * Send SMAL token value.
 * @param {object} newToken token object.
 * @param {string} oldToken token value before SS version 10.7.80.
 */
function sendSAMLToken(newToken, oldToken) {
  ext_default().runtime.sendMessage({
    method: "GetGenToken",
    token: newToken,
    oldToken,
  });
}

/**
    * locates the Password Elements .
    * @return {boolean}
    */
function isValidForm() {
  if (isCurrentSSTabloggedIn) {
    return false;
  }
  if (!isLoggedin) {
    return false;
  }

  const inputs = (0,common.$)("input");
  const inputList = document.querySelectorAll("input[type=text], input[type=password], input[type=email] ,input:not([type]), input[autocomplete=username]");
  const elements = getBestMatch(inputList);
  for (let i = 0; i < inputs.length; i++) {
    if (inputs[i].type.toLowerCase() === "password") {
      return true;
    }
  }
  if (elements.length > 0) {
    return true;
  }
  for (let i = 0; i < inputList.length; i++) {
    const arr = (0,visibility_helpers/* parents */.M8)(inputList[i]);
    for (let y = 0; y < arr.length; y++) {
      if (arr[y].innerText.toLowerCase().search(contentscript_loginPageRegEx) !== -1) {
        if ((0,visibility_helpers/* isElementVisible */.J9)(arr[y])) {
          return true;
        }
      }
    }
  }

  if (checkIfLoginURL()) {
    return true;
  }
  return false;
}

const sendMessageAsync = (message) =>
  new Promise((resolve, reject) => {
    ext_default().runtime.sendMessage(message, (response) => {
      if ((ext_default()).runtime.lastError) {
        reject((ext_default()).runtime.lastError); // Reject the promise on runtime error
      } else {
        resolve(response); // Resolve with the response
      }
    });
  });

/**
    * locates the Password Elements .
    */
async function processFormElements() {
  if(isCurrentSSTabloggedIn) {
    return;
  }
  if (!isLoggedin) {
    return;
  }
  if(isPlatformServer) {
    const response = await sendMessageAsync({ method: "checkIfPlatformLoginPage" });
    if (!response?.isPlatformLoginPage) {
      return; // Exit if it's not a platform login page
    }
  }

  let inputs = (0,common.$)("input");
  const result = getShadowDomElements(inputs);
  if(result?.inputs.length === 0) {
    result.shadowRootElements.forEach((node) => {
      attachMutationObserverToShadowroot(node);
    });
  }
  if(result?.inputs.length > 0) {
    inputs = result.inputs;
    handleShadowDomLogin(result);
  };
  let foundPasswordField = false;
  let passwordVisible = false;
  let isEleVisible = false;
  for (let i = 0; i < inputs.length; i++) {
    if ((inputs[i].type.toLowerCase() === "password"
      || (inputs[i].id.toLowerCase() === "password"
        && inputs[i].type !== "hidden"))
      && !inputs[i].classList.contains("Delinea_PWD")
      && !inputs[i].classList.contains("Delinea_OTP")
      && !inputs[i].classList.contains("Delinea_SS_PasswordField")
      && !ignorePasswordFields.includes(inputs[i].id)) {
      if (inputs[i].getAttribute("data") === "fromThyWPF"
        || inputs[i].classList.contains("Thycotic_SS_PasswordField")) {
        return;
      }
      const formElement = inputs[i].closest("form");
      if (isSignUp(formElement)) {
        continue;
      }
      if (getUsernameField(inputs[i])) {
        isEleVisible = true;
        inputs[i].classList.add("Delinea_PWD");
      }
      if ((0,visibility_helpers/* isElementVisible */.J9)(inputs[i])) {
        passwordVisible = true;
      }
      foundPasswordField = true;

    }
  }
  if (!foundPasswordField) {
    placeDelineaIcon();
    placeOtpIcon();
  } else if (isEleVisible || passwordVisible) {
    showSecretPopupOnDemand();
    ext_default().runtime.sendMessage({
      method: "isCrossDomain",
    });
  } else if (!(isEleVisible && passwordVisible && foundPasswordField)) {
    placeDelineaIcon();
    placeOtpIcon();
  }
}

function isSignUp(formElement) {
  if (!formElement) return false;
  const heading =  formElement.querySelector('h1, h2, h3');
  let headingText = heading ? heading.textContent.trim() : '';
  const inputList = formElement.querySelectorAll("input[type=text], input[type=password], input[type=email] ,input:not([type]), input[autocomplete=username]");
  const thresholdValue = Settings.inputThreshold || constants.INPUT_THRESHOLD;
  
  if (inputList && inputList.length > thresholdValue) {
    return true;
  }
  // Check if the heading text does not match specific phrases
  if ((headingText.includes("Create a free account") || 
        headingText.includes("Sign Up") || 
        headingText.includes("My Profile") || 
        headingText.includes("User Registration Form") ||
        formElement.className.includes("signup")
      )) {
    return true;
  }
  return false;
}

function attachMutationObserverToShadowroot(shadowRoot) {
  shadowObserver = new MutationObserver((mutationsList) => {
      clearTimeout(shadowRootDebounceTimeout);
      shadowRootDebounceTimeout = setTimeout(() => {
        processFormElements();
      }, 300);
    });
  shadowObserver.observe(shadowRoot, { childList: true, subtree: true, attributes: false });
}

function handleShadowDomLogin(result) {
  if(result && (result.shadowUsername || result.shadowPasswordField)) {
    if(shadowObserver) {
      shadowObserver.disconnect();
    }
    markUsername(result.shadowUsername, result.shadowPasswordField ? result.shadowPasswordField : null);
    if(result.shadowPasswordField) {
      if((0,visibility_helpers/* isElementVisible */.J9)(result.shadowPasswordField)) {
        isPasswordVisible = true;
      }
    }
    if(result.signInButtons.length > 0) {
      attachHandleSubmit(result.signInButtons);
    } else {
      const allButtons = getAllButtons();
      const loginButtons = findSignIn(allButtons);
      attachHandleSubmit(loginButtons);
    }
    ext_default().runtime.sendMessage({
      method: "isCrossDomain",
    });
  }
}

const contentscript_loginPageRegEx = /(login)|(signin)|(sign in)|(sign-in)|(logon)|(signup)|(signup_form)|(auth)|(iamsuite)/;

const getMetadata = (secret) => new Promise((resolve, reject) => {
  ext_default().runtime.sendMessage({
    method: 'GetMetadata',
    secretId: secret.id,
  }, (response) => {
    const dataJson = response && response.detail && response.detail.dataJson;
    if (dataJson && dataJson.records) {
      resolve(dataJson.records);
    } else {
      reject();
    }
  });
});

const findMappedFieldsInMatchingSecrets = async (response) => {
  // when there's multiple secrets, we'll check the first for mapping
  if (response && response.model && response.model.length > 0) {
    const secret = response.model[0];
    const metadata = await getMetadata(secret);
    // eslint-disable-next-line no-restricted-syntax
    for (const meta of metadata) {
      // eslint-disable-next-line no-continue
      if (meta.metadataFieldSectionName !== 'WPFHints') continue;
      // eslint-disable-next-line no-continue
      if (meta?.metadataFieldName?.toLowerCase() !== 'username') continue;

      const field = getElementByXpath(meta.valueString);
      if (field) {
        markUsername(field);
        getAppropriateParent(field);
        let form = field && field.closest && field.closest("form");
        findLoginButton(form);
        ext_default().runtime.sendMessage({
          method: 'isCrossDomain',
        });
        break;
      }
    }
  }
};

const searchForMappedFields = () => {
  // query elements that weren't queried before
  const inputList = document.querySelectorAll('input[type=search]');
  if (inputList.length > 0) {
    ext_default().runtime.sendMessage({
      method: 'GetSecrets',
      justRespond: true,
      isCrossDomain,
      referrer: document.referrer,
    }, findMappedFieldsInMatchingSecrets);
  }
};

/**
    * Place icon where passowrd fields not found.
    */
function placeDelineaIcon() {
  let isUsernameVisible = false;
  let elements = [];
  const otpInputList = document.querySelectorAll("input[type=text], input[autocomplete=one-time-code]");
  const otpElement = getBestOtpMatch(otpInputList);
  const alreadyMarked = (0,common.$)(".Delinea_SS_UsernameField");
  const inputList = document.querySelectorAll("input[type=text], input[type=email] ,input:not([type]), textarea, input[autocomplete=username]");
  for (let k = 0; k < alreadyMarked.length; k++) {
    if ((0,visibility_helpers/* isElementVisible */.J9)(alreadyMarked[k])) {
      isUsernameVisible = true;
      elements = [alreadyMarked[k]];
    }
  }
  let showSecret = false;
  if (!isUsernameVisible) {
    // eslint-disable-next-line

    elements = getBestMatch(inputList);
    for (let x = 0; x < elements.length; x++) {
      if (elements[x].form && checkIfLoginForm(elements[x].form)) {
        const formUsernames = elements[x].form.getElementsByClassName("Delinea_SS_UsernameField");
        if (formUsernames.length > 0) {
          continue;
        }
        if ((0,visibility_helpers/* isElementVisible */.J9)(elements[x])) {
          markUsername(elements[x], null, otpElement);
          getAppropriateParent(elements[x].form);
          showSecret = true;
        }
      }
    }
  }
  const selector = `button[type="submit"], input[type="submit"],
    button, input[type="button"], input[type="image"], *[type="submit"],
    button[type = "signup_determine_btn active"]`;
  const btns = document.querySelectorAll(selector);
  if (!showSecret) {
    for (let y = 0; y < btns.length; y++) {
      if (btns[y] && checkIfLoginForm(btns[y])) {
        if ((0,visibility_helpers/* isElementVisible */.J9)(elements[0])) {
          markUsername(elements[0], null, otpElement);
          btns[y].addEventListener("click", handleSubmit);
          getAppropriateParent(elements[0].form || elements[0]);
          showSecret = true;
          break;
        }
      }
    }
  }

  if (!showSecret
    && elements.length > 0 && checkIfLoginURL()) {
    if ((0,visibility_helpers/* isElementVisible */.J9)(elements[0])) {
      const allButtons = getAllButtons(elements[0].form);
      const allLinks = findForgotPasswordSignInLinks(allButtons);
      if (allLinks.length > 0 || isLoginTitle()) {
        markUsername(elements[0], null, otpElement);
        attachHandleSubmit(allLinks);
        showSecret = true;
      }
    }
  }

  if (showSecret && !isUsernameVisible) {
    ext_default().runtime.sendMessage({
      method: "isCrossDomain",
    });
  }

  const pwdMarked = (0,common.$)(".Delinea_PWD");
  for (let k = 0; k < pwdMarked.length; k++) {
    const { form } = pwdMarked[k];
    getAppropriateParent(form);
  }

  // if we still haven't found anything, search for mapped fields
  if (elements && elements.length === 0 && pwdMarked.length === 0) {
    searchForMappedFields();
    setTimeout(() => {
      searchForMappedFields();
    }, 2000);
  }
}

function placeOtpIcon() {
  let elements = [];
  const username = document.querySelectorAll(".Delinea_SS_UsernameField");
  const password = document.querySelectorAll(".Delinea_PWD");
  const inputListForOtp = document.querySelectorAll("input[autocomplete=one-time-code], input[type=text]");
  elements = getBestOtpMatch(inputListForOtp);
  for (let x = 0; x < elements.length; x++) {
    if (elements[x].form) {
      const formOtp = elements[x].form.getElementsByClassName("Delinea_OTP");
      if (formOtp.length > 0) {
        continue;
      }
      if ((0,visibility_helpers/* isElementVisible */.J9)(elements[x])) {
        timer/* default */.A.markOtpField(elements[x], null);
        if (username.length == 0 && password.length == 0) {
          ext_default().runtime.sendMessage({
            method: "otpOnNextPage",
          }, (response) => {
            const newElementNodes = [];
            newElementNodes.push({
              otpField: elements,
            });

            timer/* default */.A.requestNewOtp(response.secretId, newElementNodes);
          });
        }
      }
    }
  }
}

/**
   * getAppropriateParent
   * @param {object} element
   * @return {object}
   */
function getAppropriateParent(element) {
  if (!element) return;
  let _ar = (0,visibility_helpers/* parents */.M8)(element);
  if (element.tagName === "FORM") {
    _ar = [element, ..._ar];
  }
  for (let ind = 0; ind < _ar.length; ind++) {
    if (!_ar[ind]) continue;
    const btns = getAllButtons(_ar[ind]);
    const matches = findSignIn(btns);
    //   matches.push(formElements(_ar[ind]));
    attachHandleSubmit(matches);
    if (matches.length > 0) return;
  }
}

/**
   * formElements
   * @param {*} form
   * @return {element}
   */
function formElements(form) {
  if (!(form && form.elements)) return;

  for (let index = 0; index < form.elements.length; index++) {
    if (form[index] && form[index].type === "submit") return form[index];
  }
}

/**
   * attachHandleSubmit
   * @param {*} matches
   */
function attachHandleSubmit(matches) {
  if (!matches) return;

  matches.forEach((match) => {
    if (match) {
      match.addEventListener("click", handleSubmit);
    }
  });
}

/**
 * Add Delinea Icon as Background Image for textbox
 * @param {htmlElement} element
 */
function addBackgroundImage(element) {
  if (!element) return;

  if (element.classList && element.classList.contains("Delinea_SS_UsernameField")) {
    return;
  }

  if (element.style) {
    element.style.setProperty(
      "background-image",
      `url('${constants.ICONS.DELINEA}')`,
      "important",
    );
    element.style.setProperty("background-repeat", "no-repeat", "important");
    element.style.setProperty("background-position", "98%", "important");
    element.style.setProperty("background-size", "auto", "important");
    element.style.setProperty("box-shadow", "none", "important");
    element.style.setProperty("opacity", "1", "important");
  }

  if (element.setAttribute) {
    element.setAttribute("autocomplete", "off");
  }
  if (element.classList) {
    element.classList.add("Delinea_SS_UsernameField");
  }
}

/**
    *  isPasswordOnPage
    * @return {bool}
    */
function isPasswordOnPage() {
  let taggedPasswordFields = (0,common.$)(".Delinea_PWD");
  if(taggedPasswordFields.length === 0) {
    taggedPasswordFields = (0,common.$)('input[type="password"]');
  }
  if (taggedPasswordFields && taggedPasswordFields.length > 0) {
    for (let i = 0; i < taggedPasswordFields.length; i++) {
      if ((0,visibility_helpers/* isElementVisible */.J9)(taggedPasswordFields[i])) {
        isPasswordVisible = true;
        return true;
      }
    }
  }
  return isPasswordVisible;
}

/**
    *  isOtpOnPage
    * @return {bool}
    */
function isOtpOnPage() {
  const taggedOtpFields = (0,common.$)(".Delinea_OTP");
  if (taggedOtpFields && taggedOtpFields.length > 0) {
    for (let i = 0; i < taggedOtpFields.length; i++) {
      if ((0,visibility_helpers/* isElementVisible */.J9)(taggedOtpFields[i])) {
        return true;
      }
    }
  }
  return false;
}

/**
    *  Open Secret popup when click on Tycotic Icon
    * @param {object} elem
    * @param {object} isIconClick
    */
function showSecret(elem, isIconClick) {
  let targetElem = null;
  if (isIconClick === false) {
    targetElem = elem;
  } else {
    isIconClick = true;
    targetElem = elem && elem.target;
  }

  const isAddSecretPopup = (0,common.$)("#WPF-shadow-root");
  if (isAddSecretPopup) {
    removeContainer("WPF-shadow-root");
  }
  if (isLoggedin) {
    const eleCords = getTopLeftForIcon(targetElem, true);
    ext_default().runtime.sendMessage({
      method: "GetSecrets",
      showSecretPopup: true,
      eleCords,
      isIconClick,
      isCrossDomain,
      referrer: document.referrer,
      iframeId: getIframeId(),
      pageState: window.performance.navigation.type,
      isPasswordHiddenOnPage: !isPasswordOnPage(),
      isOtpHiddenOnPage: !isOtpOnPage(),
    });
  }
  if (window.parent === window) {
    userFieldElement = targetElem;
    openSecretPopup(targetElem);
  } else {
    // If in a nested iframe, send a message to the main frame
    const urlPath = document.referrer;  
    const originPath = new URL(urlPath).origin;
    window.top.postMessage(
      {
        action: "openSecretPopup",
        targetElementInfo: { id: targetElem.id, className: targetElem.className, originPath },
      },
      originPath
    );
  }
}


/**
    * check not secret server
    */
function attachWindowResize() {
  window.addEventListener("resize", (e) => {
    const element = (0,common.$)("#WPF-shadow-root");
    if (element && !(parseInt(element.style.top) === 5
      && parseInt(element.style.right) === 10)) {
      shadowElement = null;
      element && element.remove && element.remove();
    }
  });
}

/**
* Check setting and check secret avaiilable for current url or not.
* @param {boolean} fromWarning
* @param {boolean} isContextSecretRefresh
*/
function showSecretPopupOnDemand(fromWarning, isContextSecretRefresh) {
  storage/* default */.A.get("Settings", (items) => {
    if (typeof items.Settings !== "undefined") {
      if (items.Settings.set_show_popup_credential_available === true
        || isContextSecretRefresh) {
        if (items.Settings.defaultPopupPosition === true || fromWarning
          || isContextSecretRefresh) {
          const shadowElement1 = (0,common.$)("#WPF-shadow-root-AddNewSecretPop");
          if (!shadowElement1) {
            openSecretPopup();
          }
        } else {
          const getThyIcon = (0,common.$)(".Delinea_SS_UsernameField");
          for (let i = 0; i < getThyIcon.length; i++) {
            if ((0,visibility_helpers/* isElementVisible */.J9)(getThyIcon[i])) {
              openSecretPopup(getThyIcon[i]);
            }
          }
        }
      }
    }
  });
}

/**
* returns font face Manrope to the host div.
* @return {Object}
*/
function addFontFace() {
  const fontFaceStyle = document.createElement("style");
  fontFaceStyle.setAttribute("id", "THY_WPF");
  const fonts = [
    { weight: 400, name: "Regular" },
    { weight: 500, name: "Medium" },
    { weight: 600, name: "SemiBold" },
    { weight: 700, name: "Bold" },
  ];
  let css = "";
  for (const font of fonts) {
    const fontPath = ext_default().runtime.getURL(`fonts/font/Manrope-${font.name}.ttf`);
    css += `
    @font-face {
      font-family: 'Manrope';
      font-style: normal;
      font-weight: ${font.weight};
      src: url('${fontPath}');
    }
    `;
  }
  fontFaceStyle.appendChild(document.createTextNode(css));
  return fontFaceStyle;
}

/**
* create the secretlist container div on page load or icon click.
* @param {HTMLElement} e element associated with Icon image.
* @param {object} sender element
*/
function openSecretPopup(e, sender) {
  document.addEventListener("mouseup", removeSecretDivIcon);
  const container2 = (0,common.$)("#WPF-permission-root");
  if (container2 && container2.remove) {
    container2.remove();
  }
  if (window.parent === window) {
    let hostDiv = (0,common.$)("#WPF-shadow-root");
    if (!hostDiv) {
      hostDiv = createHostElement();
      hostDiv.setAttribute("id", "WPF-shadow-root");
      hostDiv.style.paddingBottom = "10px";
      hostDiv.style.width = "350px";
      shadowElement = hostDiv.shadowRoot;
    }
    let element = shadowElement.getElementById("delinea-container");
    if (!element) {
      element = document.createElement("div");
      element.style.display = "none";
      element.setAttribute("id", "delinea-container");
      element.innerHTML = `
            <div id="delinea-inner-container" >
            <div id="div-Signinas" class="Sign-in-as">
            <span id="spSigninas" >Sign in as</span>
            <input type="hidden" id="thy-selected-frameId" value="${sender ? (sender.frameId ? sender.frameId : 0) : 0}">
            <input type='button' class="refresh-secret" value='&#10227;' id="thy-refresh-secret"> </input>
            </div>
            <div id="thy-secret-container" class="secretpopup"> </div>
            </div>`;
      hostDiv.classList.add("Rectangle");
      shadowElement.appendChild(element);
      shadowElement.getElementById("delinea-inner-container").style.display = "none";
      createAddSecretPopup(element);
    }
    if (e) {
      const cords = getTopLeftForSecretDiv(e);
      if (cords) {
        if (sender && sender.eleCords) {
          cords.top += sender.eleCords.top + sender.eleCords.offsetHeight;
          cords.left += sender.eleCords.left;
        }
        hostDiv.style.top = `${cords.top + 10}px`;
        hostDiv.style.left = (cords.left + cords.width - 339) > 0
          ? `${cords.left + cords.width - 339}px` : "0px";
      }
    }

    if (!e || (e.tagName.toLowerCase() === "iframe" && !sender.eleCords)) {
      if (hostDiv.style) {
        hostDiv.style.top = "5px";
        hostDiv.style.right = "10px";
        hostDiv.style.removeProperty("left");
      }
    }
    const icon = (0,common.$)(".thy-wpf-icon-div")[0];
    if (icon) {
      const divZindex = getComputedStyle(hostDiv).zIndex;
      hostDiv.style.zIndex = (parseInt(divZindex) > parseInt(icon.style.zIndex))
        ? divZindex : icon.style.zIndex;
    }
    getSiteIconUrl(shadowElement);
  }
}

// sortSecrets function before displaySecrets
async function handleRequest(request) {
  const settings = await cache/* settingsProvider */.Pj.get();
  const exactMatchEnabled = settings.exactMatchUrl;
  const sortedSecrets = sorting_secret.sortSecrets(request.response.Secrets, request.sender.tab.url, exactMatchEnabled); // Sort the secrets
  request.response.Secrets = sortedSecrets; // Update the request with sorted secrets
  displaySecrets(request); // Now call the existing function
}



/**
* displays the Secrets in secret Container.
* @param {Array} request Secret list, iframe info.
*/
function displaySecrets(request) {
  let el = null;
  if (window.parent === window
    && request.sender && request.sender.frameId !== 0
    && request.sender.url) {
    const allIFrames = (0,common.$)("iframe");
    for (let i = 0; i < allIFrames.length; i++) {
      if (allIFrames[i].src === request.sender.url
        || (request.sender.iframeId
          && allIFrames[i].id === request.sender.iframeId)) {
        el = allIFrames[i];
        break;
      }
    }
  }

  const { Secrets } = request.response;
  if (el) {
    openSecretPopup(el, request.sender);
  }

  let secretsMarup = "";
  const currentTabURL = request?.sender?.url

  if (Secrets && Secrets.length > 0) {
    if ((request?.sender?.isRefreshClick || request?.sender?.isIconClick) && shadowElement) {
      shadowElement.getElementById("spSigninas").textContent = "Sign in as";
    }

    for (let i = 0; i < Secrets.length; i++) {
      const secretName = Secrets[i].name;
      const secretURL = Secrets[i].cleanedSecretUrl || Secrets[i].secretUrl;
      const favImg = ext_default().runtime.getURL("images/favorites.svg");
      const highlightedSecretURL = sorting_secret.highlightMatches(secretURL, currentTabURL);
      const secretItem = `
      <div class="Rectangle-Inner" id="innerRect_${Secrets[i].id}">
        <div class="siteIconContainer">
          <img class="siteIcon siteImage">
          <div class="favorite-star ${Secrets[i].isFavoriteSecret || "hide"}">
              <img class="favorites-icon" src="${favImg}" />
          </div>
          </div>
          <div class="secretNameContainer">
            <p>${(0,url_helpers/* urlEncode */.u4)(secretName)}</p>
            ${highlightedSecretURL}
          </div>
          <div class="kebabMenu" id="kebabOptions-${Secrets[i].id}">
          <div class="kebabIcon">&#8942;</div>
        </div>
      </div>`;
      secretsMarup += secretItem;
    }
    if (Secrets.length > 3 && shadowElement) {
      if (!shadowElement.getElementById("thy-Search-SecretName")) {
        if (shadowElement.getElementById("div-Signinas")) {
          shadowElement.getElementById("div-Signinas").innerHTML
            += "<input type=\"text\" id=\"thy-Search-SecretName\"  autocomplete=\"off\" placeholder=\"\"  class=\"search-secret-textbox\">";
        }
      }
      const txtSearchTextBox = shadowElement.getElementById("thy-Search-SecretName");
      if (txtSearchTextBox) { txtSearchTextBox.value = ""; }

      txtSearchTextBox.addEventListener("keyup", (e) => {
        const secretDiv = shadowElement.querySelectorAll(".secretNameContainer");
        for (let i = 0; secretDiv.length > i; i++) {
          if (e.target.value.trim().toLowerCase() !== "") {
            if (!secretDiv[i].innerHTML.toLowerCase()
              .includes(e.target.value.toLowerCase())) {
              secretDiv[i].parentNode.style.display = "none";
            } else {
              secretDiv[i].parentNode.style.display = "flex";
            }
          } else {
            secretDiv[i].parentNode.style.display = "flex";
          }
        }
      });
    }
    showContainer(secretsMarup);
    attachOnSecretClickEvent();
    attachOnKebabOptionsClickEvent(request.sender, shadowElement);
  } else if ((request.sender.isRefreshClick || request.sender.isIconClick)
    && shadowElement) {
    shadowElement.getElementById("spSigninas").textContent = "No Secrets found";
    if (shadowElement.getElementById("thy-refresh-secret") && shadowElement.getElementById("thy-refresh-secret").hidden) {
      shadowElement.getElementById("thy-refresh-secret").hidden = true;
    }
    if (request.sender.isUserPermission) {
      const addPermission = request.sender.permissions;
      if (addPermission.find((o) => o.name === "Add Secret")) {
        shadowElement.getElementById("thy-refresh-secret").hidden = false;
        secretsMarup = `
          <div class="Rectangle-Inner">
          <div class="siteIconContainer">
          <img class="siteIcon siteImage">
          </div>
          <div id ="divAddSecret" class="secretNameContainer">Add Secret</div>
          </div>`;
      }
    }
    showContainer(secretsMarup);
    shadowElement.getElementById("divAddSecret")
      .addEventListener("click", (e) => {
        if (Templates.length > 0) {
          showAddSecretForm();
        } else {
          shadowElement.host.remove();
          ext_default().runtime.sendMessage({
            method: "GetTemplatesNFolders",
          }, (response) => {
            setTemplatesNFolders(response);
            if (Templates.length > 0 && Folders.length > 0) {
              showAddSecretForm();
            }
          });
        }
      });
  }
  getSiteIconUrl(shadowElement);
  preventShortcutKeys(shadowElement);
}

/**
* show containers
*  @param {string} innerHtml html string
*/
function showContainer(innerHtml) {
  const hostDiv = (0,common.$)("#WPF-shadow-root");
  if (!hostDiv) {
    return;
  }
  if (hostDiv && hostDiv.style && hostDiv.style.display) {
    hostDiv.style.display = "block";
  }
  if (shadowElement.getElementById("add-secret-container")) {
    shadowElement.getElementById("add-secret-container").style.display = "none";
  }
  shadowElement.getElementById("delinea-container").style.display = "block";
  shadowElement.getElementById("delinea-inner-container").style.display = "block";
  const innerContainer = shadowElement.getElementById("thy-secret-container");
  if (innerContainer && innerContainer.style) {
    innerContainer.style.display = "block";
  }
  if (innerContainer && innerContainer.innerHTML) {
    innerContainer.innerHTML = innerHtml;
  }
}

/**
* sets the password and username to the respective textbox elements.
* @param {Object} resp Password and username object for given secret.
*/
function setUserNamePWD(res, id) {
  const resp = (res.autoFillData && res.autoFillData.model) || res.autoFillData || res;

  const secretId = id || res.secretId;
  if (resp.username && resp.password) {
    gusername = resp.username;
    let USet = false;
    let PSet = false;
    if (userFieldElement != null) {
      const UNamePWDPair = elementNodes.filter((x) => x.userNameField
        && x.userNameField.isSameNode(userFieldElement));
      for (let index = 0; index < UNamePWDPair.length; index++) {
        if (UNamePWDPair[index].userNameField
          && (0,visibility_helpers/* isElementVisible */.J9)(UNamePWDPair[index].userNameField)) {
          USet = true;
          const mappedUsername = getMappedValue(resp, UNamePWDPair[index].userNameField);
          if (mappedUsername) {
            gusername = mappedUsername;
            isMappingFound = true;
            sendKeystrokes(UNamePWDPair[index].userNameField, mappedUsername);
          } else {
            sendKeystrokes(UNamePWDPair[index].userNameField, resp.username);
          }
          if (document.readyState !== "complete") {
            const unameInterval = setInterval(() => {
              if (document.readyState === "complete") {
                if (mappedUsername) {
                  isMappingFound = true;
                  sendKeystrokes(UNamePWDPair[index].userNameField, mappedUsername);
                } else {
                  sendKeystrokes(UNamePWDPair[index].userNameField, resp.username);
                }
                clearInterval(unameInterval);
                applyMappings(resp);
              }
            }, 500);
          }
        }
        if (UNamePWDPair[index].passwordField
          && (0,visibility_helpers/* isElementVisible */.J9)(UNamePWDPair[index].passwordField)) {
          PSet = true;
          sendKeystrokes(UNamePWDPair[index].passwordField, resp.password);
          attachMutation(UNamePWDPair[index].passwordField, resp);
          if (document.readyState !== "complete") {
            const pwdInterval = setInterval(() => {
              if (document.readyState === "complete") {
                if (resp.mappings) {
                  if (resp.mappings.length > 0
                    && !UNamePWDPair[index].passwordField.value) {
                    applyMappings(resp);
                  }
                }
                clearInterval(pwdInterval);
              }
            }, 500);
          }
        }
      }
      handleOtp(res, secretId, elementNodes);
      userFieldElement = null;
      if (USet && PSet) {
        applyMappings(resp);
        return;
      }
    }
    handleOtp(res, secretId, elementNodes);
    setAllUserNamePassword(resp, secretId);
  }
  applyMappings(resp);
}

function handleOtp(res, secretId, elementNodes) {
  if (res.isOtpPresent || res?.sender?.isGenerateOneTimePasswordPresent) {
    timer/* default */.A.requestNewOtp(secretId, elementNodes);
  } else {
    timer/* default */.A.clearTimer();
  }
}

function setElementValue(element, valueKey, valueObject, callback) {
  // Get the currently focused element
  const previouslyFocusedElement = document.activeElement;

  // Focus on the given element, preventing scroll
  element.focus({
      preventScroll: true
  });

  // If ClipboardEvent is defined, trigger a 'paste' event on the element
  if (typeof ClipboardEvent !== 'undefined') {
      element.dispatchEvent(new ClipboardEvent("paste", {
          bubbles: true
      }));
  }
  // Determine the value to set based on the 'valueObject' and 'valueKey'
  const newValue = valueObject && valueObject[valueKey] ? valueObject[valueKey] : valueKey;

  // Set the element's value to the determined value
  element.value = newValue;

  // If KeyboardEvent is defined, trigger a 'keyup' event on the element
  if (typeof KeyboardEvent !== 'undefined') {
      element.dispatchEvent(new KeyboardEvent("keyup", {
          bubbles: true
      }));
  }
  
  if (element.value === "") {
    element.value = newValue;
  }

  // If a callback function 'callback' is provided, call it with the new value
  if (callback) {
      callback(newValue);
  }

  // If InputEvent is defined, trigger an 'input' event
  if (typeof InputEvent !== 'undefined') {
      element.dispatchEvent(new InputEvent("input", {
          bubbles: true,
          inputType: "insertFromPaste"
      }));
  }

  // Trigger a 'change' event on the element
  if ((0,common/* checkIfMultiDomain */.FS)((0,url_helpers/* parseUrl */.Dl)(window.location.href).domain).length === 0) {
    element.dispatchEvent(new Event("change", {
      bubbles: true
    }));
  }

  // Restore the focus to the previously active element (if any)
  if (previouslyFocusedElement) {
      previouslyFocusedElement.focus();
  }
}

function sendKeystrokes(inputField, inputString) {
  if (!inputField || inputField.value === inputString) return;
  setElementValue(inputField, inputString, null, null);  
}
/**
 * applyMappings
 * @param {*} resp
 */
function applyMappings(resp) {
  if (resp.mappings) {
    resp.mappings.forEach((x) => {
      if (x.xPath && x.value) {
        const field = getElementByXpath(x.xPath);
        if (field) {
          sendKeystrokes(field, x.value);
          if (field.type === "password" && (0,visibility_helpers/* isElementVisible */.J9)(field)) {
            passwordSet();
          }
        }
      }
    });
  }
}

/**
 * Password Set function where secrets are being cleared.
 */
function passwordSet() {
  const match = window && window.location && window.location.origin.match(constants.SALESFORCE_SUBDOMAINS);
  // For SaleForce Subdomain
  if (!match) {
    ext_default().runtime.sendMessage({
      method: "PasswordSet",
    });
  }
}

let pwdObserver = null;
/**
 * attachMutation
 * @param {*} pwdField
 * @param {object} response
 */
function attachMutation(pwdField, response) {
  if (!(0,visibility_helpers/* isElementVisible */.J9)(pwdField)) {
    const hiddenEle = (0,visibility_helpers/* getHiddenParent */.VH)(pwdField);
    if (hiddenEle) {
      if (pwdObserver) return;
      pwdObserver = new MutationObserver(() => {
        sendKeystrokes(pwdField, response.password);
        if ((0,visibility_helpers/* isElementVisible */.J9)(pwdField)) {
          pwdObserver.disconnect();
          passwordSet();
        }
      });
      pwdObserver.observe(hiddenEle, {
        childList: true,
        subtree: true,
        attributes: true,
      });
    }
  } else {
    passwordSet();
  }
}

/**
   * getMappedValue
   * @param {object} response
   * @return {*}
   */
function getMappedValue(response, uField) {
  let mappedValue;
  if (response.mappings) {
    response.mappings.forEach((x) => {
      if (x.xPath && x.value) {
        const field = getElementByXpath(x.xPath);
        if (uField === field) {
          mappedValue = x.value;
        }
      }
    });
  }
  return mappedValue;
}

/**
 * setUserNameValue
 * @param {*} resp
 * @param {*} uField
 */
function setUserNameValue(resp, uField) {
  const mappedUsername = getMappedValue(resp, uField);
  if (mappedUsername) {
    isMappingFound = true;
    sendKeystrokes(uField, mappedUsername);
  } else {
    sendKeystrokes(uField, resp.username);
  }
}

/**
   * setAllUserNamePassword
   * @param {object} resp
   */
function setAllUserNamePassword(resp) {
  for (let index = 0; index < elementNodes.length; index++) {
    if (elementNodes[index].userNameField
      && elementNodes[index].userNameField.value !== resp.username) {
      if ((0,visibility_helpers/* isElementVisible */.J9)(elementNodes[index].userNameField)) {
        setUserNameValue(resp, elementNodes[index].userNameField);
      }
      if (document.readyState !== "complete") {
        const unameInterval = setInterval(() => {
          if (document.readyState === "complete") {
            if ((0,visibility_helpers/* isElementVisible */.J9)(elementNodes[index].userNameField)) {
              setUserNameValue(resp, elementNodes[index].userNameField);
            }
            clearInterval(unameInterval);
            applyMappings(resp);
          }
        }, 500);
      }
    }
    if (elementNodes[index].passwordField
      && elementNodes[index].passwordField.value !== resp.password) {
        if ((0,visibility_helpers/* isElementVisible */.J9)(elementNodes[index].passwordField, true)) {
          sendKeystrokes(elementNodes[index].passwordField, resp.password);
          elementNodes[index].passwordField.value = resp.password;
          contentscript_password = resp.password;
        }
      attachMutation(elementNodes[index].passwordField, resp);

      if (document.readyState !== "complete") {
        const pwdInterval = setInterval(() => {
          if (document.readyState === "complete") {
            if (resp.mappings) {
              if (resp.mappings.length > 0 && !elementNodes[index].passwordField.value) {
                applyMappings(resp);
              }
            }
            clearInterval(pwdInterval);
          }
        }, 500);
      }
    }
  }
}

/**
* callback function when clicked on secret from
* secret list. It sends message to get password.
*/
function attachOnSecretClickEvent() {
  if (shadowElement) {
    const elements = shadowElement.querySelectorAll(".Rectangle-Inner");
    for (let j = 0; j < elements.length; j++) {
      const secretId = elements[j].id.split("_")[1];
      elements[j].addEventListener("click", () => {
        getSecretState(secretId, handleLaunchSecret);
        const container = (0,common.$)("#WPF-shadow-root");
        if (container) {
          container.parentNode.removeChild(container);
        }
      });
    }
  }
}

/**
 * getSecretState
 * @param {*} secretId
 * @param {*} handler
 */
function getSecretState(secretId, handler, token) {
  ext_default().runtime.sendMessage({
    method: "getSecretState",
    secretId,
    token,
  }, handler);
}

/**
 * getTicketSystem
 * @param {*} secretId
 * @param {*} handler
 */
function getTicketSystem(handler) {
  ext_default().runtime.sendMessage({
    method: "getTicketSystem",
  }, handler);
}

/**
   * showMFAChallenge
   * @param {*} result
   */
function showMFAChallenge(result) {
  if (serverType === constants.SERVER_TYPE.SS) {
    showErrorPop(errors/* ERR */.s.MFA_REQUIRED);
  } else {
    showRequireMFA(errors/* ERR */.s.MFA_REQUIRED, result);
  }
}

function getMFAChallenge(result, handler) {
  ext_default().runtime.sendMessage({
    method: "loginMFAChallenge",
    secretId: result.id,
    actionName: handler.name,
    fromContent: "fromcontent",
    secretListAction: result.secretListAction,
  }, handler);
}
/**
* handleLaunchSecret
* @param {*} result
*/
function handleLaunchSecret(result, request = {}) {
  if (!(result && result.id && result.secretState)) return;
  if (request.response?.secretListAction) {
    result.secretListAction = request.response.secretListAction;
  }
  if (result.secretState.toLowerCase() === constants.secretStates.none
    || result.secretState.toLowerCase() === constants.secretStates.requiresCheckout) {
    let frameId = 0;
    if (shadowElement) {
      const frameEle = shadowElement.getElementById("thy-selected-frameId");
      if (frameEle) {
        frameId = parseInt(frameEle.value);
      }
    }
    ext_default().runtime.sendMessage({
      method: "GetPassword",
      secretId: result.id,
      url: targetUrl,
      referrer: document.referrer,
      selectedframeId: frameId,
      isPasswordHiddenOnPage: !isPasswordOnPage(),
      isOtpHiddenOnPage: !isOtpOnPage(),
      singleSecret: request.singleSecret,
      secrets: request.secrets,
      secretAction: result.secretListAction || result.action,
      isGenerateOneTimePasswordPresent: Array.isArray(result.actions) && result.actions.includes("GenerateOneTimePassword"),
    });
    return;
  }

  handleSecretState(result);
}

/**
* handleTicketSystem
* @param {*} result
* @param {*} stateResponse
*/
function handleTicketSystem(result, stateResponse) {
  if (!result) return;
  if (!(stateResponse.id && stateResponse.secretState)) return;
  showRequireCommentPop(stateResponse.id, stateResponse.secretState, result, stateResponse.secretListAction);
}

/**
   * handleSecretState
   * @param {*} result
   * @param {*} action
   */
function handleSecretState(result) {
  if (!result || !result.secretState) return;
  switch (result.secretState.toLowerCase()) {
    case constants.secretStates.requiresMFAChallenge:
      showMFAChallenge(result);
      break;
    case constants.secretStates.requiresComment:
    case constants.secretStates.requiresCheckoutAndComment:
      getTicketSystem((ticketResult) => handleTicketSystem(ticketResult, result));
      break;
    case constants.secretStates.requiresApproval:
      showErrorPop(errors/* ERR */.s.requiresApprovalNotSupported(serverType));
      break;
    default:
      showErrorPop(errors/* ERR */.s.unknownSecretState(serverType));
      break;
  }
}

/**
* filters the input elements and returns the username input filed.
* @param {HTMLElement} passwordField password field for which
* paired username field  needs to be searched.
* @return {boolean}
*/
function getUsernameField(passwordField) {
  let form = passwordField && passwordField.closest && passwordField.closest("form");
  const pwdForm = form;
  if (!form || form.length === 0) {
    form = passwordField && passwordField.closest && passwordField.closest("body");
  }
  const excludeList = ["reset", "file", "button", "checkbox", "radio",
    "submit", "hidden", "image", "datetime", "datetime-local", "date",
    "month", "time", "week", "number", "range", "color", "password",
    "Password",
  ];
  const removeInputsId = ":not([id^=\"search\"])";
  const usernameFilters = [`input:not([type="${excludeList.join("\"]):not([type=\"")
  }"]):not([id^="search"])${removeInputsId}`, "textarea",
  ];
  const excludeOtpList = ["reset", "file", "button", "checkbox", "radio",
    "submit", "hidden", "image", "datetime", "datetime-local", "date",
    "month", "time", "week", "number", "range", "color",
  ];
  const otpFilters = [`input:not([type="${excludeOtpList.join("\"]):not([type=\"")
  }"]):not([id^="search"])${removeInputsId}`, "textarea",
  ];
  const possibleUsernames = form && form.querySelectorAll(usernameFilters);
  const possibleOtp = form && form.querySelectorAll(otpFilters);
  const ignoreRegEx = /(thy-input)/;
  findLoginButton(form);
  passwordField && passwordField.addEventListener && passwordField.addEventListener("keyup", (event) => {
    if (!isLoggedin) {
      return;
    }
    contentscript_password = passwordField.value;
    isNewSecretAdded = false;
  });

  let UFields = getBestMatch(possibleUsernames);
  const otpField = getBestOtpMatch(possibleOtp);
  for (let i = 0; i < UFields.length; i++) {
    if (!isWindowsAdminCenter() && (UFields[i].disabled || UFields[i].readOnly)) {
      continue;
    }

    const isEle = (0,visibility_helpers/* isElementVisible */.J9)(UFields[i]);
    if (isEle || UFields.length === 1) {
      if (!isEle
        && !UFields[i].classList.contains("Delinea_SS_UsernameField")) {
        setTimeout(() => {
          processFormElements();
          // We have added icon to hidden username,
          // which appears approximately after 1 sec.
        }, 1500);
      }
      if(isCurrentSSTabloggedIn) {
        return;
      }
      markUsername(UFields[i], passwordField, otpField);
      return isEle;
    }
  }
  if (UFields.length === 0) {
    if (pwdForm) {
      const visibleIndex = [];
      const pwdFormEle = pwdForm.querySelectorAll(usernameFilters);
      for (let v = 0; v < pwdFormEle.length; v++) {
        if (otpField && otpField.includes(pwdFormEle[v])) {
          continue;
        }

        if ((0,visibility_helpers/* isElementVisible */.J9)(pwdFormEle[v])) {
          visibleIndex.push(v);
        }
      }

      if (visibleIndex.length === 1 && !pwdFormEle[visibleIndex[0]].className.match(ignoreRegEx)) {
        markUsername(pwdFormEle[visibleIndex[0]], passwordField, otpField);
        return true;
      }
    } else if (possibleUsernames && possibleUsernames.length == 1) {
      UFields = getBestMatch([possibleUsernames[0].parentElement]);
      if (UFields.length === 1 && (0,visibility_helpers/* isElementVisible */.J9)(UFields[0])) {
        markUsername(possibleUsernames[0], passwordField, otpField);
        return true;
      }
    }
  }

  if(!passwordField.id?.includes('thyinput')) {
    elementNodes.push({
      userNameField: null,
      passwordField,
      otpField,
    });
  }
}

document.addEventListener("visibilitychange", () => {
  if (isLoggedin) {
    toggleFavIcon(true);
  }
}, false);

/**
 *
 * @param {*} form
 */
function findLoginButton(form) {
  // eslint-disable-next-line
  if (!form) return;
  const selector = "button[type=\"submit\"], input[type=\"submit\"], button, input[type=\"button\"], input[type=\"image\"], *[type=\"submit\"]";
  let btns = form.querySelectorAll(selector);
  
  if (btns.length === 0 && form.nextSibling
    && form.nextSibling.querySelectorAll) {
    btns = form.nextSibling.querySelectorAll(selector);
  }
  if (btns.length === 0 && form.elements) {
    for (let index = 0; index < form.elements.length; index++) {
      if (form[index].type === "submit") {
        form[index].addEventListener("click", handleSubmit);
      }
    }
  }
  if(btns.length === 1 && !(0,visibility_helpers/* isElementVisible */.J9)(btns[0]))
    {      
        btns = document.querySelectorAll(selector);// Move to the next sibling if it's not a button/input
    }      
  const loginButtonRegEx = /(log.?in|log.?in to$|sign.?in$|sign.?in to|sign.?on$|sign.?on to$|submit|continue$|go$|next$|inloggen|sign.?|connect|proceed)/;
  for (let k = 0; k < btns.length; k++) {
    const btnInnerText = btns[k].innerText || "";
    const btnId = btns[k].id || "";
    const btnValue = btns[k].value || "";
    if (btnInnerText.toLowerCase().match(loginButtonRegEx)
      || btnId.toLowerCase().match(loginButtonRegEx)
      || btnValue.toLowerCase().match(loginButtonRegEx)) {
      btns[k].addEventListener("click", handleSubmit);
    }
  }

  let linkElem = form.querySelectorAll("a, span");
  if (linkElem.length === 0) {
    if (form.nextElementSibling
      && form.nextElementSibling.querySelectorAll) {
      linkElem = form.nextElementSibling.querySelectorAll("a, span");
    }
  }

  // eslint-disable-next-line
  if (linkElem.length > 0) {
    for (let j = 0; j < linkElem.length; j++) {
      const eleinnertext = linkElem[j].innerText;
      if (eleinnertext.toLowerCase().match(loginButtonRegEx)) {
        if (!Array.from(btns).find((node) => node === linkElem[j].parentElement)) {
          linkElem[j].addEventListener("click", handleSubmit);
        }
      }
    }
  }
}

/**
   * markUsername
   * @param {*} uElement
   * @param {*} pElement
   */
function markUsername(uElement, pElement, otpElement) {
  if (uElement) {
    const possibleUNamePWDPair = {
      userNameField: uElement,
      passwordField: pElement,
      otpField: otpElement,
    };
    elementNodes.push(possibleUNamePWDPair);
    addBackgroundImage(uElement);
    if (otpElement && otpElement.length > 0) {
      timer/* default */.A.markOtpField(otpElement[0]);
    }
    // Detect Delinea icon space in username and
    // set cursor and click event.

    if (!uElement?.addEventListener) return;
    uElement.addEventListener("mousemove", onMouseMove);
    uElement.addEventListener("keyup", () => {
      if (!isLoggedin) {
        return;
      }
      username = uElement.value;
      isNewSecretAdded = false;
    });
  }
}

/**
 * onMouseMove
 * @param {object} event
 */
function onMouseMove(event) {
  const rect = event.target.getBoundingClientRect();
  const padding = parseInt(getComputedStyle(event.target).paddingRight);
  const textX = rect.left + rect.width - (padding + 25);
  if (event.clientX >= textX) {
    event.target.style.cursor = "pointer";
    event.target.addEventListener("click", showSecret);
  } else {
    event.target.removeEventListener("click", showSecret);
  }
}

/**
* showRecordingIcon
*/
function showRecordingIcon() {
  toggleFavIcon(false);
  setTimeout(() => {
    toggleFavIcon(true);
  }, 450);
  if (!isMouseMoveEventAdded) {
    beingRecorded = true;
    isMouseMoveEventAdded = true;
    document.addEventListener("mousemove", recordingMouseMove);
  }
}

/**
* Get the required details from storage
*/
function pageLoad() {
  storage/* default */.A.get("Configurations", (items) => {
    if (items.Configurations && items.Configurations.ssUrl) {
      let ssUrl = (0,url_helpers/* appendPath */.mR)(items.Configurations.ssUrl, "").toLowerCase();
      const url = new URL((0,url_helpers/* addDefaultProtocol */.ZG)(ssUrl));
      ssUrl = (0,url_helpers/* removeLastSlash */.ws)(ssUrl.replace("http://", ""));
      if (!url.port) {
        ssUrl = ssUrl.replace(":80", "").replace(":443", "");
      }
      calculateWindowWidthHeight(items);
      let { baseURI } = document;
      if (baseURI && baseURI.toLowerCase().startsWith(ssUrl)) {
        baseURI = baseURI.toLowerCase().replace(/\/app\/$/i, "");
        if (baseURI === ssUrl) {
          setTimeout(() => {
            // Secret server redirects to passwordexpired.aspx
            // after 2-3 seconds so added delay.
            checkIfSSLoggedIn(ssUrl);
          }, 3000);
        }
        readAndSendSAMLToken();
        attachSecretUrlClick(ssUrl);
        if (document.head) {
          document.head.appendChild(addFontFace());
        }
      }
      ext_default().runtime.sendMessage(
        { method: "IsLoggedIn" },
        (response) => {
          isLoggedin = response.isLoggedIn;
          if (isLoggedin) {
            storage/* default */.A.get("Settings", (theSettings) => {
              if (theSettings) {
                Settings = theSettings.Settings;
                if (Settings && Settings.exactMatchUrl) {
                  checkExactMatch(domLoaded, false);
                } else {
                  domLoaded();
                }
              } else {
                domLoaded();
              }
            });
            ext_default().runtime.sendMessage(
              { method: "checkWPFServerType" },
              (response) => {
                if (response) {
                  serverType = response;
                }
              },
            );
          }
        },
      );
    }
    if (items.Configurations && items.Configurations.url) {
      if (window.location.href.indexOf(items.Configurations.url) !== 0) return;
      login_mfe_handler.checkLoginMfe();

      attachSecretUrlClick(items.Configurations.url);
    }
  });
}

if (document.readyState === "complete"
  || document.readyState === "interactive") {
  pageLoad();
}
window.addEventListener("DOMContentLoaded", () => {
  pageLoad();
  // retrieveSettings(chrome.runtime.getURL('./handlers/wac-handler.js'), 'body');
});

// function injectScript(file, node) {
//   const th = document.getElementsByTagName(node)[0];
//   const s = document.createElement('script');
//   s.setAttribute('type', 'text/javascript');
//   s.setAttribute('src', file);
//   th.appendChild(s);
// }
/**
   * checkExactMatch
   * @param {function} fun
   * @param {boolean} isContextSecretRefresh
   */
function checkExactMatch(fun, isContextSecretRefresh) {
  ext_default().runtime.sendMessage(
    { method: "checkExactMatch", isContextSecretRefresh },
    (response) => {
      if (response && response.urlExactMatchAvailable) {
        urlExactMatchAvailable = true;
      } else {
        urlExactMatchAvailable = false;
      }
      fun();
    },
  );
}

/**
   * calculate the window height and width
   * @param {*} items
   */
function calculateWindowWidthHeight(items) {
  let windowHeight;
  let windowWidth;
  const loginElement = document.getElementsByClassName("login-form");
  if (loginElement.length > 0) {
    windowHeight = document.getElementsByClassName("login-form")[0].scrollHeight;
    windowWidth = document.getElementsByClassName("login-form")[0].scrollWidth;
  } else if (document.body) {
    windowHeight = document.body.scrollHeight;
    windowWidth = document.body.scrollWidth;
  }
  if (windowHeight % 2 == 0) {
    windowHeight += 100;
  } else {
    windowHeight += 101;
  }
  if (windowWidth % 2 == 0) {
    windowWidth += 100;
  } else {
    windowWidth += 101;
  }
  if (loginElement.length > 0) {
    ext_default().runtime.sendMessage({
      method: "getWindowWidthAndHeight",
      winWidth: windowWidth,
      winHeight: windowHeight,
      configURL: items.Configurations.ssUrl,
    });
  }
}

/**
   * getPathTo
   * @param {*} element
   * @return {string}
   */
function getPathTo(element) {
  const idx = (sib, name) => (sib ? idx(sib.previousElementSibling, name || sib.localName) + (sib.localName == name) : 1);
  const segs = (elm) => (!elm || elm.nodeType !== 1 ? [""] : elm.id && document.getElementById(elm.id) === elm ? [`//*[@id="${elm.id}"]`] : [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm)}]`]);
  return segs(element).join("/");
}

/**
   * domLoaded
   *
   */
function domLoaded() {
  if (window.parent !== window && (window.innerHeight === 0)) {
    return;
  }
  // Event to check if security policy violated.
  document.addEventListener("securitypolicyviolation", (e) => {
    isCspViolated = true;
  });

  if (!isCspViolated && document.head) {
    document.head.appendChild(addFontFace());
    checkIfWindowsAdminCenter();
  }
  document.addEventListener("mousedown", mousedownCallback);

  if (isLoggedin && document.body) {
    ext_default().runtime.sendMessage(
      { method: "DoIExcluded" },
      (response) => {
        if (response && !response.excluded) {
          if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
            removeFlag();
          }
          if (isValidForm()){
            processFormElements();
          }          
          observer = new MutationObserver((mutations) => {
            clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(() => {
              if (!isValidForm()) {
                return;
              }
              if (skipWPFMutations(mutations)) {
                return;
              }
              ext_default().runtime.sendMessage(
                { method: "DoIExcluded" },
                (response) => {
                  if (response && !response.excluded) {
                    if (Settings && Settings.exactMatchUrl) {
                      checkExactMatch(processFormElements);
                    } else {
                      processFormElements();
                    }
                  }
                },
              );
            }, 300);
          });
          observer.observe(document.body, {
            childList: true,
            subtree: true,
            attributes: false,
          });
          ext_default().runtime.sendMessage({
            method: "PageRedirect",
          });
        } else {
          removeFont();
          hideContextMenu = true;
          if (observer) {
            observer.disconnect();
          }
        }
      },
    );
  }
}

/**
   * skipWPFMutations
   * @param {object} mutations
   * @return {boolean}
   */
function skipWPFMutations(mutations) {
  if (mutations.length > 0) {
    if (mutations[0].addedNodes.length > 0
      && mutations[0].addedNodes[0].id === "WPF-shadow-root") {
      return true;
    } if (mutations[0].removedNodes.length > 0
      && mutations[0].removedNodes[0].id === "WPF-shadow-root") {
      return true;
    } if (mutations[0].previousSibling
      && mutations[0].previousSibling.id === "WPF-shadow-root") {
      return true;
    }
  }
  return false;
}

/**
* displays the add secret form.
*/
function showAddSecretForm() {
  if (document.head) {
    document.head.appendChild(addFontFace());
  }
  let hostDiv = (0,common.$)("#WPF-shadow-root");
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }
  hostDiv = createHostElement();
  hostDiv.setAttribute("id", "WPF-shadow-root");
  hostDiv.style.paddingBottom = "10px";
  hostDiv.style.width = "350px";
  hostDiv.style.top = "5px";
  hostDiv.style.right = "10px";
  shadowElement = hostDiv.shadowRoot;
  let element = shadowElement.getElementById("delinea-container");
  if (element && element.remove) {
    element.remove();
  }

  if (!element) {
    element = document.createElement("div");
    element.style.display = "none";
    element.setAttribute("id", "delinea-container");
    element.innerHTML = `
<div id="delinea-inner-container" >
<div id="div-Signinas" class="Sign-in-as">
<span id="spSigninas" >Sign in as</span>
<input type='button' class="refresh-secret" value='&#10227;' id="thy-refresh-secret">
 </input>
</div>
<div id="thy-secret-container" class="secretpopup"> </div>
</div>`;
    shadowElement.appendChild(element);
    shadowElement
      .getElementById("delinea-inner-container").style.display = "none";
    createAddSecretPopup(element);
  }
  setTemplates();
  setDefaultTemplateValue();
  chooseTemplateClick();
  if ((0,common.$)("#WPF-shadow-root").style && (0,common.$)("#WPF-shadow-root").style.display) {
    (0,common.$)("#WPF-shadow-root").style.display = "block";
  }
  shadowElement.getElementById("delinea-container")
    .style.display = "block";
  shadowElement.getElementById("add-secret-container")
    .style.display = "block";
  const innerContainer = shadowElement.getElementById("delinea-inner-container");
  getSiteIconUrl(shadowElement);
  if (innerContainer) {
    innerContainer.style.display = "none";
  }
}

/**
* Creats the the template and folder selection selection form  and container
* for Secret addition form.
* @param {HTMLElement} container1 The first number.
*/
function createAddSecretPopup(container1) {
  const webIconUrl = ext_default().runtime.getURL("icons/web.svg");
  const handleIconUrl = ext_default().runtime.getURL("icons/handle.svg");
  const container = document.createElement("div");
  container.setAttribute("id", "add-secret-container");
  container.setAttribute("class", "add-secret-details-container");
  container.innerHTML = `
    <div id="chooseTemplate">
    <div class="header"  >
    <a href="#" class="cancel-secret-btn" >
      <span  id="thy-cancel-choose-template-popup" class="save-cancel-text">Cancel</span>
    </a>
    <div><img  src="${handleIconUrl}" alt="" /></div>
    <div class="save-popup">
      <a href="#" class="save-popup-btn ss-Add-secret-button"
      id="thy-btn-next">
        <span class="save-cancel-text">Next</span>
      </a>
    </div>
  </div>
    <div class="input-field input-label">
    <label>Template</label>
    <input  type="text" id="thy-add-template1"
    name="template" class="inp">
  </div>
  </div>
    <div id="add-secret-template-fields">
    <div class="header"  >
    <a href="#" class="cancel-secret-btn" >
      <span id="thy-cancel-secret-popup"  class="save-cancel-text">Cancel</span>
    </a>
    <div><img  src="${handleIconUrl}" alt="" /></div>
    <div class="save-popup">
      <a href="#" class="save-popup-btn ss-Add-secret-button"
      id="thy-add-secret-popup">
        <span class="save-cancel-text">Save</span>
      </a>
    </div>
  </div>
  <div class="add-secret-details-header">
  <div class="add-secret-details-secret-header">
    <img class="web-icon siteImage" src="${webIconUrl}" />
  </div>
  <div class="add-secret-details-secret-name">
  <input type="text" id="thy-add-SecretName" name="secretName"
   class="secretname-input" title=${window && window.location && window.location.host}
  autocomplete="off" placeholder=""  value=${window && window.location && window.location.host}
  class=" required"/>
  </div>
</div>

      <div class="add-secrets-details-container">

     <div class="add-secret-template-fields">
    </div>


    </div>
    </div>
   `;
  container1.appendChild(container);
  if (shadowElement && shadowElement.getElementById) {
    shadowElement.getElementById("add-secret-template-fields").style.display = "none";
  }
  onCancelChooseTemplate();
  onTemplateChange();
  onSecretNameInput();
  preventShortcutKeys(shadowElement);
}

function onSecretNameInput() {
  if (shadowElement) {
    const sName = shadowElement.getElementById("thy-add-SecretName");
    if (sName) {
      sName.addEventListener("input", resizeInput);
      resizeInput.call(sName);
    }
  }
}

function resizeInput() {
  this.style.width = `${this.value.length + 3}ch`;
}

/**
* callback function for click event of save secret button.It sends data to
* background.js to for secret addion API.
* @param {array} fields fields of template selected forSecret Addition form.
*/
function onSaveSecret() {
  if (shadowElement) {
    const btnAddSecret = shadowElement.getElementById("thy-add-secret-popup");
    btnAddSecret.addEventListener("click", onAddSecretClick);
  }
}

/**
 * onAddSecretClick
 * @param {object} e
 */
function onAddSecretClick(e) {
  e.preventDefault();
  if (shadowElement) {
    if (!selectedTemplate || !selectedTemplate.fields) {
      return;
    }
    const secretTemplateId = shadowElement && shadowElement.getElementById("thy-add-template1") && shadowElement.getElementById("thy-add-template1")
      .getAttribute("selected-id");
    const secretFolderId = shadowElement && shadowElement.getElementById("thy-add-folder") && shadowElement.getElementById("thy-add-folder")
      .getAttribute("selected-id");

    const secretSiteId = shadowElement && shadowElement.getElementById("drp-thy-add-sites") && shadowElement.getElementById("drp-thy-add-sites")
      .getAttribute("selected-id");

    const secretName = shadowElement && shadowElement.getElementById("thy-add-SecretName") && shadowElement.getElementById("thy-add-SecretName")
      .value.trim();
    if (secretName && secretTemplateId && validateSecretFields()) {
      const secretData = {
        data : {
          name: secretName,
          folderId: secretFolderId ? parseInt(secretFolderId) : -1,
          site: parseInt(secretSiteId),
          active: true,
          templateId: parseInt(secretTemplateId),
          fields: [],
          enableInheritSecretPolicy: true,
        }
      };
      const mappingInfo = [];
      const { fields } = selectedTemplate;
      for (let k = 0; k < fields.length; k++) {
        if (!fields[k].isFile) {
          const secretField = shadowElement.getElementById(`thy-${fields[k].fieldSlugName}`);
          const secretItem = {
            slug: fields[k].fieldSlugName,
            value: secretField.value,
          };
          secretData.data.fields.push(secretItem);
          const mappingContainer = shadowElement.getElementById(`hint-${fields[k].fieldSlugName}`);
          if (mappingContainer) {
            const xpath = mappingContainer.getAttribute("title");
            mappingInfo.push({
              fieldName: fields[k].fieldSlugName,
              fieldValue: xpath,
              xpath,
            });
          }
        }
      }
      ext_default().runtime.sendMessage({
        method: "createSecret",
        data: secretData,
        mappingInfo,
      });
      isNewSecretAdded = true;
    }
  }
}

/**
* Validates the add secret form.
* @param {int} fields T fields for the given template.
* @return {bool} Add secret form is valid or not.
*/
function validateSecretFields() {
  if (!selectedTemplate || !selectedTemplate.fields) {
    return false;
  }
  const { fields } = selectedTemplate;
  for (let k = 0; k < fields.length; k++) {
    if (fields[k].isRequired) {
      const secretField = shadowElement.getElementById(`thy-${fields[k].fieldSlugName}`);
      if (!secretField || secretField.value.trim() == "") {
        return false;
      }
    }
  }
  return true;
}

/**
* call back function for cancel secret button click event.
*/
function onCancelSaveSecret() {
  const btnCancelSecret = shadowElement.getElementById("thy-cancel-secret-popup");
  if (!btnCancelSecret?.addEventListener) return;
  btnCancelSecret.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    shadowElement.host.remove();
    shadowElement = null;
  });
}

/**
* call back function for cancel choose template popup button click event.
*/
function onCancelChooseTemplate() {
  const btnCancelSecret = shadowElement && shadowElement.getElementById("thy-cancel-choose-template-popup");
  btnCancelSecret && btnCancelSecret.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    shadowElement.host.remove();
    shadowElement = null;
  });
}

/**
* loadAddSecretForm.
* @param {*} e
*/
function loadAddSecretForm(e) {
  e.preventDefault();
  setFolders();
  setSites();
  setDefaultFolderAndSiteValues();
  onCancelSaveSecret();
  if (shadowElement.getElementById("chooseTemplate")) {
    shadowElement.getElementById("chooseTemplate").style.display = "none";
  }
  shadowElement.getElementById("delinea-inner-container")
    .style.display = "none";
  shadowElement.getElementById("add-secret-template-fields")
    .style.display = "block";
  requiredFieldInput();
  preventShortcutKeys(shadowElement);
}

/**
*sets default value for  folder
*/
function setDefaultFolderAndSiteValues() {
  if (!shadowElement) {
    return;
  }

  const folderCtrl = shadowElement.getElementById("thy-add-folder");
  const siteCtrl = shadowElement.getElementById("drp-thy-add-sites");

  if (window.parent === window && folderCtrl) {
    if (personalFolder) {
      folderCtrl.value = personalFolder.folderName;
      folderCtrl.setAttribute("selected-id", personalFolder.id);
    }

    if (Sites && Sites.length > 0) {
      siteCtrl.value = Sites[0].siteName;
      siteCtrl.setAttribute("selected-id", Sites[0].siteId);
    }
  }
}
/**
* callback function for change template button click event.
*/
function onTemplateChange() {
  const txtTemplate = shadowElement && shadowElement.getElementById("thy-add-template1");
  txtTemplate && txtTemplate.addEventListener("change", templateTextChange);
}

function templateTextChange(e) {
  toggleChooseTemplateButton(!(e.target.getAttribute("selected-id")
    && e.target.value.trim()));
}

/**
* attaches secret name fields input event
*/
function triggerSecretNameInputEvent() {
  const secretName = shadowElement.getElementById("thy-add-SecretName");
  secretName.dispatchEvent(new Event("input"));
}

/**
* attaches callback function to generate password button.
*/
function attachOnGeneratePassword() {
  const btnGenPWDs = shadowElement.querySelectorAll(".btnGenPWD");
  for (let l = 0; l < btnGenPWDs.length; l++) {
    btnGenPWDs[l].addEventListener("click", (e) => {
      ext_default().runtime.sendMessage({
        method: "GeneratePassword",
        fieldId: e.target.getAttribute("for"),
        templateFieldId: e.target.getAttribute("fieldId"),
      });
    });
  }
}

/**
* toggle Choose Template Button.
* @param {int} status The first number.
*/
function toggleChooseTemplateButton(status) {
  const btnNext = shadowElement.getElementById("thy-btn-next");
  if (!btnNext) return;
  if (!status) {
    btnNext.setAttribute("href", "#");
    btnNext.addEventListener("click", loadAddSecretForm);
    btnNext.removeAttribute("disabled");
    btnNext.classList.remove("disabled");
  } else {
    btnNext.removeAttribute("href");
    btnNext.removeEventListener("click", loadAddSecretForm);
    btnNext.setAttribute("disabled", true);
    btnNext.classList.add("disabled");
  }
}

/**
* adds the message listner for the messages send from background.js.
* @param {Object} request The first number.
* @param {Object} sender sender
* @param {Object} callback callback function
* @return {boolean}
*/
function setMessageListner(request, sender, callback) {
  switch (request.method) {
    case "loggedIn":
      isLoggedin = request.response;
      if (!isLoggedin) {
        removeDelineaIcon();
      }
      break;
    case "logOff":
      removeDelineaIcon();
      removeFont();

      break;
    case "launcherAvailable":
      if (!request.response) {
        showErrorPop(errors/* NOTIFY */.W.LOGIN_REQUIRED);
      }
      break;
    case "notify":
      const temp = setInterval(() => {
        if (window.parent === window
          && (document.readyState === "complete"
            || document.readyState === "interactive")) {
          storage/* default */.A.get("Settings", (items) => {
            if (items.Settings.set_Prompt_to_save_credentials) {
              const BlockWebSite = JSON.parse(
                window.localStorage.getItem("BlockWebSite") || "[]",
              );
              if (BlockWebSite.filter((site) => site == window.location.host).length === 0) {
                gpswd = request.response.data.password;
                gusername = request.response.data.username;
                gurl = request.response.data.reqUrl;
                serverType = request.serverType;
                addNewSecretPopup(
                  request.response.data,
                  request.response.isEdit,
                );
              }
            }
            clearInterval(temp);
          });
        }
      }, 200);

      break;
    case "gotPassword":
      setUserNamePWD(request.response, request && request.sender && request.sender.secretId);
      beingRecorded = (request?.response?.useSessionRecording
        || request?.response?.autoFillData?.model?.useSessionRecording);
      if (beingRecorded) {
        showErrorPop(errors/* NOTIFY */.W.SESSION_RECORDED);
      }
      break;
    case "GotSecrets":
      if (window.parent === window) {
        handleRequest(request);
      }
      break;
    case "passwordGenerated":
      fillGeneratedPassword(request.response);
      break;
    case "isPasswordHiddenOnPage":
      callback(!isPasswordOnPage());
      break;
    case "GotTemplatesNFolders":
      setTemplatesNFolders(request.response);
      break;
    case "loadingTemplates":
      showErrorPop(errors/* NOTIFY */.W.LOADING_TEMPLATES, false);
      break;
    case "copyMsg":
      showErrorPop(errors/* NOTIFY */.W.COPYMSG(request.response.secretAction));
      (0,common/* writeToClipboard */.$L)(request.response.copyMsg);
      break;      
    case "clearStorage":
      clearStorage();
      break;
    case "gotSecretSaveError":
      removeFlag();
      if (shadowElement) {
        const errorMessage = shadowElement.getElementById("error-message");
        if (errorMessage) {
          if (request && request.response
            && request.response.errorCode === "API_InvalidSecretNamePattern") {
            const secretName = shadowElement.getElementById("thy-add-SecretName");
            if (secretName) {
              secretName.value = "";
            }
            errorMessage.innerText = errors/* ERR */.s.INVALID_SECRET_NAME_PATTERN(serverType);
          } else if (request && request.response
            && request.response.errorCode === "API_GenericException") {
            errorMessage.innerText = errors/* ERR */.s.PASSWORD_REQUIRMENT(request.response.message, serverType);
          } else if (request.response
            && request.response.errorCode === "API_AccessDeniedOnFolder") {
            errorMessage.innerText = errors/* ERR */.s.INVALID_FOLDER;
          } else {
            errorMessage.innerText = errors/* ERR */.s.SECRET_SAVE_FAILED(serverType);
          }
          errorMessage.classList.remove("hide");
        }
      }
      break;
    case "gotSecretUpdateError":
      showErrorPop(errors/* ERR */.s.SECRET_UPDATE_FAILED(serverType));
      break;
    case "gotSecretSavePopupError":
      showAddSecretForm();
      break;
    case "gotUnAuthorizeError":
      isLoggedin = false;
      if (request && request.response && request.response.includes("password has expired")) {
        showErrorPop(errors/* ERR */.s.PASSWORD_EXPIRED);
      } else {
        showErrorPop(request.response || errors/* ERR */.s.UNAUTHORIZE);
      }
      break;
    case "badRequest":
      showErrorPop(errors/* ERR */.s.BAD_REQUEST);
      break;
    case "gotSecretSave":
      showErrorPop(errors/* ERR */.s.SECRET_SAVED(serverType));
      break;
    case "gotSecretUpdatePassword":
      showErrorPop(errors/* ERR */.s.SECRET_UPDATED(serverType));
      break;
    case "removeMouseDown":
      removeDelineaIcon();
      document.removeEventListener("mousedown", mousedownCallback);
      break;
    case "showConfirmDialog":
      showConfirmDialog(request);
      break;
    case "retshowCopyToClipBoardMsg":
      showErrorPop(errors/* NOTIFY */.W.COPIED_TO_CLIPBOARD);
      break;
    case "retRemoveHostDiv":
      if (window === window.parent) {
        const event = new Event("mouseup");
        document.dispatchEvent(event);
      }
      break;
    case "gotInvalidTemplateError":
      showErrorPop(errors/* ERR */.s.INVALID_TEMPLATE);
      break;
    case "MFASecretDetails":
      getSecretState(request?.response?.secretId, (result) => handleLaunchSecret(result, request));
      break;
    case "contextSecretClicked":
      if (window.parent !== window) return;
      getSecretState(request.secretId, (result) => handleLaunchSecret(result, request));
      break;
    case "showError":
      showErrorPop(request.response);
      break;
    case "recording":
      showRecordingIcon();
      break;
    case "gotSitesError":
      break;
    case "contextSecretRefresh":
      removeUserPWDEvents();
      if (isLoggedin && document.body) {
        ext_default().runtime.sendMessage(
          { method: "DoIExcluded" },
          (response) => {
            if (response && !response.excluded) {
              storage/* default */.A.get("Settings", (theSettings) => {
                if (theSettings) {
                  Settings = theSettings.Settings;
                  if (Settings && Settings.exactMatchUrl) {
                    checkExactMatch(processFormElements, true);
                  } else {
                    processFormElements();
                  }
                }
              });
            }
          },
        );
      }
      break;
    case "confirmSwitchSecretServer":
      const settings = {
        iframe: { height: 130 },
        dialog: { position: "center", width: 450 },
      };
      openIframeDialog("confirm-switch-ss.html", settings);
      break;
    case "close-dialog":
      removeContainer("WPF-shadow-root");
      break;
    case "showAddSecretPopup":
      showAddSecretForm();
      break;
    case "multipleUrl":
      showMultipleUrlOnPopup(request.response);
      break;
    default:
      break;
  }
  // return true;
}

/**
   * removeFont
  */
function removeFont() {
  const font = document.getElementById("THY_WPF");
  if (font) {
    font && font.remove && font.remove();
  }
}
/**
   * recordingMouseMove
   * @param {*} event
   */
function recordingMouseMove(event) {

  if (!beingRecorded && isMouseMoveEventAdded) {
    isMouseMoveEventAdded = false;
    document.removeEventListener("mousemove", recordingMouseMove);
    return;
  }

  ext_default().runtime.sendMessage({
    type: "tabCapture",
    clientX: event.clientX,
    clientY: event.clientY,
  });
}

/**
   * hardcore html
   * @param {*} response
   */
function showMultipleUrlOnPopup(response) {
  let hostPopupDiv = (0,common.$)("#WPF-shadow-root");
  if (hostPopupDiv) {
    hostPopupDiv.remove();
  }
  hostPopupDiv = createHostElement();
  hostPopupDiv.setAttribute("id", "WPF-shadow-root");
  hostPopupDiv.style.paddingBottom = "10px";
  shadowElement = hostPopupDiv.shadowRoot;
  let thyContainerElement = shadowElement
    .getElementById("delinea-container");
  if (thyContainerElement) {
    thyContainerElement.remove();
  }

  const iconUrl = ext_default().runtime.getURL("icons/delinea-logo.svg");
  thyContainerElement = document.createElement("div");
  thyContainerElement.setAttribute("id", "delinea-container");
  thyContainerElement.classList.add("thy-wpf-confirm-dialog");
  thyContainerElement.innerHTML = `<div id="delinea-inner-container">
        <div class="Sign-in-as" style="font-family:Manrope" >
        <div>Select URL:</div>
       <div>
        <input type="text" class="urlInp" id="drp-url">
        </div>
        <br/>
        <br/>
        </div>
        <div class="div-fields">
        <img class="site-logo" src="${iconUrl}" />
        <button id="cancelLaunchUrl"
        class="cancel-ss-button "
        style="font-family:Manrope">Cancel</button>
        <button id="launchUrl"
        class="thy-wpf-ss-button"
        style="font-family:Manrope">Launch
        </button>
        </div>`;
  thyContainerElement.style.minWidth = "350px";
  thyContainerElement.style.right = "0px";
  shadowElement.appendChild(thyContainerElement);
  hostPopupDiv.style.top = "5px";
  hostPopupDiv.style.right = "5px";
  hostPopupDiv.style.display = "block";
  thyContainerElement.style.removeProperty("left");
  document.body.appendChild(hostPopupDiv);
  setDefaultUrlValue(response.urlList);
  setUrls(response.urlList);

  shadowElement.getElementById("cancelLaunchUrl")
    .addEventListener("click", () => {
      if (hostPopupDiv) {
        hostPopupDiv.remove();
      }
    });
  shadowElement.getElementById("launchUrl")
    .addEventListener("click", () => {
      const url = shadowElement.getElementById("drp-url").value;
      ext_default().runtime.sendMessage({
        method: "login_tab",
        newUrl: url,
        tab: response.tab,
        secretId: response.secretId,
        appPath: response.appPath,
      });
      if (hostPopupDiv) {
        hostPopupDiv.remove();
      }
    });
}

/**
* reset fav icon
* @param {boolean} reset
*/
function toggleFavIcon(reset) {
  if (!favIconUrl) {
    getSiteIconUrl();
  }

  let linkRecording = document.querySelectorAll(`
    link[type*="image/x-icon"],
    link[rel*="apple-touch-icon"],
    link[rel*="icon"],
    link[rel*="shortcut icon"]`);
  if (linkRecording.length === 0 && document.head) {
    let link = document.createElement("link");
    link.type = "image/x-icon";
    link.rel = "shortcut icon";
    (0,common.$)("head")[0].appendChild(link);
    linkRecording = [link];
  }
  if (reset) {
    for (let i = 0; i < linkRecording.length; i++) {
      if (linkRecording[i].href == constants.ICONS.RECORDING) {
        linkRecording[i].href = favIconUrl;
      }
    }
  } else {
    for (let i = 0; i < linkRecording.length; i++) {
      linkRecording[i].href = constants.ICONS.RECORDING
    }
  }
}

/**
* Set Templates and Folders along with Personal Folder and Web Password template
* @param {object} response
*/
function setTemplatesNFolders(response) {
  Templates = response.Templates;
  webPasswordTemplate = Templates[0];
  Folders = response.Folders;
  Sites = response.Sites;

  if (response && response.Folders && response.Folders.length > 0) {
    personalFolder = response.Folders.find((f) => f.isPersonalFolder === true);
    if (!personalFolder) {
      personalFolder = response.Folders[0];
    }
  }

  if (Templates.length === 0) {
    showErrorPop(errors/* NOTIFY */.W.NO_TEMPLATES);
  } else if (Folders && Folders.length === 0) {
    showErrorPop(errors/* NOTIFY */.W.NO_FOLDERS);
  } else if (response.fromContext && window.parent === window) {
    openSecretPopup();
    showAddSecretForm();
  }
}

/**
* adds autocomplete functionality to Template  textbox .
* @param {Array} templatesReturned
*/
function setTemplates() {
  const templates = Templates.map((val) => ({
    id: val.id,
    name: val.name,
  }));
  if (!shadowElement) {
    return;
  }
  const templateCtrl = shadowElement.getElementById("thy-add-template1");
  if (window.parent === window && templateCtrl) {
    autocomplete(templateCtrl, templates, shadowElement, () => {
      chooseTemplateClick();
      toggleChooseTemplateButton(false);
    });
  }
}

/**
*sets default value for template and folder
*/
function setDefaultTemplateValue() {
  if (!shadowElement) {
    return;
  }
  const templateCtrl = shadowElement.getElementById("thy-add-template1");
  if (window.parent === window && templateCtrl) {
    if (webPasswordTemplate) {
      templateCtrl.value = webPasswordTemplate.name;
      templateCtrl.setAttribute("selected-id", webPasswordTemplate.id);
      toggleChooseTemplateButton(false);
    }
  }
}

/**
* adds autocomplete functionality to folder  textbox.
* @param {Array} foldersReturned folders array.
*/
function setFolders() {
  const folders = Folders.map((val) => {
    let folderName = val && val.folderPath && val.folderPath.replace("Personal Folders\\", "");
    folderName = folderName && folderName.indexOf("\\") == 0 ? folderName.substring(1) : folderName;
    return {
      id: val.id,
      name: folderName,
    };
  });
  if (!shadowElement) {
    return;
  }
  const folderCtrl = shadowElement.getElementById("thy-add-folder");
  if (window.parent === window && folderCtrl) {
    autocomplete(folderCtrl, folders, shadowElement, () => {
      requiredFieldInput();
    }, { icon: constants.ICONS.FOLDER });
  }
}

/**
* adds site name in dropdown.
*/
function setSites() {
  const sites = Sites.map((val) => ({
    id: val.siteId,
    name: val.siteName,
  }));
  if (!shadowElement) {
    return;
  }
  const siteCtrl = shadowElement.getElementById("drp-thy-add-sites");
  if (window.parent === window && siteCtrl) {
    autocomplete(siteCtrl, sites, shadowElement, () => {
      requiredFieldInput();
    });
  }
}

/**
* adds url list in dropdown.
* @param {*} Urls
*/
function setUrls(Urls) {
  const urls = Urls && Urls.map && Urls.map((val) => ({
    name: val,
  }));
  if (!shadowElement) {
    return;
  }
  const urlCtrl = shadowElement.getElementById("drp-url");
  if (window.parent === window && urlCtrl) {
    autocomplete(urlCtrl, urls, shadowElement, "url");
  }
}

/**
* set default value to dropdown .
* @param {*} Urls
*/
function setDefaultUrlValue(Urls) {
  if (!shadowElement) {
    return;
  }
  const urlCtrl = shadowElement.getElementById("drp-url");
  if (window.parent === window && urlCtrl) {
    if (Urls && Urls.length > 0) {
      urlCtrl.value = Urls[0];
    }
  }
}
let selectedTemplate = null;
/**
* callback function for template and folder selection button.
*/
function chooseTemplateClick() {
  const txtTemplate = shadowElement.getElementById("thy-add-template1");
  const templateId = txtTemplate && txtTemplate.getAttribute("selected-id");
  selectedTemplate = Templates.find((template) => template.id == templateId);
  if (selectedTemplate) {
    const { fields } = selectedTemplate;
    const cont = shadowElement.getElementById("add-secret-template-fields");
    const markup = getAddNewSecretTemplateFieldsMarkup(fields);
    cont.innerHTML = markup;
    hideShowPWD(cont);
    attachOnDrag();
    attachOnGeneratePassword();
    markRequiredFields(fields);
    triggerSecretNameInputEvent();
    onSaveSecret(fields);
    onTemplateChange();
  }
  shadowElement.getElementById("delinea-inner-container")
    .style.display = "none";
}

/**
   * attachOnDrag()
   */
function attachOnDrag() {
  const dragLabels = shadowElement.querySelectorAll(".drag");
  dragLabels.forEach((x) => {
    x.addEventListener("dragstart", (evt) => {
      evt.dataTransfer.setData("text", evt.target.id);
    });
    x.addEventListener("mouseover", () => {
      if (shadowElement) {
        shadowElement.getElementById("thy-add-SecretName").focus();
      }
    });
  });
  attachDropEvent();
}

/**
 * attachDropEvent
 */
function attachDropEvent() {
  const inputEle = document.querySelectorAll("input");
  inputEle.forEach((x) => {
    x.addEventListener("drop", onInpuDrop);
  });
}

/**
 * attachDropEvent
 */
function removeDropEvent() {
  const inputEle = document.querySelectorAll("input");
  inputEle.forEach((x) => {
    x.removeEventListener("drop", onInpuDrop);
  });
}

/**
   * onInpuDrop
   * @param {*} evt
   */
function onInpuDrop(evt) {
  evt.preventDefault();
  const data = evt.dataTransfer.getData("text");
  const source = shadowElement.getElementById(data);
  const icon = source && source.nextElementSibling;
  if (icon) {
    icon.classList.remove("hide");
  }
  source && source.setAttribute("title", getPathTo(evt.target));
}

/**
* creates th html for selected template.
* @param {Array} fields of selected template fields.
* @return {string} returns the dynamically generated markup
* for secret addtion form.
*/
function getAddNewSecretTemplateFieldsMarkup(fields) {
  const eyeIconUrl = ext_default().runtime.getURL("icons/eye.svg");
  const hideEyeIconUrl = ext_default().runtime.getURL("icons/hide-eye.svg");
  const handleIconUrl = ext_default().runtime.getURL("icons/handle.svg");
  const webIconUrl = ext_default().runtime.getURL("icons/web.svg");
  const headerDiv = document.createElement("div");
  const block1 = document.createElement("div");
  block1.innerHTML = `
    <div class="header"  >
    <a href="#" class="cancel-secret-btn" >
      <span class="save-cancel-text" id="thy-cancel-secret-popup" >Cancel</span>
    </a>
    <div><img  src="${handleIconUrl}" alt="" /></div>
    <div class="save-popup">
      <a href="#" class="save-popup-btn ss-Add-secret-button" disabled
      id="thy-add-secret-popup">
        <span class="save-cancel-text">Save</span>
      </a>
    </div>
  </div>

  <div id="error-message" class="hide"></div>


  <div class="add-secret-details-header">
  <div class="add-secret-details-secret-header">
    <img class="web-icon siteImage" src="${webIconUrl}" />
  </div>
  <div class="add-secret-details-secret-name">
  <input type="text" id="thy-add-SecretName" name="secretName"
   class="secretname-input required" title="${window && window.location && window.location.host}"
  autocomplete="off" placeholder=""  value="${window && window.location && window.location.host}"/>
  </div>
</div>
<div class="add-secrets-details-container">
<div class="input-field input-label">
<label  >Folder</label>
<input type="text" id="thy-add-folder" class="inp required">
</div>

<div class="input-field input-label">
<label  >Site</label><span>
<input id="drp-thy-add-sites" class="inp required" type="text"
name="site-name">
</div>
</div>
`;
  headerDiv.appendChild(block1);
  const block2 = document.createElement("div");
  block2.innerHTML = "";
  let userNameField = "";
  let userNameIndex = -1;
  if (fields && fields.length) {
    for (let k = 0; k < fields.length; k++) {
      if (!fields[k].isUrl && !fields[k].isPassword && !fields[k].isNotes
        && !fields[k].isFile) {
        const userNameFieldDisplayList = ["user name", "username", "email",
          "email address", "tel", "telephone"];
        if (userNameFieldDisplayList.find((expression) => expression.includes(fields[k].displayName.toLowerCase()))) {
          userNameIndex = k;
          userNameField = `value="${gusername}"`;
          break;
        } else if (userNameField.length === 0) {
          userNameIndex = k;
          userNameField = `value="${gusername}"`;
        }
      }
    }

    for (let k = 0; k < fields.length; k++) {
      const isRequired = fields[k].isRequired ? "required" : "";
      const urlValue = (fields[k].isUrl && fields[k].isRequired) ? (gurl || targetUrl) : "";
      const displayName = sanitizeHtml(fields[k].displayName);
      const slugName = sanitizeHtml(fields[k].fieldSlugName);
      if (fields[k].isUrl) {
        const urlField = document.createElement('div');
        urlField.classList.add('input-field');
            
        const label = document.createElement('label');
        label.classList.add('field-label');
        label.textContent = displayName;
        urlField.appendChild(label);
    
        const input = document.createElement('input');
        input.type = 'text';
        input.id = `thy-${slugName}`;
        input.name = slugName;
        input.classList.add('inp', isRequired);
        input.value = urlValue;
        input.defaultValue = urlValue;        
        urlField.appendChild(input);
        
        block2.appendChild(urlField);  
      }else if (fields[k].isPassword) {
        const password = `  <div class="input-field">
         <div class="drag-container" >
         <span class="drag-tooltip"> Drag this to the ${displayName}
          field on the page </span>
         <span class="Add-Secret-lable drag" id="hint-${slugName}"
          draggable="true">${displayName}</span>
         <div class="drop-success hide"></div>
         </div>

        <div class="field-group">
        <input type="password"
        id="thy-${slugName}"
        name="${slugName}" data="fromThyWPF" `
          + `value="${String(gpswd).replace(/\"/g, "&quot;")}"`
          + ` class="inp  ${isRequired}"/>
        <svg for="thy-${slugName}" class="hide-show-pwd" width="25" height="19" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M17.94 17.94L18.5462 18.7353C18.7757 18.5604 18.9184 18.2949 18.9377 18.007C18.9571 17.7191 18.8511 17.4369 18.6471 17.2329L17.94 17.94ZM12 20V21C12.0054 21 12.0109 20.9999 12.0163 20.9998L12 20ZM0.999985 12L0.118829 11.5271C-0.0348048 11.8135 -0.039754 12.1566 0.105558 12.4472L0.999985 12ZM6.05998 6.05997L6.76709 5.35286C6.41287 4.99865 5.85122 4.96117 5.45308 5.26519L6.05998 6.05997ZM9.67207 3.26629C9.13432 3.39216 8.80043 3.93013 8.9263 4.46788C9.05217 5.00563 9.59015 5.33952 10.1279 5.21365L9.67207 3.26629ZM12 3.99997L11.9976 4.99997H12V3.99997ZM23 12L23.8819 12.4714C24.0348 12.1853 24.0395 11.8429 23.8944 11.5528L23 12ZM20.0748 14.5461C19.7192 14.9687 19.7736 15.5995 20.1961 15.9551C20.6187 16.3107 21.2496 16.2564 21.6051 15.8338L20.0748 14.5461ZM14.8516 14.8017C15.2281 14.3976 15.2058 13.7649 14.8017 13.3884C14.3976 13.0119 13.7649 13.0342 13.3884 13.4382L14.8516 14.8017ZM10.5617 10.6116C10.9658 10.2351 10.9881 9.60231 10.6116 9.19825C10.2351 8.79419 9.60232 8.77185 9.19826 9.14836L10.5617 10.6116ZM1.70709 0.292863C1.31657 -0.0976616 0.683402 -0.0976616 0.292878 0.292863C-0.0976464 0.683387 -0.0976464 1.31655 0.292878 1.70708L1.70709 0.292863ZM22.2929 23.7071C22.6834 24.0976 23.3166 24.0976 23.7071 23.7071C24.0976 23.3166 24.0976 22.6834 23.7071 22.2929L22.2929 23.7071ZM17.3338 17.1447C15.7941 18.3183 13.9193 18.9685 11.9836 19.0001L12.0163 20.9998C14.3789 20.9612 16.667 20.1677 18.5462 18.7353L17.3338 17.1447ZM12 19C8.89949 19 6.3955 17.2264 4.60452 15.316C3.71815 14.3706 3.03542 13.4213 2.5744 12.7074C2.34451 12.3515 2.17138 12.0566 2.05711 11.8535C2.00001 11.752 1.95772 11.6735 1.93049 11.6221C1.91688 11.5964 1.90705 11.5774 1.90102 11.5657C1.89801 11.5598 1.89595 11.5558 1.89485 11.5536C1.89429 11.5525 1.89398 11.5519 1.89391 11.5518C1.89387 11.5517 1.8939 11.5517 1.89398 11.5519C1.89402 11.552 1.89413 11.5522 1.89415 11.5522C1.89427 11.5525 1.89441 11.5528 0.999985 12C0.105558 12.4472 0.105726 12.4475 0.10591 12.4479C0.105991 12.4481 0.106191 12.4484 0.106355 12.4488C0.106683 12.4494 0.107072 12.4502 0.107524 12.4511C0.108427 12.4529 0.109577 12.4552 0.110975 12.4579C0.11377 12.4634 0.117554 12.4709 0.122323 12.4801C0.13186 12.4987 0.145341 12.5247 0.162738 12.5575C0.197525 12.6233 0.248008 12.7167 0.313956 12.834C0.445777 13.0683 0.639835 13.3985 0.89432 13.7925C1.40205 14.5787 2.15682 15.6294 3.14545 16.6839C5.10447 18.7735 8.10048 21 12 21V19ZM1.88114 12.4728C3.05761 10.2803 4.68935 8.36482 6.66689 6.85475L5.45308 5.26519C3.24889 6.94834 1.43014 9.0834 0.118829 11.5271L1.88114 12.4728ZM5.35288 6.76708L17.2329 18.6471L18.6471 17.2329L6.76709 5.35286L5.35288 6.76708ZM10.1279 5.21365C10.7408 5.0702 11.3682 4.99849 11.9976 4.99997L12.0023 2.99997C11.2179 2.99813 10.4359 3.0875 9.67207 3.26629L10.1279 5.21365ZM12 4.99997C15.1005 4.99997 17.6045 6.77353 19.3954 8.68391C20.2818 9.62937 20.9646 10.5787 21.4256 11.2925C21.6555 11.6485 21.8286 11.9433 21.9429 12.1465C22 12.248 22.0423 12.3264 22.0695 12.3778C22.0831 12.4036 22.0929 12.4225 22.0989 12.4342C22.102 12.4401 22.104 12.4442 22.1051 12.4463C22.1057 12.4474 22.106 12.448 22.1061 12.4482C22.1061 12.4483 22.1061 12.4482 22.106 12.448C22.1059 12.448 22.1058 12.4477 22.1058 12.4477C22.1057 12.4475 22.1056 12.4472 23 12C23.8944 11.5528 23.8942 11.5524 23.8941 11.5521C23.894 11.5519 23.8938 11.5515 23.8936 11.5512C23.8933 11.5505 23.8929 11.5497 23.8924 11.5488C23.8915 11.547 23.8904 11.5448 23.889 11.542C23.8862 11.5365 23.8824 11.5291 23.8776 11.5198C23.8681 11.5012 23.8546 11.4753 23.8372 11.4424C23.8024 11.3767 23.752 11.2832 23.686 11.166C23.5542 10.9316 23.3601 10.6015 23.1056 10.2074C22.5979 9.42128 21.8432 8.37057 20.8545 7.31603C18.8955 5.22641 15.8995 2.99997 12 2.99997V4.99997ZM22.1181 11.5286C21.5439 12.6028 20.8591 13.6141 20.0748 14.5461L21.6051 15.8338C22.479 14.7953 23.2421 13.6684 23.8819 12.4714L22.1181 11.5286ZM13.3884 13.4382C13.2053 13.6347 12.9845 13.7924 12.7391 13.9017L13.5531 15.7285C14.0438 15.5099 14.4854 15.1947 14.8516 14.8017L13.3884 13.4382ZM12.7391 13.9017C12.4938 14.011 12.229 14.0698 11.9604 14.0745L11.9957 16.0742C12.5328 16.0647 13.0625 15.9471 13.5531 15.7285L12.7391 13.9017ZM11.9604 14.0745C11.6919 14.0792 11.4251 14.0298 11.1761 13.9292L10.4271 15.7837C10.9251 15.9849 11.4586 16.0837 11.9957 16.0742L11.9604 14.0745ZM11.1761 13.9292C10.9271 13.8287 10.7009 13.6789 10.5109 13.489L9.09672 14.9032C9.47656 15.2831 9.92901 15.5825 10.4271 15.7837L11.1761 13.9292ZM10.5109 13.489C10.321 13.2991 10.1713 13.0729 10.0707 12.8238L8.21627 13.5729C8.41745 14.0709 8.71689 14.5234 9.09672 14.9032L10.5109 13.489ZM10.0707 12.8238C9.97012 12.5748 9.92072 12.3081 9.92546 12.0395L7.92577 12.0042C7.9163 12.5413 8.0151 13.0748 8.21627 13.5729L10.0707 12.8238ZM9.92546 12.0395C9.9302 11.771 9.98898 11.5061 10.0983 11.2608L8.27143 10.4468C8.05281 10.9375 7.93525 11.4672 7.92577 12.0042L9.92546 12.0395ZM10.0983 11.2608C10.2076 11.0155 10.3652 10.7947 10.5617 10.6116L9.19826 9.14836C8.80527 9.51456 8.49005 9.95616 8.27143 10.4468L10.0983 11.2608ZM0.292878 1.70708L22.2929 23.7071L23.7071 22.2929L1.70709 0.292863L0.292878 1.70708Z" fill="#121321"/>
        </svg>
        <svg for="thy-${slugName}" class="show-pwd hide" width="22" height="16" viewBox="0 0 22 16" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path fill-rule="evenodd" clip-rule="evenodd" d="M11 0.5C6 0.5 1.73 3.61 0 8C1.73 12.39 6 15.5 11 15.5C16 15.5 20.27 12.39 22 8C20.27 3.61 16 0.5 11 0.5ZM11 5.5C12.38 5.5 13.5 6.62 13.5 8C13.5 9.38 12.38 10.5 11 10.5C9.62 10.5 8.5 9.38 8.5 8C8.5 6.62 9.62 5.5 11 5.5ZM6.5 8C6.5 5.52 8.52 3.5 11 3.5C13.48 3.5 15.5 5.52 15.5 8C15.5 10.48 13.48 12.5 11 12.5C8.52 12.5 6.5 10.48 6.5 8Z" fill="#484848"/>
        </svg>
        </div>
        <div class="ss-Add-secret-button btnGenPWD"
        for="thy-${slugName}"
        slug="${slugName}"
        fieldId="${fields[k].secretTemplateFieldId}">Generate Password</div>
      </div>
      <div class="section-divider"></div>
      `;

        block2.innerHTML += password;
      } else if (fields[k].isNotes) {
        const notes = `<div class="input-field">
<label class="Add-Secret-lable">${displayName}</label>
<div class="field-group">
<textarea id="thy-${slugName}" name="${slugName}"
placeholder="" class="add-secret-textarea  ${isRequired}"></textarea>
</div></div>`;
        block2.innerHTML += notes;
      } else {
        let tmpUserName = "";
        if (k === userNameIndex) {
          tmpUserName = userNameField;
        }
        const textbox = `<div class="input-field">
<div class="drag-container">
<span class="drag-tooltip"> Drag this to the ${displayName}
 field on the page </span>
<span class="Add-Secret-lable drag" id="hint-${slugName}"
draggable="true">${fields[k].displayName}</span>

<div class="drop-success hide"></div>
</div>
<input type="text" id="thy-${slugName}" class="inp  ${isRequired}"
autocomplete="off" name="${slugName}" ${tmpUserName}
placeholder="" class="add-secret-textbox ${isRequired} ${tmpUserName
  ? "add-secret-username" : ""}"></div>`;
        block2.innerHTML += textbox;
      }
    }
  }
  headerDiv.querySelector(".add-secrets-details-container").appendChild(block2).innerHTML;
  return headerDiv.innerHTML;
}

/**
   * reassign password
   */
function reassignPwd() {
  if (shadowElement) {
    const pwdFields = shadowElement.querySelectorAll(".add-secret-password");
    for (let i = 0; i < pwdFields.length; i++) {
      if (pwdFields[i].value) {
        gpswd = pwdFields[i].value;
      }
    }
  }
}

/**
   * reassign username
   */
function reassignUsername() {
  if (shadowElement) {
    const unameFields = shadowElement.querySelectorAll(".add-secret-username");
    for (let i = 0; i < unameFields.length; i++) {
      if (unameFields[i].value) {
        gusername = unameFields[i].value;
      }
    }
  }
}

/**
* marks the fields, of selected template, isreuired or not.
*
*/
function markRequiredFields() {
  const elements = shadowElement.querySelectorAll(".required");
  for (let l = 0; l < elements.length; l++) {
    elements[l].addEventListener("keyup", (e) => {
      if (e.target.value.trim() == "") {
        e.target.classList.add("addBlur");
      } else {
        e.target.classList.remove("addBlur");
      }
    });
    elements[l].addEventListener("blur", (e) => {
      if (e.target.value.trim() == "") {
        e.target.classList.add("addBlur");
      } else {
        e.target.classList.remove("addBlur");
      }
    });
    elements[l].addEventListener("input", requiredFieldInput);
    elements[l].addEventListener("change", requiredFieldInput);
  }
}

/**
 * requiredFieldInput
 * @param {*} e
 */
function requiredFieldInput(e) {
  const secretName = shadowElement.getElementById("thy-add-SecretName").value;
  const folderName = shadowElement.getElementById("thy-add-folder")
    .getAttribute("selected-id");
  const siteName = shadowElement.getElementById("drp-thy-add-sites")
    .getAttribute("selected-id");
  const secretTemplateId = shadowElement.getElementById("thy-add-template1")
    .getAttribute("selected-id");
  const isdisabled = secretName.trim() == "" || !folderName || !siteName
    || !secretTemplateId || !validateSecretFields();

  if (isdisabled) {
    shadowElement.getElementById("thy-add-secret-popup")
      .classList.add("disabled");
  } else {
    shadowElement.getElementById("thy-add-secret-popup")
      .classList.remove("disabled");
  }
}

/**
* adds message listner for generate password.
* @param {object} response pwd element needs to filed after
* password is generated.
*/
function fillGeneratedPassword(response) {
  if (response) {
    let passwordField;
    if (response.fieldId) {
      const hostDiv = (0,common.$)("#WPF-shadow-root");
      if (hostDiv && shadowElement) {
        passwordField = shadowElement.getElementById(response.fieldId);
      }
    } else if (lastClickedElement && lastClickedElement.type === "password") {
      passwordField = lastClickedElement;
    }
    if (passwordField) {
      const content = response.password;
      navigator.clipboard.writeText(content);
      passwordField.value = response.password;
      passwordField.dispatchEvent(new Event("change"));
      showCopyToClipBoardMsg();
    }
  }
}

/**
* Show password copied to clipboard msg
* */
function showCopyToClipBoardMsg() {
  if (shadowElement) {
    const element = shadowElement.getElementById("add-secret-container");
    if (element) {
      if (element.style.display !== "none" && element.style.display !== "") {
        return;
      }
    }
  }
  if (window !== window.parent) {
    ext_default().runtime.sendMessage({
      method: "showCopyToClipBoardMsg",
    });
    return;
  }
  showErrorPop(errors/* NOTIFY */.W.COPIED_TO_CLIPBOARD);
}

document.addEventListener("click", (e) => {
  const path = e.path || (e.composedPath && e.composedPath());
  if ((path && path[0].id === "thy-refresh-secret")
    || (e.originalTarget
      && e.originalTarget.id
      && e.originalTarget.id === "thy-refresh-secret")) {
    ext_default().runtime.sendMessage({
      method: "refreshSecretList",
      url: targetUrl,
    }, () => {
      const eleCords = null;
      const isIconClick = false;
      ext_default().runtime.sendMessage({
        method: "GetSecrets",
        showSecretPopup: true,
        eleCords,
        isIconClick,
        isCrossDomain,
        isRefreshClick: true,
        referrer: document.referrer,
        iframeId: getIframeId(),
        pageState: window.performance.navigation.type,
        isPasswordHiddenOnPage: !isPasswordOnPage(),
        isOtpHiddenOnPage: !isOtpOnPage(),

      });
    });
    const refreshButton = shadowElement.getElementById("thy-refresh-secret");
    refreshButton.disabled = true;
    refreshButton.title = "Disable for 30 second.";
    setTimeout(() => {
      refreshButton.disabled = false;
      refreshButton.removeAttribute("title");
    }, 30000);
  }
});


function startSavePromptTimeout(shadowElement1, btnNotNever) {
  clearTimeout(savePromptTimeout);
  savePromptTimeout = setTimeout(() => {
    if (btnNotNever) {
      btnNotNever.click(); 
    }
  }, 180000); 
}
function clearSavePromptTimeout() {
  clearTimeout(savePromptTimeout); 
}


/**
* shows the Save secret popup.
* @param {Object} data Secret Data to add.
* @param {boolean} isEdit Secret Data to add.
*/
function addNewSecretPopup(data, isEdit) {
  removeContainer("WPF-shadow-root");

  let hostDiv = (0,common.$)("#WPF-shadow-root-AddNewSecretPop");
  if (!hostDiv) {
    hostDiv = createHostElement(() => {
      const x = (0,common.$)("#WPF-shadow-root-AddNewSecretPop").shadowRoot;
      const y = x.getElementById("delinea-container-AddNewSecretPop");
      y.style.display = "";
    });
    hostDiv.setAttribute("id", "WPF-shadow-root-AddNewSecretPop");
    hostDiv.style.top = "5px";
    hostDiv.style.right = "10px";
    hostDiv.style.display = "block";
  }
  const shadowElement1 = (0,common.$)("#WPF-shadow-root-AddNewSecretPop").shadowRoot;
  const element = shadowElement1.getElementById("delinea-container-AddNewSecretPop");
  if (!element && shadowElement1) {
    const container = document.createElement("div");
    container.style.display = "none";
    container.setAttribute("id", "delinea-container-AddNewSecretPop");
    let header = "";
    if (isEdit) {
      header = `${serverType} wants to update your password.`;
    } else {
      header = `${serverType} wants to save your password.`;
      ext_default().runtime.sendMessage({ method: "SecretAdded" });
      // toggleFavIcon(true);
    }
    container.innerHTML = `
<div class="AddNewSecret-normal-label">
<img class="v_align_middle siteImage">${header}</div>
<div class="AddNewSecret-container1">
<div class="siteIconContainer">
<img class="web-site-logo siteImage">
</div>
<div class="AddNewSecret-inner-container">
<label  name="baseUrl" placeholder=""
class="AddNewSecret-SecretName">
${data && data.url}</label>
<label name="baseUrl" placeholder=""
class="AddNewSecret-UserName">
${data && data.username}</label>
</div>
</div>
<div>
<div  class="AddNewSecret-button-group">
<div id="divdropdown" class="thy-dropdown">
<button id="btnNotNever" class="thy-dropbtn" value="Not Now">Not Now
</button>
</div>
<div id="divNotNever" class='thy-wpf-divNotNever'>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 490.656 490.656"
height="10px" width="10px"
xml:space="preserve">
<g>
<g>
<path d="M487.536,120.445c-4.16-4.16-10.923-4.16-15.083,0L245.339,347.581L18.203,120.467c-4.16-4.16-10.923-4.16-15.083,0
c-4.16,4.16-4.16,10.923,0,15.083l234.667,234.667c2.091,2.069,4.821,3.115,7.552,3.115s5.461-1.045,7.531-3.136l234.667-234.667
C491.696,131.368,491.696,124.605,487.536,120.445z"/>
</g>
</g>
</svg>
</div>
<button class="AddNewSecret-button" id="btnAddnewSecret">OK</button>
</div>
</div>`;
    container.classList.add("AddNewSecret-container");
    shadowElement1.appendChild(container);
    getSiteIconUrl(shadowElement1);
    const btnNotNever = shadowElement1.getElementById("btnNotNever");
    // Start the timeout to auto-click the "Not Now" button
    startSavePromptTimeout(shadowElement1, btnNotNever);    
    shadowElement1.getElementById("btnAddnewSecret")
      .addEventListener("click", () => {
        clearSavePromptTimeout(); // Clear timeout if OK button is clicked
        removeFlag();
        shadowElement1.getElementById("delinea-container-AddNewSecretPop").remove();
        if (shadowElement1.getElementById("delinea-container-AddNewSecretPop")) {
          removeContainer("WPF-shadow-root-AddNewSecretPop");
        }
        if (isEdit) {
          const passwordData = {
            value: data.password,
          };
          ext_default().runtime.sendMessage({
            method: "UpdateSecretPassword",
            secretId: data.secretId,
            data: passwordData,
          });
        } else {
          ext_default().runtime.sendMessage({
            method: "GetTemplatesNFolders",
          }, (response) => {
            setTemplatesNFolders(response);
            if (Templates.length > 0 && personalFolder != null) {
              showAddSecretForm();
            }
          });
        }
      });
    
    btnNotNever.addEventListener("click", () => {
      removeFlag();
      shadowElement1.getElementById("delinea-container-AddNewSecretPop").remove();
      ext_default().runtime.sendMessage({
        method: "RemovePersistedData",
      });
    });

    shadowElement1.getElementById("divNotNever").addEventListener(
      "click",
      (e) => {
        let element = shadowElement1.getElementById("divOption");
        if (!element) {
          element = document.createElement("div");
          element.setAttribute("id", "divOption");
          element.classList.add("thy-dropdown-content");
        }
        if (btnNotNever.getAttribute("value") == "Not Now") {
          element.innerHTML = "<a id=\"aNever\" href=\"#\">Never</a>";
        } else {
          element.innerHTML = "<a id=\"aNotNow\" href=\"#\">Not Now</a>";
        }
        shadowElement1.appendChild(element);
        element.classList.toggle("thy-show");
        const posShadowEleDiv = getAbsolutePos(document, hostDiv);
        const absoluteRect = getAbsolutePos(document, e.target);
        element.style.left = `${absoluteRect.left - posShadowEleDiv.left - 68}px`;
        element.style.top = `${absoluteRect.top + 10}px`;
        shadowElement1.getElementById("aNever").addEventListener(
          "click",
          (e) => {
            e.preventDefault();
            btnNotNever.textContent = "Never";
            btnNotNever.value = "Never";
            element.classList.remove("thy-show");
            btnNotNever.click();
            ext_default().runtime.sendMessage({
              method: "SaveForNever",
            });
          },
        );
      },
    );

    container.style.display = "";
  }
}

/**
* saves secret data.
* @param {Object} data Secret Data to add.
* @param {Object} shadowEle element.
*/
function saveNewSecret(data, shadowEle) {
  ext.runtime.sendMessage({
    method: "GetTemplatesNFolders",
  }, (response) => {
    setTemplatesNFolders(response);
    if (personalFolder && Templates.length > 0) {
      const secretName = window && window.location && window.location.hostname;
      // Host name will be secret name
      if (secretName) {
        const secretData = {
          data: {
            name: secretName,
            folderId: personalFolder.id,
            active: true,
            site: 1,
            templateId: parseInt(Templates[0].id),
            fields: [],
          }
        };
        const { fields } = Templates[0];
        fields.forEach((element) => {
          let val = "";
          if (element.isUrl) {
            val = data.url;
          } else if (element.isPassword) {
            val = data.password;
          } else if (!element.isNotes && !element.isFile) {
            const userNameFieldDisplayList = ["user name", "username", "email", "email address", "tel", "telephone"];
            if (userNameFieldDisplayList.find((expression) => expression.includes(element.displayName.toLowerCase()))) {
              val = data.username;
            }
          }
          secretData.data.fields.push({
            slug: element.fieldSlugName,
            value: val,
          });
        });
        if (shadowEle.getElementById("delinea-container-AddNewSecretPop")) {
          shadowEle.getElementById("delinea-container-AddNewSecretPop").remove();
        }
        ext.runtime.sendMessage({
          method: "createSecret",
          type: "isPopup",
          data: secretData,
        });
      }
    }
  });
}
/**
* handles the submit click and send notification to Background.JS.
* @param{object} e
*/
function handleSubmit(e) {
  const data = {
    username,
    password: contentscript_password,
    url: targetUrl,
    isMappingFound,
  };
  data.isUsernameChanged = false;
  if ((username.length > 0 || contentscript_password.length > 0) 
    && !isCurrentSSTabloggedIn) {
    if (username && username !== gusername) {
      data.isUsernameChanged = true;
      if(pwdObserver) {
        pwdObserver.disconnect();
      }
      if(!isPasswordOnPage()) {
        data.password = '';
      }
    }
    if (!isNewSecretAdded) {
      ext_default().runtime.sendMessage({
        method: "CheckIfExists",
        data,
      });
    }
  }
}
/**
 * getConfirmDialogMarkup
 * @param {string} rootDomain
 * @param {string} iframeDomain
 * @param {string} iconUrl
 * @return {string}
 */
function getConfirmDialogMarkup(rootDomain, iframeDomain, iconUrl) {
  return `<div id="delinea-inner-container">
    <div class="Sign-in-as" >
    <span>
    The login prompt on this site, ${rootDomain} provides authentication to
    ${iframeDomain}.
    Do you want to enable Secret Server vault integration for
    this site? You should only select OK if this is a trusted site.</span>
    <br/>
    <br/>
    <div class="checkbox">
      <input type="checkbox" id="rememberCross">
      <label class="normal-lable" for="rememberCross"></label>
      <span class="marginLeft">Remember selection for this site</span>
    </div>
    <br/>
    </div>
    <div class="div-fields">
      <img class="site-logo" src="${iconUrl}">
      <div class="btn-group">
        <button id="btnthyCancelConfirm" class="cancel-ss-button">Cancel</button>
        <button id="btnthyConfirm" class="thy-wpf-ss-button ">Ok</button>
      </div>
    </div>`;
}

/**
   * rememberSelection
   * @param {boolean} accept
   */
function rememberSelection(accept) {
  if ((0,common.$)("#rememberCross") && (0,common.$)("#rememberCross").checked) {
    localStorage.setItem("acceptCrossDomainWarning", accept);
  }
}

/**
   * onSecurityWarningAccepted
   */
function onSecurityWarningAccepted() {
  const hostDiv = (0,common.$)("#thy-wpf-confirm-dialog");
  rememberSelection(true);
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }

  showSecretPopupOnDemand(true);
  storage/* default */.A.get("Settings", (storageSettings) => {
    if (storageSettings) {
      if (!storageSettings.Settings.defaultPopupPosition) {
        const frames = document.getElementsByTagName("iframe");
        for (let i = 0; i < frames.length; i++) {
          frames[i].contentWindow.postMessage({
            action: "SecurityWarningAccepted",
          }, "*");
        }
      } else {
        ext_default().runtime.sendMessage({
          method: "GetSecrets",
          showSecretPopup: true,
          isCrossDomain: true,
          referrer: document.referrer,
          iframeId: getIframeId(),
          pageState: window.performance.navigation.type,
          isPasswordHiddenOnPage: !isPasswordOnPage(),
          isOtpHiddenOnPage: !isOtpOnPage(),
        });
      }
    }
  });
}

/**
   * onSecurityWarningRejected
   */
function onSecurityWarningRejected() {
  const hostDiv = (0,common.$)("#thy-wpf-confirm-dialog");
  rememberSelection(false);
  if (hostDiv && hostDiv.remove) {
    hostDiv.remove();
  }
  removeDelineaIcon();
  ext_default().runtime.sendMessage({
    method: "clearContextMenu",
  });
}

/**
   * getIframeId
   * @return {number} iframeId
   */
function getIframeId() {
  if (window.parent !== window && window.frameElement) {
    return window.frameElement.id;
  }
  return "";
}

/**
* Created generic pop to show error message.
* @param {Object} request the text to display.
*/
function showConfirmDialog(request) {
  isCrossDomain = request.response.isCrossDomain;
  if (window !== window.parent) {
    if (!isCrossDomain) {
      openSecretPopupOnIframe();
    }
  } else if (isCrossDomain) {
    const selection = localStorage.getItem("acceptCrossDomainWarning");
    if (selection !== null) {
      if (selection === "true") {
        onSecurityWarningAccepted();
      } else {
        onSecurityWarningRejected();
      }
    } else {
      let hostDiv = (0,common.$)("#thy-wpf-confirm-dialog");
      if (hostDiv && hostDiv.remove) {
        hostDiv.remove();
      }
      hostDiv = document.createElement("div");
      document.body.appendChild(hostDiv);
      const checkLink = document.createElement("link");
      checkLink.href = ext_default().runtime.getURL("style.css");
      checkLink.type = "text/css";
      checkLink.rel = "stylesheet";
      document.body.appendChild(checkLink);
      hostDiv.setAttribute("id", "thy-wpf-confirm-dialog");
      hostDiv.classList.add("thy-wpf-confirm-dialog");
      const iconUrl = ext_default().runtime.getURL("icons/delinea-logo.svg");
      hostDiv.innerHTML = getConfirmDialogMarkup(
        request.response.rootDomain,
        request.response.frameDomain,
        iconUrl,
      );

      (0,common.$)("#btnthyCancelConfirm")
        .addEventListener("click", onSecurityWarningRejected);
      (0,common.$)("#btnthyConfirm")
        .addEventListener("click", onSecurityWarningAccepted);
    }
  } else {
    showSecretPopupOnDemand();
    let isUsernameChanged = sessionStorage.getItem("isUsernameChanged");
    isUsernameChanged = JSON.parse(isUsernameChanged);
    ext_default().runtime.sendMessage({
      method: "GetSecrets",
      showSecretPopup: true,
      isCrossDomain,
      referrer: document.referrer,
      iframeId: getIframeId(),
      pageState: window?.performance?.navigation?.type,
      isPasswordHiddenOnPage: !isPasswordOnPage(),
      isUsernameChanged,
      isOtpHiddenOnPage: !isOtpOnPage(),
    });
  }
}

/**
 * remove flag form session storage
 */
function removeFlag() {
  sessionStorage.removeItem("isUsernameChanged");
}

/**
 * hideShowPWD
 * @param {*} container
 */
function hideShowPWD(container) {
  const hideShowBtns = container.getElementsByClassName("hide-show-pwd");
  const showBtns = container.getElementsByClassName("show-pwd");
  for (let i = 0; i < hideShowBtns.length; i++) {
    hideShowBtns[i].addEventListener("click", (evt) => {
      evt.preventDefault();
      const pwdId = evt.target.getAttribute("for");
      const passInput = evt.target.parentElement.querySelector(`#${pwdId}`);
      if (!passInput) return;
      passInput.setAttribute("type", "text");
      hideShowBtns[i].classList.add("hide");
      showBtns[i].classList.remove("hide");
    });
  }
  for (let i = 0; i < showBtns.length; i++) {
    showBtns[i].addEventListener("click", (evt) => {
      evt.preventDefault();
      const pwdId = evt.target.getAttribute("for");
      const passInput = evt.target.parentElement.querySelector(`#${pwdId}`);
      if (!passInput) return;
      passInput.setAttribute("type", "password");
      hideShowBtns[i].classList.remove("hide");
      showBtns[i].classList.add("hide");
    });
  }
}


/***/ }),

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

/* global browser, chrome */

const apis = [
  'alarms',
  'bookmarks',
  'browserAction',
  'action',
  'commands',
  'contextMenus',
  'cookies',
  'downloads',
  'events',
  'extension',
  'extensionTypes',
  'history',
  'i18n',
  'idle',
  'notifications',
  'pageAction',
  'offscreen',
  'runtime',
  'storage',
  'tabs',
  'activeTab',
  'webNavigation',
  'webRequest',
  'windows',
  'clipboardWrite',
  'tabCapture',
  'desktopCapture',
  'browsingData',
  'scripting'
];

/**
 * API Extension Class
 */
function Extension() {
  const _this = this;

  apis.forEach((api) => {
    _this[api] = null;

    try {
      if (chrome[api]) {
        _this[api] = chrome[api];
      }
    } catch (e) {}

    try {
      if (window[api]) {
        _this[api] = window[api];
      }
    } catch (e) {}

    try {
      if (browser[api]) {
        _this[api] = browser[api];
      }
    } catch (e) {}
    try {
      _this.api = browser.extension[api];
    } catch (e) {}
  });

  try {
    if (browser && browser.runtime) {
      this.runtime = browser.runtime;
    }
  } catch (e) {}

  try {
    if (browser && (browser.browserAction || browser.action)) {
      this.browserAction = browser.browserAction || browser.action;
    }
  } catch (e) {}
}

module.exports = new Extension();


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _ext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(666);
/* harmony import */ var _ext__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_ext__WEBPACK_IMPORTED_MODULE_0__);


/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((_ext__WEBPACK_IMPORTED_MODULE_0___default().storage).local ? (_ext__WEBPACK_IMPORTED_MODULE_0___default().storage).local : (_ext__WEBPACK_IMPORTED_MODULE_0___default().storage).sync);


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _utils_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(942);
/* harmony import */ var _utils_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(482);
/* harmony import */ var _user_permissions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(973);




let currentSSVersion = _utils_constants__WEBPACK_IMPORTED_MODULE_1__.UNKNOWN_VERSION;
let isSecretServerCloud = false;
const currentContext = {
  getCurrentContext(context, value) {
    const key = this.getContextKey(context);
    const obj = {};
    obj[key] = value;
    return obj;
  },

  getContextKey(context) {
    // Append with # or anything else other than |
    const userId = _user_permissions__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .A.getUserId();
    return `${_utils_common__WEBPACK_IMPORTED_MODULE_0__/* .config */ .$W.BaseURL}#${userId}#${context}`;
  },
  setSSVersion(version) {
    currentSSVersion = version;
  },

  getSSVersion() {
    return currentSSVersion;
  },

  setCloud(isSSC) {
    isSecretServerCloud = isSSC;
  },
  getCloud() {
    return isSecretServerCloud;
  },
};

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (currentContext);


/***/ }),

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

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: () => (/* binding */ user_permissions)
});

// EXTERNAL MODULE: ./src/scripts/cache/session-storage-provider.js
var session_storage_provider = __webpack_require__(576);
;// CONCATENATED MODULE: ./src/scripts/cache/user-permissions-provider.js


const key = "Permissions";

const userPermissionProvider = {
  async load() {
    return session_storage_provider/* default */.A.get(this.getKey());
  },
  async get() {
    return this.load();
  },
  clear() {
    this.set([]);
  },
  set(value) {
    session_storage_provider/* default */.A.set(this.getKey(), value);
  },
  getKey() {
    return key;
  },
};

/* harmony default export */ const user_permissions_provider = (userPermissionProvider);

;// CONCATENATED MODULE: ./src/scripts/handlers/user-permissions.js


const { PERMISSIONS } = __webpack_require__(482);

// let permissions = [];
let userId = 0;

const userPermissionHandler = {
  async getPermissions() {
    return user_permissions_provider.get();
  },
  gotPermissions(result) {
    const { permissions } = result;
    userId = result.id;
    user_permissions_provider.set(permissions);
  },
  async isAddPermission() {
    const permissions = await user_permissions_provider.get();
    for (let i = 0; i < permissions.length; i++) {
      if (permissions[i].name === PERMISSIONS.AddSecret) {
        return true;
      }
    }
    return false;
  },

  async isEditPermission() {
    const permissions = await user_permissions_provider.get();
    for (let i = 0; i < permissions.length; i++) {
      if (permissions[i].name === PERMISSIONS.EditSecret) {
        return true;
      }
    }
    return false;
  },

  getUserId() {
    return userId;
  },

  loggedOff() {
    userId = 0;
    user_permissions_provider.clear();
  },

};

/* harmony default export */ const user_permissions = (userPermissionHandler);


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Dl: () => (/* binding */ parseUrl),
/* harmony export */   ZG: () => (/* binding */ addDefaultProtocol),
/* harmony export */   gU: () => (/* binding */ isUrl),
/* harmony export */   mR: () => (/* binding */ appendPath),
/* harmony export */   u4: () => (/* binding */ urlEncode),
/* harmony export */   ws: () => (/* binding */ removeLastSlash)
/* harmony export */ });
/* unused harmony export cleanUrlString */
/* harmony import */ var _utils_domain_ext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(237);


/**
 * appendPath
 * @param {string} urlString
 * @param {string} path
 * @return {string}
 */
function appendPath(urlString, path) {
  return (urlString + path).replace(/([^:]\/)\/+/g, '$1').toLowerCase();
}

/**
   * urlEncode
   * @param {string} string
   * @return {string}
   */
function urlEncode(string) {
  // eslint-disable-next-line
    return String(string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, ' ').replace(/'/g, ' ');
}

/**
 * removeLastSlash
 * @param {string} str
 * @return {string}
 */
function removeLastSlash(str) {
  if (str) {
    return (str.split('?')[0]).replace(/\/+$/, '');
  }
  return '';
}

/**
 * It remove last slash and www from url string.
 * @param {string} str
 * @return {string}
 */
function cleanUrlString(str, removeSlash = true) {
  if (str) {
    if (removeSlash) { str = removeLastSlash(str.toLowerCase()); }
    str = addDefaultProtocol(str);
    if (str.includes('https://www.')) {
      return str.replace('https://www.', 'https://');
    }
    return str.replace('http://www.', 'http://');
  }
  return '';
}

/**
 * Add default protocol Https
 * @param {string} string url string
 * @return{string} string
 */
const addDefaultProtocol = (string) => {
  string = string && string.trim();
  if (!string) return;
  if (string.toLowerCase().indexOf('https://') != 0 && string.toLowerCase().indexOf('http://') != 0) {
    string = `https://${string}`;
  }
  return string;
};

/**
 * validate URL
 * @param {string} string url string
 * @return{boolean} true if valid URL else false
 */
const isUrl = (string) => {
  try {
    string = addDefaultProtocol(string);
    const x = new URL(string);
    return Boolean(x) && Boolean(x.origin) && Boolean(x.hostname);
  } catch (e) {
    return false;
  }
};

/**
   * Parses the URL and get the different sections of URL.
   * @param {string} url The first number.
   * @param {boolean} getDomain
   * @return {string} the objectwhich contains different sections of URL.
   */
function parseUrl(url, getDomain = true) {
  if (!url) return;
  let extExist = false;
  url = url.toLowerCase().replace('www.', '');
  // eslint-disable-next-line max-len
  const m = url.match(/^(([^:\/?#]+:)?(?:\/\/((?:([^\/?#:]*):([^\/?#:]*)@)?([^\/?#:]*)(?::([^\/?#:]*))?)))?([^?#]*)(\?[^#]*)?(#.*)?$/);
  const r = {
    hash: m[10] || '',
    host: m[3] || '',
    hostname: m[6] || '',
    href: m[0] || '',
    origin: m[1] || '',
    pathname: m[8] || (m[1] ? '/' : ''),
    port: m[7] || '',
    protocol: m[2] || '',
    search: m[9] || '',
    username: m[4] || '',
    password: m[5] || '',
    domain: m[3] || '',
  };

  if (m[3]) {
    m[3] = m[3];
    if (getDomain) {
      // eslint-disable-next-line
        let ip = new RegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]+)?$');
      if (ip.test(m[3])) {
        r.domain = m[3];
      } else {
        const tmp = m[3].split('.');
        for (let index = tmp.length - 1; index >= 0; index--) {
          const exist = _utils_domain_ext__WEBPACK_IMPORTED_MODULE_0__/* .DOMAIN_EXT */ .t.has(`.${tmp.slice(index).join('.')}`);
          if (exist) {
            extExist = true;
          } else if (!exist && extExist) {
            r.domain = tmp.slice(index).join('.');
            break;
          } else {
            break;
          }
        }
      }
    }
  }
  return m && r;
}


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   J9: () => (/* binding */ isElementVisible),
/* harmony export */   M8: () => (/* binding */ parents),
/* harmony export */   VH: () => (/* binding */ getHiddenParent)
/* harmony export */ });
/* unused harmony export checkVisibility */
/**
* checks if element is visible or not.
* @param {Object} element element to check visibility.
* @param {bool} isParent Are we checking the parent element.
* @return {bool} visibility status
*/
function checkVisibility(element, isParent = false, isImmediateParent = false, allowFocus = false) {
  let isVis = true;
  if (!element) {
    return false;
  }
  if (element && element.nodeName === '#document-fragment') {
    return true;
  } if (element instanceof HTMLElement === false) {
    return false;
  }
  // check for document fragment
  const ele = window && window.getComputedStyle && window.getComputedStyle(element, null);
  if (!ele || (ele && ele.visibility.toLowerCase() === 'hidden')) {
    isVis = false;
  }

  if (isImmediateParent && ele?.height === '0px' && ele?.overflow === 'hidden') {
    isVis = false;
  }

  if (element.style.visibility !== ''
      && (element.style.visibility.toLocaleLowerCase() !== 'visible'
        && element.style.visibility.toLocaleLowerCase() !== 'inherit')) {
    isVis = false;
  }
  if (ele && ele.display && ele.display.toLowerCase() === 'none') {
    isVis = false;
  }

  if (element.type === 'password'
      && !isNaN(ele.opacity) && ele.opacity === '0') {
    if (allowFocus) {
      element.focus();
      setTimeout(() => {
        isVis = ele.opacity !== '0';
      }, 50);
    } else {
      isVis = false;
    }
  }

  if (!isNaN(parseInt(element.style.maxHeight))
      && parseInt(element.style.maxHeight) < 1) {
    isVis = false;
  }  
  if (!isNaN(parseInt(ele?.width))
    && parseInt(ele?.width) < 10) {
    isVis = false;
  }
  if (!isNaN(parseInt(element.style.maxWidth))
      && parseInt(element.style.maxWidth) < 1) {
    isVis = false;
  }

  if (element.nodeName !== 'DIV' || isParent) {
    if ((parseInt(element.style.width) < 1
        && parseInt(element.getBoundingClientRect().width) < 1
        && parseInt(ele.width) < 1)) {
      isVis = false;
    }
  }

  if (element.style.transition.includes('opacity')) {
    const transitions = element.style.transition.split(' ');
    for (let index = 0; index < transitions.length; index++) {
      if (transitions[index] === 'opacity'
          && (index + 1) <= transitions.length) {
        const opacity = transitions[(index + 1)].replace(/[^0-9.]/g, '');
        if (!isNaN(opacity) && parseFloat(opacity) < 1) {
          return false;
        }
      }
    }
  }
  return isVis;
}

/**
* checks if element is visible or not.
* @param {HTMLElement} element element to check visibility.
* @return {bool} visibility status
*/
function isElementVisible(element, allowFocus = false) {
  if (!checkVisibility(element, false, false, allowFocus)) {
    return false;
  }
  const ar = parents(element);
  for (let ind = 0; ind < ar.length; ind++) {
    if (ar[ind] && !checkVisibility(ar[ind], true, ind === 0)) {
      return false;
    }
  }
  return true;
}

/**
* get parent elements for a given element
* @param {object} element a html node element
* @param {Array} _array
* @return {Array} _array array of elements all the way to body
*/
function parents(element, array) {
  if (array === undefined) {
    array = [];
  } else {
    array.push(element); // add current element
  }
  // need to check tagname aad
  if (element && element.tagName
      && element.tagName.toLowerCase() !== 'body') {
    if (element.parentNode) return parents(element.parentNode, array);
    return array;
  }
  return array;
}

/**
   * getHiddenParent
   * @param {*} element
   * @return {htmlElement}
   */
function getHiddenParent(element) {
  const ar = parents(element);
  for (let ind = 0; ind < ar.length; ind++) {
    if (ar[ind] && !checkVisibility(ar[ind], true)) {
      return ar[ind];
    }
  }
  if (!checkVisibility(element)) {
    return element;
  }
  return null;
}


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _contentscript__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(458);
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(666);
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_core_ext__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _helpers_visibility_helpers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(511);
/* harmony import */ var _utils_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(942);





let otpTimeout = 0;
let otpObserver = null;
const otpTimer = {

  getOtpSvg(remaining, durationSeconds, width = 20) {
    const maxTime = durationSeconds;
    const maxWidth = 126.92;

    const remainingPercent = ((maxTime - remaining) / maxTime);
    const offset = maxWidth * remainingPercent; // Calculate offset from left to right
    const svg = `
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="${width}px" viewBox="22 22 44 44" enable-background="new 22 22 44 44" xml:space="preserve">
    <circle style="stroke: #570fd4;" cx="44" cy="44" r="20.2" stroke-width="3.6" fill="none"></circle>
    <circle transform="rotate(-90 44 44)" style="stroke: #d3baff; stroke-dasharray: ${maxWidth}; stroke-dashoffset: ${offset}px;" cx="44" cy="44" r="20.2" stroke-width="3.6" fill="none"></circle>
    <text style="font-family: Arial; fill:#570fd4" x="44" y="53" text-anchor="middle">${remaining}</text>
    </svg>`;
    return svg;
  },

  setAnimatedInnerHtml(element, remaining, duration, width = 20, callback = () => { }) {
    const svg = this.getOtpSvg(remaining, duration, width);
    element.innerHTML = svg;

    if (remaining <= 0) {
      callback();
      return;
    }

    clearTimeout(otpTimeout);
    otpTimeout = setTimeout(() => {
      this.setAnimatedInnerHtml(element, remaining - 1, duration, width, callback);
    }, 990);
  },

  setAnimatedBackground(element, remaining, durationSeconds, newOtpCallback) {
    const svg = this.getOtpSvg(remaining, durationSeconds);
    const encoded = window.btoa(svg);
    const element1 = document.getElementById(element && element.id);
    const image = `url(data:image/svg+xml;base64,${encoded})`;
    element?.style?.setProperty('background-image', image, 'important');
    this.setCommonCSS(element);

    if (remaining <= 0) {
      newOtpCallback();
      return;
    }

    clearTimeout(otpTimeout);
    otpTimeout = setTimeout(() => {
      this.setAnimatedBackground(element1, remaining - 1, durationSeconds, newOtpCallback);
    }, 990);
  },

  fillOtp(message, secretId, elementNodes = []) {
    if (elementNodes && elementNodes.length == 0) {
      this.clearTimer();
    }
    for (let index = 0; index < elementNodes.length; index++) {
      if (elementNodes[index].otpField) {
        if ((0,_helpers_visibility_helpers__WEBPACK_IMPORTED_MODULE_3__/* .isElementVisible */ .J9)(elementNodes[index].otpField[0])) {
          (0,_contentscript__WEBPACK_IMPORTED_MODULE_0__/* .sendKeystrokes */ .rW)(elementNodes[index].otpField[0], message[0].code);
          this.setAnimatedBackground(
            elementNodes[index].otpField[0],
            message[0].remainingSeconds,
            message[0].durationSeconds,
            () => {
              this.requestNewOtp(secretId, elementNodes);
            },
          );
        } else {
          this.attachOtpMutation(elementNodes[index].otpField[0], message[0].code, secretId, elementNodes);
        }
      }
    }
  },

  attachOtpMutation(otpField, message, secretId, elementNodes) {
    if (!(0,_helpers_visibility_helpers__WEBPACK_IMPORTED_MODULE_3__/* .isElementVisible */ .J9)(otpField)) {
      const hiddenEle = (0,_helpers_visibility_helpers__WEBPACK_IMPORTED_MODULE_3__/* .getHiddenParent */ .VH)(otpField);
      if (hiddenEle) {
        if (otpObserver) return;
        otpObserver = new MutationObserver(() => {
          this.requestNewOtp(secretId, elementNodes);

          if ((0,_helpers_visibility_helpers__WEBPACK_IMPORTED_MODULE_3__/* .isElementVisible */ .J9)(otpField)) {
            otpObserver.disconnect();
            this.otpSet();
          }
        });
        otpObserver.observe(hiddenEle, {
          childList: true,
          subtree: true,
          attributes: true,
        });
      }
    }
  },

  clearTimer() {
    clearTimeout(otpTimeout);
    this.removeOtpField();
  },
  otpSet() {
    _core_ext__WEBPACK_IMPORTED_MODULE_1___default().runtime.sendMessage({
      method: 'otpSet',
    });
  },
  requestNewOtp(secretId, elementNodes) {
    for (let index = 0; index < elementNodes.length; index++) {
      if (elementNodes[index].otpField?.length) {
        _core_ext__WEBPACK_IMPORTED_MODULE_1___default().runtime.sendMessage({
          method: 'GetOtp',
          secretId,
        }, (result) => this.fillOtp(result, secretId, elementNodes));
      }
    }
  },
  requestOtp(secretId, callback) {
    _core_ext__WEBPACK_IMPORTED_MODULE_1___default().runtime.sendMessage({
      method: 'GetOtp',
      secretId,
    }, (res) => {
      callback(res);
    });
  },

  markOtpField(input) {
    if (!input) return;
    input.classList.add('Delinea_OTP');
    this.setCommonCSS(input);
    // requestNewOtp();
  },
  setCommonCSS(input) {
    if (!input) return;
    input.style.setProperty('background-repeat', 'no-repeat', 'important');
    input.style.setProperty('background-position', '98%', 'important');
    input.style.setProperty('background-size', '26px', 'important');
    input.style.setProperty('box-shadow', 'none', 'important');
    input.style.setProperty('opacity', '1', 'important');
  },
  removeOtpField() {
    const taggedTotpdFields = (0,_utils_common__WEBPACK_IMPORTED_MODULE_2__.$)('.Delinea_OTP');
    for (let i = 0; i < taggedTotpdFields.length; i++) {
      taggedTotpdFields[i].value = '';
      taggedTotpdFields[i].style.backgroundImage = 'none';
    }
  },
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (otpTimer);


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $: () => (/* binding */ $),
/* harmony export */   $L: () => (/* binding */ writeToClipboard),
/* harmony export */   $W: () => (/* binding */ config),
/* harmony export */   FS: () => (/* binding */ checkIfMultiDomain)
/* harmony export */ });
/* unused harmony exports removeArrayEle, chunkSubstr, hidePassword, passwordIsHidden, getHiddenPassword, isFirefox, isSafari, addObjectsToArray */
/* harmony import */ var _helpers_url_helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(714);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(482);



const config = {
  _url: '',
  _urlAuth: '',
  _urlHost: '',
  _baseURL: '',
  _hostName: '',
  _soapURL: '',
  _samlURL: '',
  _samlPath: '',
  set BaseURL(url) {
    if (!url) return;
    url = (0,_helpers_url_helpers__WEBPACK_IMPORTED_MODULE_0__/* .addDefaultProtocol */ .ZG)(url);
    const configUrl = new URL(url);
    this._hostName = configUrl.hostname.toLowerCase();
    this._baseURL = url.replace(/([^:]\/)\/+/g, '$1').replace(/\/$/, '');
    this._soapURL = configUrl.origin
      + (configUrl.pathname + _constants__WEBPACK_IMPORTED_MODULE_1__.RDP_SOAP_URL).replace(/\/+/g, '/');
    this._samlPath = configUrl.pathname + _constants__WEBPACK_IMPORTED_MODULE_1__.SAML_URL;
    this._samlURL = configUrl.origin
      + (`${configUrl.pathname}/login.aspx?ReturnUrl=${
        this._samlPath}`).replace(/\/+/g, '/');
  },
  set Url(url) {
    if (!url) return;
    url = (0,_helpers_url_helpers__WEBPACK_IMPORTED_MODULE_0__/* .addDefaultProtocol */ .ZG)(url);
    const configUrl = new URL(url);
    this._url = url.replace(/([^:]\/)\/+/g, '$1').replace(/\/$/, '');
    this._urlAuth = `${this._url}/auth`;
    this._urlHost = configUrl.host.toLowerCase();
  },
  get Url() {
    return this._url;
  },
  get PlatformAuthUrl() {
    return this._urlAuth;
  },
  get PlatformHost() {
    return this._urlHost;
  },
  get BaseURL() {
    return this._baseURL;
  },
  get SoapURL() {
    return this._soapURL;
  },
  get SamlURL() {
    return this._samlURL;
  },
  get SamlPath() {
    return this._samlPath;
  },
  get HostName() {
    return this._hostName;
  },
};

const $ = function (input) {
  switch (input[0]) {
    case '#':
      return document.getElementById(input.substring(1));
    case '.':
      return document.getElementsByClassName(input.substring(1));
    default:
      return document.querySelectorAll(input);
  }
};

// eslint-disable-next-line
Array.prototype.removeIf = function (callback) {
  let i = this.length;
  while (i--) {
    if (callback(this[i], i)) {
      this.splice(i, 1);
    }
  }
};

/**
 * create secret
 * @param {Array} arr Array of Secrets.
 * @param {int} tabid tabid for which secret needs to remove.
 * @return {Array}
 */
function removeArrayEle(arr, tabid) {
  for (let x = 0; x < arr.length; x++) {
    if (arr[x].tabid === tabid) {
      arr.splice(x, 1);
      break;
    }
  }
  return arr;
}

/**
 * checkIfMultiDomain
 * @param {string} domain
 * @return {array} sites
 */
function checkIfMultiDomain(domain) {
  const sites = _constants__WEBPACK_IMPORTED_MODULE_1__.MULTI_DOMAIN && _constants__WEBPACK_IMPORTED_MODULE_1__.MULTI_DOMAIN.find((item) => {
    if (item.domains.includes(domain)) {
      return true;
    }
  });
  if (sites) {
    return [...sites.values];
  }
  return [];
}

/**
 * chunkSubstr
 * @param {*} str
 * @param {*} size
 * @return {char[]}
 */
function chunkSubstr(str, size) {
  if (str && str.length) {
    const numChunks = Math.ceil(str.length / size);
    const chunks = new Array(numChunks);

    for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
      chunks[i] = str.substr(o, size);
    }

    return chunks;
  }
}

/**
 * It replaces password with ... in api response
 * @param {*} response
 * @param {*} value
 */
function hidePassword(response) {
  for (let i = 0; i < response.length; i++) {
    if (response[i].fieldName == 'Password' || response[i].isPassword) {
      response[i].itemValue = '...';
    }
  }
}
/**
 * The sentinel value for hidden passwords is:
 * "*** Not Valid For Display ***"
 * This function checks a string for that value
 * @param {string} str string to check for sentinel value
 * @returns {boolean}
 */
function isSentinelHiddenValue(str) {
  return str.toLowerCase().includes('not valid for display');
}

/**
 * Given a set of fields for a secret, return true if password is hidden
 * @param {*} fields an array of fields
 * @returns {boolean}
 */
function passwordIsHidden(fields) {
  for (const field of fields) {
    if (field.isPassword && isSentinelHiddenValue(field.itemValue)) {
      return true;
    }
  }
  return false;
}

/**
 * Given a set of fields for a secret, return the sentinel hidden password value
 * @param {*} fields an array of fields
 * @returns {string}
 */
function getHiddenPassword(fields) {
  for (const field of fields) {
    if (field.isPassword && isSentinelHiddenValue(field.itemValue)) {
      return field.itemValue;
    }
  }
  return '';
}

function isFirefox() {
  return navigator.userAgent.toLowerCase().includes('firefox');
}

// Function to check if the browser is Safari
function isSafari() {
  return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}

function addObjectsToArray(array, newObjects) {
  newObjects.forEach((newObject) => {
    const exists = array.some((item) => item.id === newObject.id);
    if (!exists) {
      array.push(newObject);
    }
  });
}

function writeToClipboard(content) {
  if (!content) return;
  const copyFrom = document.createElement("textarea");
  copyFrom.textContent = content.trim();
  const body = document.getElementsByTagName("body")[0];
  body.appendChild(copyFrom);
  copyFrom.select();
  document.execCommand("copy");
  body.removeChild(copyFrom);
}


/***/ }),

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

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ACTIVE_TAB_QUERY: () => (/* binding */ ACTIVE_TAB_QUERY),
/* harmony export */   ACTIVE_TAB_QUERY_MIN_REQ: () => (/* binding */ ACTIVE_TAB_QUERY_MIN_REQ),
/* harmony export */   API: () => (/* binding */ API),
/* harmony export */   APP_NAME: () => (/* binding */ APP_NAME),
/* harmony export */   CLIENT_ID: () => (/* binding */ CLIENT_ID),
/* harmony export */   CM_NATIVE_HOST: () => (/* binding */ CM_NATIVE_HOST),
/* harmony export */   CONTENT: () => (/* binding */ CONTENT),
/* harmony export */   DEFAULT_RECORDING_LIMIT: () => (/* binding */ DEFAULT_RECORDING_LIMIT),
/* harmony export */   GASETUP_URL: () => (/* binding */ GASETUP_URL),
/* harmony export */   ICONS: () => (/* binding */ ICONS),
/* harmony export */   INPUT_THRESHOLD: () => (/* binding */ INPUT_THRESHOLD),
/* harmony export */   KEYWORDS: () => (/* binding */ KEYWORDS),
/* harmony export */   LICENSES_URL: () => (/* binding */ LICENSES_URL),
/* harmony export */   MAX_RECORDING_LIMIT: () => (/* binding */ MAX_RECORDING_LIMIT),
/* harmony export */   MFA_OPTIONS: () => (/* binding */ MFA_OPTIONS),
/* harmony export */   MULTI_DOMAIN: () => (/* binding */ MULTI_DOMAIN),
/* harmony export */   NATIVE_HOST: () => (/* binding */ NATIVE_HOST),
/* harmony export */   PASSWORD_EXPIRED_URL: () => (/* binding */ PASSWORD_EXPIRED_URL),
/* harmony export */   PERMISSIONS: () => (/* binding */ PERMISSIONS),
/* harmony export */   PLATFORM_DOMAIN1: () => (/* binding */ PLATFORM_DOMAIN1),
/* harmony export */   PLATFORM_DOMAIN2: () => (/* binding */ PLATFORM_DOMAIN2),
/* harmony export */   RDP_SOAP_URL: () => (/* binding */ RDP_SOAP_URL),
/* harmony export */   RECORDING_FAILED_RETRY_COUNT: () => (/* binding */ RECORDING_FAILED_RETRY_COUNT),
/* harmony export */   REDIRCTION_URLS: () => (/* binding */ REDIRCTION_URLS),
/* harmony export */   SALESFORCE_SUBDOMAINS: () => (/* binding */ SALESFORCE_SUBDOMAINS),
/* harmony export */   SAML_URL: () => (/* binding */ SAML_URL),
/* harmony export */   SERVER_TYPE: () => (/* binding */ SERVER_TYPE),
/* harmony export */   SSGUID: () => (/* binding */ SSGUID),
/* harmony export */   UNKNOWN_VERSION: () => (/* binding */ UNKNOWN_VERSION),
/* harmony export */   URL_PATTERN: () => (/* binding */ URL_PATTERN),
/* harmony export */   WPF_HINTS_SECTION: () => (/* binding */ WPF_HINTS_SECTION),
/* harmony export */   secretAction: () => (/* binding */ secretAction),
/* harmony export */   secretStates: () => (/* binding */ secretStates),
/* harmony export */   ssCloud: () => (/* binding */ ssCloud)
/* harmony export */ });
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(666);
/* harmony import */ var _core_ext__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_core_ext__WEBPACK_IMPORTED_MODULE_0__);


const DEFAULT_RECORDING_LIMIT = 120; // in minutes (2 Hours)
const MAX_RECORDING_LIMIT = 480; // in minutes (8 Hours)
const RDP_SOAP_URL = "/Rdp/v2/rdpwebservice.asmx";
const SAML_URL = "/AlreadyLoggedIn.aspx";
const PASSWORD_EXPIRED_URL = "/PasswordExpired.aspx";
const LICENSES_URL = "/licenses.aspx";
const GASETUP_URL = "/GASetup.aspx";
const SSGUID = "f8f49a36873c4d579b30b4238c2563fb";
const NATIVE_HOST = "com.thycotic.wpf.host";
const CM_NATIVE_HOST = "com.delinea.cm.message_host";
const WPF_HINTS_SECTION = "WPFHints";
const RECORDING_FAILED_RETRY_COUNT = 15;
const INPUT_THRESHOLD = 10;
const URL_PATTERN = ["http://*/*", "https://*/*"];
const SALESFORCE_SUBDOMAINS = /https:\/\/.*\.my\.salesforce\.com/i;
const PLATFORM_DOMAIN1 = /(https|http)?:\/\/([\w\d-]+\.)*?secureplatform\.io(\/)?$/;
const PLATFORM_DOMAIN2 = /(https|http)?:\/\/([\w\d-]+\.)*?delinea\.app(\/)?$/;
const KEYWORDS = ["captureInterval", "matchUrl"];
const UNKNOWN_VERSION = "0.0.0";
const REDIRCTION_URLS = [PASSWORD_EXPIRED_URL, LICENSES_URL, GASETUP_URL];
const CLIENT_ID = 'a654aa7b-46c1-4138-81b2-67e8392426e8';
const APP_NAME = 'Web Password Filler';

/* eslint-disable max-len */
const ICONS = {
  GLOBE: (_core_ext__WEBPACK_IMPORTED_MODULE_0___default()) && (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime) && _core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime.getURL("images/globe.svg"),

  DELINEA: (_core_ext__WEBPACK_IMPORTED_MODULE_0___default()) && (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime) && _core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime.getURL("icons/icon.png"),

  RECORDING: (_core_ext__WEBPACK_IMPORTED_MODULE_0___default()) && (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime) && _core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime.getURL("icons/record.png"),

  MOUSE_POINTER: (_core_ext__WEBPACK_IMPORTED_MODULE_0___default()) && (_core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime) && _core_ext__WEBPACK_IMPORTED_MODULE_0___default().runtime.getURL("icons/handCursor.png"),

  FOLDER: `<svg  width="17px" height="13px" viewBox="0 0 17 13" version="1.1"
  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <title>outline-folder-24px (1)</title>
  <g id="UX-Flow" stroke="none" stroke-width="1"
  fill="none" fill-rule="evenodd">
  <g id="Web-Password-Filler-(Add)---Folder-Selection"
  transform="translate(-140.000000, -257.000000)">
  <g id="outline-folder-24px-(1)"
  transform="translate(138.000000, 254.000000)">
  <polygon id="Path" points="0 0 20 0 20 20 0 20"></polygon>
  <polygon id="Path" points="0 0 20 0 20 20 0 20"></polygon>
  <path d="M8.0945,4.625 L9.7945,6.25 L17.3,6.25 L17.3,
  14.375 L3.7,14.375 L3.7,4.625 L8.0945,4.625 L8.0945,
  4.625 Z M8.8,3 L3.7,3 C2.765,3 2.0085,3.73125 2.0085,
  4.625 L2,14.375 C2,15.26875 2.765,16 3.7,16 L17.3,
  16 C18.235,16 19,15.26875 19,14.375 L19,6.25 C19,
  5.35625 18.235,4.625 17.3,4.625 L10.5,4.625 L8.8,3 Z"
  id="Shape" fill="#C2CFDA" fill-rule="nonzero"></path>
  </g></g></g></svg> `,
};

const ACTIVE_TAB_QUERY = {
  active: true,
  currentWindow: true,
  windowType: "normal",
  highlighted: true,
  // url: URL_PATTERN,
};

const ACTIVE_TAB_QUERY_MIN_REQ = {
  active: true,
  currentWindow: true,
};

const MULTI_DOMAIN = [
  {
    name: "MICROSOFT",
    values: ["https://login.live.com", "https://login.microsoftonline.com/"],
    domains: ["live.com", "microsoftonline.com"],
  },
];

const secretStates = {
  none: "none",
  requiresComment: "requirescomment",
  requiresCheckoutAndComment: "requirescheckoutandcomment",
  requiresCheckout: "requirescheckout",
  requiresApproval: "requiresapproval",
  requiresMFAChallenge: "requiresmfachallenge",
};

const CONTENT = {
  APP_JSON: "application/json",
  APP_URL_ENCODED: "application/x-www-form-urlencoded",
  TEXT_XML: "text/xml",
};

const SERVER_TYPE = {
  SS: "Secret Server",
  PLATFORM: "Delinea Platform",
};

const API = {
  GOOGLE_FAVICON: "https://www.google.com/s2/favicons?domain=",
};

const secretAction = {
  launch: "launch-secret",
  view: "view-secret",
  fillSecret: "fill-secret",
  copyUsername: "copy-username",
  copyPassword: "copy-password",
  copyOtp: "copy-otp-code",
};

const MFA_OPTIONS = {
  PUSH: "push",
  SMS: "SMS",
  PHONE: "phone",
};

const PERMISSIONS = {
  AddSecret: "Add Secret",
  EditSecret: "Edit Secret",
  ViewSecret: "View Secret",
};

const ssCloud = {
  PUSH: "push",
  SMS: "SMS",
  PHONE: "phone",
};


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   t: () => (/* binding */ DOMAIN_EXT)
/* harmony export */ });
/* eslint-disable max-len */
const DOMAIN_EXT = new Set (['.com', '.org', '.net', '.info', '.biz', '.us', '.co', '.me', '.io', '.xyz', '.pro', '.app', '.online', '.store', '.site', '.tech', '.club', '.blog', '.design', '.art', '.co.uk', '.org.uk', '.gov.uk', '.com.au',
  '.com.br', '.com.mx', '.com.sg', '.edu.au', '.ac.uk', '.gov.in', '.com.ph', '.com.cn', '.com.hk', '.gov.ca', '.net.au', '.edu.in', '.gov.au', '.org.nz', '.co.nz', '.com.de', '.edu', '.mil', '.tel', '.int',
  '.cat', '.jobs', '.travel', '.name', '.mobi', '.cc', '.tv', '.co.in', '.accountant', '.architect', '.beauty', '.furniture', '.net.pe', '.org.pe', '.toys', '.yachts', '.aaa.pro', '.ab.ca', '.abc.br', '.abo.pa', '.abogado', '.abudhabi',
  '.ac', '.ac.cr', '.ac.id', '.ac.ke', '.ac.mu', '.ac.ni', '.ac.nz', '.ac.pa', '.ac.th', '.ac.vn', '.aca.pro', '.academy', '.accountant', '.accountants', '.acct.pro', '.actor', '.ad', '.ads',
  '.adult', '.adult.ht', '.ae', '.ae.org', '.aero', '.af', '.africa', '.africa.com', '.ag', '.agency', '.ai', '.airforce', '.al', '.alsace', '.am', '.amsterdam', '.analytics', '.antivirus',
  '.apartments', '.aq', '.aquitaine', '.ar.com', '.arab', '.archi', '.architect', '.army', '.art.do', '.arts.nf', '.arts.ve', '.as', '.asia', '.asn.au', '.asn.lv', '.asso.km',
  '.asso.mc', '.associates', '.at', '.attorney', '.auction', '.audio', '.author', '.auto', '.autos', '.avocat.pro', '.aw', '.ax', '.az', '.ba', '.baby', '.band', '.bank', '.banque', '.bar',
  '.bar.pro', '.barcelona', '.bargains', '.baseball', '.basketball', '.bayern', '.bb', '.bc.ca', '.bcn', '.be', '.beauty', '.beer', '.belem.br', '.berlin', '.best', '.bet', '.bg', '.bh', '.bi',
  '.bib.ve', '.bible', '.bid', '.bike', '.bingo', '.bio', '.biz.az', '.biz.bb', '.biz.ck', '.biz.cy', '.biz.et', '.biz.fj', '.biz.ki', '.biz.mv', '.biz.ng', '.biz.nr', '.biz.om', '.biz.pk',
  '.biz.pl', '.biz.pr', '.biz.tj', '.biz.tr', '.biz.tt', '.biz.vn', '.bj', '.black', '.blackfriday', '.blog.br', '.blue', '.bm', '.bo', '.boats', '.bom', '.bond', '.boo', '.book', '.boston',
  '.bot', '.boutique', '.br.com', '.broadway', '.broker', '.brussels', '.bs', '.bt', '.budapest', '.build', '.builders', '.business', '.buy', '.buzz', '.bw', '.by', '.bz', '.bzh', '.ca', '.cab',
  '.cafe', '.cal', '.call', '.cam', '.camera', '.camp', '.cancerresearch', '.capetown', '.capital', '.car', '.cards', '.care', '.career', '.careers', '.cars', '.casa', '.cash', '.casino',
  '.catering', '.catholic', '.cd', '.center', '.ceo', '.cf', '.cfa', '.cfd', '.cg', '.ch', '.channel', '.charity', '.chat', '.cheap', '.christmas', '.church', '.ci', '.cin.kg', '.circle',
  '.city', '.ck', '.cl', '.claims', '.cleaning', '.click', '.clinic', '.clothing', '.cloud', '.club.tw', '.cm', '.cn', '.cn.com', '.cnidn', '.cnregional', '.co.ae', '.co.ag', '.co.ao',
  '.co.at', '.co.az', '.co.bb', '.co.bi', '.co.bw', '.co.bz', '.co.ci', '.co.ck', '.co.cm', '.co.com', '.co.cr', '.co.de', '.co.dm', '.co.ee', '.co.fk', '.co.gg', '.co.gl', '.co.gy', '.co.id', '.co.il',
  '.co.ir', '.co.je', '.co.jp', '.co.ke', '.co.lc', '.co.ls', '.co.ma', '.co.me', '.co.mu', '.co.mw', '.co.mz', '.co.na', '.co.ni', '.co.nl', '.co.no', '.co.nu', '.co.om', '.co.pn',
  '.co.rs', '.co.sh', '.co.th', '.co.tj', '.co.tt', '.co.tz', '.co.ug', '.co.ve', '.co.vi', '.co.za', '.co.zm', '.co.zw', '.coach', '.codes', '.coffee', '.college', '.cologne',
  '.com.af', '.com.ag', '.com.al', '.com.an', '.com.aq', '.com.ar', '.com.az', '.com.ba', '.com.bb', '.com.bd', '.com.bh', '.com.bi', '.com.bj', '.com.bm', '.com.bn', '.com.bo',
  '.com.bs', '.com.bt', '.com.bw', '.com.by', '.com.bz', '.com.ca', '.com.ci', '.com.cm', '.com.cn', '.com.co', '.com.cu', '.com.cv', '.com.cy', '.com.do', '.com.dz', '.com.ec',
  '.com.ee', '.com.eg', '.com.es', '.com.et', '.com.fj', '.com.ge', '.com.gh', '.com.gi', '.com.gl', '.com.gn', '.com.gp', '.com.gt', '.com.gu', '.com.gy', '.com.hn', '.com.hr', '.com.ht',
  '.com.io', '.com.jm', '.com.jo', '.com.kg', '.com.kh', '.com.ki', '.com.km', '.com.kn', '.com.kw', '.com.ky', '.com.kz', '.com.lb', '.com.lc', '.com.lk', '.com.lr', '.com.ls', '.com.lv', '.com.ly',
  '.com.mk', '.com.mm', '.com.mo', '.com.mt', '.com.mu', '.com.mv', '.com.mw', '.com.my', '.com.na', '.com.nf', '.com.ng', '.com.ni', '.com.np', '.com.nr', '.com.om', '.com.pa', '.com.pe',
  '.com.pf', '.com.pg', '.com.ph', '.com.pk', '.com.pl', '.com.pn', '.com.pr', '.com.ps', '.com.pt', '.com.py', '.com.qa', '.com.sa', '.com.sb', '.com.sc', '.com.sd', '.com.se', '.com.sh',
  '.com.sl', '.com.sn', '.com.so', '.com.sv', '.com.tj', '.com.tl', '.com.tm', '.com.tn', '.com.tr', '.com.tt', '.com.tw', '.com.ua', '.com.ug', '.com.uy', '.com.vc', '.com.ve', '.com.vi', '.com.vn',
  '.com.ws', '.com.ye', '.community', '.company', '.compare', '.computer', '.condos', '.conf.au', '.conf.lv', '.construction', '.consulting', '.contact', '.contractors', '.cooking', '.cool', '.coop',
  '.coop.km', '.corp', '.corsica', '.country', '.coupon', '.coupons', '.courses', '.cpa', '.cpa.pro', '.cr', '.credit', '.creditcard', '.creditunion', '.cricket', '.cruise', '.cruises', '.cu', '.cv',
  '.cw', '.cx', '.cy', '.cymru', '.cz', '.dad', '.dance', '.data', '.date', '.dating', '.day', '.dds', '.de', '.de.com', '.deal', '.dealer', '.deals', '.degree', '.delivery', '.democrat', '.dental',
  '.dentist', '.desi', '.dev', '.diamonds', '.diet', '.digital', '.direct', '.directory', '.discount', '.diy', '.dj', '.dk', '.dm', '.do', '.docs', '.doctor', '.dog', '.domains', '.dot',
  '.download', '.drive', '.dubai', '.durban', '.dz', '.earth', '.eat', '.ebiz.tw', '.ec', '.eco', '.ecom', '.edu.bb', '.edu.bi', '.edu.bz', '.edu.do', '.edu.gl', '.edu.gy', '.edu.ki', '.edu.km',
  '.edu.lk', '.edu.lv', '.edu.mm', '.edu.ni', '.edu.np', '.edu.pa', '.edu.pl', '.edu.pt', '.edu.sl', '.edu.sv', '.edu.ve', '.edu.vg', '.edu.vn', '.education', '.ee', '.eg', '.email', '.emp.br',
  '.energy', '.eng.pro', '.engineer', '.engineering', '.enterprises', '.equipment', '.erotica.hu', '.es', '.esp.br', '.esq', '.estate', '.et', '.eu', '.eu.com', '.eus', '.events', '.exchange',
  '.expert', '.exposed', '.express', '.fail', '.faith', '.family', '.fan', '.fans', '.far.br', '.farm', '.fashion', '.fast', '.feedback', '.fi', '.film', '.fin.ec', '.final', '.finance',
  '.financial', '.financialaid', '.finish', '.fire', '.firm.in', '.firm.nf', '.firm.ve', '.fish', '.fishing', '.fit', '.fitness', '.flights', '.floripa.br', '.florist', '.flowers', '.fly',
  '.fm', '.fo', '.foo', '.food', '.football', '.forex', '.forsale', '.forum', '.foundation', '.fr', '.free', '.frl', '.fun', '.fund', '.furniture', '.futbol', '.fyi', '.ga', '.gal', '.gallery',
  '.game', '.game.tw', '.games', '.garden', '.gay', '.gb.com', '.gb.net', '.gd', '.gdn', '.ge', '.geek.nz', '.gen.ck', '.gen.in', '.gen.nz', '.gen.tr', '.gent', '.gf', '.gg', '.gh', '.gi',
  '.gift', '.gifts', '.gives', '.giving', '.gl', '.glass', '.global', '.gm', '.gmbh', '.go.id', '.gold', '.golf', '.gop', '.got', '.gouv.km', '.gov.bb', '.gov.gy', '.gov.ki', '.gov.mm', '.gov.np',
  '.gov.pt', '.gov.sv', '.gov.vn', '.gp', '.gq', '.gr', '.gr.com', '.gr.jp', '.graphics', '.gratis', '.green', '.gripe', '.grocery', '.group', '.gs', '.gt', '.guge', '.guide', '.guitars', '.guru',
  '.gy', '.hair', '.halal', '.hamburg', '.hangout', '.haus', '.health', '.health.vn', '.healthcare', '.help', '.helsinki', '.here', '.hiphop', '.hiv', '.hk', '.hm', '.hn', '.hockey', '.holdings',
  '.holiday', '.home', '.homes', '.horse', '.hospital', '.host', '.hosting', '.hot', '.hoteis', '.hotel', '.hoteles', '.hotels', '.house', '.how', '.hr', '.ht', '.hu', '.hu.com', '.hu.net', '.icu',
  '.id', '.id.au', '.id.lv', '.idn', '.idv.tw', '.ie', '.im', '.imamat', '.immo', '.immobilien', '.in', '.in.net', '.in.th', '.inc', '.ind.br', '.ind.gt', '.ind.in', '.industries',
  '.info.au', '.info.az', '.info.bb', '.info.bi', '.info.ck', '.info.ec', '.info.et', '.info.fj', '.info.ht', '.info.hu', '.info.ke', '.info.ki', '.info.mv', '.info.nf', '.info.nr', '.info.pl',
  '.info.pr', '.info.tr', '.info.tt', '.info.ve', '.info.vn', '.ing', '.ing.pa', '.ink', '.institute', '.insurance', '.insure', '.int.ve', '.int.vn', '.international', '.investments',
  '.iq', '.ir', '.irish', '.is', '.isla.pr', '.islam', '.ismaili', '.ist', '.istanbul', '.it', '.it.ao', '.its.me', '.jampa.br', '.je', '.jetzt', '.jewelry', '.jo', '.joburg', '.jot',
  '.joy', '.jp', '.jp.net', '.jpn.com', '.juegos', '.jur.pro', '.kaufen', '.ke', '.kg', '.ki', '.kid', '.kids', '.kiev.ua', '.kim', '.kitchen', '.kiwi', '.kiwi.nz', '.km', '.kn', '.koeln', '.kosher',
  '.kr', '.kr.com', '.krd', '.ky', '.kyoto', '.kz', '.la', '.land', '.lat', '.latino', '.law', '.law.pro', '.lawyer', '.lb', '.lc', '.lds', '.lease', '.legal', '.lgbt', '.li', '.life',
  '.lifeinsurance', '.lifestyle', '.lighting', '.like', '.limited', '.limo', '.link', '.live', '.living', '.lk', '.llc', '.llp', '.loan', '.loans', '.lol', '.london', '.lotto', '.love', '.lr',
  '.ls', '.lt', '.ltd', '.ltd.im', '.ltd.uk', '.ltda', '.lu', '.luxe', '.luxury', '.lv', '.ly', '.ma', '.macapa.br', '.madrid', '.mail', '.maison', '.makeup', '.man', '.management', '.maori.nz',
  '.map', '.market', '.marketing', '.markets', '.mba', '.mc', '.md', '.me.ke', '.me.uk', '.med', '.med.ec', '.med.pa', '.med.pro', '.medecin.km', '.media', '.medical', '.meet', '.melbourne',
  '.meme', '.memorial', '.men', '.menu', '.mex.com', '.mg', '.miami', '.mil.id', '.mil.km', '.mil.mm', '.mil.np', '.minsk.by', '.mk', '.ml', '.mls', '.mn', '.mo', '.mo.bi', '.mobi.ke',
  '.mobile', '.moda', '.moe', '.moi', '.mom', '.money', '.monster', '.mormon', '.mortgage', '.moscow', '.moto', '.motorcycles', '.mov', '.movie', '.mp', '.mq', '.mr', '.ms', '.mt', '.mu', '.museum',
  '.music', '.mutual', '.mutualfunds', '.mutuelle', '.mv', '.mw', '.mx', '.my', '.my.tj', '.mz', '.na', '.nagoya', '.name.ae', '.name.az', '.name.cy', '.name.eg', '.name.et', '.name.fj',
  '.name.jo', '.name.mv', '.name.pr', '.name.tr', '.name.tt', '.name.vn', '.navy', '.nc', '.ne.jp', '.ne.ke', '.ne.tz', '.ne.ug', '.net.ae', '.net.af', '.net.ag', '.net.al', '.net.ar',
  '.net.az', '.net.ba', '.net.bb', '.net.bd', '.net.bh', '.net.bm', '.net.bn', '.net.bo', '.net.br', '.net.bs', '.net.by', '.net.bz', '.net.ck', '.net.cm', '.net.cn', '.net.co', '.net.cv',
  '.net.cy', '.net.do', '.net.dz', '.net.ec', '.net.eg', '.net.et', '.net.fj', '.net.ge', '.net.gg', '.net.gl', '.net.gn', '.net.gp', '.net.gr', '.net.gt', '.net.gu', '.net.gy', '.net.hn',
  '.net.ht', '.net.id', '.net.il', '.net.in', '.net.io', '.net.ir', '.net.je', '.net.jm', '.net.jo', '.net.kg', '.net.kh', '.net.ki', '.net.kn', '.net.kw', '.net.ky', '.net.kz', '.net.lb',
  '.net.lc', '.net.lk', '.net.lr', '.net.ls', '.net.lv', '.net.ly', '.net.ma', '.net.me', '.net.mm', '.net.mo', '.net.mt', '.net.mu', '.net.mv', '.net.mw', '.net.mx', '.net.my', '.net.nf',
  '.net.ng', '.net.ni', '.net.np', '.net.nr', '.net.nz', '.net.om', '.net.pa', '.net.pe', '.net.pg', '.net.ph', '.net.pk', '.net.pl', '.net.pn', '.net.pr', '.net.ps', '.net.py', '.net.qa',
  '.net.ru', '.net.sa', '.net.sb', '.net.sc', '.net.sg', '.net.sh', '.net.sl', '.net.so', '.net.th', '.net.tj', '.net.tl', '.net.tn', '.net.tr', '.net.tt', '.net.tw', '.net.ua', '.net.uk',
  '.net.uy', '.net.vc', '.net.ve', '.net.vi', '.net.vn', '.net.ws', '.net.za', '.network', '.new', '.news', '.nf', '.ng', '.ngo', '.ni', '.nic.im', '.ninja', '.nl', '.no', '.no.com', '.nom.ad',
  '.nom.ag', '.nom.br', '.nom.co', '.nom.es', '.nom.fr', '.nom.km', '.nom.ni', '.nom.pa', '.nom.pe', '.nom.ve', '.notaires.km', '.now', '.nowruz', '.nr', '.nrw', '.nu', '.nuidn', '.nyc', '.nz',
  '.observer', '.off', '.okinawa', '.om', '.one', '.ong', '.onl', '.ooo', '.open', '.or.at', '.or.bi', '.or.cr', '.or.id', '.or.jp', '.or.ke', '.or.th', '.or.tz', '.or.ug',
  '.org.ae', '.org.af', '.org.ag', '.org.al', '.org.ar', '.org.au', '.org.az', '.org.ba', '.org.bb', '.org.bd', '.org.bh', '.org.bi', '.org.bm', '.org.bn', '.org.bo', '.org.br', '.org.bs',
  '.org.bw', '.org.bz', '.org.ck', '.org.cn', '.org.cv', '.org.cy', '.org.do', '.org.dz', '.org.ec', '.org.eg', '.org.es', '.org.et', '.org.fj', '.org.ge', '.org.gg', '.org.gh', '.org.gi',
  '.org.gl', '.org.gn', '.org.gr', '.org.gt', '.org.gu', '.org.gy', '.org.hn', '.org.ht', '.org.hu', '.org.il', '.org.in', '.org.io', '.org.ir', '.org.je', '.org.jm', '.org.jo', '.org.kg',
  '.org.kh', '.org.ki', '.org.kn', '.org.ky', '.org.kz', '.org.lb', '.org.lc', '.org.lk', '.org.lr', '.org.ls', '.org.lv', '.org.ly', '.org.ma', '.org.me', '.org.mm', '.org.mo', '.org.mt',
  '.org.mu', '.org.mv', '.org.mw', '.org.mx', '.org.my', '.org.mz', '.org.na', '.org.nf', '.org.ng', '.org.ni', '.org.np', '.org.nr', '.org.om', '.org.os', '.org.pa', '.org.pe',
  '.org.pg', '.org.ph', '.org.pk', '.org.pl', '.org.pn', '.org.pr', '.org.ps', '.org.pt', '.org.py', '.org.qa', '.org.rs', '.org.ru', '.org.sa', '.org.sb', '.org.sc', '.org.sh', '.org.sl',
  '.org.sn', '.org.so', '.org.sv', '.org.tj', '.org.tl', '.org.to', '.org.tr', '.org.tt', '.org.tw', '.org.ua', '.org.ug', '.org.uy', '.org.vc', '.org.ve', '.org.vi', '.org.vn',
  '.org.ws', '.org.za', '.organic', '.osaka', '.other.nf', '.oz.au', '.pa', '.page', '.paris', '.pars', '.partners', '.parts', '.party', '.pay', '.pe', '.per.kh', '.per.nf', '.persiangulf',
  '.pet', '.pets', '.pf', '.ph', '.pharmaciens.km', '.pharmacy', '.phd', '.phone', '.photo', '.photography', '.photos', '.physio', '.pics', '.pictures', '.pid', '.pin', '.ping', '.pink',
  '.pizza', '.pk', '.pl', '.place', '.play', '.plc.im', '.plc.uk', '.plumbing', '.plus', '.pm', '.pn', '.poa.br', '.poker', '.porn', '.pp.ru', '.pr', '.press', '.presse.fr', '.presse.km',
  '.priv.me', '.priv.no', '.pro.ae', '.pro.ec', '.pro.fj', '.pro.pr', '.pro.vn', '.prod', '.productions', '.prof', '.promo', '.properties', '.property', '.protection', '.ps',
  '.pt', '.pub', '.pvt.ge', '.pw', '.py', '.qa', '.qc.ca', '.qc.com', '.qpon', '.quebec', '.racing', '.radio', '.radio.am', '.radio.fm', '.re', '.read', '.realestate', '.realtor',
  '.realty', '.rec.nf', '.rec.ve', '.recht.pro', '.recife.br', '.recipes', '.red', '.rehab', '.reise', '.reisen', '.reit', '.ren', '.rent', '.rentals', '.repair', '.report', '.republican',
  '.res.in', '.rest', '.restaurant', '.retirement', '.review', '.reviews', '.rich', '.rio', '.rio.br', '.rip', '.ro', '.rocks', '.rodeo', '.room', '.rs', '.rsvp', '.ru', '.ru.com',
  '.rugby', '.ruhr', '.run', '.rw', '.ryukyu', '.sa', '.sa.com', '.saarland', '.safe', '.safety', '.sale', '.salon', '.sarl', '.sas', '.save', '.sb', '.sc', '.sc.ke', '.sch.id',
  '.scholarships', '.school', '.school.nz', '.schule', '.science', '.scot', '.sd', '.se', '.se.com', '.se.net', '.search', '.secure', '.security', '.services', '.sex', '.sexy',
  '.sg', '.sh', '.shiksha', '.shoes', '.shop', '.shopping', '.show', '.si', '.silk', '.singles', '.sjc.br', '.sk', '.ski', '.skin', '.sl', '.sld.pa', '.sm', '.smile',
  '.sn', '.so', '.soccer', '.social', '.software', '.solar', '.solutions', '.song', '.soy', '.spa', '.space', '.sport', '.sports', '.spot', '.spreadbetting', '.sr', '.srl',
  '.st', '.stockholm', '.storage', '.store.bb', '.store.nf', '.store.ve', '.stream', '.studio', '.study', '.style', '.su', '.sucks', '.supplies', '.supply',
  '.support', '.surf', '.surgery', '.sv', '.swiss', '.sx', '.sy', '.sydney', '.systems', '.taipei', '.talk', '.tatar', '.tattoo', '.tax', '.taxi', '.tc', '.td', '.team',
  '.technology', '.tennis', '.tf', '.tg', '.th', '.thai', '.theater', '.theatre', '.tickets', '.tienda', '.tips', '.tires', '.tirol', '.tj', '.tk', '.tl', '.tm', '.tm.cy',
  '.tm.fr', '.tm.km', '.tm.mc', '.tn', '.to', '.today', '.tokyo', '.tools', '.top', '.tour', '.tours', '.town', '.toys', '.trade', '.trading', '.training', '.translations',
  '.tt', '.tube', '.tunes', '.tur.br', '.tv.bb', '.tv.br', '.tw', '.twidn', '.ua', '.ug', '.uk', '.uk.com', '.uk.net', '.um', '.university', '.uno', '.us.com', '.us.org',
  '.uy', '.uy.com', '.uz', '.vacations', '.vc', '.ve', '.vegas', '.ventures', '.versicherung', '.vet', '.veterinaire.km', '.vg', '.vi', '.viajes', '.video', '.villas', '.vin', '.vip',
  '.vision', '.vix.br', '.vlaanderen', '.vn', '.vodka', '.vote', '.voting', '.voto', '.voyage', '.vu', '.wales', '.wang', '.watch', '.watches', '.waw.pl', '.weather', '.web', '.web.do',
  '.web.id', '.web.nf', '.web.pk', '.web.tj', '.web.tr', '.web.ve', '.web.za', '.webcam', '.webs', '.website', '.wed', '.wedding', '.weibo', '.wf', '.whoswho', '.wien', '.wiki', '.win',
  '.wine', '.winners', '.work', '.works', '.world', '.wow', '.ws', '.wtf', '.xihuan', '.xin', '.xxx', '.yachts', '.ye', '.yellowpages', '.yoga', '.yokohama', '.you', '.yt', '.yun',
  '.za.com', '.zip', '.zm', '.zone', '.zw']);


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ NOTIFY),
/* harmony export */   s: () => (/* binding */ ERR)
/* harmony export */ });
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(482);


/* eslint-disable max-len */
const ERR = {
  // eslint-disable-next-line
    INVALID_CERT_ERROR: 'The server you are attempting to reach presented a self signed certificate.',
  // eslint-disable-next-line
    EXPIRED_CERT_ERROR: 'The server you attempted to reach presented a self signed, untrusted or invalid certificate.',
  CERT_ERROR: "Web Password Filler is unable to validate the server certificate. Please contact your site administrator.",
  NO_WINDOWS_ADMIN_CENTER_SUPPORT(type) {
    return `No Windows Admin Center Support with Current version of ${type}`;
  },
  // eslint-disable-next-line
    WIN_AD_SESSION_RECORDING_NOT_SUPPORTED: 'Windows/AD Secret Session Recording Not Supported.',  
  SECRET_SAVE_FAILED(type) {
    return `Secret not saved. 
      Contact your ${type} Administrator for more information.`;
  },

  SECRET_UPDATE_FAILED(type) {
    return `There was an error updating the Secret.  
      Contact your ${type} Administrator to check your permissions.`;
  },

  UNAUTHORIZE: `You are not authorized to perform this operation. 
  Check your permissions with your Administrator`,

  PASSWORD_EXPIRED: `Your Secret Server password has expired, 
    login to Secret Server to reset your password.`,

  BAD_REQUEST: `Bad request. report this 
  error to Delinea support.`,

  safariGeneralError: "Unable to reach server. Verify that the server URL is correct, and that the server has a valid certificate.",

  requiresApprovalNotSupported(type) {
    return `In order to view this Secret you must request access from  ${type}`;
  },

  unknownSecretState(type) {
    return `This Secret has a security restriction that WPF does not support. Complete the challenge in ${type} to view this Secret.`;
  },

  CHECK_OUT_REQUIRED(type) {
    return `Secret requires check out in  ${type}`;
  },

  COMMENTS_REQUIRED(type) {
    return `Secret requires comments in ${type}`;
  },

  CHECK_OUT_AND_COMMENTS_REQUIRED(type) {
    return `Secret requires check out and comments in ${type}`;
  },
  PERMISSION_SETTING(type) {
    return `Your permissions have been configured by your ${type} Admin.`;
  },

  logoutPopMsg(number) {
    return `${number} tab has security restrictions. Logging out of Web Password Filler will close this tab.`;
  },

  logoutPopMsgPlural(number) {
    return `${number} tabs have security restrictions. Logging out of Web Password Filler will close these tabs.`;
  },

  contentLogoutMsg(number, checkServer) {
    return `You are not logged in to ${checkServer}. However, ${number} tab with security restrictions is still open, and will be closed if you logout from Web Password Filler.`;
  },

  contentLogoutMsgPlural(number, checkServer) {
    return `You are not logged in to ${checkServer}. However, ${number} tabs with security restrictions are still open, and will be closed if you logout from Web Password Filler.`;
  },

  CHECK_OUT_BY_ANOTHER_USER: "This Secret is currently checked out to another user",

  SESSION_RECORDING_NOTSUPPORTED: "Session Recording is not supported on this browser version",

  SESSION_RECORDING_NOTSUPPORTED_ONSAFARI15: "Session Recording is not supported on safari version 15 and above.",
  LOGIN_FAILED: "Login failed.",

  INVALID_SECRET_NAME_PATTERN(type) {
    return `Invalid Secret Name Pattern. If you need more information regarding the secret naming standards, 
      contact your ${type} Administrator`;
  },

  TICKET_REQ: "Enter ticket and comment to view secret.",

  COMMENT_REQ: "Enter comment to view secret.",

  VERSIONHIDESETTING: "User is not able to add comment remotely because 'Hide Secret Server Version Number' is enabled",

  SWITCH_SS(url) {
    return `Web Password Filler does not recognize ${url} as a trusted vault. You must first log in to this vault in Web Password Filler`;
  },

  TICKET_ERROR: "Error occured while gettting ticket details",

  API_NOT_SUPPORTED(feature, ssVersion) {
    return `${feature} is not supported in Secret Server version ${ssVersion}`;
  },
  requiredCommentNotSupported(ssVersion) {
    return `Version ${ssVersion} of Secret Server does not support adding a comment remotely.`;
  },

  SECRET_UPDATED(type) {
    return `${type} just updated your password.`;
  },

  SECRET_SAVED(type) {
    return `${type} just saved your password.`;
  },

  NO_SECRET: "No data found",

  NOT_LOGGEDIN_WPF: "You must be logged in to Web Password Filler to launch this secret. Log in with your Delinea Platform url and try again.",

  LOGGEDIN_WPF: `Web Password Filler is currently logged in to a different tenant and cannot launch this secret.
            Log in with your Delinea Platform url and try again.`,

  INVALID_DUO_PIN_CODE: [
    "Invalid Duo pin code.",
    "Duo PIN コードが無効です。",
    "Duo PIN 코드가 올바르지 않습니다.",
    "Código pin do Duo inválido.",
    "Ungültiger Duo-PIN-Code.",
    "Code PIN Duo non valide.",
  ],

  INVALID_TOTP_AUTHENTICATOR_PIN_CODE: [
    "Invalid TOTP Authenticator pin code.",
    "TOTP オーセンティケーターの PIN コードが無効です。",
    "TOTP 인증기 PIN 코드가 올바르지 않습니다.",
    "Código pin do TOTP Authenticator inválido.",
    "Ungültiger PIN-Code für TOTP-Authentifikator.",
    "TOTP 鑑別器 PIN 碼無效。",
  ],

  DUO_PUSH_VERIFICATION_FAILED_LOGIN_REQUEST_DENIED: [
    "Duo Push verification failed: Login request denied.",
    "Duo Push 検証に失敗しました",
    "Duo Push 확인이 실패함",
    "Echec de la vérification de Duo Push",
    "Verifizierung für Duo-Push-Operation fehlgeschlagen",
    "A verificação do Duo Push falhou",
  ],

  DUO_PUSH_VERIFICATION_FAILED_LOGIN_TIMEDOUT:
      "Duo Push verification failed: Login timed out.",

  FETCHING_TEMPLATE_FAILED:
      "There was an error while fetching templates and folders",
  INVALID_TEMPLATE: "Provided Secret Template is invalid.",
  INVALID_FOLDER: "Provided Secret Folder is invalid.",
  SAML_INVALID_TOKEN: "Failed to acquire valid token",
  // eslint-disable-next-line
  CONNECTION_LOST: 'Lost connection to session recording server, closing session',
  SESSION_INIT_ERROR: "Error occurred while initiating a new session",
  INCOGNITO_NOT_ENABLED: "Secret configured to launch using an incognito/private window, extension must be enabled for 'Allow in Incognito'/ 'Run in Private Window' to launch this secret",
  INCOGNITO_SECRET_IN_NORMAL_WINDOW_AUTOFILL_ERROR: "Autofill for the secret will only work in incognito window as secret configured to launch in incognito/private window",
  RADIUS_AUTHENTICATION_FAILED: [
    "RADIUS Authentication Failed.",
    "RADIUS 인증이 실패했습니다.",
    "A Autenticação RADIUS falhou.",
    "RADIUS 認証に失敗しました。",
    "RADIUS-Authentifizierung fehlgeschlagen.",
  ],
  REQUEST_TIMED_OUT: "This server is not responding. Try again or contact your administrator.",
  INVALID_SS_URL: "Not a valid Platform or Secret Server URL.",
  SSL_VERIFICATION_FAILED: "SSL Verification Failed",
  METADATA_SECTION_ACCESS_DENIED: "Additional permissions required to add a new metadata section, contact your administrator for more details",
  COMMENT_SAVE_FAILED: "Comment not saved.",
  CHECKOUT_FAILED: "Secret not checked out.",
  MFA_REQUIRED: "You must complete your Multifactor Challenge to view this Secret.",
  PASSWORD_REQUIRMENT(message, serverType) {
    return `${message} If you need more information, 
      contact your ${serverType} Administrator`;
  },
  NO_DEFAULT_VAULT_CONFIGURED: "No Default Vault Configured",
  FETCHING_SECRETS_FAILED: "Error occurred while fetching secrets.",
  FAILED_TO_FETCH_WINAD: "Error occurred while getting Windows Account and Active Directory secrets",
  FAILED_TO_FETCH_ADD_SECRET: "Failed to fetch templates, folders and sites",
};

const NOTIFY = {

  COPIED_TO_CLIPBOARD: "Password copied to clipboard.",

  LOGIN_REQUIRED: `You must log into the extension to use the 
      web launcher`,

  LOADING_TEMPLATES: "Fetching templates and folders...",

  NO_TEMPLATES: "No templates found.",

  NO_FOLDERS: "No folders available to add a secret.",

  SESSION_RECORDED: "This session will be recorded for auditing purposes",

  MAX_RECORDING_REACHED: `Your session has reached to maximum limit, 
    session will be closed immediately.`,

  COPYMSG(type) {
    if (type === _constants__WEBPACK_IMPORTED_MODULE_0__.secretAction.copyUsername) {
      return "Username copied to clipboard";
    }
    if (type === _constants__WEBPACK_IMPORTED_MODULE_0__.secretAction.copyPassword) {
      return "Password copied to clipboard";
    }
    if (type === _constants__WEBPACK_IMPORTED_MODULE_0__.secretAction.copyOtp) {
      return "OTP copied to clipboard";
    }
  },

};


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// 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](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 });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__(458);
/******/ 	
/******/ })()
;
//# sourceMappingURL=contentscript.js.map