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

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

"use strict";


const validator = __webpack_require__(918);
const XMLParser = __webpack_require__(923);
const XMLBuilder = __webpack_require__(904);

module.exports = {
  XMLParser: XMLParser,
  XMLValidator: validator,
  XMLBuilder: XMLBuilder
}

/***/ }),

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

function getIgnoreAttributesFn(ignoreAttributes) {
    if (typeof ignoreAttributes === 'function') {
        return ignoreAttributes
    }
    if (Array.isArray(ignoreAttributes)) {
        return (attrName) => {
            for (const pattern of ignoreAttributes) {
                if (typeof pattern === 'string' && attrName === pattern) {
                    return true
                }
                if (pattern instanceof RegExp && pattern.test(attrName)) {
                    return true
                }
            }
        }
    }
    return () => false
}

module.exports = getIgnoreAttributesFn

/***/ }),

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

"use strict";


const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'
const regexName = new RegExp('^' + nameRegexp + '$');

const getAllMatches = function(string, regex) {
  const matches = [];
  let match = regex.exec(string);
  while (match) {
    const allmatches = [];
    allmatches.startIndex = regex.lastIndex - match[0].length;
    const len = match.length;
    for (let index = 0; index < len; index++) {
      allmatches.push(match[index]);
    }
    matches.push(allmatches);
    match = regex.exec(string);
  }
  return matches;
};

const isName = function(string) {
  const match = regexName.exec(string);
  return !(match === null || typeof match === 'undefined');
};

exports.isExist = function(v) {
  return typeof v !== 'undefined';
};

exports.isEmptyObject = function(obj) {
  return Object.keys(obj).length === 0;
};

/**
 * Copy all the properties of a into b.
 * @param {*} target
 * @param {*} a
 */
exports.merge = function(target, a, arrayMode) {
  if (a) {
    const keys = Object.keys(a); // will return an array of own properties
    const len = keys.length; //don't make it inline
    for (let i = 0; i < len; i++) {
      if (arrayMode === 'strict') {
        target[keys[i]] = [ a[keys[i]] ];
      } else {
        target[keys[i]] = a[keys[i]];
      }
    }
  }
};
/* exports.merge =function (b,a){
  return Object.assign(b,a);
} */

exports.getValue = function(v) {
  if (exports.isExist(v)) {
    return v;
  } else {
    return '';
  }
};

// const fakeCall = function(a) {return a;};
// const fakeCallNoReturn = function() {};

exports.isName = isName;
exports.getAllMatches = getAllMatches;
exports.nameRegexp = nameRegexp;


/***/ }),

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

"use strict";


const util = __webpack_require__(334);

const defaultOptions = {
  allowBooleanAttributes: false, //A tag can have attributes without any value
  unpairedTags: []
};

//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
exports.validate = function (xmlData, options) {
  options = Object.assign({}, defaultOptions, options);

  //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
  //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
  //xmlData = xmlData.replace(/(<!DOCTYPE[\s\w\"\.\/\-\:]+(\[.*\])*\s*>)/g,"");//Remove DOCTYPE
  const tags = [];
  let tagFound = false;

  //indicates that the root tag has been closed (aka. depth 0 has been reached)
  let reachedRoot = false;

  if (xmlData[0] === '\ufeff') {
    // check for byte order mark (BOM)
    xmlData = xmlData.substr(1);
  }
  
  for (let i = 0; i < xmlData.length; i++) {

    if (xmlData[i] === '<' && xmlData[i+1] === '?') {
      i+=2;
      i = readPI(xmlData,i);
      if (i.err) return i;
    }else if (xmlData[i] === '<') {
      //starting of tag
      //read until you reach to '>' avoiding any '>' in attribute value
      let tagStartPos = i;
      i++;
      
      if (xmlData[i] === '!') {
        i = readCommentAndCDATA(xmlData, i);
        continue;
      } else {
        let closingTag = false;
        if (xmlData[i] === '/') {
          //closing tag
          closingTag = true;
          i++;
        }
        //read tagname
        let tagName = '';
        for (; i < xmlData.length &&
          xmlData[i] !== '>' &&
          xmlData[i] !== ' ' &&
          xmlData[i] !== '\t' &&
          xmlData[i] !== '\n' &&
          xmlData[i] !== '\r'; i++
        ) {
          tagName += xmlData[i];
        }
        tagName = tagName.trim();
        //console.log(tagName);

        if (tagName[tagName.length - 1] === '/') {
          //self closing tag without attributes
          tagName = tagName.substring(0, tagName.length - 1);
          //continue;
          i--;
        }
        if (!validateTagName(tagName)) {
          let msg;
          if (tagName.trim().length === 0) {
            msg = "Invalid space after '<'.";
          } else {
            msg = "Tag '"+tagName+"' is an invalid name.";
          }
          return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
        }

        const result = readAttributeStr(xmlData, i);
        if (result === false) {
          return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
        }
        let attrStr = result.value;
        i = result.index;

        if (attrStr[attrStr.length - 1] === '/') {
          //self closing tag
          const attrStrStart = i - attrStr.length;
          attrStr = attrStr.substring(0, attrStr.length - 1);
          const isValid = validateAttributeString(attrStr, options);
          if (isValid === true) {
            tagFound = true;
            //continue; //text may presents after self closing tag
          } else {
            //the result from the nested function returns the position of the error within the attribute
            //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
            //this gives us the absolute index in the entire xml, which we can use to find the line at last
            return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
          }
        } else if (closingTag) {
          if (!result.tagClosed) {
            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
          } else if (attrStr.trim().length > 0) {
            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
          } else if (tags.length === 0) {
            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
          } else {
            const otg = tags.pop();
            if (tagName !== otg.tagName) {
              let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
              return getErrorObject('InvalidTag',
                "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
                getLineNumberForPosition(xmlData, tagStartPos));
            }

            //when there are no more tags, we reached the root level.
            if (tags.length == 0) {
              reachedRoot = true;
            }
          }
        } else {
          const isValid = validateAttributeString(attrStr, options);
          if (isValid !== true) {
            //the result from the nested function returns the position of the error within the attribute
            //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
            //this gives us the absolute index in the entire xml, which we can use to find the line at last
            return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
          }

          //if the root level has been reached before ...
          if (reachedRoot === true) {
            return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
          } else if(options.unpairedTags.indexOf(tagName) !== -1){
            //don't push into stack
          } else {
            tags.push({tagName, tagStartPos});
          }
          tagFound = true;
        }

        //skip tag text value
        //It may include comments and CDATA value
        for (i++; i < xmlData.length; i++) {
          if (xmlData[i] === '<') {
            if (xmlData[i + 1] === '!') {
              //comment or CADATA
              i++;
              i = readCommentAndCDATA(xmlData, i);
              continue;
            } else if (xmlData[i+1] === '?') {
              i = readPI(xmlData, ++i);
              if (i.err) return i;
            } else{
              break;
            }
          } else if (xmlData[i] === '&') {
            const afterAmp = validateAmpersand(xmlData, i);
            if (afterAmp == -1)
              return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
            i = afterAmp;
          }else{
            if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
              return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
            }
          }
        } //end of reading tag text value
        if (xmlData[i] === '<') {
          i--;
        }
      }
    } else {
      if ( isWhiteSpace(xmlData[i])) {
        continue;
      }
      return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
    }
  }

  if (!tagFound) {
    return getErrorObject('InvalidXml', 'Start tag expected.', 1);
  }else if (tags.length == 1) {
      return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
  }else if (tags.length > 0) {
      return getErrorObject('InvalidXml', "Invalid '"+
          JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
          "' found.", {line: 1, col: 1});
  }

  return true;
};

function isWhiteSpace(char){
  return char === ' ' || char === '\t' || char === '\n'  || char === '\r';
}
/**
 * Read Processing insstructions and skip
 * @param {*} xmlData
 * @param {*} i
 */
function readPI(xmlData, i) {
  const start = i;
  for (; i < xmlData.length; i++) {
    if (xmlData[i] == '?' || xmlData[i] == ' ') {
      //tagname
      const tagname = xmlData.substr(start, i - start);
      if (i > 5 && tagname === 'xml') {
        return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
      } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
        //check if valid attribut string
        i++;
        break;
      } else {
        continue;
      }
    }
  }
  return i;
}

function readCommentAndCDATA(xmlData, i) {
  if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
    //comment
    for (i += 3; i < xmlData.length; i++) {
      if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
        i += 2;
        break;
      }
    }
  } else if (
    xmlData.length > i + 8 &&
    xmlData[i + 1] === 'D' &&
    xmlData[i + 2] === 'O' &&
    xmlData[i + 3] === 'C' &&
    xmlData[i + 4] === 'T' &&
    xmlData[i + 5] === 'Y' &&
    xmlData[i + 6] === 'P' &&
    xmlData[i + 7] === 'E'
  ) {
    let angleBracketsCount = 1;
    for (i += 8; i < xmlData.length; i++) {
      if (xmlData[i] === '<') {
        angleBracketsCount++;
      } else if (xmlData[i] === '>') {
        angleBracketsCount--;
        if (angleBracketsCount === 0) {
          break;
        }
      }
    }
  } else if (
    xmlData.length > i + 9 &&
    xmlData[i + 1] === '[' &&
    xmlData[i + 2] === 'C' &&
    xmlData[i + 3] === 'D' &&
    xmlData[i + 4] === 'A' &&
    xmlData[i + 5] === 'T' &&
    xmlData[i + 6] === 'A' &&
    xmlData[i + 7] === '['
  ) {
    for (i += 8; i < xmlData.length; i++) {
      if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
        i += 2;
        break;
      }
    }
  }

  return i;
}

const doubleQuote = '"';
const singleQuote = "'";

/**
 * Keep reading xmlData until '<' is found outside the attribute value.
 * @param {string} xmlData
 * @param {number} i
 */
function readAttributeStr(xmlData, i) {
  let attrStr = '';
  let startChar = '';
  let tagClosed = false;
  for (; i < xmlData.length; i++) {
    if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
      if (startChar === '') {
        startChar = xmlData[i];
      } else if (startChar !== xmlData[i]) {
        //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
      } else {
        startChar = '';
      }
    } else if (xmlData[i] === '>') {
      if (startChar === '') {
        tagClosed = true;
        break;
      }
    }
    attrStr += xmlData[i];
  }
  if (startChar !== '') {
    return false;
  }

  return {
    value: attrStr,
    index: i,
    tagClosed: tagClosed
  };
}

/**
 * Select all the attributes whether valid or invalid.
 */
const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');

//attr, ="sd", a="amit's", a="sd"b="saf", ab  cd=""

function validateAttributeString(attrStr, options) {
  //console.log("start:"+attrStr+":end");

  //if(attrStr.trim().length === 0) return true; //empty string

  const matches = util.getAllMatches(attrStr, validAttrStrRegxp);
  const attrNames = {};

  for (let i = 0; i < matches.length; i++) {
    if (matches[i][1].length === 0) {
      //nospace before attribute name: a="sd"b="saf"
      return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
    } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
      return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
    } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
      //independent attribute: ab
      return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
    }
    /* else if(matches[i][6] === undefined){//attribute without value: ab=
                    return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
                } */
    const attrName = matches[i][2];
    if (!validateAttrName(attrName)) {
      return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
    }
    if (!attrNames.hasOwnProperty(attrName)) {
      //check for duplicate attribute.
      attrNames[attrName] = 1;
    } else {
      return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
    }
  }

  return true;
}

function validateNumberAmpersand(xmlData, i) {
  let re = /\d/;
  if (xmlData[i] === 'x') {
    i++;
    re = /[\da-fA-F]/;
  }
  for (; i < xmlData.length; i++) {
    if (xmlData[i] === ';')
      return i;
    if (!xmlData[i].match(re))
      break;
  }
  return -1;
}

function validateAmpersand(xmlData, i) {
  // https://www.w3.org/TR/xml/#dt-charref
  i++;
  if (xmlData[i] === ';')
    return -1;
  if (xmlData[i] === '#') {
    i++;
    return validateNumberAmpersand(xmlData, i);
  }
  let count = 0;
  for (; i < xmlData.length; i++, count++) {
    if (xmlData[i].match(/\w/) && count < 20)
      continue;
    if (xmlData[i] === ';')
      break;
    return -1;
  }
  return i;
}

function getErrorObject(code, message, lineNumber) {
  return {
    err: {
      code: code,
      msg: message,
      line: lineNumber.line || lineNumber,
      col: lineNumber.col,
    },
  };
}

function validateAttrName(attrName) {
  return util.isName(attrName);
}

// const startsWithXML = /^xml/i;

function validateTagName(tagname) {
  return util.isName(tagname) /* && !tagname.match(startsWithXML) */;
}

//this function returns the line number for the character at the given index
function getLineNumberForPosition(xmlData, index) {
  const lines = xmlData.substring(0, index).split(/\r?\n/);
  return {
    line: lines.length,

    // column number is last line's length + 1, because column numbering starts at 1:
    col: lines[lines.length - 1].length + 1
  };
}

//this function returns the position of the first character of match within attrStr
function getPositionFromMatch(match) {
  return match.startIndex + match[1].length;
}


/***/ }),

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

"use strict";

//parse Empty Node as self closing node
const buildFromOrderedJs = __webpack_require__(788);
const getIgnoreAttributesFn = __webpack_require__(85)

const defaultOptions = {
  attributeNamePrefix: '@_',
  attributesGroupName: false,
  textNodeName: '#text',
  ignoreAttributes: true,
  cdataPropName: false,
  format: false,
  indentBy: '  ',
  suppressEmptyNode: false,
  suppressUnpairedNode: true,
  suppressBooleanAttributes: true,
  tagValueProcessor: function(key, a) {
    return a;
  },
  attributeValueProcessor: function(attrName, a) {
    return a;
  },
  preserveOrder: false,
  commentPropName: false,
  unpairedTags: [],
  entities: [
    { regex: new RegExp("&", "g"), val: "&amp;" },//it must be on top
    { regex: new RegExp(">", "g"), val: "&gt;" },
    { regex: new RegExp("<", "g"), val: "&lt;" },
    { regex: new RegExp("\'", "g"), val: "&apos;" },
    { regex: new RegExp("\"", "g"), val: "&quot;" }
  ],
  processEntities: true,
  stopNodes: [],
  // transformTagName: false,
  // transformAttributeName: false,
  oneListGroup: false
};

function Builder(options) {
  this.options = Object.assign({}, defaultOptions, options);
  if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
    this.isAttribute = function(/*a*/) {
      return false;
    };
  } else {
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
    this.attrPrefixLen = this.options.attributeNamePrefix.length;
    this.isAttribute = isAttribute;
  }

  this.processTextOrObjNode = processTextOrObjNode

  if (this.options.format) {
    this.indentate = indentate;
    this.tagEndChar = '>\n';
    this.newLine = '\n';
  } else {
    this.indentate = function() {
      return '';
    };
    this.tagEndChar = '>';
    this.newLine = '';
  }
}

Builder.prototype.build = function(jObj) {
  if(this.options.preserveOrder){
    return buildFromOrderedJs(jObj, this.options);
  }else {
    if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
      jObj = {
        [this.options.arrayNodeName] : jObj
      }
    }
    return this.j2x(jObj, 0, []).val;
  }
};

Builder.prototype.j2x = function(jObj, level, ajPath) {
  let attrStr = '';
  let val = '';
  const jPath = ajPath.join('.')
  for (let key in jObj) {
    if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
    if (typeof jObj[key] === 'undefined') {
      // supress undefined node only if it is not an attribute
      if (this.isAttribute(key)) {
        val += '';
      }
    } else if (jObj[key] === null) {
      // null attribute should be ignored by the attribute list, but should not cause the tag closing
      if (this.isAttribute(key)) {
        val += '';
      } else if (key[0] === '?') {
        val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
      } else {
        val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
      }
      // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
    } else if (jObj[key] instanceof Date) {
      val += this.buildTextValNode(jObj[key], key, '', level);
    } else if (typeof jObj[key] !== 'object') {
      //premitive type
      const attr = this.isAttribute(key);
      if (attr && !this.ignoreAttributesFn(attr, jPath)) {
        attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
      } else if (!attr) {
        //tag value
        if (key === this.options.textNodeName) {
          let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
          val += this.replaceEntitiesValue(newval);
        } else {
          val += this.buildTextValNode(jObj[key], key, '', level);
        }
      }
    } else if (Array.isArray(jObj[key])) {
      //repeated nodes
      const arrLen = jObj[key].length;
      let listTagVal = "";
      let listTagAttr = "";
      for (let j = 0; j < arrLen; j++) {
        const item = jObj[key][j];
        if (typeof item === 'undefined') {
          // supress undefined node
        } else if (item === null) {
          if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
          else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
          // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
        } else if (typeof item === 'object') {
          if(this.options.oneListGroup){
            const result = this.j2x(item, level + 1, ajPath.concat(key));
            listTagVal += result.val;
            if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
              listTagAttr += result.attrStr
            }
          }else{
            listTagVal += this.processTextOrObjNode(item, key, level, ajPath)
          }
        } else {
          if (this.options.oneListGroup) {
            let textValue = this.options.tagValueProcessor(key, item);
            textValue = this.replaceEntitiesValue(textValue);
            listTagVal += textValue;
          } else {
            listTagVal += this.buildTextValNode(item, key, '', level);
          }
        }
      }
      if(this.options.oneListGroup){
        listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
      }
      val += listTagVal;
    } else {
      //nested node
      if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
        const Ks = Object.keys(jObj[key]);
        const L = Ks.length;
        for (let j = 0; j < L; j++) {
          attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
        }
      } else {
        val += this.processTextOrObjNode(jObj[key], key, level, ajPath)
      }
    }
  }
  return {attrStr: attrStr, val: val};
};

Builder.prototype.buildAttrPairStr = function(attrName, val){
  val = this.options.attributeValueProcessor(attrName, '' + val);
  val = this.replaceEntitiesValue(val);
  if (this.options.suppressBooleanAttributes && val === "true") {
    return ' ' + attrName;
  } else return ' ' + attrName + '="' + val + '"';
}

function processTextOrObjNode (object, key, level, ajPath) {
  const result = this.j2x(object, level + 1, ajPath.concat(key));
  if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
    return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
  } else {
    return this.buildObjectNode(result.val, key, result.attrStr, level);
  }
}

Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
  if(val === ""){
    if(key[0] === "?") return  this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
    else {
      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
    }
  }else{

    let tagEndExp = '</' + key + this.tagEndChar;
    let piClosingChar = "";
    
    if(key[0] === "?") {
      piClosingChar = "?";
      tagEndExp = "";
    }
  
    // attrStr is an empty string in case the attribute came as undefined or null
    if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
      return ( this.indentate(level) + '<' +  key + attrStr + piClosingChar + '>' + val + tagEndExp );
    } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
      return this.indentate(level) + `<!--${val}-->` + this.newLine;
    }else {
      return (
        this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
        val +
        this.indentate(level) + tagEndExp    );
    }
  }
}

Builder.prototype.closeTag = function(key){
  let closeTag = "";
  if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
    if(!this.options.suppressUnpairedNode) closeTag = "/"
  }else if(this.options.suppressEmptyNode){ //empty
    closeTag = "/";
  }else{
    closeTag = `></${key}`
  }
  return closeTag;
}

function buildEmptyObjNode(val, key, attrStr, level) {
  if (val !== '') {
    return this.buildObjectNode(val, key, attrStr, level);
  } else {
    if(key[0] === "?") return  this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
    else {
      return  this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
      // return this.buildTagStr(level,key, attrStr);
    }
  }
}

Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
  if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
    return this.indentate(level) + `<![CDATA[${val}]]>` +  this.newLine;
  }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
    return this.indentate(level) + `<!--${val}-->` +  this.newLine;
  }else if(key[0] === "?") {//PI tag
    return  this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; 
  }else{
    let textValue = this.options.tagValueProcessor(key, val);
    textValue = this.replaceEntitiesValue(textValue);
  
    if( textValue === ''){
      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
    }else{
      return this.indentate(level) + '<' + key + attrStr + '>' +
         textValue +
        '</' + key + this.tagEndChar;
    }
  }
}

Builder.prototype.replaceEntitiesValue = function(textValue){
  if(textValue && textValue.length > 0 && this.options.processEntities){
    for (let i=0; i<this.options.entities.length; i++) {
      const entity = this.options.entities[i];
      textValue = textValue.replace(entity.regex, entity.val);
    }
  }
  return textValue;
}

function indentate(level) {
  return this.options.indentBy.repeat(level);
}

function isAttribute(name /*, options*/) {
  if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
    return name.substr(this.attrPrefixLen);
  } else {
    return false;
  }
}

module.exports = Builder;


/***/ }),

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

const EOL = "\n";

/**
 * 
 * @param {array} jArray 
 * @param {any} options 
 * @returns 
 */
function toXml(jArray, options) {
    let indentation = "";
    if (options.format && options.indentBy.length > 0) {
        indentation = EOL;
    }
    return arrToStr(jArray, options, "", indentation);
}

function arrToStr(arr, options, jPath, indentation) {
    let xmlStr = "";
    let isPreviousElementTag = false;

    for (let i = 0; i < arr.length; i++) {
        const tagObj = arr[i];
        const tagName = propName(tagObj);
        if(tagName === undefined) continue;

        let newJPath = "";
        if (jPath.length === 0) newJPath = tagName
        else newJPath = `${jPath}.${tagName}`;

        if (tagName === options.textNodeName) {
            let tagText = tagObj[tagName];
            if (!isStopNode(newJPath, options)) {
                tagText = options.tagValueProcessor(tagName, tagText);
                tagText = replaceEntitiesValue(tagText, options);
            }
            if (isPreviousElementTag) {
                xmlStr += indentation;
            }
            xmlStr += tagText;
            isPreviousElementTag = false;
            continue;
        } else if (tagName === options.cdataPropName) {
            if (isPreviousElementTag) {
                xmlStr += indentation;
            }
            xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
            isPreviousElementTag = false;
            continue;
        } else if (tagName === options.commentPropName) {
            xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
            isPreviousElementTag = true;
            continue;
        } else if (tagName[0] === "?") {
            const attStr = attr_to_str(tagObj[":@"], options);
            const tempInd = tagName === "?xml" ? "" : indentation;
            let piTextNodeName = tagObj[tagName][0][options.textNodeName];
            piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
            xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
            isPreviousElementTag = true;
            continue;
        }
        let newIdentation = indentation;
        if (newIdentation !== "") {
            newIdentation += options.indentBy;
        }
        const attStr = attr_to_str(tagObj[":@"], options);
        const tagStart = indentation + `<${tagName}${attStr}`;
        const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
        if (options.unpairedTags.indexOf(tagName) !== -1) {
            if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
            else xmlStr += tagStart + "/>";
        } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
            xmlStr += tagStart + "/>";
        } else if (tagValue && tagValue.endsWith(">")) {
            xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
        } else {
            xmlStr += tagStart + ">";
            if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
                xmlStr += indentation + options.indentBy + tagValue + indentation;
            } else {
                xmlStr += tagValue;
            }
            xmlStr += `</${tagName}>`;
        }
        isPreviousElementTag = true;
    }

    return xmlStr;
}

function propName(obj) {
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if(!obj.hasOwnProperty(key)) continue;
        if (key !== ":@") return key;
    }
}

function attr_to_str(attrMap, options) {
    let attrStr = "";
    if (attrMap && !options.ignoreAttributes) {
        for (let attr in attrMap) {
            if(!attrMap.hasOwnProperty(attr)) continue;
            let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
            attrVal = replaceEntitiesValue(attrVal, options);
            if (attrVal === true && options.suppressBooleanAttributes) {
                attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
            } else {
                attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
            }
        }
    }
    return attrStr;
}

function isStopNode(jPath, options) {
    jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
    let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
    for (let index in options.stopNodes) {
        if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
    }
    return false;
}

function replaceEntitiesValue(textValue, options) {
    if (textValue && textValue.length > 0 && options.processEntities) {
        for (let i = 0; i < options.entities.length; i++) {
            const entity = options.entities[i];
            textValue = textValue.replace(entity.regex, entity.val);
        }
    }
    return textValue;
}
module.exports = toXml;


/***/ }),

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

const util = __webpack_require__(334);

//TODO: handle comments
function readDocType(xmlData, i){
    
    const entities = {};
    if( xmlData[i + 3] === 'O' &&
         xmlData[i + 4] === 'C' &&
         xmlData[i + 5] === 'T' &&
         xmlData[i + 6] === 'Y' &&
         xmlData[i + 7] === 'P' &&
         xmlData[i + 8] === 'E')
    {    
        i = i+9;
        let angleBracketsCount = 1;
        let hasBody = false, comment = false;
        let exp = "";
        for(;i<xmlData.length;i++){
            if (xmlData[i] === '<' && !comment) { //Determine the tag type
                if( hasBody && isEntity(xmlData, i)){
                    i += 7; 
                    [entityName, val,i] = readEntityExp(xmlData,i+1);
                    if(val.indexOf("&") === -1) //Parameter entities are not supported
                        entities[ validateEntityName(entityName) ] = {
                            regx : RegExp( `&${entityName};`,"g"),
                            val: val
                        };
                }
                else if( hasBody && isElement(xmlData, i))  i += 8;//Not supported
                else if( hasBody && isAttlist(xmlData, i))  i += 8;//Not supported
                else if( hasBody && isNotation(xmlData, i)) i += 9;//Not supported
                else if( isComment)                         comment = true;
                else                                        throw new Error("Invalid DOCTYPE");

                angleBracketsCount++;
                exp = "";
            } else if (xmlData[i] === '>') { //Read tag content
                if(comment){
                    if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
                        comment = false;
                        angleBracketsCount--;
                    }
                }else{
                    angleBracketsCount--;
                }
                if (angleBracketsCount === 0) {
                  break;
                }
            }else if( xmlData[i] === '['){
                hasBody = true;
            }else{
                exp += xmlData[i];
            }
        }
        if(angleBracketsCount !== 0){
            throw new Error(`Unclosed DOCTYPE`);
        }
    }else{
        throw new Error(`Invalid Tag instead of DOCTYPE`);
    }
    return {entities, i};
}

function readEntityExp(xmlData,i){
    //External entities are not supported
    //    <!ENTITY ext SYSTEM "http://normal-website.com" >

    //Parameter entities are not supported
    //    <!ENTITY entityname "&anotherElement;">

    //Internal entities are supported
    //    <!ENTITY entityname "replacement text">
    
    //read EntityName
    let entityName = "";
    for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) {
        // if(xmlData[i] === " ") continue;
        // else 
        entityName += xmlData[i];
    }
    entityName = entityName.trim();
    if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported");

    //read Entity Value
    const startChar = xmlData[i++];
    let val = ""
    for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {
        val += xmlData[i];
    }
    return [entityName, val, i];
}

function isComment(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === '-' &&
    xmlData[i+3] === '-') return true
    return false
}
function isEntity(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'E' &&
    xmlData[i+3] === 'N' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'I' &&
    xmlData[i+6] === 'T' &&
    xmlData[i+7] === 'Y') return true
    return false
}
function isElement(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'E' &&
    xmlData[i+3] === 'L' &&
    xmlData[i+4] === 'E' &&
    xmlData[i+5] === 'M' &&
    xmlData[i+6] === 'E' &&
    xmlData[i+7] === 'N' &&
    xmlData[i+8] === 'T') return true
    return false
}

function isAttlist(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'A' &&
    xmlData[i+3] === 'T' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'L' &&
    xmlData[i+6] === 'I' &&
    xmlData[i+7] === 'S' &&
    xmlData[i+8] === 'T') return true
    return false
}
function isNotation(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'N' &&
    xmlData[i+3] === 'O' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'A' &&
    xmlData[i+6] === 'T' &&
    xmlData[i+7] === 'I' &&
    xmlData[i+8] === 'O' &&
    xmlData[i+9] === 'N') return true
    return false
}

function validateEntityName(name){
    if (util.isName(name))
	return name;
    else
        throw new Error(`Invalid entity name ${name}`);
}

module.exports = readDocType;


/***/ }),

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


const defaultOptions = {
    preserveOrder: false,
    attributeNamePrefix: '@_',
    attributesGroupName: false,
    textNodeName: '#text',
    ignoreAttributes: true,
    removeNSPrefix: false, // remove NS from tag name or attribute name if true
    allowBooleanAttributes: false, //a tag can have attributes without any value
    //ignoreRootElement : false,
    parseTagValue: true,
    parseAttributeValue: false,
    trimValues: true, //Trim string values of tag and attributes
    cdataPropName: false,
    numberParseOptions: {
      hex: true,
      leadingZeros: true,
      eNotation: true
    },
    tagValueProcessor: function(tagName, val) {
      return val;
    },
    attributeValueProcessor: function(attrName, val) {
      return val;
    },
    stopNodes: [], //nested tags will not be parsed even for errors
    alwaysCreateTextNode: false,
    isArray: () => false,
    commentPropName: false,
    unpairedTags: [],
    processEntities: true,
    htmlEntities: false,
    ignoreDeclaration: false,
    ignorePiTags: false,
    transformTagName: false,
    transformAttributeName: false,
    updateTag: function(tagName, jPath, attrs){
      return tagName
    },
    // skipEmptyListItem: false
};
   
const buildOptions = function(options) {
    return Object.assign({}, defaultOptions, options);
};

exports.buildOptions = buildOptions;
exports.defaultOptions = defaultOptions;

/***/ }),

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

"use strict";

///@ts-check

const util = __webpack_require__(334);
const xmlNode = __webpack_require__(832);
const readDocType = __webpack_require__(400);
const toNumber = __webpack_require__(983);
const getIgnoreAttributesFn = __webpack_require__(85)

// const regx =
//   '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
//   .replace(/NAME/g, util.nameRegexp);

//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");

class OrderedObjParser{
  constructor(options){
    this.options = options;
    this.currentNode = null;
    this.tagsNodeStack = [];
    this.docTypeEntities = {};
    this.lastEntities = {
      "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
      "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
      "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
      "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
    };
    this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
    this.htmlEntities = {
      "space": { regex: /&(nbsp|#160);/g, val: " " },
      // "lt" : { regex: /&(lt|#60);/g, val: "<" },
      // "gt" : { regex: /&(gt|#62);/g, val: ">" },
      // "amp" : { regex: /&(amp|#38);/g, val: "&" },
      // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
      // "apos" : { regex: /&(apos|#39);/g, val: "'" },
      "cent" : { regex: /&(cent|#162);/g, val: "¢" },
      "pound" : { regex: /&(pound|#163);/g, val: "£" },
      "yen" : { regex: /&(yen|#165);/g, val: "¥" },
      "euro" : { regex: /&(euro|#8364);/g, val: "€" },
      "copyright" : { regex: /&(copy|#169);/g, val: "©" },
      "reg" : { regex: /&(reg|#174);/g, val: "®" },
      "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
      "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
      "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },
    };
    this.addExternalEntities = addExternalEntities;
    this.parseXml = parseXml;
    this.parseTextData = parseTextData;
    this.resolveNameSpace = resolveNameSpace;
    this.buildAttributesMap = buildAttributesMap;
    this.isItStopNode = isItStopNode;
    this.replaceEntitiesValue = replaceEntitiesValue;
    this.readStopNodeData = readStopNodeData;
    this.saveTextToParentTag = saveTextToParentTag;
    this.addChild = addChild;
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
  }

}

function addExternalEntities(externalEntities){
  const entKeys = Object.keys(externalEntities);
  for (let i = 0; i < entKeys.length; i++) {
    const ent = entKeys[i];
    this.lastEntities[ent] = {
       regex: new RegExp("&"+ent+";","g"),
       val : externalEntities[ent]
    }
  }
}

/**
 * @param {string} val
 * @param {string} tagName
 * @param {string} jPath
 * @param {boolean} dontTrim
 * @param {boolean} hasAttributes
 * @param {boolean} isLeafNode
 * @param {boolean} escapeEntities
 */
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
  if (val !== undefined) {
    if (this.options.trimValues && !dontTrim) {
      val = val.trim();
    }
    if(val.length > 0){
      if(!escapeEntities) val = this.replaceEntitiesValue(val);
      
      const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
      if(newval === null || newval === undefined){
        //don't parse
        return val;
      }else if(typeof newval !== typeof val || newval !== val){
        //overwrite
        return newval;
      }else if(this.options.trimValues){
        return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
      }else{
        const trimmedVal = val.trim();
        if(trimmedVal === val){
          return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
        }else{
          return val;
        }
      }
    }
  }
}

function resolveNameSpace(tagname) {
  if (this.options.removeNSPrefix) {
    const tags = tagname.split(':');
    const prefix = tagname.charAt(0) === '/' ? '/' : '';
    if (tags[0] === 'xmlns') {
      return '';
    }
    if (tags.length === 2) {
      tagname = prefix + tags[1];
    }
  }
  return tagname;
}

//TODO: change regex to capture NS
//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');

function buildAttributesMap(attrStr, jPath, tagName) {
  if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
    // attrStr = attrStr.replace(/\r?\n/g, ' ');
    //attrStr = attrStr || attrStr.trim();

    const matches = util.getAllMatches(attrStr, attrsRegx);
    const len = matches.length; //don't make it inline
    const attrs = {};
    for (let i = 0; i < len; i++) {
      const attrName = this.resolveNameSpace(matches[i][1]);
      if (this.ignoreAttributesFn(attrName, jPath)) {
        continue
      }
      let oldVal = matches[i][4];
      let aName = this.options.attributeNamePrefix + attrName;
      if (attrName.length) {
        if (this.options.transformAttributeName) {
          aName = this.options.transformAttributeName(aName);
        }
        if(aName === "__proto__") aName  = "#__proto__";
        if (oldVal !== undefined) {
          if (this.options.trimValues) {
            oldVal = oldVal.trim();
          }
          oldVal = this.replaceEntitiesValue(oldVal);
          const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
          if(newVal === null || newVal === undefined){
            //don't parse
            attrs[aName] = oldVal;
          }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
            //overwrite
            attrs[aName] = newVal;
          }else{
            //parse
            attrs[aName] = parseValue(
              oldVal,
              this.options.parseAttributeValue,
              this.options.numberParseOptions
            );
          }
        } else if (this.options.allowBooleanAttributes) {
          attrs[aName] = true;
        }
      }
    }
    if (!Object.keys(attrs).length) {
      return;
    }
    if (this.options.attributesGroupName) {
      const attrCollection = {};
      attrCollection[this.options.attributesGroupName] = attrs;
      return attrCollection;
    }
    return attrs
  }
}

const parseXml = function(xmlData) {
  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
  const xmlObj = new xmlNode('!xml');
  let currentNode = xmlObj;
  let textData = "";
  let jPath = "";
  for(let i=0; i< xmlData.length; i++){//for each char in XML data
    const ch = xmlData[i];
    if(ch === '<'){
      // const nextIndex = i+1;
      // const _2ndChar = xmlData[nextIndex];
      if( xmlData[i+1] === '/') {//Closing Tag
        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
        let tagName = xmlData.substring(i+2,closeIndex).trim();

        if(this.options.removeNSPrefix){
          const colonIndex = tagName.indexOf(":");
          if(colonIndex !== -1){
            tagName = tagName.substr(colonIndex+1);
          }
        }

        if(this.options.transformTagName) {
          tagName = this.options.transformTagName(tagName);
        }

        if(currentNode){
          textData = this.saveTextToParentTag(textData, currentNode, jPath);
        }

        //check if last tag of nested tag was unpaired tag
        const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
        if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
        }
        let propIndex = 0
        if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
          propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
          this.tagsNodeStack.pop();
        }else{
          propIndex = jPath.lastIndexOf(".");
        }
        jPath = jPath.substring(0, propIndex);

        currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
        textData = "";
        i = closeIndex;
      } else if( xmlData[i+1] === '?') {

        let tagData = readTagExp(xmlData,i, false, "?>");
        if(!tagData) throw new Error("Pi Tag is not closed.");

        textData = this.saveTextToParentTag(textData, currentNode, jPath);
        if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){

        }else{
  
          const childNode = new xmlNode(tagData.tagName);
          childNode.add(this.options.textNodeName, "");
          
          if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
            childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
          }
          this.addChild(currentNode, childNode, jPath)

        }


        i = tagData.closeIndex + 1;
      } else if(xmlData.substr(i + 1, 3) === '!--') {
        const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
        if(this.options.commentPropName){
          const comment = xmlData.substring(i + 4, endIndex - 2);

          textData = this.saveTextToParentTag(textData, currentNode, jPath);

          currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
        }
        i = endIndex;
      } else if( xmlData.substr(i + 1, 2) === '!D') {
        const result = readDocType(xmlData, i);
        this.docTypeEntities = result.entities;
        i = result.i;
      }else if(xmlData.substr(i + 1, 2) === '![') {
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
        const tagExp = xmlData.substring(i + 9,closeIndex);

        textData = this.saveTextToParentTag(textData, currentNode, jPath);

        let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
        if(val == undefined) val = "";

        //cdata should be set even if it is 0 length string
        if(this.options.cdataPropName){
          currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
        }else{
          currentNode.add(this.options.textNodeName, val);
        }
        
        i = closeIndex + 2;
      }else {//Opening tag
        let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
        let tagName= result.tagName;
        const rawTagName = result.rawTagName;
        let tagExp = result.tagExp;
        let attrExpPresent = result.attrExpPresent;
        let closeIndex = result.closeIndex;

        if (this.options.transformTagName) {
          tagName = this.options.transformTagName(tagName);
        }
        
        //save text as child node
        if (currentNode && textData) {
          if(currentNode.tagname !== '!xml'){
            //when nested tag is found
            textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
          }
        }

        //check if last tag was unpaired tag
        const lastTag = currentNode;
        if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
          currentNode = this.tagsNodeStack.pop();
          jPath = jPath.substring(0, jPath.lastIndexOf("."));
        }
        if(tagName !== xmlObj.tagname){
          jPath += jPath ? "." + tagName : tagName;
        }
        if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
          let tagContent = "";
          //self-closing tag
          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
              tagName = tagName.substr(0, tagName.length - 1);
              jPath = jPath.substr(0, jPath.length - 1);
              tagExp = tagName;
            }else{
              tagExp = tagExp.substr(0, tagExp.length - 1);
            }
            i = result.closeIndex;
          }
          //unpaired tag
          else if(this.options.unpairedTags.indexOf(tagName) !== -1){
            
            i = result.closeIndex;
          }
          //normal tag
          else{
            //read until closing tag is found
            const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
            if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
            i = result.i;
            tagContent = result.tagContent;
          }

          const childNode = new xmlNode(tagName);
          if(tagName !== tagExp && attrExpPresent){
            childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
          }
          if(tagContent) {
            tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
          }
          
          jPath = jPath.substr(0, jPath.lastIndexOf("."));
          childNode.add(this.options.textNodeName, tagContent);
          
          this.addChild(currentNode, childNode, jPath)
        }else{
  //selfClosing tag
          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
              tagName = tagName.substr(0, tagName.length - 1);
              jPath = jPath.substr(0, jPath.length - 1);
              tagExp = tagName;
            }else{
              tagExp = tagExp.substr(0, tagExp.length - 1);
            }
            
            if(this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }

            const childNode = new xmlNode(tagName);
            if(tagName !== tagExp && attrExpPresent){
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
            }
            this.addChild(currentNode, childNode, jPath)
            jPath = jPath.substr(0, jPath.lastIndexOf("."));
          }
    //opening tag
          else{
            const childNode = new xmlNode( tagName);
            this.tagsNodeStack.push(currentNode);
            
            if(tagName !== tagExp && attrExpPresent){
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
            }
            this.addChild(currentNode, childNode, jPath)
            currentNode = childNode;
          }
          textData = "";
          i = closeIndex;
        }
      }
    }else{
      textData += xmlData[i];
    }
  }
  return xmlObj.child;
}

function addChild(currentNode, childNode, jPath){
  const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
  if(result === false){
  }else if(typeof result === "string"){
    childNode.tagname = result
    currentNode.addChild(childNode);
  }else{
    currentNode.addChild(childNode);
  }
}

const replaceEntitiesValue = function(val){

  if(this.options.processEntities){
    for(let entityName in this.docTypeEntities){
      const entity = this.docTypeEntities[entityName];
      val = val.replace( entity.regx, entity.val);
    }
    for(let entityName in this.lastEntities){
      const entity = this.lastEntities[entityName];
      val = val.replace( entity.regex, entity.val);
    }
    if(this.options.htmlEntities){
      for(let entityName in this.htmlEntities){
        const entity = this.htmlEntities[entityName];
        val = val.replace( entity.regex, entity.val);
      }
    }
    val = val.replace( this.ampEntity.regex, this.ampEntity.val);
  }
  return val;
}
function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
  if (textData) { //store previously collected data as textNode
    if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0
    
    textData = this.parseTextData(textData,
      currentNode.tagname,
      jPath,
      false,
      currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
      isLeafNode);

    if (textData !== undefined && textData !== "")
      currentNode.add(this.options.textNodeName, textData);
    textData = "";
  }
  return textData;
}

//TODO: use jPath to simplify the logic
/**
 * 
 * @param {string[]} stopNodes 
 * @param {string} jPath
 * @param {string} currentTagName 
 */
function isItStopNode(stopNodes, jPath, currentTagName){
  const allNodesExp = "*." + currentTagName;
  for (const stopNodePath in stopNodes) {
    const stopNodeExp = stopNodes[stopNodePath];
    if( allNodesExp === stopNodeExp || jPath === stopNodeExp  ) return true;
  }
  return false;
}

/**
 * Returns the tag Expression and where it is ending handling single-double quotes situation
 * @param {string} xmlData 
 * @param {number} i starting index
 * @returns 
 */
function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
  let attrBoundary;
  let tagExp = "";
  for (let index = i; index < xmlData.length; index++) {
    let ch = xmlData[index];
    if (attrBoundary) {
        if (ch === attrBoundary) attrBoundary = "";//reset
    } else if (ch === '"' || ch === "'") {
        attrBoundary = ch;
    } else if (ch === closingChar[0]) {
      if(closingChar[1]){
        if(xmlData[index + 1] === closingChar[1]){
          return {
            data: tagExp,
            index: index
          }
        }
      }else{
        return {
          data: tagExp,
          index: index
        }
      }
    } else if (ch === '\t') {
      ch = " "
    }
    tagExp += ch;
  }
}

function findClosingIndex(xmlData, str, i, errMsg){
  const closingIndex = xmlData.indexOf(str, i);
  if(closingIndex === -1){
    throw new Error(errMsg)
  }else{
    return closingIndex + str.length - 1;
  }
}

function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
  const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
  if(!result) return;
  let tagExp = result.data;
  const closeIndex = result.index;
  const separatorIndex = tagExp.search(/\s/);
  let tagName = tagExp;
  let attrExpPresent = true;
  if(separatorIndex !== -1){//separate tag name and attributes expression
    tagName = tagExp.substring(0, separatorIndex);
    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
  }

  const rawTagName = tagName;
  if(removeNSPrefix){
    const colonIndex = tagName.indexOf(":");
    if(colonIndex !== -1){
      tagName = tagName.substr(colonIndex+1);
      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
    }
  }

  return {
    tagName: tagName,
    tagExp: tagExp,
    closeIndex: closeIndex,
    attrExpPresent: attrExpPresent,
    rawTagName: rawTagName,
  }
}
/**
 * find paired tag for a stop node
 * @param {string} xmlData 
 * @param {string} tagName 
 * @param {number} i 
 */
function readStopNodeData(xmlData, tagName, i){
  const startIndex = i;
  // Starting at 1 since we already have an open tag
  let openTagCount = 1;

  for (; i < xmlData.length; i++) {
    if( xmlData[i] === "<"){ 
      if (xmlData[i+1] === "/") {//close tag
          const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
          let closeTagName = xmlData.substring(i+2,closeIndex).trim();
          if(closeTagName === tagName){
            openTagCount--;
            if (openTagCount === 0) {
              return {
                tagContent: xmlData.substring(startIndex, i),
                i : closeIndex
              }
            }
          }
          i=closeIndex;
        } else if(xmlData[i+1] === '?') { 
          const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
          i=closeIndex;
        } else if(xmlData.substr(i + 1, 3) === '!--') { 
          const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
          i=closeIndex;
        } else if(xmlData.substr(i + 1, 2) === '![') { 
          const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
          i=closeIndex;
        } else {
          const tagData = readTagExp(xmlData, i, '>')

          if (tagData) {
            const openTagName = tagData && tagData.tagName;
            if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
              openTagCount++;
            }
            i=tagData.closeIndex;
          }
        }
      }
  }//end for loop
}

function parseValue(val, shouldParse, options) {
  if (shouldParse && typeof val === 'string') {
    //console.log(options)
    const newval = val.trim();
    if(newval === 'true' ) return true;
    else if(newval === 'false' ) return false;
    else return toNumber(val, options);
  } else {
    if (util.isExist(val)) {
      return val;
    } else {
      return '';
    }
  }
}


module.exports = OrderedObjParser;


/***/ }),

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

const { buildOptions} = __webpack_require__(460);
const OrderedObjParser = __webpack_require__(680);
const { prettify} = __webpack_require__(629);
const validator = __webpack_require__(918);

class XMLParser{
    
    constructor(options){
        this.externalEntities = {};
        this.options = buildOptions(options);
        
    }
    /**
     * Parse XML dats to JS object 
     * @param {string|Buffer} xmlData 
     * @param {boolean|Object} validationOption 
     */
    parse(xmlData,validationOption){
        if(typeof xmlData === "string"){
        }else if( xmlData.toString){
            xmlData = xmlData.toString();
        }else{
            throw new Error("XML data is accepted in String or Bytes[] form.")
        }
        if( validationOption){
            if(validationOption === true) validationOption = {}; //validate with default options
            
            const result = validator.validate(xmlData, validationOption);
            if (result !== true) {
              throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
            }
          }
        const orderedObjParser = new OrderedObjParser(this.options);
        orderedObjParser.addExternalEntities(this.externalEntities);
        const orderedResult = orderedObjParser.parseXml(xmlData);
        if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
        else return prettify(orderedResult, this.options);
    }

    /**
     * Add Entity which is not by default supported by this library
     * @param {string} key 
     * @param {string} value 
     */
    addEntity(key, value){
        if(value.indexOf("&") !== -1){
            throw new Error("Entity value can't have '&'")
        }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
            throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'")
        }else if(value === "&"){
            throw new Error("An entity with value '&' is not permitted");
        }else{
            this.externalEntities[key] = value;
        }
    }
}

module.exports = XMLParser;

/***/ }),

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

"use strict";


/**
 * 
 * @param {array} node 
 * @param {any} options 
 * @returns 
 */
function prettify(node, options){
  return compress( node, options);
}

/**
 * 
 * @param {array} arr 
 * @param {object} options 
 * @param {string} jPath 
 * @returns object
 */
function compress(arr, options, jPath){
  let text;
  const compressedObj = {};
  for (let i = 0; i < arr.length; i++) {
    const tagObj = arr[i];
    const property = propName(tagObj);
    let newJpath = "";
    if(jPath === undefined) newJpath = property;
    else newJpath = jPath + "." + property;

    if(property === options.textNodeName){
      if(text === undefined) text = tagObj[property];
      else text += "" + tagObj[property];
    }else if(property === undefined){
      continue;
    }else if(tagObj[property]){
      
      let val = compress(tagObj[property], options, newJpath);
      const isLeaf = isLeafTag(val, options);

      if(tagObj[":@"]){
        assignAttributes( val, tagObj[":@"], newJpath, options);
      }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
        val = val[options.textNodeName];
      }else if(Object.keys(val).length === 0){
        if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
        else val = "";
      }

      if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
        if(!Array.isArray(compressedObj[property])) {
            compressedObj[property] = [ compressedObj[property] ];
        }
        compressedObj[property].push(val);
      }else{
        //TODO: if a node is not an array, then check if it should be an array
        //also determine if it is a leaf node
        if (options.isArray(property, newJpath, isLeaf )) {
          compressedObj[property] = [val];
        }else{
          compressedObj[property] = val;
        }
      }
    }
    
  }
  // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
  if(typeof text === "string"){
    if(text.length > 0) compressedObj[options.textNodeName] = text;
  }else if(text !== undefined) compressedObj[options.textNodeName] = text;
  return compressedObj;
}

function propName(obj){
  const keys = Object.keys(obj);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    if(key !== ":@") return key;
  }
}

function assignAttributes(obj, attrMap, jpath, options){
  if (attrMap) {
    const keys = Object.keys(attrMap);
    const len = keys.length; //don't make it inline
    for (let i = 0; i < len; i++) {
      const atrrName = keys[i];
      if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
        obj[atrrName] = [ attrMap[atrrName] ];
      } else {
        obj[atrrName] = attrMap[atrrName];
      }
    }
  }
}

function isLeafTag(obj, options){
  const { textNodeName } = options;
  const propCount = Object.keys(obj).length;
  
  if (propCount === 0) {
    return true;
  }

  if (
    propCount === 1 &&
    (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
  ) {
    return true;
  }

  return false;
}
exports.prettify = prettify;


/***/ }),

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

"use strict";


class XmlNode{
  constructor(tagname) {
    this.tagname = tagname;
    this.child = []; //nested tags, text, cdata, comments in order
    this[":@"] = {}; //attributes map
  }
  add(key,val){
    // this.child.push( {name : key, val: val, isCdata: isCdata });
    if(key === "__proto__") key = "#__proto__";
    this.child.push( {[key]: val });
  }
  addChild(node) {
    if(node.tagname === "__proto__") node.tagname = "#__proto__";
    if(node[":@"] && Object.keys(node[":@"]).length > 0){
      this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
    }else{
      this.child.push( { [node.tagname]: node.child });
    }
  };
};


module.exports = XmlNode;

/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
const ENDPOINTS = {
  identity_token: "/identity/oauth2/token/xpmplatform",
  getAllVaults: "/vaultbroker/api/vaults",
  CHECK_SS: "/healthcheck.aspx",
  CHECK_PLATFORM: "/health",
  LOGIN: "/oauth2/token",
  SECRETS: "/api/v1/secrets/",
  SECRETS_V2: "/api/v2/secrets/",
  Favorites: "/api/v1/secrets/favorite",
  deviceCode: "/identity/oauth2/devicecode",
  logoutPlatform: "/identity/api/Security/Logout",
  CREATE_SECRET: "/internals/secret-detail",
  SECRETS_STATES(secretId) {
    return `/api/v1/secrets/${secretId}/state`;
  },
  folderPath(folderId) {
    return `/internals/folder-details/?ids=${folderId}`;
  },
  getOTP(secretId) {
    return `/api/v1/one-time-password-code/${secretId}?numberOfCodesToGenerate=2`;
  },
  TEMPLATES: "/api/v1/secret-templates",
  secretTemplateList: "/api/v1/secret-templates-list?filter.onlyIncludeTemplatesWithUrl=true&take=1000",
  WEB_SECRET_TEMPLATE: "/api/v1/secret-extensions/web-secret-templates",
  FOLDERS: "/api/v1/folders?filter.permissionRequired=AddSecret&skip=0&take=30000",
  FOLDER_PERMISSIONS(userId, count) {
    return `/api/v1/folder-permissions?filter.userId=${userId}&take=${count}`;
  },
  GENERATE_PASSWORD: "/api/v1/secret-templates/generate-password",
  OAUTH_EXPIRATION: "/api/v1/oauth-expiration",
  SECRETS_BY_URL: "/api/v1/secret-extensions/search-by-url",
  AUTOFILL: "/api/v1/secret-extensions/autofill-values",
  USERPERMISSIONS: "/api/v1/users/current",
  update_secret_password(secretId, slug) {
    return `/api/v1/secrets/${secretId}/fields/${slug}`;
  },
  EXTENDED_FIELDS: "/api/v1/extended-fields/regex/",
  LAUNCHER_SECRET: "/api/v1/launchers/secret/",
  // eslint-disable-next-line
  WINDOWS_SECRETS_BY_HOSTNAME: '/api/v1/secret-extensions/search-windows-account-secrets-by-computer-name',
  AD_SECRETS_BY_DOMAIN: "/api/v1/secret-extensions/search-ad-secrets-by-domain",
  SITES: "/internals/sites?includeInactive=false",
  VERSION: "/api/v1/version",
  PERSONAL_FOLDER: "/internals/user-detail/configuration?loadAll=true&isFirstLoad=false",
  post_metadata(secretId) {
    return `/api/v1/metadata/Secret/${secretId}`;
  },
  METADATA_FIELD_SECTIONS: "/api/v1/metadata/field-sections?paging.filter.metadataType=Secret",
  get_metadata(secretId) {
    return `/api/v1/metadata?filter.metadataType=Secret&filter.itemId=${secretId}`;
  },
  view_comment(secretId) {
    return `/api/v1/secret-access-requests/secrets/${secretId}/view-comment`;
  },
  check_out(secretId) {
    return `/api/v1/secrets/${secretId}/check-out`;
  },
  ticket_systems() {
    return "/api/v1/ticket-systems?includeInactive=false";
  },
  recentQueryString(skip, take) {
    return `?filter.doNotCalculateTotal=true&filter.includeRestricted=true&skip=${skip || 0}&take=${take || 100}&sortBy[0].direction=Desc&sortBy[0].name=lastAccessed&filter.scope=1&`;
  },
  favouriteQueryString(skip, take) {
    return `?filter.doNotCalculateTotal=true&filter.includeRestricted=true&skip=${skip || 0}&take=${take || 100}&sortBy[0].direction=Asc&sortBy[0].name=Name&filter.scope=3&`;
  },
  launcherURL(secretId) {
    return `/internals/secret-detail/${secretId}/launcher/3`;
  },
};

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


/***/ }),

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

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  IR: () => (/* reexport */ add_secret_array_provider),
  eP: () => (/* reexport */ block_website_provider),
  Xr: () => (/* reexport */ cache_keys),
  UY: () => (/* reexport */ checkout_secrets_state_provider),
  FJ: () => (/* reexport */ common_cache_provider),
  RV: () => (/* reexport */ folders_provider),
  iF: () => (/* reexport */ last_fetched_secrets_provider),
  dH: () => (/* reexport */ last_fetched_winAD_secrets_provider),
  oA: () => (/* reexport */ selection_history_provider),
  Pj: () => (/* reexport */ settings_provider),
  wk: () => (/* reexport */ sites_provider),
  aS: () => (/* reexport */ sso_secret_provider),
  Tm: () => (/* reexport */ sso_urls_provider),
  El: () => (/* reexport */ url_templates_provider),
  q7: () => (/* reexport */ windows_admin_center_item_provider)
});

// UNUSED EXPORTS: favIconsProvider

// 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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (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 = (cacheKeys);

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




















/***/ }),

/***/ 322:
/***/ ((__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 _session_storage_provider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(576);


const key = "Log";

const loggerProvider = {
  async load() {
    return _session_storage_provider__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A.get(key);
  },
  set(value) {
    _session_storage_provider__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A.set(key, value);
  },
  async get() {
    return this.load();
  },
  async add(item) {
    if (!item) return;
    const items = await this.load();
    items.push(item);
    this.set(items);
  },

  clear() {
    this.set([]);
  },
};

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


/***/ }),

/***/ 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);


/***/ }),

/***/ 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();


/***/ }),

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

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   addSecret: () => (/* binding */ addSecret),
/* harmony export */   autoFillCall: () => (/* binding */ autoFillCall),
/* harmony export */   checkoutSecret: () => (/* binding */ checkoutSecret),
/* harmony export */   generatePassword: () => (/* binding */ generatePassword),
/* harmony export */   getADSecretsByDomain: () => (/* binding */ getADSecretsByDomain),
/* harmony export */   getAllFavoriteSecrets: () => (/* binding */ getAllFavoriteSecrets),
/* harmony export */   getFavoriteSecrets: () => (/* binding */ getFavoriteSecrets),
/* harmony export */   getFolderPath: () => (/* binding */ getFolderPath),
/* harmony export */   getFolders: () => (/* binding */ getFolders),
/* harmony export */   getMetaData: () => (/* binding */ getMetaData),
/* harmony export */   getMetadataFieldSections: () => (/* binding */ getMetadataFieldSections),
/* harmony export */   getOneTimePassword: () => (/* binding */ getOneTimePassword),
/* harmony export */   getPersonalFolder: () => (/* binding */ getPersonalFolder),
/* harmony export */   getRecentSecrets: () => (/* binding */ getRecentSecrets),
/* harmony export */   getSSVersion: () => (/* binding */ getSSVersion),
/* harmony export */   getSecretById: () => (/* binding */ getSecretById),
/* harmony export */   getSecretState: () => (/* binding */ getSecretState),
/* harmony export */   getSecretTemplates: () => (/* binding */ getSecretTemplates),
/* harmony export */   getSecretlauncherURL: () => (/* binding */ getSecretlauncherURL),
/* harmony export */   getSecrets: () => (/* binding */ getSecrets),
/* harmony export */   getSites: () => (/* binding */ getSites),
/* harmony export */   getTemplateList: () => (/* binding */ getTemplateList),
/* harmony export */   getTicketSystem: () => (/* binding */ getTicketSystem),
/* harmony export */   getUserPermissions: () => (/* binding */ getUserPermissions),
/* harmony export */   getWebSecretTemplates: () => (/* binding */ getWebSecretTemplates),
/* harmony export */   getWindowsSecretsByHostName: () => (/* binding */ getWindowsSecretsByHostName),
/* harmony export */   healthCheck: () => (/* binding */ healthCheck),
/* harmony export */   httpRequest: () => (/* binding */ httpRequest),
/* harmony export */   platformHealthCheck: () => (/* binding */ platformHealthCheck),
/* harmony export */   postMetadata: () => (/* binding */ postMetadata),
/* harmony export */   requestParams: () => (/* binding */ requestParams),
/* harmony export */   saveComments: () => (/* binding */ saveComments),
/* harmony export */   searchByURL: () => (/* binding */ searchByURL),
/* harmony export */   soapRequest: () => (/* binding */ soapRequest),
/* harmony export */   updatePassword: () => (/* binding */ updatePassword)
/* harmony export */ });
/* harmony import */ var fast_xml_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(454);
/* harmony import */ var fast_xml_parser__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fast_xml_parser__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(942);
/* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(72);
/* harmony import */ var _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(165);
/* harmony import */ var _helpers_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(183);






const { CONTENT } = __webpack_require__(482);

const getHeaders = (contentType) => new Headers({
  Authorization: _tokens__WEBPACK_IMPORTED_MODULE_2__/* .oauth */ .o.access_token,
  "vault-application": "WebPasswordFiller",
  Accept: "*/*",
  "Cache-Control": "no-cache",
  Host: _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.HostName,
  "Accept-Encoding": "gzip, deflate",
  Connection: "keep-alive",
  "Content-Type": contentType || (CONTENT && CONTENT.APP_JSON),
});

const requestParams = (method, data, contentType) => ({
  method: method || "GET",
  headers: getHeaders(contentType),
  body: data,
  credentials: "omit",
});

/**
 * call api
 * @param {*} url
 * @param {*} requestDetails
 * @return {Promise}
 */
function httpRequest(url, requestDetails, maxRetries = 3, delay = 1500) {
  return new Promise((resolve, reject) => {
    fetch(url, requestDetails).then((response) => {
      const contentType = response.headers.get("content-type");
      if (!contentType && !response.ok) return reject(response);
      const isJSON = contentType.includes(CONTENT.APP_JSON);
      const result = isJSON ? response.json() : response.text();
      // response only can be ok in range of 2XX
      if (response.ok) {
        _helpers_logger__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A.logInfo(`API Called: ${url} Status code: ${response.status}`);
        // you can call response.json() here too if you want to return json
        return resolve(isJSON ? result : response);
      }
      // handle errors in the way you want to
      switch (response.status) {
        case 400:
        case 401:
        case 403:
          if (isJSON) {
            result.then((json) => {
              if (!json) return null;
              json.status = response.status;
              if (!json.message) return reject(json);
              if (!json.message.includes("expired token")
               || !_tokens__WEBPACK_IMPORTED_MODULE_2__/* .oauth */ .o.refresh_token) return reject(json);
              setTimeout(() => {
                if (maxRetries <= 0) {
                  return reject(json);
                }
                requestDetails.headers = getHeaders();
                httpRequest(url, requestDetails, maxRetries - 1)
                  .then(resolve, reject);
              }, delay);
            });
          }
          break;
        case 404:
          _helpers_logger__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A.logError(`Not found API: ${url}`);
          return reject(response);
        case 500:
          _helpers_logger__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A.logError("Internal server error");
          break;
        default:
          _helpers_logger__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A.logError("Some error occured");
          break;
      }
      // here you also can thorow custom error too
      return result.then(Promise.reject.bind(Promise));
    }).catch((error) => {
      // it will be invoked mostly for network errors
      // do what ever you want to do with error here
      console.log(error);
      reject(error);
    });
  });
}

async function soapRequest(url, body) {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "text/xml" },
      body,
    });

    if (!response.ok) {
      throw new Error("Failed to make SOAP call");
    }

    const responseText = await response.text();
    const parser = new fast_xml_parser__WEBPACK_IMPORTED_MODULE_0__.XMLParser();
    return parser.parse(responseText);
  } catch (err) {
    throw new Error("Failed to make SOAP call");
  }
}

/**
 * Get Secrets
 * @param {object} data
 * @return {Promise}
 */
function getSecrets(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS_BY_URL,
    requestParams("POST", data),
  );
}

/**
 * Get Sites
 * @return {Promise}
 */
async function getSites() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SITES,
    requestParams("GET"),
  );
}

/**
 * Get Folders
 * @return {Promise}
 */
async function getFolders() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.FOLDERS,
    requestParams("GET"),
  );
}

/**
 * Get Secret Templates
 * @return {Promise}
 */
function getSecretTemplates() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.TEMPLATES,
    requestParams("GET"),
  );
}

/**
 * Get Web Secret Templates
 * @return {Promise}
 */
async function getWebSecretTemplates() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.WEB_SECRET_TEMPLATE,
    requestParams("GET"),
  );
}

/**
 * Get  Secret Templates list
 * @return {Promise}
 */
function getTemplateList() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.secretTemplateList,
    requestParams("GET"),
  );
}

/**
 * Get Windows Secrets By HostName
 * @param {object} data
 * @return {Promise}
 */
async function getWindowsSecretsByHostName(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.WINDOWS_SECRETS_BY_HOSTNAME,
    requestParams("POST", data),
  );
}

/**
 * Get Active Directory Secrets By Domain
 * @param {object} data
 * @return {Promise}
 */
async function getADSecretsByDomain(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.AD_SECRETS_BY_DOMAIN,
    requestParams("POST", data),
  );
}

/**
 * Update Secret Password
 * @param {number} secretId
 * @param {string} slug
 * @return {Promise}
 */
function updatePassword(secretId, slug) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL
    + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.update_secret_password(secretId, slug),
    requestParams("PUT"),
  );
}

/**
 * Add Secret Password
 * @param {object} data
 * @return {Promise}
 */
function addSecret(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.CREATE_SECRET,
    requestParams("POST", data),
  );
}

/**
 * Add Secret Password
 * @param {object} data
 * @return {Promise}
 */
function generatePassword(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.GENERATE_PASSWORD,
    requestParams("POST", data),
  );
}

/**
 * Get Secret Server health Check
 * @return {Promise}
 */
function healthCheck(url) {
  return new Promise((resolve, reject) => {
    fetch(url).then((response) => {
      const contentType = response.headers.get("content-type");
      if (!contentType && !response.ok) return reject(response);
      const isJSON = contentType.includes(CONTENT.APP_JSON);
      const result = isJSON ? response.json() : response;
      if (response.ok || response.status === 401) {
        if (response.status === 401) {
          response.healthy = true;
        }
        resolve(result);
        return;
      }
      reject(result);
    }).catch((error) => {
      reject(error);
    });
  });
}

function platformHealthCheck(url) {
  return new Promise((resolve, reject) => {
    fetch(url, { redirect: "error" }).then((response) => {
      if (response.ok) {
        resolve(response);
        return;
      }
      reject(response);
    }).catch((error) => {
      reject(error);
    });
  });
}

function searchByURL(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS_BY_URL,
    requestParams("POST", data, CONTENT && CONTENT.APP_JSON),
  );
}

/**
 * Get Secret State
 * @param {number} secretId
 * @return {Promise}
 */
function getSecretState(secretId, accessToken) {
  const reqParams = requestParams("GET");

  reqParams.headers.set("Authorization", accessToken || _tokens__WEBPACK_IMPORTED_MODULE_2__/* .oauth */ .o.access_token);

  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS_STATES(secretId),
    reqParams,
  );
}

/**
 * get Meta Data
 * @return {Promise}
 */
function getMetaData(secretId, accessToken) {
  const reqParams = requestParams("GET");
  reqParams.headers.set("Authorization", accessToken || _tokens__WEBPACK_IMPORTED_MODULE_2__/* .oauth */ .o.access_token);
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.get_metadata(secretId),
    reqParams,
  );
}
/**
 * Get one time password
 * @param {number} secretId
 * @return {Promise}
 */
function getOneTimePassword(secretId, accessToken) {
  const reqParams = requestParams("GET");

  reqParams.headers.set("Authorization", accessToken || _tokens__WEBPACK_IMPORTED_MODULE_2__/* .oauth */ .o.access_token);

  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.getOTP(secretId),
    reqParams,
  );
}

/**
 * autofill
 * @param {*} data
 * @returns
 */
function autoFillCall(data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.AUTOFILL,
    requestParams("POST", data, CONTENT.APP_JSON),
  );
}
/**
 * Get Secret By Id
 * @param {number} secretId
 * @return {Promise}
 */
function getSecretById(secretId) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS + secretId,
    requestParams("GET"),
  );
}

/**
 * Get Secret By Id
 * @param {number} secretId
 * @return {Promise}
 */
function getFolderPath(folderId) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.folderPath(folderId),
    requestParams("GET"),
  );
}

/**
 * Get Ticket System
 * @return {Promise}
 */
function getTicketSystem() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.ticket_systems(),
    requestParams("GET"),
  );
}

/**
 * saveComments
 * @param {*} data
 * @returns
 */
function saveComments(secretId, data) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.view_comment(secretId),
    requestParams("POST", data, CONTENT.APP_JSON),
  );
}

/**
 * checkoutSecret
 * @param {*} data
 * @returns
 */
function checkoutSecret(secretId) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.check_out(secretId),
    requestParams("POST", {}, CONTENT.APP_JSON),
  );
}

/**
 * Get Recent Secrets
 * @param {string} filter
 * @param {boolean} useVersion1
 * @return {Promise}
 */
function getRecentSecrets(filter, useVersion1) {
  const secrets = useVersion1 ? _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS : _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS_V2;
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + secrets + filter,
    requestParams("GET"),

    2,
  );
}

/**
 * Get Favorite Secrets
 * @param {string} filter
 * @param {boolean} useVersion1
 * @return {Promise}
 */
function getFavoriteSecrets(filter, useVersion1) {
  const secrets = useVersion1 ? _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS : _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.SECRETS_V2;
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + secrets + filter,
    requestParams("GET"),
  );
}

/**
 * Get All Favorite Secrets
 * @return {Promise}
 */
function getAllFavoriteSecrets() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.Favorites,
    requestParams("GET"),
  );
}

/**
 * Get Secet Server Version
 * @return {Promise}
 */
function getSSVersion() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.VERSION,
    requestParams("GET"),
  );
}

/**
 * Get Secet Server Version
 * @return {Promise}
 */
function getUserPermissions() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.USERPERMISSIONS,
    requestParams("GET"),
  );
}

/**
 * launcherURL
 * @param {number} secretId
 * @return {Promise}
 */
function getSecretlauncherURL(secretId) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.launcherURL(secretId),
    requestParams("GET"),
  );
}

function postMetadata(secretId, jsonData) {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.post_metadata(secretId),
    requestParams("POST", jsonData, CONTENT.APP_JSON),
  );
}

function getMetadataFieldSections() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.METADATA_FIELD_SECTIONS,
    requestParams("GET"),
  );
}

/**
 * Get Personal folder
 * @return {Promise}
 */
async function getPersonalFolder() {
  return httpRequest(
    _utils_common__WEBPACK_IMPORTED_MODULE_1__/* .config */ .$W.BaseURL + _apis_endpoints__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A.PERSONAL_FOLDER,
    requestParams("GET"),
  );
}


/***/ }),

/***/ 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);


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   o: () => (/* binding */ oauth),
/* harmony export */   y: () => (/* binding */ allTokens)
/* harmony export */ });
/* harmony import */ var _cache__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(845);


const oauth = {
  accessToken: '',
  refreshToken: '',
  expiresIn: '',
  clearToken() {
    this.accessToken = '';
    this.refreshToken = '';
    this.expiresIn = '';
    _cache__WEBPACK_IMPORTED_MODULE_0__/* .commonCacheProvider */ .FJ.set(_cache__WEBPACK_IMPORTED_MODULE_0__/* .cacheKeys */ .Xr.token, '');
  },
  set token(token) {
    this.accessToken = `${(token && token.token_type) || ''} ${token && token.access_token}`.trim();
    this.expiresIn = token && token.expires_in;
    this.refreshToken = token && token.refresh_token;
    _cache__WEBPACK_IMPORTED_MODULE_0__/* .commonCacheProvider */ .FJ.set(_cache__WEBPACK_IMPORTED_MODULE_0__/* .cacheKeys */ .Xr.token, token);
  },
  get access_token() {
    return this.accessToken;
  },
  get expires_in() {
    return this.expiresIn;
  },
  get refresh_token() {
    return this.refreshToken;
  },
  set expires_in(value) {
    this.expiresIn = value;
  },
  async restore() {
    const token = await _cache__WEBPACK_IMPORTED_MODULE_0__/* .commonCacheProvider */ .FJ.get(_cache__WEBPACK_IMPORTED_MODULE_0__/* .cacheKeys */ .Xr.token);
    if (!token) return;
    this.token = token;
  },
};

const allTokens = {
  restore() {
    oauth.restore();
  },
};


/***/ }),

/***/ 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);


/***/ }),

/***/ 183:
/***/ ((__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 _cache__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(845);
/* harmony import */ var _cache_logger_provider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(322);



/**
     * addLogs
     *  @param {*} msg
     */

const errorType = {
  INFO: 'INFO',
  ERROR: 'ERROR',
};

const logger = {

  async isEnabled(callback) {
    const items = await _cache__WEBPACK_IMPORTED_MODULE_0__/* .settingsProvider */ .Pj.get();
    callback(items.set_enable_diagnostic_logging);
  },

  logInfo(message) {
    this.isEnabled((enabled) => {
      if (!enabled) return;
      const formattedLog = this.getFormattedLog(errorType.INFO, message);
      _cache_logger_provider__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A.add(formattedLog);
    });
  },
  logError(message) {
    this.isEnabled((enabled) => {
      if (!enabled) return;
      const formattedLog = this.getFormattedLog(errorType.ERROR, message);
      _cache_logger_provider__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A.add(formattedLog);
    });
  },
  getFormattedLog(type, msg) {
    let message = msg;
    if (typeof msg === 'object') {
      message = JSON.stringify(msg);
    }
    const currDateTime = new Date().toLocaleString().replace(',', '');
    return `${type}: ${currDateTime} : ${message}`;
  },
  getLogs() {
    return _cache_logger_provider__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A.get();
  },
  clear() {
    _cache_logger_provider__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A.clear();
  },

};

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


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A2: () => (/* binding */ cleanUrlString),
/* harmony export */   Dl: () => (/* binding */ parseUrl),
/* harmony export */   ZG: () => (/* binding */ addDefaultProtocol),
/* harmony export */   gU: () => (/* binding */ isUrl),
/* harmony export */   mR: () => (/* binding */ appendPath),
/* harmony export */   ws: () => (/* binding */ removeLastSlash)
/* harmony export */ });
/* unused harmony export urlEncode */
/* 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;
}


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ dataURLtoBlob),
/* harmony export */   y: () => (/* binding */ blobToDataURL)
/* harmony export */ });
// These functions are used to convert a blob to a base64 data URL and
// back. They are potentially duplicative of other base64 encode operations
// but these were the only thing that seemed to allow passing a blob in an
// extension message payload.
const blobToDataURL = (blob, cb) => {
  const reader = new FileReader();
  reader.onload = () => {
    const dataUrl = reader.result;
    cb(dataUrl);
  };
  reader.readAsDataURL(blob);
};

const dataURLtoBlob = (dataURL) => {
  const base64 = dataURL.split(",")[1];
  const byteString = atob(base64);
  const mimeString = dataURL.split(",")[0].split(":")[1].split(";")[0];

  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  const blob = new Blob([ia], { type: mimeString });
  return blob;
};


/***/ }),

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

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $W: () => (/* binding */ config),
/* harmony export */   FS: () => (/* binding */ checkIfMultiDomain),
/* harmony export */   U8: () => (/* binding */ addObjectsToArray),
/* harmony export */   Wk: () => (/* binding */ passwordIsHidden),
/* harmony export */   Ye: () => (/* binding */ getHiddenPassword),
/* harmony export */   cT: () => (/* binding */ hidePassword),
/* harmony export */   gm: () => (/* binding */ isFirefox),
/* harmony export */   ld: () => (/* binding */ chunkSubstr),
/* harmony export */   nr: () => (/* binding */ isSafari)
/* harmony export */ });
/* unused harmony exports $, removeArrayEle, writeToClipboard */
/* 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']);


/***/ }),

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

const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
// const octRegex = /0x[a-z0-9]+/;
// const binRegex = /0x[a-z0-9]+/;


//polyfill
if (!Number.parseInt && window.parseInt) {
    Number.parseInt = window.parseInt;
}
if (!Number.parseFloat && window.parseFloat) {
    Number.parseFloat = window.parseFloat;
}

  
const consider = {
    hex :  true,
    leadingZeros: true,
    decimalPoint: "\.",
    eNotation: true
    //skipLike: /regex/
};

function toNumber(str, options = {}){
    // const options = Object.assign({}, consider);
    // if(opt.leadingZeros === false){
    //     options.leadingZeros = false;
    // }else if(opt.hex === false){
    //     options.hex = false;
    // }

    options = Object.assign({}, consider, options );
    if(!str || typeof str !== "string" ) return str;
    
    let trimmedStr  = str.trim();
    // if(trimmedStr === "0.0") return 0;
    // else if(trimmedStr === "+0.0") return 0;
    // else if(trimmedStr === "-0.0") return -0;

    if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
    else if (options.hex && hexRegex.test(trimmedStr)) {
        return Number.parseInt(trimmedStr, 16);
    // } else if (options.parseOct && octRegex.test(str)) {
    //     return Number.parseInt(val, 8);
    // }else if (options.parseBin && binRegex.test(str)) {
    //     return Number.parseInt(val, 2);
    }else{
        //separate negative sign, leading zeros, and rest number
        const match = numRegex.exec(trimmedStr);
        if(match){
            const sign = match[1];
            const leadingZeros = match[2];
            let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
            //trim ending zeros for floating number
            
            const eNotation = match[4] || match[6];
            if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123
            else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123
            else{//no leading zeros or leading zeros are allowed
                const num = Number(trimmedStr);
                const numStr = "" + num;
                if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
                    if(options.eNotation) return num;
                    else return str;
                }else if(eNotation){ //given number has enotation
                    if(options.eNotation) return num;
                    else return str;
                }else if(trimmedStr.indexOf(".") !== -1){ //floating number
                    // const decimalPart = match[5].substr(1);
                    // const intPart = trimmedStr.substr(0,trimmedStr.indexOf("."));

                    
                    // const p = numStr.indexOf(".");
                    // const givenIntPart = numStr.substr(0,p);
                    // const givenDecPart = numStr.substr(p+1);
                    if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0
                    else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000
                    else if( sign && numStr === "-"+numTrimmedByZeros) return num;
                    else return str;
                }
                
                if(leadingZeros){
                    // if(numTrimmedByZeros === numStr){
                    //     if(options.leadingZeros) return num;
                    //     else return str;
                    // }else return str;
                    if(numTrimmedByZeros === numStr) return num;
                    else if(sign+numTrimmedByZeros === numStr) return num;
                    else return str;
                }

                if(trimmedStr === numStr) return num;
                else if(trimmedStr === sign+numStr) return num;
                // else{
                //     //number with +/- sign
                //     trimmedStr.test(/[-+][0-9]);

                // }
                return str;
            }
            // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;
            
        }else{ //non-numeric string
            return str;
        }
    }
}

/**
 * 
 * @param {string} numStr without leading zeros
 * @returns 
 */
function trimZeros(numStr){
    if(numStr && numStr.indexOf(".") !== -1){//float
        numStr = numStr.replace(/0+$/, ""); //remove ending zeros
        if(numStr === ".")  numStr = "0";
        else if(numStr[0] === ".")  numStr = "0"+numStr;
        else if(numStr[numStr.length-1] === ".")  numStr = numStr.substr(0,numStr.length-1);
        return numStr;
    }
    return numStr;
}
module.exports = toNumber


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// 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;
/******/ 	}
/******/ 	
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/ 	
/************************************************************************/
/******/ 	/* 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/ensure chunk */
/******/ 	(() => {
/******/ 		__webpack_require__.f = {};
/******/ 		// This file contains only the entry chunk.
/******/ 		// The chunk loading function for additional chunks
/******/ 		__webpack_require__.e = (chunkId) => {
/******/ 			return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ 				__webpack_require__.f[key](chunkId, promises);
/******/ 				return promises;
/******/ 			}, []));
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/get javascript chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks
/******/ 		__webpack_require__.u = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return "" + chunkId + ".js";
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/load script */
/******/ 	(() => {
/******/ 		var inProgress = {};
/******/ 		var dataWebpackPrefix = "web-password-filler:";
/******/ 		// loadScript function to load a script via script tag
/******/ 		__webpack_require__.l = (url, done, key, chunkId) => {
/******/ 			if(inProgress[url]) { inProgress[url].push(done); return; }
/******/ 			var script, needAttach;
/******/ 			if(key !== undefined) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				for(var i = 0; i < scripts.length; i++) {
/******/ 					var s = scripts[i];
/******/ 					if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
/******/ 				}
/******/ 			}
/******/ 			if(!script) {
/******/ 				needAttach = true;
/******/ 				script = document.createElement('script');
/******/ 		
/******/ 				script.charset = 'utf-8';
/******/ 				script.timeout = 120;
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/ 				script.setAttribute("data-webpack", dataWebpackPrefix + key);
/******/ 		
/******/ 				script.src = url;
/******/ 			}
/******/ 			inProgress[url] = [done];
/******/ 			var onScriptComplete = (prev, event) => {
/******/ 				// avoid mem leaks in IE.
/******/ 				script.onerror = script.onload = null;
/******/ 				clearTimeout(timeout);
/******/ 				var doneFns = inProgress[url];
/******/ 				delete inProgress[url];
/******/ 				script.parentNode && script.parentNode.removeChild(script);
/******/ 				doneFns && doneFns.forEach((fn) => (fn(event)));
/******/ 				if(prev) return prev(event);
/******/ 			}
/******/ 			var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
/******/ 			script.onerror = onScriptComplete.bind(null, script.onerror);
/******/ 			script.onload = onScriptComplete.bind(null, script.onload);
/******/ 			needAttach && document.head.appendChild(script);
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* 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 });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/publicPath */
/******/ 	(() => {
/******/ 		var scriptUrl;
/******/ 		if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
/******/ 		var document = __webpack_require__.g.document;
/******/ 		if (!scriptUrl && document) {
/******/ 			if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')
/******/ 				scriptUrl = document.currentScript.src;
/******/ 			if (!scriptUrl) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				if(scripts.length) {
/******/ 					var i = scripts.length - 1;
/******/ 					while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;
/******/ 				}
/******/ 			}
/******/ 		}
/******/ 		// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
/******/ 		// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
/******/ 		if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
/******/ 		scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
/******/ 		__webpack_require__.p = scriptUrl;
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/ 		
/******/ 		// object to store loaded and loading chunks
/******/ 		// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 		// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ 		var installedChunks = {
/******/ 			471: 0
/******/ 		};
/******/ 		
/******/ 		__webpack_require__.f.j = (chunkId, promises) => {
/******/ 				// JSONP chunk loading for javascript
/******/ 				var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ 				if(installedChunkData !== 0) { // 0 means "already installed".
/******/ 		
/******/ 					// a Promise means "currently loading".
/******/ 					if(installedChunkData) {
/******/ 						promises.push(installedChunkData[2]);
/******/ 					} else {
/******/ 						if(true) { // all chunks have JS
/******/ 							// setup Promise in chunk cache
/******/ 							var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
/******/ 							promises.push(installedChunkData[2] = promise);
/******/ 		
/******/ 							// start chunk loading
/******/ 							var url = __webpack_require__.p + __webpack_require__.u(chunkId);
/******/ 							// create error before stack unwound to get useful stacktrace later
/******/ 							var error = new Error();
/******/ 							var loadingEnded = (event) => {
/******/ 								if(__webpack_require__.o(installedChunks, chunkId)) {
/******/ 									installedChunkData = installedChunks[chunkId];
/******/ 									if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
/******/ 									if(installedChunkData) {
/******/ 										var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 										var realSrc = event && event.target && event.target.src;
/******/ 										error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 										error.name = 'ChunkLoadError';
/******/ 										error.type = errorType;
/******/ 										error.request = realSrc;
/******/ 										installedChunkData[1](error);
/******/ 									}
/******/ 								}
/******/ 							};
/******/ 							__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
/******/ 						}
/******/ 					}
/******/ 				}
/******/ 		};
/******/ 		
/******/ 		// no prefetching
/******/ 		
/******/ 		// no preloaded
/******/ 		
/******/ 		// no HMR
/******/ 		
/******/ 		// no HMR manifest
/******/ 		
/******/ 		// no on chunks loaded
/******/ 		
/******/ 		// install a JSONP callback for chunk loading
/******/ 		var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			// add "moreModules" to the modules object,
/******/ 			// then flag all "chunkIds" as loaded and fire callback
/******/ 			var moduleId, chunkId, i = 0;
/******/ 			if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ 				for(moduleId in moreModules) {
/******/ 					if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 						__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 					}
/******/ 				}
/******/ 				if(runtime) var result = runtime(__webpack_require__);
/******/ 			}
/******/ 			if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ 			for(;i < chunkIds.length; i++) {
/******/ 				chunkId = chunkIds[i];
/******/ 				if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 					installedChunks[chunkId][0]();
/******/ 				}
/******/ 				installedChunks[chunkId] = 0;
/******/ 			}
/******/ 		
/******/ 		}
/******/ 		
/******/ 		var chunkLoadingGlobal = self["webpackChunkweb_password_filler"] = self["webpackChunkweb_password_filler"] || [];
/******/ 		chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ 		chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";

// UNUSED EXPORTS: addMinutes, changeToolbarIcon, checkExactMatch, checkForCrossDomain, checkIfPlatformLoginPage, checkIfPlatformOrSS, checkIfPlatformServer, checkIfSecretServer, checkIncognito, checkRecording, checkWPFServerType, convertResponse, createContextMenu, createSecret, createSecretMenu, createTab, createWindow, filterSecrets, generatePassword, getAutoLoginToken, getAutofillDetails, getCommonData, getFavIcon, getLastSecretEntry, getMFAChallenge, getMetadata, getPassword, getPlatformRefreshToken, getRefreshToken, getSSOSecrets, getSecretPassword, getSecrets, getSecretsByUrl, getSessionTabCount, getTemplatesNFolders, getVaultInfo, getWPFHintSection, gotAllVaults, gotInvalidTemplateErrorEvent, gotLoginErrorEvent, gotMFAErrorEvent, gotMetadata, gotMetadataError, gotPasswordErrorEvent, gotPasswordEvent, gotRefreshTokenEvent, gotSSToken, gotSecretPasswordEvent, gotSecretSaveErrorEvent, gotSecretSaveEvent, gotSecretSavePopupErrorEvent, gotSecretUpdateErrorEvent, gotSecretUserPassword, gotSecretsByURLEvent, gotSecretsByUrl, gotTemplateInfoEvent, gotTicketError, gotTokenEvent, gotUniversalToken, gotUpdateSecretsPasswordEvent, gotUserPermission, gotVersion, handleCheckoutTimeout, handleError, handleSwitchSS, handlelaunchSecret, insertMetadata, isSecretCapuredInList, launchAfterSwitch, launchSecret, logOffUser, loginWithSS, notifyCS, onRefreshTokenError, onSSLogOff, openAddSecretPopup, organizeMapInfo, otpOnNextPage, passwordGeneratedEvent, persistSecret, promptUser, pushToLastFetchedList, refreshRecentAndFavorites, refreshSecretList, reloadContextMenus, reloadOtherSSTabs, removeOpenedWindow, removePersistSecret, saveForNever, search, sendORAutofill, setIncognitoFlag, setLauncherInfo, setLoggedIn, setMFALoginWindow, setSSLoginTab, setSSLoginWindow, setWindowHeightWidth, stepUpAction, switchLogin, tokenExpired, updateSecretPassword, usePlatformLogin, useSecretServerLogin, userLogin

// 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/core/promise.js
var promise = __webpack_require__(128);
// EXTERNAL MODULE: ./src/scripts/apis/endpoints.js
var endpoints = __webpack_require__(165);
;// CONCATENATED MODULE: ./src/scripts/apis/recording-apis.js





const soapRequestBody = (request) => {
  if (!(request && request.operation && request.args)) return null;
  let argsXML = '';
  // eslint-disable-next-line no-restricted-syntax
  for (const key in request.args) {
    // eslint-disable-next-line no-prototype-builtins
    if (request.args.hasOwnProperty(key)) {
      argsXML += `<urn:${key}>${request.args[key]}</urn:${key}>`;
    }
  }
  return `<?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:thesecretserver.com">
        <soap:Body>
          <urn:${request.operation}>${argsXML}</urn:${request.operation}>
        </soap:Body>
        </soap:Envelope>`;
};

const invalidArgs = (operation) => Promise.reject(new Error(`${operation}: invalid args`));

const operations = {
  getSymmetricKey: 'GetSymmetricKey',
  getLauncherArguments: 'GetLauncherArguments',
  postEncodedSegment: 'PostEncodedSegment',
  updateStatus: 'UpdateStatus',
  sessionRecordingComplete: 'SessionRecordingComplete',
  endSession: 'EndSession',
};

const recordingApis = {
  async getLauncherSecret(data) {
    if (!data) return invalidArgs('LauncherSecret');
    return (0,promise.httpRequest)(
      common/* config */.$W.BaseURL + endpoints/* default */.A.LAUNCHER_SECRET,
      (0,promise.requestParams)('POST', data, constants.CONTENT.APP_URL_ENCODED),
    );
  },
  async getExtendedUrls(secretId) {
    if (!secretId) return invalidArgs('getExtendedUrls');
    return (0,promise.httpRequest)(
      common/* config */.$W.BaseURL + endpoints/* default */.A.EXTENDED_FIELDS + secretId,
      (0,promise.requestParams)('GET'),
    );
  },
  async getSymmetricKey(args) {
    if (!args) return invalidArgs(operations.getSymmetricKey);
    const body = soapRequestBody({ operation: operations.getSymmetricKey, args });
    return (0,promise.soapRequest)(
      common/* config */.$W.SoapURL,
      body,
    );
  },

  async getLauncherArguments(args) {
    if (!args) return invalidArgs(operations.getLauncherArguments);
    const body = soapRequestBody({ operation: operations.getLauncherArguments, args });
    return (0,promise.soapRequest)(
      common/* config */.$W.SoapURL,
      body,
    );
  },

  postEncodedSegment: (args) => {
    if (!args) return invalidArgs(operations.postEncodedSegment);
    const body = soapRequestBody({ operation: operations.postEncodedSegment, args });
    return (0,promise.httpRequest)(
      common/* config */.$W.SoapURL,
      (0,promise.requestParams)('POST', body, constants.CONTENT.TEXT_XML),
    );
  },

  updateStatus: (args) => {
    if (!args) return invalidArgs(operations.updateStatus);
    const body = soapRequestBody({ operation: operations.updateStatus, args });
    return (0,promise.soapRequest)(
      common/* config */.$W.SoapURL,
      body,
    );
  },

  sessionRecordingComplete: (args) => {
    if (!args) return invalidArgs(operations.sessionRecordingComplete);
    const body = soapRequestBody({ operation: operations.sessionRecordingComplete, args });
    return (0,promise.httpRequest)(
      common/* config */.$W.SoapURL,
      (0,promise.requestParams)('POST', body, constants.CONTENT.TEXT_XML),
    );
  },

  endSession: (args) => {
    if (!args) return invalidArgs(operations.endSession);
    const body = soapRequestBody({ operation: operations.endSession, args });
    return (0,promise.httpRequest)(
      common/* config */.$W.SoapURL,
      (0,promise.requestParams)('POST', body, constants.CONTENT.TEXT_XML),
    );
  },
};

/* harmony default export */ const recording_apis = (recordingApis);

// EXTERNAL MODULE: ./src/scripts/helpers/url-helpers.js
var url_helpers = __webpack_require__(714);
;// CONCATENATED MODULE: ./src/scripts/utils/errors.js


/* eslint-disable max-len */
const errors_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.secretAction.copyUsername) {
      return "Username copied to clipboard";
    }
    if (type === constants.secretAction.copyPassword) {
      return "Password copied to clipboard";
    }
    if (type === constants.secretAction.copyOtp) {
      return "OTP copied to clipboard";
    }
  },

};

// EXTERNAL MODULE: ./src/scripts/helpers/logger.js
var logger = __webpack_require__(183);
;// CONCATENATED MODULE: ./src/scripts/utils/message.js






const regExp = /^http/i;


/**
 * checkLastError
 * @param {boolean} print
 */
function checkLastError(print = true) {
  if (((ext_default()).runtime.lastError
    && (ext_default()).runtime.lastError !== 'undefined') && print) {
    if ((ext_default()).runtime.lastError.message) {
      return;
    }
    if ((ext_default()).runtime.lastError.message === ''
    || (ext_default()).runtime.lastError.message === 'The message port closed before a response was received.') {
      return;
    }
    console.log((ext_default()).runtime.lastError.message);
  }
}

/**
 * Send the data to cuurent tab
 * @param {string} method method name to receive response
 * @param {object} result data to send
 * @param {object} sender requestor info
 */
function sendDataToSpecificTab(method, result, sender) {
  ext_default().tabs.get(sender.tab.id, (tab) => {
    checkLastError();
    if (tab) {
      const tabURL = (0,url_helpers/* parseUrl */.Dl)(tab.url).domain;
      const senderURL = (0,url_helpers/* parseUrl */.Dl)(sender.url).domain;
      if (tabURL === senderURL
         || ((0,common/* checkIfMultiDomain */.FS)(tabURL) && (0,common/* checkIfMultiDomain */.FS)(senderURL))) {
        sender.apicall = null;
        sender.args = [];
        sender.selectedframeId = sender.selectedframeId > 0
          ? sender.selectedframeId : undefined;
        ext_default().tabs.sendMessage(sender.tab.id, {
          response: result,
          method,
          sender,
        }, { frameId: sender.selectedframeId }, () => {
          checkLastError(false);
        });
      }
    }
  });
}

/**
 * Send the data to cuurent tab
 * @param {string} method method name to receive response
 * @param {object} result data to send
 * @param {object} sender requestor info
 */
function sendMessageToSpecificWindowTab(method, result, sender) {
  const tab = sender.tab ? sender.tab : sender;
  if (!(ext_default())?.windows?.getAll) return;
  ext_default().windows.getAll({
    populate: true,
    windowTypes: ['normal', 'popup'],
  }, (windowArray) => {
    for (let w = 0; w < windowArray.length; w++) {
      for (let t = 0; t < windowArray[w].tabs.length; t++) {
        if (windowArray[w].tabs[t].id === tab.id) {
          if (windowArray[w].tabs[t].url === tab.url) {
            ext_default().tabs.sendMessage(windowArray[w].tabs[t].id, {
              method,
              response: result,
              sender,
            }, () => {
              checkLastError();
            });
            break;
          }
        }
      }
    }
  });
}

/**
 * callback of windows.getAll returning all window objcts
 * @param {string} method
 * @param {object} result
 * @param {boolean}  includeTabs
 */
function sendMessage(method, result, includeTabs = true) {
  // sendDataToPop(method, result);
  if (includeTabs) {
    if (!(ext_default())?.windows?.getAll) return;
    ext_default().windows.getAll({
      populate: true,
      windowTypes: ['normal'],
    }, (windowInfoArray) => {
      if (windowInfoArray.length > 0) {
        windowInfoArray.forEach((windowInfo) => {
          windowInfo.tabs.forEach((tab) => {
            if (regExp.exec(tab.url)) {
              ext_default().tabs.sendMessage(tab.id, {
                method,
                response: result,
              }, () => {
                checkLastError();
              });
            }
          }, () => {
            checkLastError();
          });
        });
      }
    });
  }
}

/**
 * Send the data to cuurent tab
 * @param {string} method method name to receive response
 * @param {object} result data to send
 * @param {string} secretState state of secret
 * @param {Number} secretId
 * @param {boolean} isSupported
 * @param {Array} records
 */
function message_sendDataToTab(
  method,
  result,
  secretState,
  secretId,
  isSupported,
  records,
) {
 
  if(method === 'showError'){
    logger/* default */.A.logError(result);
  }
  ext_default().tabs.query(constants.ACTIVE_TAB_QUERY, (tabs) => {
    if (tabs && tabs.length > 0) {
      if (!(ext_default())?.tabs?.sendMessage) return;
      ext_default().tabs.sendMessage(tabs[0].id, {
        response: result,
        method,
        state: secretState,
        secretId,
        isSupported,
        records,
      }, () => {
        checkLastError();
      });
    }
  });
}

/**
 * Send the data to cuurent tab
 * @param {string} method method name to receive response
 * @param {object} result data to send
 * @param {string} secretState state of secret
 * @param {number} secretId
 * @param {boolean} isSupported
 * @param {string} action
 * @param {string} records
 */
function sendDataToPop(
  method,
  result,
  secretState,
  secretId,
  isSupported,
  action,
  records,
) {  
  if(method === 'showError'){
    logger/* default */.A.logError(result);
  }
  ext_default().runtime.sendMessage({
    method,
    response: result,
    state: secretState,
    secretId,
    isSupported,
    action,
    records,
  }, () => {
    checkLastError(false);
  });
}

self.addEventListener('error', function(event) {
  console.error('Service worker error:', event.error);  
  logger/* default */.A.logError(event.error);
});

/**
 * getContextKey
 * @param {*} configBaseURL
 * @param {*} loggedInUserId
 * @param {*} context
 * @return {string}
 */
function getContextKey(configBaseURL, loggedInUserId, context) {
  // Append with # or anything else other than |
  return `${configBaseURL}#${
    loggedInUserId}#${context}`;
}

function sendShowConfirmMessage(tab, method, result) {
  ext.windows.update(tab && tab.windowId, {
    drawAttention: true,
  }, () => {
    ext.tabs.sendMessage(tab.id, {
      response: result,
      method,
      url: tab.url,
      active: true,
      currentWindow: true,
      pinned: true,
    });
    ext.tabs.update(tab.id, { active: true });
  });
}

function getConfigUrlTab(callback) {
  ext.tabs.query({}, (tabs) => {
    if (tabs && tabs.length > 0) {
      for (let i = 0; i < tabs.length; i++) {
        const activeTab = tabs[i];
        const tabUrl = activeTab.url;
        const url1 = new URL(tabUrl);
        const url2 = new URL(config.Url);
        // check if tab url matches config URL
        if (url1.origin === url2.origin) {
          callback(activeTab);
          return;
        }
      }
    }
    callback(null);
  });
}

function setConfigUrlTabActive(method, result) {
  getConfigUrlTab((tab) => {
    if (!tab) return;
    sendShowConfirmMessage(tab, method, result);
  });
}

/**
 * Send the data to cuurent tab
 * @param {string} method method name to receive response
 * @param {object} result data to send
 * @param {string} secretState state of secret
 * @param {Number} secretId
 * @param {boolean} isSupported
 * @param {Array} records
 */
function sendDataToTabForActiveSession(
  method,
  result,
) { 
  ext.tabs.query(ACTIVE_TAB_QUERY_MIN_REQ, (tabs) => {
    if (tabs && tabs.length > 0) {
      const tabWithContentScript = tabs.find((t) => (t.url.startsWith('https://') || t.url.startsWith('http://')) && !t.url.startsWith('about:'));
      if (tabWithContentScript) {
        sendShowConfirmMessage(tabWithContentScript, method, result);
      } else {
        setConfigUrlTabActive(method, result);
      }
    }
  });
}

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





/**
 * getCurrentTicks
 * @return {string}
 */
function utils_getCurrentTicks() {
  const currentDate = new Date();
  const epochTicks = 621355968000000000;
  const ticksPerMillisecond = 10000;
  return epochTicks + (currentDate.getTime() * ticksPerMillisecond);
}

const createOffscreenDocument = async () => {

  if (!(ext_default()).offscreen) {
    return;
  }

  const existingContexts = await ext_default().runtime.getContexts({});
  const offscreenDocument = existingContexts.find(
    (c) => c.contextType === "OFFSCREEN_DOCUMENT"
  );

  const reasons = ["USER_MEDIA"];
  // If an offscreen document is not already open, create one.
  if (!offscreenDocument) {
    // Create an offscreen document.
    await ext_default().offscreen.createDocument({
      url: "offscreen.html",
      reasons,
      justification: "Recording active tab",
    });
  }
};

// ["soap:Envelope"]["soap:Body"].GetSymmetricKeyResponse.GetSymmetricKeyResult
function getSymmetricKeyProperty(data, property) {
  try {
    // eslint-disable-next-line operator-linebreak
    const keyResult =
      data["soap:Envelope"]["soap:Body"].GetSymmetricKeyResponse
        .GetSymmetricKeyResult;
    return keyResult[property];
  } catch (e) {
    throw new Error("Error parsing Symmetric Key Response");
  }
}

/**
 *
 * @param {*} sessKey
 */
function setSessionTimeout(sessKey) {
  storage/* default */.A.get("Settings", (items) => {
    if (items.Settings) {
      let delay = constants.DEFAULT_RECORDING_LIMIT;
      // eslint-disable-next-line no-restricted-globals
      if (!isNaN(items.Settings.maxSessionRecordingLimit)) {
        delay = parseInt(items.Settings.maxSessionRecordingLimit, 10);
      }
      ext_default().alarms.create(`SESSION_TIMEOUT#${sessKey}`, {
        delayInMinutes: delay,
      });
      logger/* default */.A.logInfo(`Alarm created for SESSION_TIMEOUT#${sessKey}} with ${delay}`);
    }
  });
}

const debounce = (mainFunction, delay) => {
  let timer;

  return (...args) => {
    clearTimeout(timer);

    timer = setTimeout(() => {
      mainFunction(...args);
    }, delay);
  };
};


async function loadOffscreen() {
  const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  if (!isFirefox) {
    return null;
  }
  try {
    return await __webpack_require__.e(/* import() */ 955).then(__webpack_require__.bind(__webpack_require__, 955));
  } catch (err) {
    console.error("Failed to load module:", err);
    return null;
  }
}

;// CONCATENATED MODULE: ./src/scripts/recording/recording-encryption.js


/* eslint-disable function-paren-newline */
/* eslint-disable implicit-arrow-linebreak */
/* eslint-disable no-bitwise */
/* eslint-disable no-console */
/* global System importScripts proto */
if (typeof importScripts === "function") {
  importScripts("encryption/thycotic-pb.js");
  importScripts("encryption/System.js");
  importScripts("encryption/System.BigInt.js");
  importScripts("encryption/System.IO.js");
  importScripts("encryption/System.Text.js");
  importScripts("encryption/System.Convert.js");
  importScripts("encryption/System.BitConverter.js");
  importScripts("encryption/System.Security.Cryptography.SHA1.js");
  importScripts("encryption/System.Security.Cryptography.js");
  importScripts("encryption/System.Security.Cryptography.RSA.js");
  importScripts("encryption/System.Security.Cryptography.HMACSHA1.js");
  importScripts("encryption/System.Security.Cryptography.AES.js");
  importScripts("encryption/queue.js");
}

const { AES } = System.Security.Cryptography;

/**
 * getRsaProvider
 * @param {number} dwKeySize keysize
 * @return {object} provider
 */
function getRsaProvider(dwKeySize) {
  if (!dwKeySize) dwKeySize = 1024;
  return new System.Security.Cryptography.RSACryptoServiceProvider(dwKeySize);
}

/**
 * convertKeyToBase64
 * @param {boolean} includePrivateKey includePrivateKey to export
 * @param {boolean} RSAKey includePrivateKey to export
 * @return {string}
 */
function convertKeyToBase64(includePrivateKey, RSAKey) {
  const rsa = getRsaProvider();
  if (RSAKey[0] === "<") {
    // eslint-disable-next-line
    rsa.FromXmlString(RSAKey); // Import parameters from XML.
  } else {
    // eslint-disable-next-line
    const keyBlob = System.Convert.FromBase64String(RSAKey); // Import parameters from BLOB.
    // eslint-disable-next-line
    rsa.ImportCspBlob(keyBlob);
  }
  // Export RSA key to RSAParameters and include:
  //    false - Only public key required for encryption.
  //    true  - Private key required for decryption.
  // eslint-disable-next-line
  const bytes = rsa.ExportCspBlob(includePrivateKey);
  // eslint-disable-next-line
  const base64 = System.Convert.ToBase64String(bytes);
  return base64;
}

/**
 * generateRSAKey()
 */
function generateRSAKey() {
  const keySize = Number(1024);
  const rsa = getRsaProvider(keySize);
  // eslint-disable-next-line
  let RSAKey = rsa.ToXmlString(true);
  const publicKeyBase64Blob = convertKeyToBase64(false, RSAKey);
  // eslint-disable-next-line
  const privateKeyRSA = rsa.ExportParameters(true);
  return { publicKeyBase64Blob, privateKeyRSA };
}

/**
 * byte array to hex string
 * @param {byteArray} byteArray byte Array
 * @return {string} hexadecimal string
 */
function toHexString(byteArray) {
  return Array.from(byteArray, (byte) =>
    `0${(byte & 0xff).toString(16)}`.slice(-2)
  ).join("");
}

function toBase64String(data) {
  return System.Convert.ToBase64String(data);
}

/**
 * hexToBinary
 * @param {object} hex hexString
 * @return {string}
 */
function hexToBinary(hex) {
  const bytes = [];
  for (let i = 0; i < hex.length - 1; i += 2) {
    bytes.push(parseInt(hex.substr(i, 2), 16));
  }
  return bytes;
}

/**
 * decrypt RSA
 * @param {string} encryptedText encrypted text
 * @return {string}
 */
function decryptRSA(encryptedText, privateKeyRSA) {
  // eslint-disable-next-line
  const encryptedBytes = System.Convert.FromBase64String(encryptedText);
  const doOaepPadding = "OAEP";
  const rsa = getRsaProvider(1024);
  // eslint-disable-next-line
  rsa.ImportParameters(privateKeyRSA);
  // eslint-disable-next-line
  const decryptedBytes = rsa.Decrypt(encryptedBytes, doOaepPadding);
  const decryptedString = toHexString(decryptedBytes);
  return decryptedString;
}

function decryptAES(value, key, iv) {
  return AES.Decrypt(hexToBinary(value), hexToBinary(key), hexToBinary(iv));
}

/**
 * encryptAES
 * @param {object} inputBytes inputBytes
 * @param {object} cSession current Session
 * @return {string}
 */
function encryptAES(inputBytes, cSession) {
  // inputBytes === protobuf list
  const key = hexToBinary(cSession.sessionKey);
  // eslint-disable-next-line
  const encrypted = AES.Encrypt(inputBytes, key);
  return encrypted;
}

/**
 * getBinary
 * @param {*} uint8array
 * @return {*}
 */
function getBinary(uint8array) {
  const op1 = proto.RecordedStreamOperation.create();
  const ops = proto.RecordedStreamOperationList.create();
  op1.type = 0;
  op1.data = uint8array;
  op1.offset = 0;
  ops.operations = [op1];
  return proto.RecordedStreamOperationList.encode(ops).finish();
}

/**
 * getEncodedSegmentArgs
 * @param {*} uint8array
 * @param {*} session
 * @param {*} blobInfo
 * @return {object}
 */
function getEncodedSegmentArgs(uint8array, session, blobInfo) {
  const binary = getBinary(uint8array);
  const encryptedObj = encryptAES(binary, session);
  const args = {
    sessionGuid: session.launcherSessionGuid,
    // eslint-disable-next-line new-cap
    iv: System.Convert.ToBase64String(encryptedObj.iv),
    contents: encryptedObj.text,
    ticks: getCurrentTicks(),
    imageDifferential: 100,
    headersIncluded: blobInfo.headersIncluded,
  };
  return args;
}

;// CONCATENATED MODULE: ./src/scripts/recording/session-completion.js
/* eslint-disable no-plusplus */
/* global Queue */






let offscreenModule;

loadOffscreen().then((module) => {
  offscreenModule = module;
});

/**
 * sendEndSessionRequest
 * @param {guid} ssk
 */
function sendEndSessionRequest(ssk) {
  if (ssk) {
    const args = {
      sessionKey: ssk,
    };
    Queue.enqueue(() => recording_apis.endSession(args));
  }
}

/**
 * sendRecordingComplete
 * @param {guid} lsg
 */
function sendRecordingCompleteRequest(launchSessionGuid) {
  if (launchSessionGuid) {
    ext_default().alarms.clear(launchSessionGuid, () => logger/* default */.A.logInfo(`Alarm cleared ${launchSessionGuid}`));
    const args = {
      sessionGuid: launchSessionGuid,
    };
    Queue.enqueue(() => recording_apis.sessionRecordingComplete(args));
  }
}

/**
 * Delete cookies so user can not continue to be logged in
 * if session recording has ended
 * or no longer able to connect to SS
 * @param {object} domainInfo
 * @param {bool} isIncognitoSession
 */
function deleteCookies(domainInfo, isIncognitoSession) {
  if (!isIncognitoSession) {
    ext_default().cookies.getAll({ domain: domainInfo.domain }, (cookies) => {
      for (let i = 0; i < cookies.length; i++) {
        if (cookies[i].domain.includes(domainInfo.domain)) {
          ext_default().cookies.remove({ url: domainInfo.origin, name: cookies[i].name });
        }
      }
    });
  }
}

/**
 * clearSessionCookies
 * @param {*} activeSession
 */
function clearSessionCookies(session) {
  session.regExList.forEach((item) => {
    if(!item) return;
    const domainInfo = (0,url_helpers/* parseUrl */.Dl)((0,url_helpers/* addDefaultProtocol */.ZG)(item));
    deleteCookies(domainInfo, session.launchedInIncognito);
  });
}

function clearSessionTabs(tabsToRemove, session) {
  tabsToRemove.forEach((tabId) => {
    session.hosts.forEach((item) => {
      if (item === 'myapps.microsoft.com') {
        ext_default().tabs.sendMessage(tabId, {
          method: "clearStorage",
        })
      }
    })
    ext_default().tabs.remove(tabId);
  });
}

function sendEndSessionMessage(session) {
  if (offscreenModule) {
    offscreenModule.endRecording(session.guid);
    return;
  }
  ext_default().runtime.sendMessage({
    type: "endingSession",
    sessionGuid: session.guid,
  });

}

// eslint-disable-next-line import/prefer-default-export
function endSession(session, tabsToRemove) {
  // removes session in offscreen document
  sendEndSessionMessage(session);
  sendEndSessionRequest(session.secretSessionKey);
  sendRecordingCompleteRequest(session.launcherSessionGuid);
  clearInterval(session.updateStatusInterval);
  clearSessionCookies(session);
  clearSessionTabs(tabsToRemove, session);
  ext_default().alarms.clear(session.launcherSessionGuid, logger/* default */.A.logInfo(`Alarm cleared ${session.launcherSessionGuid}`));
  ext_default().alarms.clear(`SESSION_TIMEOUT#${session.secretSessionKey}`, logger/* default */.A.logInfo(`Alarm cleared SESSION_TIMEOUT#${session.secretSessionKey}`));
  console.log("Session ended");
  logger/* default */.A.logInfo();
}

// EXTERNAL MODULE: ./src/scripts/cache/index.js + 17 modules
var cache = __webpack_require__(845);
;// CONCATENATED MODULE: ./src/scripts/recording/session-manager.js
/* eslint-disable class-methods-use-this */





// const sampleSession = {
//   secretId: 123,
//   launcherId: 3,
//   guid: "e92cd242-[...]",
//   launcherSessionGuid: "262e6468-[...]",
//   publicKeyBase64Blob: "BgIAAACkA[...]",
//   key: "1e51b2[...]",
//   iv: "b78ac[...]",
//   sessionKey: "0421c8d[...]",
//   launchedInIncognito: false,
//   secretSessionKey: "d7bf1511-[...]",
//   incognito: false,
//   segments: [],
//   showMousePathRecording: false,
//   // currently this does contain duplicate domains
//   sessionUrls: ["example.com", "example.com"],
// };

const URL_ATTRIBUTION_STRATEGY = "host";

class SessionManager {
  constructor() {
    this.sessions = [];
    this.clearStorageKey = false;
  }

  addSession(session) {
    const index = this.getIndex(session.secretId, session.launchedInIncognito);
    // Don't allow duplicate sessions
    // Should this update instead?
    if (index >= 0) {
      console.log("Skipping duplicate session.", session);
      return;
    }
    this.sessions.push({ ...session });
  }

  removeSession(sessionOrSecretId, incognito) {
    const index = this.getIndex(sessionOrSecretId, incognito);
    if (index === -1) {
      return;
    }
    this.sessions.splice(index, 1);
  }

  updateSession(session) {
    const index = this.getIndex(session.secretId, session.launchedInIncognito);
    if (index >= 0) {
      this.sessions[index] = { ...session };
    }
  }
 
  async getAttributedUrls(session, tabs) {
    const attributedUrls = [];
    // eslint-disable-next-line no-restricted-syntax
    for (const tab of tabs) {
      if(session.launchedInIncognito !== tab?.incognito) {
        continue;
      }

      if (await this.urlIsAttributed(session, tab.url)) {
        attributedUrls.push(tab.url);
      }
    }
    return attributedUrls;
  }

  async getAttributedSessions(url, incognito) {
    const attributedSessions = [];
    // eslint-disable-next-line no-restricted-syntax
    for (const session of this.sessions) {
      if(session.launchedInIncognito !== incognito) {
        continue;
      }
      if (await this.urlIsAttributed(session, url)) {
        attributedSessions.push(session.guid);
      }
    }
    return attributedSessions;
  }

  async urlIsAttributed(session, url) {
    const details = (0,url_helpers/* parseUrl */.Dl)(url);
    if (!details) return;
    const settings = await cache/* settingsProvider */.Pj.get();
    

    if (settings.matchSessionByHost) {
      return session.hosts.includes(details.host);
    }
    return session.domains.includes(details.domain);
  }

  getSession(sessionOrSecretId, incognito) {
    const index = this.getIndex(sessionOrSecretId, incognito);
    if (index >= 0) {
      return { ...this.sessions[index] };
    }
    return null;
  }

  async getSessionTabIds(session, excludeActive = false) {
    const tabIds = [];
    const tabs = await ext_default().tabs.query({});    
    for (let i = 0; i < tabs.length; i++) {
      let tab = tabs[i];
      if (await this.urlIsAttributed(session, tab.url)) {
        if (excludeActive && tab.active) {
          continue;
        }
        if(session.launchedInIncognito !== tab.incognito) {
          continue;
        }
        tabIds.push(tab.id);
      }
    }
    return tabIds;
  }

  getSessions() {
    return [...this.sessions];
  }

  async endSession(sessionOrSecretId, incognito) {
    const index = this.getIndex(sessionOrSecretId, incognito);
    if (index === -1) {
      console.warn("Session not found", sessionOrSecretId, incognito);
      return;
    }
    const session = this.sessions[index];
    const tabIds = await this.getSessionTabIds(session);
    endSession(session, tabIds);
    this.removeSession(session.secretId, session.launchedInIncognito);
  }

  async endConflictingSessions(url, incognito) {
    console.log(url);
    const attributedSessions = await this.getAttributedSessions(url, incognito);
    // eslint-disable-next-line no-restricted-syntax
    for (const sessionGuid of attributedSessions) {
      const session = this.getSession(sessionGuid);
      if (session && session.launchedInIncognito === incognito) {
        this.getSessionTabIds(session, true).then((tabIds) => {
          endSession(session, tabIds);
          this.removeSession(session.secretId, session.launchedInIncognito);
        });
      }
    }
  }

  endAllSessions() {
    this.sessions.forEach((session) => {
      this.endSession(session.guid, session.launchedInIncognito);
    });
  }

  /*
   * TODO: Remove incognito from the function signature and use session guid instead
   */
  getIndex(sessionOrSecretId, incognito) {
    for (let i = 0; i < this.sessions.length; i += 1) {
      const s = this.sessions[i];
      const incognitoMatch = incognito === s.launchedInIncognito;
      const secretMatch = s.secretId === sessionOrSecretId && incognitoMatch;
      const guidMatch = s.guid === sessionOrSecretId;
      if (secretMatch || guidMatch) {
        return i;
      }
    }
    return -1;
  }
   isSessionActive() {
    return this.sessions.length > 0 ;  
  }
}

// eslint-disable-next-line import/prefer-default-export
const sessionManager = new SessionManager();

;// CONCATENATED MODULE: ./src/scripts/recording/send-video-segment.js
/* global Queue */
/* eslint-disable no-plusplus */
/* eslint-disable import/prefer-default-export */








const lastEncodedSegments = [];

/**
 * getEncodedSegmentArgs
 * @param {*} uint8array
 * @param {*} session
 * @param {*} blobInfo
 * @return {object}
 */
function send_video_segment_getEncodedSegmentArgs(uint8array, session, blobInfo) {
  const binary = getBinary(uint8array);
  const encryptedObj = encryptAES(binary, session);
  const args = {
    sessionGuid: session.launcherSessionGuid,
    // eslint-disable-next-line new-cap
    iv: toBase64String(encryptedObj.iv),
    contents: encryptedObj.text,
    ticks: utils_getCurrentTicks(),
    imageDifferential: 100,
    headersIncluded: blobInfo.headersIncluded,
  };
  lastEncodedSegments[session.launcherSessionGuid] = args;
  return args;
}

/**
 * isHeaderPresent
 * @param {*} uint8array
 * @return {*}
 */
function hasWebMHeader(uint8array) {
  const webMHeader = [0x1a, 0x45, 0xdf, 0xa3];
  const header = uint8array.slice(0, 4);
  return header.every((item, index) => item === webMHeader[index]);
}
/**
 * isHeaderSent
 * @param {*} session
 * @param {*} uint8array
 * @param {object} blobInfo
 * @return {bool}
 */
function isHeaderSent(session, uint8array, blobInfo) {
  if (!session) return true;
  if (session.headerSent) return true;
  if (!hasWebMHeader(uint8array)) {
    return false;
  }
  session.headerSent = true;
  sessionManager.updateSession(session);
  blobInfo.headersIncluded = true;
  return true;
}

/**
 * queueUnprocessed
 * @param {*} session
 * @param {*} args
 */
function queueUnprocessed(session, args) {
  if (args.headersIncluded && session.segments.length > 0) {
    const segments = [...session.segments];
    session.segments.length = 0;
    sessionManager.updateSession(session);
    for (let i = segments.length; i >= 0; i--) {
      const blob = segments[i];
      Queue.offer(() => postEncodedBlob(blob, session));
    }
  }
}

/**
 * handleError
 */
function handleError() {
  if (Queue.getFailedRequestCount() < constants.RECORDING_FAILED_RETRY_COUNT) return;
  // clearTimeout(recordingTimeOut);
  message_sendDataToTab("showError", errors_ERR.CONNECTION_LOST);
  setTimeout(() => {
    // TODO: stop all sessions
    // stopAllSessions(false);
  }, 5000);
}

/**
 * postEncodedBlob
 * @param {*} blob
 * @param {*} session
 * @return {promise}
 */
function postEncodedBlob(blob, session) {
  if (!session) {
    return Promise.resolve(true);
  }
  return new Promise((resolve, reject) => {
    new Response(blob).arrayBuffer().then((arrayBuffer) => {
      const uint8array = new Uint8Array(arrayBuffer);
      const blobInfo = { headersIncluded: false };
      if (!isHeaderSent(session, uint8array, blobInfo)) {
        // if (!session.segments) {
        //   session.segments = [];
        // }
        session.segments.push(blob);
        resolve(true);
        return;
      }
      const args = send_video_segment_getEncodedSegmentArgs(uint8array, session, blobInfo);
      lastEncodedSegments[session.launcherSessionGuid] = args;
      recording_apis
        .postEncodedSegment(args)
        .then((response) => {
          if (response.ok) {
            queueUnprocessed(session, args);
            resolve(true);
          } else {
            handleError();
            reject(response);
          }
        })
        .catch((err) => {
          console.log(err);
          handleError();
          reject(err);
        });
    });
  });
}

/**
 * onDataAvailable
 * @param {stream} blob recorded blob
 * @param {object} session
 */
function onDataAvailable(blob, session) {
  if (!blob || !session) return;
  Queue.enqueue(() => postEncodedBlob(blob, session));
}

;// CONCATENATED MODULE: ./src/scripts/recording/session-monitoring.js




const getAllWindowTabs = async (incognito) => {
  const tabs = await ext_default().tabs.query({});
  return tabs.filter(tab => tab.incognito === incognito)
};

const pruneAbandonedSessions = async () => {
  const sessions = sessionManager.getSessions();
  if (!sessions || !sessions.length) {
    return;
  }  
  // eslint-disable-next-line no-restricted-syntax
  for (const session of sessions) {
    const tabs = await getAllWindowTabs(session.launchedInIncognito);
    const attributedUrls = await sessionManager.getAttributedUrls(session, tabs);
    if (attributedUrls.length === 0) {
      if(session.hosts.includes("myapps.microsoft.com")) {
        sessionManager.clearStorageKey = true;        
      }
      sessionManager.endSession(session.guid, session.launchedInIncognito);
    }
  }
};

const countRecordedUrls = async () => {
  const sessions = sessionManager.getSessions();
  let count = 0;
  // eslint-disable-next-line no-restricted-syntax
  for (const session of sessions) {
    const tabs = await getAllWindowTabs(session.launchedInIncognito);
    const attributedUrls = await sessionManager.getAttributedUrls(session, tabs);
    count += attributedUrls.length;
  }
  return count;
};

const debouncedPruneAbandonedSessions = debounce(pruneAbandonedSessions, 1500);

// eslint-disable-next-line import/prefer-default-export
const listenToTabEvents = () => {
  ext_default().windows.onFocusChanged.addListener(() => {
    debouncedPruneAbandonedSessions();
  });

  ext_default().tabs.onActivated.addListener(() => {
    debouncedPruneAbandonedSessions();
  });

  ext_default().tabs.onRemoved.addListener(() => {
    debouncedPruneAbandonedSessions();
  });

  ext_default().tabs.onUpdated.addListener(() => {
    debouncedPruneAbandonedSessions();
  });
};

// EXTERNAL MODULE: ./src/scripts/recording/blob-conversion.js
var blob_conversion = __webpack_require__(615);
;// CONCATENATED MODULE: ./src/scripts/recording/main-recording.js
/* eslint-disable import/prefer-default-export */
/* eslint-disable implicit-arrow-linebreak */
/* eslint-disable operator-linebreak */
/* global */












// TODO: figure out why we do this
const launcherId = 3;
let currentPositions = [];
let main_recording_offscreenModule;
let hideRecordingIndicator;

loadOffscreen().then((module) => {
  main_recording_offscreenModule = module;
  if(main_recording_offscreenModule) {    
    main_recording_offscreenModule.setCallback(getActiveTabData);
   }
})  

function sendStartRecording(sessionGuid, handleVideoSegment) {
  if (!(ext_default()).offscreen && main_recording_offscreenModule) {
    main_recording_offscreenModule.startRecording(sessionGuid, handleVideoSegment);
    return;
  }

  ext_default().runtime.sendMessage({
    type: "startRecording",
    sessionGuid: sessionGuid,
  });

}

/**
 * initiateNewSession
 * @param {int} secretId
 * @param {object} evt
 */
async function initiateNewSession(secretId, evt, callback) {
  if (!secretId) return;
  const data = {
    secretId,
    launcherId,
    promptFieldValue: evt.detail.Data.sUrl || evt.detail.Data.secretUrl,
  };

  try {
    await createOffscreenDocument();
    const extendedRaw = await recording_apis.getExtendedUrls(secretId);
    const extendedResponse = gotExtendedFieldsEvent(extendedRaw, evt);
    const secretDetails = new URLSearchParams(data);
    const launcherRaw = await recording_apis.getLauncherSecret(secretDetails);
    const launcherResponse = gotLauncherSecretEvent(launcherRaw);
    const keypair = generateRSAKey(); // { publicKeyBase64Blob, privateKeyRSA }
    const symmetricRaw = await recording_apis.getSymmetricKey({
      ...launcherResponse,
      publicKeyBlob: keypair.publicKeyBase64Blob,
    });
    const symmetricResponse = gotSymmetricKeyEvent(keypair, symmetricRaw);
    const launcherArgsRaw = await recording_apis.getLauncherArguments({
      guid: launcherResponse.guid,
    });
    const secretSessionData = gotLauncherArguments(
      launcherArgsRaw,
      symmetricResponse
    );
    const secretSessionKey = secretSessionData.sessionKey;
    hideRecordingIndicator = secretSessionData.hideRecordingIndicator;
    const incognitoEnabled = evt.detail.dataJson.webLauncherRequiresIncognitoMode;
    const launchedInIncognito = evt.detail.Data.tab.incognito;
    const updateStatusInterval = updateStatus(secretSessionKey, launcherResponse.guid, launchedInIncognito);
    setSessionTimeout(secretSessionKey);
    const newSession = {
      ...launcherResponse,
      ...symmetricResponse,
      secretId,
      secretSessionKey,
      updateStatusInterval,
      launchedInIncognito: launchedInIncognito,
      incognito: incognitoEnabled,
      segments: [],
      ...extendedResponse,
    }

    sendStartRecording(newSession.guid, handleVideoSegment);

    setSessionTimeout(secretSessionKey);
    sessionManager.addSession(newSession);

    callback(evt);
  } catch (error) {
    console.log(error);
    message_sendDataToTab("showError", errors_ERR.SESSION_INIT_ERROR);
  }
}

/**
 * callback function called after gotExtendedFields are returned.
 * @param {string} result Event Arguments
 */
function gotExtendedFieldsEvent(result, evt) {
  const regEx = result.model.regexList;
  const request = evt.detail.Data;
  const domains = [];
  const hosts = [];

  if (request && request.sUrl) {
    regEx.push(request.sUrl);
  }

  if (request && request.url) {
    regEx.push(request.url);
  }

  if (request && request.secretUrl) {
    regEx.push(request.secretUrl);
  }

  if (
    request &&
    request.SSOUrls &&
    request.SSOUrls.map((s) => (0,url_helpers/* parseUrl */.Dl)(s).domain).includes(
      (0,url_helpers/* parseUrl */.Dl)(request.url).domain
    )
  ) {
    regEx.push(...request.SSOUrls);
  }

  if (request.referrer) {
    regEx.push(request.referrer);
  }
  const uniqueList = [...new Set(regEx)];
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < uniqueList.length; i++) {
    if ((0,url_helpers/* isUrl */.gU)(uniqueList[i])) {
      // domains.push(parseUrl(regEx[i]).domain);
      const { domain, host } = (0,url_helpers/* parseUrl */.Dl)(uniqueList[i]);
      domains.push(domain);
      hosts.push(host);
    }
  }

  return {
    secretUrl: request.url,
    extendedUrls: domains,
    sessionUrls: domains,
    regExList: uniqueList,
    domains,
    hosts
  };
}

/**
 * Passes token as result to pop.js
 * @param {string} resp response.
 */
function gotLauncherSecretEvent(resp) {
  const launcherSecretDetails = resp.model;
  return {
    guid: launcherSecretDetails.guid,
    sessionGuid: launcherSecretDetails.sessionGuid,
    launcherSessionGuid: launcherSecretDetails.sessionGuid,
  };
}

/**
 * gotSymmetricKeyEvent
 * @param {object} evt response.
 */
function gotSymmetricKeyEvent(keypair, resp) {
  const encSessionKey = getSymmetricKeyProperty(resp, "SessionKey");
  const encKey = getSymmetricKeyProperty(resp, "Key");
  const encIV = getSymmetricKeyProperty(resp, "IV");

  return {
    sessionKey: decryptRSA(encSessionKey, keypair.privateKeyRSA),
    key: decryptRSA(encKey, keypair.privateKeyRSA),
    iv: decryptRSA(encIV, keypair.privateKeyRSA),
  };
}

function gotLauncherArguments(resp, symmetricResponse) {
  let launcherArgs;
  try {
    const response =
      resp["soap:Envelope"]["soap:Body"].GetLauncherArgumentsResponse
        .GetLauncherArgumentsResult;
    launcherArgs = JSON.parse(response);
  } catch (e) {
    throw new Error("Error parsing Launcher Arguments Response");
  }
  const sessionObj = launcherArgs.find(
    (i) => i.Key.toLowerCase() === "sessionkey"
  );
  const sessionHideRecordingIndicator= launcherArgs.find(
    (i) => i.Key.toLowerCase() === "hiderecordingindicator"
  );
  const decryptedSessionKey = decryptAES(
    sessionObj.Value,
    symmetricResponse.key,
    symmetricResponse.iv
  );
  const decryptedHideRecordingIndicator = decryptAES(
    sessionHideRecordingIndicator.Value,
    symmetricResponse.key,
    symmetricResponse.iv
  );

  let decryptedSessionData = {
    sessionKey : decryptedSessionKey.text.split("\x00").join(""), 
    hideRecordingIndicator : decryptedHideRecordingIndicator.text.split("\x00").join(""),
  }

  return decryptedSessionData;
}

/**
 * Handle Update Status
 * @param {*} response 
 * @param {*} ssk 
 * @returns 
 */
function handleUpdateStatus(resp, guid, incognito) {
  if (!resp) return;

  let updateStatusResult;
  try {
    updateStatusResult =
      resp["soap:Envelope"]["soap:Body"].UpdateStatusResponse
        .UpdateStatusResult;
  } catch (e) {
    throw new Error("Error parsing Update Status Response");
  }
  const isTerminated = updateStatusResult.IsTerminate;
  let errorMessage = updateStatusResult.ErrorMessage

  if (isTerminated !== true) {
    return;
  }
  let session = sessionManager.getSession(guid, incognito);
  sessionManager.endSession(guid, incognito);
  if (errorMessage && session && session.secretUrl) {
    const { hostname } = (0,url_helpers/* parseUrl */.Dl)(session.secretUrl);
    errorMessage += ` All tabs for ${hostname} have been closed.`;
    setTimeout(() => {
      message_sendDataToTab('showError', errorMessage);
    }, 500);
  }
}


/**
 *
 * @param {*} secretSessionKey
 * @returns
 */
function updateStatus(secretSessionKey, guid, incognito) {
  if (!secretSessionKey) return 0;
  return setInterval(async () => {
    const args = {
      sessionKey: secretSessionKey,
    };
    const response = await recording_apis.updateStatus(args);
    handleUpdateStatus(response, guid, incognito);
    // setHeartBit(secretSessionKey);
  }, 10000);
}

async function getActiveTabData() {
  try {
    const tab = await ext_default().tabs.query({ active: true, lastFocusedWindow: true });
    const applicableSessionIds = await sessionManager.getAttributedSessions(
      tab[0].url, tab[0].incognito
    );
    if (applicableSessionIds.length === 0) {
      return { image: null, applicableSessionIds, mousePositions: [] };
    }

    const image = await ext_default().tabs.captureVisibleTab(null, { format: "png" });
    if(hideRecordingIndicator === 'False') {
      ext_default().tabs.sendMessage(tab[0].id, { method: "recording" }, { frameId: 0 });
    }
    let mousePositions = [...currentPositions];
    currentPositions.length = 0;
    return { image, applicableSessionIds, mousePositions };
  } catch (error) {
    return { image: null, applicableSessionIds: [], mousePositions: [] };
  }
}

function handleVideoSegment(request) {
  const blob = (0,blob_conversion/* dataURLtoBlob */.W)(request.data);

  const session = sessionManager.getSession(request.sessionGuid);
  onDataAvailable(blob, session);
}

ext_default().runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "getActiveTabData") {
    getActiveTabData().then((tabData) => {
      sendResponse(tabData);
    });
    return true;
  }
  if (request.type === "tabCapture") {
    currentPositions.push({ clientX: request.clientX, clientY: request.clientY });
    return;
  }
  if (request.type === "sendVideoSegment") {
    handleVideoSegment(request);
  }
  return null;
});

listenToTabEvents();

// EXTERNAL MODULE: ./src/scripts/core/tokens.js
var tokens = __webpack_require__(72);
;// CONCATENATED MODULE: ./src/scripts/utils/config.js




/**
 * Is Native Messaging Host Configured
 * @param {*} handler
 */
function isNMHConfigured(handler) {
  storage/* default */.A.get('Configurations', (items) => {
    if (items && items.Configurations) {
      if (items.Configurations.fromNativeHost
        && items.Configurations.ssUrl) {
        handler(items, true);
        return;
      }
    }
    handler(items, false);
  });
}

/**
 * resetConfiguration
 * @param {*} url
 */
function resetConfiguration(url) {
  if (!(0,url_helpers/* isUrl */.gU)(url.trim())) return;
  isNMHConfigured((items, skipSaveConfig) => {
    if (!skipSaveConfig) {
      url = url.replace(/([^:]\/)\/+/g, '$1').replace(/\/$/, '');
      url = (0,url_helpers/* addDefaultProtocol */.ZG)(url);
      if (items.Configurations.ssUrl === url) return;
      items.Configurations.ssUrl = url;
      storage/* default */.A.set({
        Configurations: items.Configurations,
      });
      ext_default().runtime.sendMessage({
        method: 'ssUrlReset',
      }, () => {
        if ((ext_default()).runtime.lastError) {
          // console.log(ext.runtime.lastError);
        }
      });
    }
  });
}

/**
 * storeSSUrl
 * @param {*} url
 * @param {*} callback
 */
function storeSSUrl(url, callback) {
  storage/* default */.A.get('SSURLs', (items) => {
    let SSURLs = [];
    if (items.SSURLs && items.SSURLs.length > 0) {
      SSURLs = items.SSURLs;
    }

    if (!SSURLs.find((x) => x && x.toLowerCase && x.toLowerCase() === url.toLowerCase())) {
      SSURLs.push(url);
      storage/* default */.A.set({
        SSURLs,
      });

      if (!callback) return;
      callback();
    }
  });
}

/**
 *
 * @param {*} config
 * @param {*} handler
 */
function setConfig(config, handler) {
  storage/* default */.A.get('Configurations', (items) => {
    if (items && items.Configurations) {
      const setByNMH = items.Configurations.fromNativeHost;
      if (setByNMH) {
        handler(items.Configurations);
        return;
      }      
    } 
    const Configurations = {
      ssUrl: config.ssUrl || items.Configurations.ssUrl || '',
      url: config.url,
      domain: config.domain || 'local',
    };
    storage/* default */.A.set({
      Configurations,
    });

    handler(Configurations, true);
    return;
  });
}

;// CONCATENATED MODULE: ./src/scripts/utils/cache.js
/* eslint-disable import/prefer-default-export */



const DEFAULT_TTL_MINS = 20;
const MAX_CACHE_SIZE = 30;
let cache_cache = {};

const cacheConfig = {
  [endpoints/* default */.A.SECRETS_BY_URL]: {
    ttlMinutes: DEFAULT_TTL_MINS,
    key: (options) => endpoints/* default */.A.SECRETS_BY_URL + options.body,
  },
};

const getFromCache = (key) => {
  const cached = cache_cache[key];
  if (cached && cached.expiry > Date.now()) {
    return cached.response;
  }
  return null;
};

const enforceMaxCacheSize = () => {
  const keys = Object.keys(cache_cache);
  if (keys.length > MAX_CACHE_SIZE) {
    const oldestKey = keys.reduce((a, b) => {
      if (cache_cache[a].expiry < cache_cache[b].expiry) return a;
      return b;
    });
    delete cache_cache[oldestKey];
  }
};

const addToCache = (key, response) => {
  cache_cache[key] = {
    response,
    expiry: Date.now() + DEFAULT_TTL_MINS * 60 * 1000,
  };

  enforceMaxCacheSize();
};

const processResponse = async (response) => {
  if (!response.status  || response.status >= 500) {
    throw new Error('Network response was not ok.');
  }
  let data = '';
  const contentType = response.headers.get('content-type');
  if (contentType && contentType.indexOf('application/json') !== -1) {
    data = await response.json();
  } else {
    data = await response.text();
  }
  return {
    ...response,
    ok: response.ok,
    status: response.status,
    data,
  };
};

const getEndpointFromUrl = (url) => {
  if (url.startsWith(common/* config */.$W.BaseURL)) {
    return url.replace(common/* config */.$W.BaseURL, '');
  }
  return url;
};

const cachedFetch = (url, options, skipCache = false) => {
  const endpoint = getEndpointFromUrl(url);
  const urlConfig = cacheConfig[endpoint];
  let key = null;
  if (urlConfig) {
    key = urlConfig.key(options);
    const cached = getFromCache(key);
    if (cached && !skipCache) {
      return Promise.resolve(cached);
    }
  }

  return fetch(url, options)
    .then(processResponse)
    .then((response) => {
      if (key) {
        addToCache(key, response);
      }
      return response;
    });
};

const removeCache = () => {
  cache_cache = {};
};
// These functions are not used in the current implementation, but might be useful in the future

// export const removeKeyFromCache = (key) => {
//   delete cache[key];
// };

// export const removeUrlFromCache = (url) => {
//   const endpoint = getEndpointFromUrl(url);
//   const keys = Object.keys(cache);
//   keys.forEach((key) => {
//     if (key.startsWith(endpoint)) {
//       delete cache[key];
//     }
//   });
// };

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








/**
 * Raise Custom Event
 * @param {string} eventName
 * @param {object} eventData
 */
function dispatchCustomEvent(callback, eventData) {
  if (typeof callback === "function") {
    callback(eventData);
  }
}

/**
 * handle soap Error
 * @param {string} message
 * @param {function} callback
 */
function service_handleError(message, callback) {
  if (typeof message !== "object") {
    sendDataToTab("showError", message);
  }
  if (callback) {
    callback(message);
  }
}

/**
 * dispatches error events to the window.
 * @param {string} error code
 * @param {string} customErrorEvent event error happened
 * @param {string} status
 * @param {string} passThroughData
 */
function triggerErrorEvents(error, customErrorEvent, status, passThroughData) {
  if (customErrorEvent) {
    dispatchCustomEvent(customErrorEvent, {
      detail: {
        request: passThroughData,
        Data: error,
        status,
      },
    });
    logger/* default */.A.logError(`Error Message: ${error.message}`);
  } else {
    switch (status) {
      case 400:
        message_sendDataToTab("badRequest", "");
        break;
      case 401:  
      case 403:
      case 503:
        message_sendDataToTab("gotUnAuthorizeError", error.message || "");
        dispatchCustomEvent("gotUnAuthorizeError", "");
        break;
      default:
        break;
    }
  }
}

/**
 * Common REST API Call
 * @param {string} URL
 * @param {string} callMethod
 * @param {object} data
 * @param {string} bearerToken
 * @param {string} contentType
 * @param {string} customEventName
 * @param {string} passThroughData
 * @param {string} otp
 * @param {string} customErrorEvent
 * @param {boolean} isRefreshToken
 */
function callAPI(
  URL,
  callMethod,
  data,
  bearerToken,
  contentType,
  customEventName,
  passThroughData,
  otp = "",
  customErrorEvent = "",
  isRefreshToken = false,
) {
  const postHeader = new Headers({
    "vault-application": "WebPasswordFiller",
    Accept: "*/*",
    "Cache-Control": "no-cache",
    Host: common/* config */.$W.HostName,
    "Accept-Encoding": "gzip, deflate",
    Connection: "keep-alive",
    "Content-Type": contentType || (constants.CONTENT && constants.CONTENT.APP_JSON),
  });
  if (otp) {
    postHeader.append("OTP", otp);
  }
  if (!isRefreshToken) {
    postHeader.append("Authorization", tokens/* oauth */.o.access_token);
  }
  const requestDetails = {
    method: callMethod,
    headers: postHeader,
    credentials: "omit",
  };

  if (callMethod.toLowerCase() !== "get") {
    requestDetails.body = data;
  }
  let catched = false;
  const skipCache = passThroughData && passThroughData.isRefreshClick === true;
  cachedFetch(common/* config */.$W.BaseURL + URL, requestDetails, skipCache).then((response) => {
    if (response.ok) {
      const protocol = ["http:/", "http://", "http:///"];
      protocol.forEach((x) => {
        common/* config */.$W.BaseURL = common/* config */.$W.BaseURL.replace(x, "http://");
      });
      const httpsProtocol = ["https:/", "https:///"];
      httpsProtocol.forEach((x) => {
        common/* config */.$W.BaseURL = common/* config */.$W.BaseURL.replace(x, "https://");
      });
      resetConfiguration(common/* config */.$W.BaseURL);
    }
      return Promise.all([response.status, response.status === 404
        ? { error: "404" } : response.data]);
  })
    .then(([status, dataJson]) => {
      let errorWithSuccessCode = false;
      if (status === 200 && Array.isArray(dataJson)
        && dataJson.length > 0 && dataJson[0].code && dataJson[0].message) {
        errorWithSuccessCode = true;
        dataJson.code = dataJson[0].code;
        dataJson.message = dataJson[0].message;
      }

      if (status === 200 && !errorWithSuccessCode) {
        if (typeof customEventName === "function") {
          customEventName({
            detail: {
              dataJson,
              Data: passThroughData,
            },
          });
        } else {
          dispatchCustomEvent(customEventName, {
            detail: {
              dataJson,
              Data: passThroughData,
            },
          });
        }

        let responseJson = JSON.parse(JSON.stringify(dataJson));

        if (responseJson.access_token) {
          responseJson.access_token = "...";
        }
        if (responseJson.refresh_token) {
          responseJson.refresh_token = "...";
        }

        if (URL.includes("/fields/password")) {
          if (responseJson) {
            responseJson = "...";
          }
        } else if (URL.includes("/api/v1/secrets/")) {
          if (responseJson.items && responseJson) {
            (0,common/* hidePassword */.cT)(responseJson.items);
          }
          if (responseJson.model && responseJson) {
            if (responseJson.model.password) {
              responseJson.model.password = "...";
            }
            (0,common/* hidePassword */.cT)(responseJson.model.items);
          }
        }
        if (responseJson.model && responseJson) {
          if (responseJson.model.password) {
            responseJson.model.password = "...";
          }
        }
        logger/* default */.A.logInfo(`API Called: ${URL} Status code: ${status} 
         \nResponse: ${JSON.stringify(responseJson, null, 5)}`);

        return Promise.resolve(dataJson);
      }
      if ((status === 403 || status === 401) && URL !== endpoints/* default */.A.OAUTH_EXPIRATION) {
        if (dataJson.errorCode !== "API_AccessDenied") {
          passThroughData = passThroughData || {};
          customErrorEvent = "tokenExpired";
          passThroughData.apicall = callAPI;
          passThroughData.args = [URL, callMethod, data, bearerToken,
            contentType, customEventName, passThroughData, otp,
            customErrorEvent, isRefreshToken];
        }
      }
      catched = true;
      triggerErrorEvents(
        dataJson,
        customErrorEvent,
        status,
        passThroughData,
      );
      dataJson.name = dataJson.name || "Error";
      return Promise.reject(dataJson);
    }).catch((err) => {
      const error = err.message || err.error || err;
      if (error.includes("certificate") || error.includes("Load failed")) {
        triggerErrorEvents(error, "gotCertificateError");
        return;
      }
      if (error.includes("Could not connect to the server.")
        || error.includes("The request timed out.")) {
        triggerErrorEvents(error, "gotRequestTimedout");
        return;
      }
      if (catched) {
        return;
      }
      triggerErrorEvents({ error: "Bad Request" }, customErrorEvent, 400);
      console.log(error);
    });
}

;// CONCATENATED MODULE: ./src/scripts/background.native.js








let Settings = {};

/**
 * getSettings()
 */
function getSettings(callback) {
  ext_default().runtime.sendNativeMessage(
    constants.NATIVE_HOST,
    { method: "getSettings" },
    (response) => {
      checkLastError(false);
      if (response && !response["Response to"]) {
        const urlCheck = response.ConfigSSUrl;
        if ((0,url_helpers/* isUrl */.gU)(urlCheck)) {
          const Configurations = {
            url: (0,url_helpers/* addDefaultProtocol */.ZG)(response.ConfigSSUrl),
            ssUrl: (0,url_helpers/* addDefaultProtocol */.ZG)(response.ConfigSSUrl),
            domain: response.ConfigDomain,
            fromNativeHost: true,
          };
          storage/* default */.A.set({
            Configurations,
          });
          common/* config */.$W.BaseURL = Configurations.ssUrl;
          common/* config */.$W.Url = Configurations.ssUrl;
        } else {
          console.log("Invalid Native host Secret Server Url ");
        }
        storage/* default */.A.get("Settings", (items) => {
          if (items && items.Settings) {
            Settings = items.Settings;
            // Settings.useSecretServerToSignOn = response['SettingUserSSLogin'];
            Settings.set_Prompt_to_save_credentials =
              response.SettingPrompToSave;
            Settings.set_show_popup_credential_available =
              response.SettingShowPopup;
            Settings.hideViewOnlyAccessFolders =
              response.SettingHideReadOnlyFolders;
            Settings.enableAutoPopulate = response.SettingEnableAutoPopulate;
            Settings.defaultPopupPosition = response.PopupDefaultPosition;
            Settings.exactMatchUrl = response.ExactMatchUrl;
            Settings.secretServerLoginWindow = response.SecretServerLoginWindow;
            Settings.defaultSessionRecordingLimit =
              response.defaultSessionRecordingLimit || constants.DEFAULT_RECORDING_LIMIT;
            Settings.maxSessionRecordingLimit =
              response.maxSessionRecordingLimit || constants.DEFAULT_RECORDING_LIMIT;
            Settings.inputThreshold = response.inputThreshold;
            Settings.fromNativeHost = true;
            Settings.matchSessionByHost = response.matchSessionByHost;
            storage/* default */.A.set({
              Settings,
            });
            getStoredToken(callback);
          }
        });
      } else {
        storage/* default */.A.get("Configurations", (items) => {
          if (typeof items.Configurations !== "undefined") {
            const { Configurations } = items;
            Configurations.fromNativeHost = false;
            storage/* default */.A.set({
              Configurations,
            });
            common/* config */.$W.BaseURL = Configurations.ssUrl;
            common/* config */.$W.Url = Configurations.url;
            callback(null);
          }
        });
        storage/* default */.A.get("Settings", (items) => {
          if (typeof items.Settings !== "undefined") {
            const { Settings } = items;
            Settings.defaultSessionRecordingLimit = constants.DEFAULT_RECORDING_LIMIT;
            Settings.maxSessionRecordingLimit =
              items.Settings.maxSessionRecordingLimit ||
              constants.DEFAULT_RECORDING_LIMIT;
            Settings.fromNativeHost = false;
            storage/* default */.A.set({
              Settings,
            });
          }
        });
      }
    },
  );
}

/**
 * set default values of settings tab for safari browser
 */
function setDefaultSettings() {
  storage/* default */.A.get("Settings", (items) => {
    if (!items || (items && !items.length && !items.Settings)) {
      Settings = {
        useSecretServerToSignOn: false,
        set_Prompt_to_save_credentials: true,
        set_show_popup_credential_available: true,
        hideViewOnlyAccessFolders: true,
        enableAutoPopulate: true,
        defaultPopupPosition: true,
        exactMatchUrl: false,
        secretServerLoginWindow: true,
        defaultSessionRecordingLimit: constants.DEFAULT_RECORDING_LIMIT,
        maxSessionRecordingLimit: constants.DEFAULT_RECORDING_LIMIT,
        matchSessionByHost: true,
      };
      storage/* default */.A.set({
        Settings,
      });
    }
  });
}

/**
 * getStoredToken
 *  get stored token from native host
 */
function getStoredToken(callback) {
  ext_default().runtime.sendNativeMessage(
    constants.NATIVE_HOST,
    { method: "getToken" },
    (response) => {
      checkLastError(false);
      if (response && response.access_token) {
        if (!response.ssUrl || response.url !== common/* config */.$W.Url) {
          removeToken();
          response = null;
          return;
        }
        common/* config */.$W.BaseURL = response.ssUrl;
        storage/* default */.A.get("Configurations", (items) => {
          const { Configurations } = items;
          Configurations.ssUrl = response.ssUrl;
          storage/* default */.A.set({
            Configurations,
          });
          callback(response);
        });
      }
    },
  );
}

/**
 * removeToken()
 */
function removeToken() {
  ext_default().runtime.sendNativeMessage(
    constants.NATIVE_HOST,
    { method: "removeToken" },
    (response) => {
      checkLastError(false);
    },
  );
}

/**
 * checkExcluded
 * @param {*} tabUrl
 * @param {*} sendResponse
 */
function checkExcluded(tabUrl, sendResponse) {
  tabUrl = tabUrl.split("?")[0];
  ext_default().runtime.sendNativeMessage(
    constants.NATIVE_HOST,
    { method: "checkExcluded", url: tabUrl },
    (response) => {
      checkLastError(false);
      if (response) {
        sendResponse({ excluded: response.excluded });
      } else {
        sendResponse({ excluded: false });
      }
    },
  );
}

ext_default().runtime.onInstalled.addListener(() => {
  setDefaultSettings();
});

/**
 * store Token to native host
 * @param {object} token
 */
function storeToken(token) {
  const tokenString = JSON.stringify(token);
  const chunks = (0,common/* chunkSubstr */.ld)(tokenString, 500);
  const guid = Math.floor(Math.random() * 0x10000).toString(16);
  const port = ext_default().runtime.connectNative(constants.NATIVE_HOST);
  port.onDisconnect.addListener(() => {
    checkLastError(false);
  });

  port.onMessage.addListener((message) => {
    checkLastError();
    if (message && !isNaN(message.received)) {
      const chunk = message.received + 1;
      if (chunks.length > chunk) {
        port.postMessage({
          method: "keepToken",
          chunkGroupId: guid,
          chunk,
          totalChunks: chunks.length,
          token: chunks[chunk],
        });
      }
    }
  });

  if (chunks && chunks.length > 0) {
    port.postMessage({
      method: "keepToken",
      chunkGroupId: guid,
      chunk: 0,
      totalChunks: chunks.length,
      token: chunks[0],
    });
  }
}

async function getUserAndTenant() {
  const promise = new Promise((resolve) => {
    storage/* default */.A.get(["Configurations", 'userId'], (items) => {
      if (items && items.Configurations && items.userId) {
        const { Configurations } = items;
        const tenantUrl = Configurations.url;
        const userId = items.userId;
        resolve({ userId, tenantUrl });
      } else {
        resolve({ userId: null, tenantUrl: null });
      }
    });
  });
  return promise;
}

function normalize(userIdOrUrl) {
  let returnValue = `${userIdOrUrl}`;
  returnValue = returnValue.replace(/https?:\/\//, "");
  returnValue = returnValue.replace(/\/$/, "");
  return returnValue;
}

async function launchSecretFromCm(
  launchSecretFunction,
  secretId,
  launchUrl,
  userId,
  tenantUrl,
  token,
) {
  if (!secretId) return { error: "Secret Id is required" };
  if (!launchUrl) return { error: "Launch URL is required" };
  if (!userId) return { error: "User Id is required" };
  if (!tenantUrl) return { error: "Tenant URL is required" };
  if (!token) return { error: "Token is required" };

  const userAndTenent = await getUserAndTenant();
  const { userId: currentUserId, tenantUrl: currentTenantUrl } = userAndTenent;
  if (normalize(userId) !== normalize(currentUserId)) {
    return { error: `Provided userId '${normalize(userId)}' does not match current userId '${normalize(currentUserId)}'` };
  }
  if (normalize(tenantUrl) !== normalize(currentTenantUrl)) {
    return { error: `Provided tenantUrl '${normalize(tenantUrl)}' does not match current tenantUrl '${normalize(currentTenantUrl)}'` };
  }

  const request = {
    appPath: tenantUrl,
    newUrl: launchUrl,
    secretId,
    wpfLauncherClicked: false,
  };
  const sender = {
    tab: {},
    frameId: 0,
    id: "cm-messaging-host",
    url: launchUrl,
    referrer: launchUrl,
    secretUrl: launchUrl,
    origin: launchUrl,
    tabId: 0,
  };
  // just remove the secret from the cache for now since there is a bug when it gets cached
  const before = await cache/* lastFetchedSecretsProvider */.iF.findBySecretId(secretId)
  await cache/* lastFetchedSecretsProvider */.iF.removeBySecretId(secretId);
  const after = await cache/* lastFetchedSecretsProvider */.iF.findBySecretId(secretId)
  launchSecretFunction(request, sender);
  return { success: true };
}

function listenForCmMessages(launchSecretFunction) {
  try {
    const cmConnection = ext_default().runtime.connectNative(constants.CM_NATIVE_HOST);
    cmConnection.onDisconnect.addListener(() => {
      // TODO: handle disconnection
    });

    cmConnection.onMessage.addListener(async (message) => {
      if (message.type === "LaunchSecret") {
        const { secretId, launchUrl, userId, tenantUrl, token } = message.body;
        const response = await launchSecretFromCm(
          launchSecretFunction,
          secretId,
          launchUrl,
          userId,
          tenantUrl,
          token,
        );
        cmConnection.postMessage({
          type: "LaunchSecretResponse",
          body: response,
        });
      }
    });
  } catch (e) {
    // silent error because NMH wont be installed in many cases
  }
}

;// CONCATENATED MODULE: ./src/scripts/helpers/api-support.js
/* eslint-disable max-len */

/**
 * checkMacSupport
 * @param {*} userAgent
 * @return {boolean}
 */
function macVersionSupport(userAgent) {
  if (userAgent.includes('Safari/')
        && !userAgent.includes('Chrome/')
        && !userAgent.includes('Edg/')) {
    // Check future versions of safari to see if this code is still valid.
    if (userAgent.includes('Version/')) {
      const versionString = userAgent.substring(
        userAgent.indexOf('Version'),
        userAgent.indexOf('Version') + 12,
      );
      const browserVersion = versionString.slice(8);
      if (browserVersion) {
        const browserNumber = parseInt(browserVersion, 10);
        if (browserNumber >= 15.0) {
          return false;
        }
      }
    }
  }
  return true;
}

/**
 * isMediaRecorderSupported
 * @return {bool}
 */
function isMediaRecorderSupported() {
  // TODO: update
  return true;
  return !(typeof MediaRecorder === 'undefined'
  || (MediaRecorder && !MediaRecorder.isTypeSupported));
}

;// CONCATENATED MODULE: ./src/scripts/apis/platform-apis.js






const platform = {
  getPlatformCheck: () => (0,promise.httpRequest)(
    common/* config */.$W.Url + endpoints/* default */.A.CHECK_PLATFORM,
    (0,promise.requestParams)('GET'),
  ),
  getAllVaults: () => {
    const reqParams = (0,promise.requestParams)('GET');
    reqParams.headers.set('Authorization', tokens/* oauth */.o.access_token);
    return (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.getAllVaults,
      reqParams,
    );
  },
  getPlatformRefreshToken: (data) => {
    const reqParams = (0,promise.requestParams)('POST', data, constants.CONTENT.APP_URL_ENCODED);
    reqParams.headers.set('Authorization', tokens/* oauth */.o.access_token);
    return (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.identity_token,
      reqParams,
    );
  },

  getPlatformToken: (data) => {
    const dataJson = new URLSearchParams(data);
    const reqParams = (0,promise.requestParams)('POST', dataJson, constants.CONTENT.APP_URL_ENCODED);
    return (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.identity_token,
      reqParams,
    );
  },
  getDeviceCode: () => {
    const formData = new FormData();
    formData.append('client_id', constants.CLIENT_ID);
    const reqParams = { method: 'POST', redirect: 'follow', body: formData };
    return (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.deviceCode,
      reqParams,
    );
  },
  getMfaDeviceCode: (acrValue, suToken) => {
    const formData = {
      client_id: constants.CLIENT_ID,
      acr_values: acrValue,
      su_token: suToken,
    };
    const dataJson = new URLSearchParams(formData);
    const reqParams = (0,promise.requestParams)('POST', dataJson, constants.CONTENT.APP_URL_ENCODED);
    reqParams.headers.set('Authorization', tokens/* oauth */.o.access_token);
    return (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.deviceCode,
      reqParams,
    );
  },  
  logoutPlatform: () => {
    const reqParams = (0,promise.requestParams)();
    reqParams.headers.set('Authorization', tokens/* oauth */.o.access_token);
    (0,promise.httpRequest)(
      common/* config */.$W.Url + endpoints/* default */.A.logoutPlatform,
      reqParams,
    )
  },
};

/* harmony default export */ const platform_apis = (platform);

;// CONCATENATED MODULE: ./src/scripts/helpers/generate-password.js
/* eslint-disable no-use-before-define */

/**
 * calls the API to Generate password oly.
 * generates a password for the right click menu option and
 * allows content script to copy to clipboard
 * @return {string}
 */
function generatePasswordLocally() {
  const specials = '!@#$%^&*()_+{}:"<>?\|[];\',./`~';
  const lowercase = 'abcdefghijklmnopqrstuvwxyz';
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numbers = '0123456789';
  const all = specials + lowercase + uppercase + numbers;
  let tmpPwd = '';
  tmpPwd += pick(1, 1, specials);
  tmpPwd += pick(1, 1, lowercase);
  tmpPwd += pick(1, 1, uppercase);
  tmpPwd += pick(3, 10, all);
  tmpPwd = shuffle(tmpPwd);
  return tmpPwd;
}

/**
     * picks of random chars for a password
     * @param {int} min min value
     * @param {int} max max value
     * @param {string} chars string to pick from
     * @return {string} the chars
     */
function pick(min, max, chars) {
  let newValue = min + crypto.getRandomValues(new Uint8Array(1))[0] % (max - min + 1);
  for (let i = 0; i < max; i++) {
    const randomIndex = crypto.getRandomValues(new Uint8Array(1))[0] % chars.length;
    newValue += chars.charAt(randomIndex);
  }
  return newValue;
}

/**
     * picks of random chars for a password
     *  @param {string} chars string to pick from
     * @return {array} the chars
     */
function shuffle(chars) {
  const array = chars.split('');
  let tmp; let current; let top = array.length;
  if (top) {
    while (--top) {
      current = crypto.getRandomValues(new Uint8Array(1))[0] % (top + 1);
      tmp = array[current];
      array[current] = array[top];
      array[top] = tmp;
    }
  }
  return array.join('');
}

;// CONCATENATED MODULE: ./src/scripts/helpers/image-loader.js
const { ICONS } = __webpack_require__(482);

/**
 * imageLoader
 * @param {*} urlList
 * @param {*} callback
 * @returns
 */
function imageLoader(urlList, callback) {
  if (urlList.length === 0) {
    callback.call(undefined, { error: [ICONS.GLOBE] });
    return;
  }
  let allLoaded = 0;
  const log = {
    success: [],
    error: [],
  };
  const verifier = function () {
    allLoaded++;
    if (allLoaded === urlList.length || log.success.length > 0) {
      callback.call(undefined, log);
    }
  };
  for (let index = 0; index < urlList.length; index++) {
    // Prevent that index has the same value
    // by wrapping it inside an anonymous fn
    if (log.success.length > 0) {
      break;
    }
    (function (i) {
      // Image path provided in the array e.g image.png
      const imgSource = urlList[i];
      const img = new Image();
      img.addEventListener('load', () => {
        log.success.push(imgSource);
        verifier();
      }, false);
      img.addEventListener('error', () => {
        log.error.push(imgSource);
        verifier();
      }, false);
      try {
        img.src = imgSource;
      } catch (e) {
        // do nothing
      }
    }(index));
  }
}

/* harmony default export */ const image_loader = (imageLoader);

;// CONCATENATED MODULE: ./src/scripts/handlers/state-handler.js



const { saveComments, checkoutSecret } = __webpack_require__(128);

function sendError(message, sender) {
  if (sender && sender.tab) {
    message_sendDataToTab('showError', message);
  } else {
    sendDataToPop('showError', message);
  }
}

const stateError = {
  commentSaveError(err, sender) {
    if (err && err.modelState) {
      sendError(err.modelState.ticketNumber[0], sender);
      return;
    }
    if (err && err.message) {
      sendError(err.message, sender);
      return;
    }
    sendError(errors_ERR.COMMENT_SAVE_FAILED, sender);
  },
  checkoutError(err, sender) {
    sendError(errors_ERR.CHECKOUT_FAILED, sender);
  },
};

const stateHandler = {

  addComment(request, sender, sendResponse) {
    if (!(request && request.data && request.secretId)) return;
    const jsonData = JSON.stringify(request.data);
    saveComments(request.secretId, jsonData)
      .then(sendResponse).catch((err) => stateError.commentSaveError(err, sender));
  },

  checkoutSecret(request, sender, sendResponse) {
    if (!(request && request.data && request.secretId)) return;
    const jsonData = JSON.stringify(request.data);
    checkoutSecret(request.secretId, jsonData)
      .then(sendResponse).catch((err) => stateError.checkoutError(err, sender));
  },

  commentAndCheckoutSecret(request, sender, sendResponse) {
    if (!(request && request.data && request.secretId)) return;
    const jsonData = JSON.stringify(request.data);
    const promises = [saveComments(request.secretId, jsonData),
      checkoutSecret(request.secretId)];

    Promise.all(promises).then((results) => {
      sendResponse(results);
    }).catch((err) => stateError.commentSaveError(err, sender));
  },
};

/* harmony default export */ const state_handler = (stateHandler);

// EXTERNAL MODULE: ./src/scripts/handlers/user-permissions.js + 1 modules
var user_permissions = __webpack_require__(973);
// EXTERNAL MODULE: ./src/scripts/handlers/current-context.js
var current_context = __webpack_require__(208);
;// CONCATENATED MODULE: ./src/scripts/handlers/cached-secrets.js



let lastFetchedSecrets = [];

const secretType = {
  lastFetched: 'lastFetchedSecrets',
  recent: 'recentSecrets',
  favourite: 'favoriteSecrets',
};

const cachedSecrets = {

  loadSecrets(callback) {
    const key = current_context/* default */.A.getContextKey(secretType.lastFetched);
    storage/* default */.A.get(key, (items) => {
      if (items[key]) {
        lastFetchedSecrets = items[key];
        callback(lastFetchedSecrets);
        return;
      }
      callback([]);
    });
  },
  clear() {
    storage/* default */.A.set(current_context/* default */.A.getCurrentContext(secretType.lastFetched, []));
  },
  setLastFetched(result) {
    storage/* default */.A.set(current_context/* default */.A.getCurrentContext(secretType.lastFetched, result));
  },
  secretById(request, callback) {
    const { secretId } = request;
    this.loadSecrets((cached) => {
      const item = cached.find((s) => s.Secrets && s.Secrets.find((k) => k.id === secretId));
      if (item) {
        const secret = item.Secrets.find((k) => k.id === secretId);
        if (callback) callback(secret);
        return;
      }
      if (callback) callback(null);
    });
  },
  getAllSecrets(callback) {
    this.loadSecrets(callback);
  },
  getAllUrls(callback) {
    this.loadSecrets((secrets) => {
      const urls = [];
      for (let j = 0; j < secrets.length; j++) {
        if (!urls.find((x) => x.includes(secrets[j].host))) {
          urls.push(secrets[j].url);
          callback(urls);
        }
      }
    });
  },

  searchSecrets(showFavorites, searchText, callback) {
    const filteredSecrets = [];
    this.loadSecrets((cached) => {
      for (let t = 0; t < cached.length; t++) {
        for (let q = 0; q < cached[t].Secrets.length; q++) {
          const secret = cached[t].Secrets[q];
          const { favIconUrl } = cached[t];
          if (showFavorites && !secret.isFavoriteSecret) {
            continue;
          }

          if (searchText && !secret.name.toLowerCase().includes(searchText)) {
            continue;
          }

          if (filteredSecrets.find((s) => s.id === secret.id)) {
            continue;
          }
          secret.favIconUrl = favIconUrl;
          filteredSecrets.push(secret);
        }
      }
      callback({ secrets: filteredSecrets, append: false });
    });
  },
  getCurrentKeyResult(showFavorites, handler) {
    const context = showFavorites ? secretType.favourite : secretType.recent;
    const key = current_context/* default */.A.getContextKey(context);
    storage/* default */.A.get(key, (items) => {
      const result = items[key];
      handler(result);
    });
  },

  setRecent(result) {
    storage/* default */.A.set(current_context/* default */.A.getCurrentContext(
      secretType.recent,
      result,
    ));
  },
  setFavourites(result) {
    storage/* default */.A.set(current_context/* default */.A.getCurrentContext(
      secretType.favourite,
      result,
    ));
  },
};

/* harmony default export */ const cached_secrets = (cachedSecrets);

;// CONCATENATED MODULE: ./src/scripts/handlers/template-provider.js






const templateProvider = {

  getWebTemplates(callback) {
    if (current_context/* default */.A.getSSVersion() !== constants.UNKNOWN_VERSION && current_context/* default */.A.getSSVersion() < '11.5' && user_permissions/* default */.A.isAddPermission()) {
      this.requestWebTemplates(callback);
    } else {
      this.versionCheck(callback);
    }
  },
  requestWebTemplates(callback) {
    (0,promise.getWebSecretTemplates)()
      .then((templates) => this.gotWebTemplates(templates, callback))
      .catch((err) => {
        if (err.status === 404) {
          callback(true);
        }
      });
  },
  async getWebTemplateFilters() {   
    if((current_context/* default */.A.getSSVersion() == constants.UNKNOWN_VERSION) || current_context/* default */.A.getSSVersion() >= '11.6' || current_context/* default */.A.getCloud()) {
      const filters = await this.getWebTemplateFiltersByCommaSeparated();
      return filters;
    }
    return this.getWebTemplateFiltersByQueryString();
  },
  async getWebTemplateFiltersByQueryString() {
    const URLTemplates = await cache/* urlTemplatesProvider */.El.get();
    if (!URLTemplates || URLTemplates.length === 0) return '';
    const filterArray = [];
    URLTemplates.forEach((item, i) => {
      filterArray.push(`filter.secretTemplateIds[${i}]=${item.id}`);
    });
    return filterArray.join('&');
  },
  async getWebTemplateFiltersByCommaSeparated() {
    const URLTemplates = await cache/* urlTemplatesProvider */.El.get();
    if (!URLTemplates || URLTemplates.length === 0) return '';
    const filterArray = [];
    const secretTemplateIds = [];
    URLTemplates.forEach((item) => {
      filterArray.push(item.id);
    });
    const secretTemplateIdsCombined = filterArray.join(',');
    secretTemplateIds.push(`&filter.SecretTemplateIdsCombined=${secretTemplateIdsCombined}`);
    return secretTemplateIds;
  },
  gotWebTemplates(result, callback) {
    if (!result) return;

    if (result.model) {
      cache/* urlTemplatesProvider */.El.set(result.model);
      if (callback) callback(false);
      return;
    }

    if (result.filter) {
      if ('onlyIncludeTemplatesWithUrl' in result.filter) {
        cache/* urlTemplatesProvider */.El.set(result.records);
        if (callback) callback(false);
        return;
      }
      if (user_permissions/* default */.A.isAddPermission()) {
        this.requestWebTemplates(callback);
        return;
      }
    }
    if (callback) callback(true);
  },
  async removeNonWebSecrets(result) {
    if (!result || !result.records) return;
    const URLTemplates = await cache/* urlTemplatesProvider */.El.get();
    if (!URLTemplates || URLTemplates.length === 0) return;
    const templateIds = URLTemplates.map((t) => t.id);
    let i = result.records.length;
    while (i--) {
      if (!templateIds.includes(result.records[i].secretTemplateId)) {
        result.records.splice(i, 1);
      }
    }
  },
  versionCheck(callback) {
    if (current_context/* default */.A.getSSVersion() !== constants.UNKNOWN_VERSION && current_context/* default */.A.getSSVersion() < '11.5') {
      if (callback) callback(true);
      return;
    }

    (0,promise.getTemplateList)()
      .then((templates) => templateProvider.gotWebTemplates(templates, callback))
      .catch((err) => {
        if (err.status === 404 && user_permissions/* default */.A.isAddPermission()) {
          this.requestWebTemplates(callback);
        } else {
          callback(true);
        }
      });
  },
};

/* harmony default export */ const template_provider = (templateProvider);

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







let ssV2NotSupported = false;
let idsCombinedNotSupported = false; // new filter PARM in api
let favSecretIds = [];

const oldWay = {
  searchSecrets(request, callback) {
    cached_secrets.searchSecrets(request.showFavorites, request.searchText, callback);
  },
  pageResult(request, callback) {
  },
  launchSecret(request, callback) {
    cached_secrets.secretById(request, callback);
  },

};

const newWay = {
  refreshSecrets(request, callback) {
    template_provider.getWebTemplates((isOldWay) => {
      if (!isOldWay) {
        this.searchSecrets(request, callback);
      }
    });
  },
  async searchSecrets(request, callback, showAllTemplates = false) {
    if (!request) return;
    if (request.showFavorites) {
      (0,promise.getFavoriteSecrets)(await this.getFavoriteFilter(
        request.searchText,
        request.skip,
        request.take,
        showAllTemplates,
      ), ssV2NotSupported).then((resp) => this.enableIsFavorite(resp, callback))
        .catch((e) => {
          if (e.status === 404) {
            if (!ssV2NotSupported) {
              ssV2NotSupported = true;
              this.searchSecrets(request, callback);
            } else {            
              this.searchSecrets(request, callback, true);
            }
          }
        });
      return;
    }

    const requests = [(0,promise.getRecentSecrets)(await this.getRecentFilter(
      request.searchText,
      request.skip,
      request.take,
      showAllTemplates,
    ), ssV2NotSupported)];
    if (!request.searchText) {
      requests.push((0,promise.getAllFavoriteSecrets)());
    }
    Promise.all(requests)
      .then((results) => {
        if (!results || !results.length) return;
        if (!('secretTemplateIdsCombined' in results[0].filter) && !idsCombinedNotSupported) {
          idsCombinedNotSupported = true;
          this.searchSecrets(request, callback);
        }
        this.cacheFavorites(results[1]);
        this.setRecentAsFavourite(results[0], callback);
      }).catch((e) => {
        if (e.status === 404) {
          if (!ssV2NotSupported) {
            ssV2NotSupported = true;
            this.searchSecrets(request, callback);
          } else {            
            this.searchSecrets(request, callback, true);
          }
        } else { 
          sendDataToPop('showError', errors_ERR.FETCHING_SECRETS_FAILED); 
        }
      });
  },
  handleError() {

  },
  gotRecentSecret(result) {
    cached_secrets.setRecent(result);
  },

  gotFavoritesSecret(result) {
    cached_secrets.setFavourites(result);
  },

  async getRecentFilter(searchText, skip, take, showAllTemplates = false) {
    if (searchText) {
      searchText = `&filter.searchText=${searchText}`;
    } else {
      searchText = '';
    }
    if(showAllTemplates) {
      return endpoints/* default */.A.recentQueryString(skip, take)  + searchText;
    }
    if (idsCombinedNotSupported) {
      const result = await template_provider.getWebTemplateFiltersByQueryString();
      return endpoints/* default */.A.recentQueryString(skip, take) + result
        + searchText;
    } 
    const result1 = await template_provider.getWebTemplateFilters();
      return endpoints/* default */.A.recentQueryString(skip, take) + result1
        + searchText;
    
  },

  async getFavoriteFilter(searchText, skip, take, showAllTemplates = false) {
    if (searchText) {
      searchText = `&filter.searchText=${searchText}`;
    } else {
      searchText = '';
    }
    if(showAllTemplates) {
      return endpoints/* default */.A.favouriteQueryString(skip, take)  + searchText;
    }
    if (idsCombinedNotSupported) {
      const result = await template_provider.getWebTemplateFiltersByQueryString();
      return endpoints/* default */.A.favouriteQueryString(skip, take) + result
        + searchText;
    } 
    const result1 = await template_provider.getWebTemplateFilters();
      return endpoints/* default */.A.favouriteQueryString(skip, take) + result1
        + searchText;
    
  },

  cacheFavorites(result) {
    if (!result) return;
    favSecretIds.length = 0;
    favSecretIds = result.map((s) => s.id);
  },

  async enableIsFavorite(result, callback) {
    if (!result || !result.records) return;
    await template_provider.removeNonWebSecrets(result);
    result.records.forEach((s) => {
      s.isFavoriteSecret = true;
    });
    this.gotFavoritesSecret(result);
    if (!callback) return;
    callback({ secrets: result.records, append: result.skip > 0 });
  },

  async setRecentAsFavourite(result, callback) {
    if (!result || !result.records) return;
    await template_provider.removeNonWebSecrets(result);
    result.records.forEach((s) => {
      if (favSecretIds.includes(s.id)) {
        s.isFavoriteSecret = true;
      }
    });
    this.gotRecentSecret(result);
    if (!callback) return;

    callback({ secrets: result.records, append: result.skip > 0 });
  },

  gotWebSecretTemplates(result, onLogin = false, onFavoriteTab = false) {
    if (onLogin) return;
    let requests = [];
    if (onFavoriteTab) {
      requests = [(0,promise.getFavoriteSecrets)(this.getFavoriteFilter(), ssV2NotSupported)];
    } else {
      requests = [(0,promise.getAllFavoriteSecrets)(),
      (0,promise.getRecentSecrets)(this.getRecentFilter(), ssV2NotSupported)];
    }

    Promise.all(requests)
      .then((results) => {
        if (!results || !results.length) return;
        if (!('secretTemplateIdsCombined' in results[0].filter) && !idsCombinedNotSupported) {
          idsCombinedNotSupported = true;
          this.gotWebSecretTemplates(result);
        }
        if (onFavoriteTab && results[0]) {
          this.enableIsFavorite(results[0]);
        } else {
          this.cacheFavorites(results[0]);
          if (!results[1]) return;
          this.setRecentAsFavourite(results[1]);
        }
      })
      .catch((e) => {
        if (e.includes('404')) {
          ssV2NotSupported = true;
          this.gotWebSecretTemplates(result);
        } else if (e.status === 404) {
          ssV2NotSupported = true;
          this.gotWebSecretTemplates(result);
        }
      });
  },

  pageResult(request, callback) {
    cached_secrets.getCurrentKeyResult(request.showFavorites, (result) => {
      if (result && this.hasMoreSecrets(result.skip, result.take, result.total)) {
        request.skip = result.skip + result.take;
        this.searchSecrets(request, callback);
      }
    });
  },

  hasMoreSecrets(skip, take, total) {
    if (skip + take > total) return false;
    return true;
  },
  launchSecret(request, callback) {
    (0,promise.getSecretlauncherURL)(request.secretId).then((result) => this.gotlaunchSecret(result, callback))
      .catch(this.handleError);
  },
  gotlaunchSecret(result, callback) {
    if (!result) return;
    if (result.restrictedHosts) {
      result.secretUrl = result.restrictedHosts[0].value;
    }
    if (callback) callback(result);
  },
  resetIdsCombinedNotSupported(){
    idsCombinedNotSupported = false
  },
};

;// CONCATENATED MODULE: ./src/scripts/utils/remove-cookie.js



const removeCookies = {
    removeCookie(tabUrl, isIncognito) {
        const cookieUrl = tabUrl.origin; // Use the origin of the URL to match cookies
        const removalOptions = (0,common/* isFirefox */.gm)()
            ? { hostnames: [tabUrl.host, tabUrl.domain] }
            : { origins: [cookieUrl] };

        const handleCookiesRemoval = (cookies) => {
            cookies.forEach((cookie) => {
                const removeOptions = isIncognito ? { name: cookie.name, url: cookieUrl, storeId: '1' }
                    : { url: cookieUrl, name: cookie.name, path: cookie.path, domain: cookie.domain };
                ext_default().cookies.remove(removeOptions)
                    .then(() => console.log("Site data cleared successfully."))
                    .catch(err => console.error("Error removing cookie:", err));
            });
        };

        if ((0,common/* isSafari */.nr)()) {
            ext_default().cookies.getAll({ url: cookieUrl }, handleCookiesRemoval);
        } else if (isIncognito && !(0,common/* isFirefox */.gm)()) {
            ext_default().cookies.getAll({ storeId: '1', url: cookieUrl }, handleCookiesRemoval);
        } else {
            // Remove cookies using browsingData for Firefox and Chrome
            ext_default().browsingData.remove(removalOptions, {
                cookies: true
            }, () => {
                console.log("Site data cleared successfully.");
            });
        }
    }
}
/* harmony default export */ const remove_cookie = (removeCookies);
;// CONCATENATED MODULE: ./src/scripts/background.js
/* eslint-disable no-plusplus */
/* eslint-disable no-use-before-define */



// import * as recorder from "./background.recording";




























// No change
let MFALoginWindowId = 0;
let newWindowHeight = 0;
let newWindowWidth = 0;
let toolBarIconStateChecked = false;
let isLoggedIn = false;
let loggedInUserId = 0;
let messageDisplayed = false;
let provider = oldWay;
let isConfigUrl = false;

const twoFactorUrl = "/login.aspx?preventautologin=true";
const { userAgent } = navigator;

changeToolbarIcon();
getSettings(restoreSession);

async function restoreSession(storedToken) {
  if (storedToken && storedToken.access_token) {
    gotTokenEvent({ detail: { dataJson: storedToken }, fromNativeHost:  true});
    return;
  }
  const token = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.token);
  if (token && token.access_token) {
    tokens/* allTokens */.y.restore();
    gotTokenEvent({ detail: { dataJson:  { ...token, isRestore: true }  } });
  }
}

ext_default().runtime.onStartup.addListener(() => {
  cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.webLauncherData);
  ext_default().alarms.clearAll(() => {
    console.log("All alarms cleared on startup");
    logger/* default */.A.logInfo("All alarms cleared on startup");
  });
});

ext_default().runtime.onInstalled.addListener((details) => {
  if(details.reason === "install" && (0,common/* isFirefox */.gm)()) {
    ext_default().runtime.reload();
  }
  if (details.reason === "install" || details.reason === "update") {
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.webLauncherData);
    reloadTabs();
  }
});

listenForCmMessages(launchSecret);

// Reload tab only if tabId is found in cookies
function reloadTabs() {
  ext_default().tabs.query({ url: "https://*/*" }, (tabs) => {
    // Reload tabs based on 'ihawu' cookie
    ext_default().cookies.getAll(
      { name: "ihawu" },
      (cookies) => {
        for (let i = 0; i < cookies.length; i++) {
          for (let j = 0; j < tabs.length; j++) {
            if (tabs[j].url.includes(cookies[i].domain)) {
              ext_default().tabs.reload(tabs[j].id);
            }
          }
        }
      },
    );
    ext_default().cookies.getAll(
      { name: "sessdata" },
      (cookies) => {
        for (let i = 0; i < cookies.length; i++) {
          for (let j = 0; j < tabs.length; j++) {
            if (tabs[j].url.includes(cookies[i].domain)) {
              ext_default().tabs.reload(tabs[j].id);
            }
          }
        }
      },
    );
  });
}


/**
* checkIfSecretServer
* @param {*} sender
* @param {*} sendResponse
*/
async function checkIfSecretServer(sender, sendResponse) {
  const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
  if (!(sender && sender.tab)) return;
  const { hostname } = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url);
  ext_default().cookies.getAllCookieStores((stores) => {
    stores.forEach((p) => {
      if (p.tabIds.includes(sender.tab.id)) {
        ext_default().cookies.getAll(
          { name: "Thycotic_Embedded", storeId: p.id },
          (cookies) => {
            for (let i = 0; i < cookies.length; i++) {
              if (hostname.toLowerCase() === cookies[i].domain.toLowerCase()) {
                sendResponse({
                  isSecretServer: true,
                  serverType,
                  url: common/* config */.$W.Url,
                });
              }
            }
            sendResponse({
              isSecretServer: false,
              serverType,
              url: common/* config */.$W.Url,
            });
          },
        );
      }
    });
  });
}

/**
* checkIfPlatformServer
* @param {*} sender
* @param {*} sendResponse
*/
async function checkIfPlatformServer(sender, sendResponse) {
  if (sender.tab && sender.tab.url) {
    const { origin } = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url);
    const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
    if (origin.match(constants.PLATFORM_DOMAIN1) || origin.match(constants.PLATFORM_DOMAIN2)) {
      sendResponse({ isPlatform: true, serverType, url: common/* config */.$W.Url });
    }
    sendResponse({ isPlatform: false, serverType, url: common/* config */.$W.Url });
  }
}

/**
* checkIfPlatformServer
* @param {*} sender
* @param {*} sendResponse
*/
async function otpOnNextPage(sender, sendResponse) {
  const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
  if (twoStepSecret && twoStepSecret.secretId) {
    sendResponse({ secretId: twoStepSecret.secretId });
  }
  cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
}

/**
* * Set secret server version.
* @param {*} evt
*/
function gotVersion(result) {
  let ssVersion = constants.UNKNOWN_VERSION;
  try {
    if (result && result.model && result.model.version) {
      ssVersion = result.model.version;
    } else {
      ssVersion = constants.UNKNOWN_VERSION;
    }
    current_context/* default */.A.setSSVersion(ssVersion);
    (0,promise.getUserPermissions)()
      .then((permissionResult) => gotUserPermission(permissionResult))
      .catch(() => {
        tokenExpired();
      });
  } catch (err) {
    ssVersion = constants.UNKNOWN_VERSION;
  }
  logger/* default */.A.logInfo(`ssVersion: ${ssVersion}`);
}

/**
* gotMetadata
* @param {object} evt
*/
async function gotMetadata(evt) {
  if (evt.detail && evt.detail.dataJson) {
    const lastFetchedSecrets = await cache/* lastFetchedSecretsProvider */.iF.get();
    const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
    (0,promise.getSecretState)(evt.detail.Data.sender.secretId).then(async (result) => {
      if (result.actions) {
        evt.detail.Data.sender.isGenerateOneTimePasswordPresent = result.actions.includes("GenerateOneTimePassword");
      }
      const data = {
        secretId: evt.detail.Data.sender.secretId,
        url: evt.detail.Data.url || evt.detail.Data.sender.secretUrl,
      };

      lastFetchedSecrets.forEach((s) => {
        if (!s?.Secrets) return;
        const item = s.Secrets.find((k) => k.id === evt.detail.Data.sender.secretId);
        if (item) {
          data.url = item.secretUrl;
        }
      });

      if (data.url) {
        data.url = data.url.split(",")[0];
        data.url = (0,url_helpers/* cleanUrlString */.A2)(data.url, false);
      }

      const hints = evt.detail.dataJson.records
        .filter((x) => x.metadataFieldSectionName === constants.WPF_HINTS_SECTION)
        .map((y) => ({
          fieldName: y.metadataFieldName,
          fieldValue: y.valueString,
        }));

        const { secretId } = evt.detail.Data.sender;
        const isOtpPresent = evt.detail.Data.sender.isGenerateOneTimePasswordPresent;
        if (twoStepSecret && twoStepSecret.secretId === secretId) {
          twoStepSecret.isGenerateOneTimePasswordPresent = isOtpPresent;
          await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.twoStepSecret, twoStepSecret);
        }

        if (hints.length === 0) {
        autofillApiDetails(data, secretId, isOtpPresent)
          .then((combinedResult) => {
            callbackGotPassword(combinedResult, evt.detail.Data);
          })
          .catch((error) => background_handleError(error, evt.detail.Data.sender));
        return;
      }
      evt.detail.Data.mappings = organizeMapInfo(hints, evt.detail.Data);
      if (!evt.detail.Data.username || !evt.detail.Data.password
        || (evt.detail.Data.password
          && evt.detail.Data.password.toLowerCase().includes("not valid for display"))) {
        autofillApiDetails(data, secretId, isOtpPresent)
          .then((combinedResult) => {
            callbackGotPassword(combinedResult, evt.detail.Data);
          })
          .catch((error) => background_handleError(error, evt.detail.Data.sender));
        return;
      }

      sendDataToSpecificTab(
        "gotPassword",
        evt.detail.Data,
        evt.detail.Data.sender,
      );
    }).catch((err) => background_handleError(err, evt.detail.Data.sender));
  }
}

function callbackGotPassword(output, evt) {
  sendDataToSpecificTab(
    "gotPassword",
    output,
    evt.sender,
  );
}

function autofillApiDetails(data, secretId, isOtpPresent) {
  const jsonData = JSON.stringify(data);
  const promises = [(0,promise.autoFillCall)(jsonData)];
  return Promise.all(promises).then((results) => {
    //  Combine the results
    const combinedResult = {
      autoFillData: results[0],
      oneTimePassword: results[1],
      isOtpPresent,
    };
    return combinedResult;
  }).catch((error) => {
    if (error.status === 400 && !error.response) {
      cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
      throw new Error("Unable to autofill from the selected Secret.");
    }
    // Re-throw the error for higher-level handling
    throw error;
  });
}
/**
* organizeMapInfo
* @param {*} hints
* @param {*} data
* @return {object}
*/
function organizeMapInfo(hints, data) {
  if ((data && !data.items) || !hints) {
    return [];
  }
  const mapInfo = [];
  data.items.forEach((x) => {
    const fieldHint = hints.find((y) => y.fieldName.toLowerCase() === x.slug.toLowerCase());

    mapInfo.push({
      xPath: fieldHint ? fieldHint.fieldValue : "",
      fieldName: x.slug,
      value: data[x.slug.toLowerCase()] || "",
    });
  });
  return mapInfo;
}

/**
* * tokenExpired
* @param {*} evt
* @return {bool}
*/
async function tokenExpired(evt) {
  const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
  if (serverType === constants.SERVER_TYPE.PLATFORM) {
    if (tokens/* oauth */.o && tokens/* oauth */.o.refresh_token) {
      return getPlatformRefreshToken();
    }
  }
  if (tokens/* oauth */.o && tokens/* oauth */.o.refresh_token) {
    return getRefreshToken(evt ? evt.detail.request : "");
  }
  logOffUser();
}

/**
* * Get User Permission for Accessing WPF.
* @param {*} evt
*/
function gotUserPermission(result) {
  user_permissions/* default */.A.gotPermissions(result);
  loggedInUserId = result.id;
  storage/* default */.A.set({ userId: result.id });
  changeToolbarIcon();
  // restoreCache();
  launchAfterSwitch();

  template_provider.getWebTemplates((isOldWay) => {
    provider = isOldWay ? oldWay : newWay;
  });
  sendDataToPop("currentUserId", loggedInUserId);
}

async function launchAfterSwitch() {
  const webLauncherData = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.webLauncherData);
  if (webLauncherData && !webLauncherData.loggedin
    && webLauncherData.secretId && webLauncherData.tab) {
    getAutofillDetails(
      webLauncherData.secretId,
      webLauncherData.tab.url,
      webLauncherData,
      checkIncognito,
    );
    webLauncherData.loggedin = true;
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);
  }
}

/**
* Parses the URL and get the different sections of URL.
* @param {string} resp The first number.
*/
function gotLoginErrorEvent(resp) {
  if (typeof resp.detail.Data === "object") {
    resp.detail.Data.pincode = resp.detail.request;
    sendDataToPop("gotTokenError", resp.detail.Data);
    return;
  }
  sendDataToPop("gotTokenError", { error: "Login failed." });
}

/**
* When refresh token attempt completed ,user get logoff from WPF.
*/
function getPlatformRefreshToken() {
  if (tokens/* oauth */.o && tokens/* oauth */.o.refresh_token) {
    const data = {
      grant_type: "refresh_token",
      refresh_token: tokens/* oauth */.o.refresh_token,
    };
    const jsonData = new URLSearchParams(data);
    platform_apis.getPlatformRefreshToken(jsonData)
      .then((json) => gotUniversalToken(json))
      .catch(() => {
        onRefreshTokenError();
      });
    return;
  }

  logOffUser();
}

/**
* onPlatformRefreshTokenError
*
*/
function onRefreshTokenError() {
  countRecordedUrls().then((count) => {
    if (count > 0) {
      const url = ext_default().runtime.getURL("session-timeout.html");
      ext_default().tabs.create({ url: `${url}?tabCount=${count}` });
    }
    setTimeout(() => { logOffUser(); }, 200);
  });
}

function getSessionTabCount(callback) {
  countRecordedUrls().then((count) => {
    callback(count);
  });
}
/**
* When user save secret then send message to tab,
*  to show successful message in pop.
* @param {string} resp response.
*/
async function gotSecretSaveEvent(resp) {
  message_sendDataToTab("gotSecretSave", "");
  const { host } = (0,url_helpers/* parseUrl */.Dl)(resp.detail.Data.url, false);
  const obj = {
    id: resp.detail.dataJson,
    secretTypeId: resp.detail.Data.secretTypeId,
    name: resp.detail.Data.name,
    useSessionRecording: false,
    tabid: resp.detail.Data.tab.id,
    url: resp.detail.Data.url,
    secretUrl: resp.detail.Data.url,
    secretId: resp.detail.dataJson,
    host,
  };
  await cache/* lastFetchedSecretsProvider */.iF.addSecret(host, obj);
  await insertMetadata(obj.id, resp.detail.Data.mappingInfo);

  const sender = resp.detail.Data;
  sender.secretId = obj.id;
  removeAndUpdate(sender.tab.id);
  await cache/* selectionHistoryProvider */.oA.add(obj);
  resp.detail.dataJson = convertResponse(resp.detail.dataJson);
  if (resp && resp.detail && resp.detail.dataJson && resp.detail.dataJson.mappings) {
    resp.detail.dataJson.mappings = organizeMapInfo(
      resp.detail.Data.mappingInfo,
      resp.detail.dataJson,
    );
  }
  const tabUrl = sender.tab.url;
  const tabDomain = (0,url_helpers/* parseUrl */.Dl)(tabUrl, true).domain;
  if ((0,common/* checkIfMultiDomain */.FS)(tabDomain).length > 0) {
    const SSOUrls = await cache/* ssoUrlsProvider */.Tm.get();
    if (SSOUrls.length === 0) {
      SSOUrls.push(sender.tab.url);
      cache/* ssoUrlsProvider */.Tm.set(SSOUrls);
    }
    const twoStepSecret = {
      secretId: obj.id,
      url: sender.tab.url,
      tab: sender.tab,
      SSOUrls: [...SSOUrls],
    };
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.twoStepSecret, twoStepSecret);
  }
  //sendDataToSpecificTab("gotPassword", resp.detail.dataJson, sender);
  ext_default().tabs.sendMessage(
    sender.tab.id,
    {
      method: "contextSecretClicked",
      secretId: sender.secretId,
      secretUrl: sender.secretUrl,
      singleSecret: false,
    },
  );
}

/**
* When user try to save secret,
* if got error then send message to tab, to show error pop.
* @param {object} res
*/
function gotSecretSaveErrorEvent(res) {
  if (res && res.detail.Data.errorCode
    && res.detail.Data.errorCode === "API_InvalidTemplate") {
    gotInvalidTemplateErrorEvent(res);
  } else {
    message_sendDataToTab("gotSecretSaveError", res && res.detail && res.detail.Data);
  }
}

/**
* When user try to save secret but it fails
* due to required fields / permissions, etc,
* if got error then send message to tab, to show advanced add secret dialog.
* @param {object} evt
*/
function gotSecretSavePopupErrorEvent(evt) {
  message_sendDataToTab("gotSecretSavePopupError", evt.detail.Data.message);
}

/**
* When user try to update secret,
* if got error then send message to tab, to show error pop.
* @param {object} evt
*/
function gotSecretUpdateErrorEvent(evt) {
  message_sendDataToTab("gotSecretUpdateError", evt.detail.Data.message);
}

/**
* Get response when password updated.
*/
function gotUpdateSecretsPasswordEvent() {
  message_sendDataToTab("gotSecretUpdatePassword", "");
}

/**
* Passes token as result to pop.js
* @param {string} resp response.
*/
function gotTokenEvent(resp) {
  let tokenResponse = resp.detail.dataJson;
  tokens/* oauth */.o.token = tokenResponse;
  if (!resp.detail.fromNativeHost) {
    resp.detail.dataJson.url = common/* config */.$W.Url;
    resp.detail.dataJson.ssUrl = common/* config */.$W.BaseURL;
    const minutes = (tokens/* oauth */.o.expires_in ? tokens/* oauth */.o.expires_in : 345686339) / 60;
    resp.detail.dataJson.tokenExpireDateTime = addMinutes(new Date(), minutes);
    storeToken(resp.detail.dataJson);
  } else {
    const startDate = new Date(resp.detail.dataJson.tokenExpireDateTime);
    const endDate = new Date();
    tokens/* oauth */.o.expires_in = (startDate.getTime() - endDate.getTime()) / 1000;
    if (tokens/* oauth */.o.expires_in < 1) {
      tokenExpired(null);
      return;
    }
  }

  if (!tokens/* oauth */.o.expires_in) {
    tokens/* oauth */.o.expires_in = 345686339;
  }

  setLoggedIn(Math.floor(tokens/* oauth */.o.expires_in), tokenResponse.isRestore);


  if (!resp.detail.skipCurrent) {
    sendDataToPop("gotTokenResult", resp.detail.dataJson);
    storeSSUrl(common/* config */.$W.Url);
    (0,promise.getSSVersion)().then((result) => gotVersion(result)).catch(gotVersion);
  }

  logger/* default */.A.logInfo(`Logged into ${common/* config */.$W.Url}`);
}

/**
* Add minutes to date.
* @param {string} dt
* @param {int} minutes
* @return {Date}
*/
function addMinutes(dt, minutes) {
  return new Date(dt.getTime() + minutes * 60000);
}

/**
* Use refresh token and get token.
* @param {string} resp response.
*/
function gotRefreshTokenEvent(resp) {
  resp.detail.skipCurrent = true;
  gotTokenEvent(resp);
  const passThroughData = resp.detail.Data;
  if (passThroughData && passThroughData.apicall) {
    passThroughData.apicall.apply(null, passThroughData.args);
  }
}

/**
* Error when user try to add invalid template.
*/
function gotInvalidTemplateErrorEvent() {
  message_sendDataToTab("gotInvalidTemplateError", "");
}


function clearCache() {
  cache/* selectionHistoryProvider */.oA.clear();
  cache/* lastFetchedSecretsProvider */.iF.clear();
  cache/* ssoUrlsProvider */.Tm.clear();
  cache/* ssoSecretsProvider */.aS.clear();
  cache/* addSecretArrayProvider */.IR.clear();
  cache/* foldersProvider */.RV.clear();
  cache/* lastFetchedWinADSecretsProvider */.dH.clear();
  cache/* sitesProvider */.wk.clear();
  cache/* windowsAdminCenterItemProvider */.q7.clear();
  cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
  removeCache();
}

/**
* remove token.
*/
function logOff() {
  clearCache();
  // checkoutSecretsState.length = 0;
  // checkoutSecretsStateProvider.clear();
  tabCalls.length = 0;
  isLoggedIn = false;
  loggedInUserId = 0;
  user_permissions/* default */.A.loggedOff();
  logger/* default */.A.clear();
  // twoStepSecret = null;
  changeToolbarIcon();
  tokens/* oauth */.o.clearToken();
  ext_default().alarms.clear("tokenExpired", () => logger/* default */.A.logInfo("User logged out"));
  ext_default().contextMenus.removeAll();
  sendMessage("logOff", isLoggedIn);
  sendDataToPop("logOff", isLoggedIn);
  removeToken();
  cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.serverType, "");
  newWay.resetIdsCombinedNotSupported();
}


/**
* on Secret Server Log Off, log off WPF
*/
function onSSLogOff() {
  const cookieUrl = (0,url_helpers/* parseUrl */.Dl)(common/* config */.$W.BaseURL);
  ext_default().cookies.getAll(
    { url: cookieUrl && cookieUrl.origin },
    (cookies) => {
      let cookieExist = false;
      for (let i = 0; i < cookies.length; i++) {
        if (cookies[i].name === "ihawu" && cookies[i].value) {
          cookieExist = true;
        }
      }
      if (!cookieExist) {
        checkLastError();
        logger/* default */.A.logInfo("Logged out from SS");
        logOffUser();
        cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.webLauncherData);
      }
    },
  );
}

ext_default().webNavigation.onErrorOccurred.addListener(async (details) => {
  const samlTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.samlTabId);
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  if (details.tabId === samlTabId
    && details.error !== "Error code 2152398850"
    && details.error !== "net::ERR_ABORTED") {
    newWindowHeight = 0;
    newWindowWidth = 0;
    centerDialog(ssLoginWindowId);
  }
});

// Add listener for web request errors if not Safari
if (!(0,common/* isSafari */.nr)()) {
ext_default().webRequest.onErrorOccurred.addListener((details) => {
  const sourceUrl = details.initiator || details.originUrl;
  const extensionUrl = (0,url_helpers/* removeLastSlash */.ws)(ext_default().runtime.getURL(""));
  if (sourceUrl && sourceUrl.indexOf(extensionUrl) === -1) {
    return;
  }

  console.log(`Error: ${details.error}`);
  logger/* default */.A.logError(`${details.error}`);
  if (details.error == "net::ERR_CERT_AUTHORITY_INVALID") {
    if (isLoggedIn) {
      message_sendDataToTab("showError", errors_ERR.EXPIRED_CERT_ERROR);
    }
    sendDataToPop("showSsConfigError", "Certificate General Error");
  } else if (details.error.toLowerCase().includes("cert")
    || details.error === "NET::ERR_SSL_OBSOLETE_VERSION") {
    message_sendDataToTab("showError", errors_ERR.INVALID_CERT_ERROR);
    sendDataToPop("showSsConfigError", "Certificate General Error");
  } else if (details.error === "net::ERR_SSL_PROTOCOL_ERROR"
    || details.error === "net::ERR_NAME_NOT_RESOLVED"
    || details.error === "net::ERR_TIMED_OUT" || details.error === "net::ERR_CONNECTION_TIMED_OUT"
    || details.error === "NS_ERROR_NET_TIMEOUT") {
    sendDataToPop("showSsConfigError", "Invalid SS URL");
  } else if (
    details.error === "net::ERR_CONNECTION_REFUSED") {
    console.log("Request timed out");
    sendDataToPop("gotRequestTimedout", details.error);
    console.log("Connection timed out or invalid Secret Server Url");
  }
}, {
  urls: ["*://*/*"],
  types: ["xmlhttprequest"],
});
}
/**
 * call the API to get Secrets By URL.
 *  @param {string} sender requesting tab info
 *  @param {string} callback callback function name.
 */
async function getSecretsByUrl(sender, callback = gotSecretsByURLEvent) {
  const secretUrl = sender.tab.url;
  const SSOUrls = await cache/* ssoUrlsProvider */.Tm.get();
  if (SSOUrls.length > 0) {
    getSSOSecrets(SSOUrls, sender);
    return;
  }

  const data = JSON.stringify(secretUrl);
  const tabItem = { ...await cache/* windowsAdminCenterItemProvider */.q7.findByTabId(sender.tab.id) };

  if (tabItem.itemName) {
    try {
      const body = JSON.stringify(tabItem.itemName);
      const urlSecrets = await (0,promise.searchByURL)(data);
      const windowsSecrets = await (0,promise.getWindowsSecretsByHostName)(body);
      const adSecrets = await (0,promise.getADSecretsByDomain)(body);
      const winADSecrets = [...windowsSecrets.model, ...adSecrets.model];
      cache/* lastFetchedWinADSecretsProvider */.dH.add(tabItem.itemName, winADSecrets);
      const secretList = [...urlSecrets.model, ...winADSecrets];
      sendORAutofill(secretList, sender, secretUrl);
    } catch (err) {
      message_sendDataToTab("showError", errors_ERR.FAILED_TO_FETCH_WINAD);
    }
    return;
  }

  callAPI(
    endpoints/* default */.A.SECRETS_BY_URL,
    "post",
    data,
    tokens/* oauth */.o.access_token,
    constants.CONTENT && constants.CONTENT.APP_JSON,
    callback,
    sender,
  );
}

/**
* get SSO Secrets
* @param {*} sender
*/
async function getSSOSecrets(ssoUrls, sender) {
  const secretUrl = sender.referrer;
  const promises = [];
  ssoUrls.forEach((site) => {
    const data = JSON.stringify(site);
    promises.push((0,promise.searchByURL)(data));
  });
  const combined = [];
  const hostEntries = [];
  try {
    const responses = await Promise.all(promises);
    responses.forEach((response, index) => {
      if (response.model.length > 0) {
        (0,common/* addObjectsToArray */.U8)(combined, response.model);
        const ssoUrl = ssoUrls[index];
        const { host, origin } = (0,url_helpers/* parseUrl */.Dl)((0,url_helpers/* addDefaultProtocol */.ZG)(ssoUrl), false);
        hostEntries.push({ host, url: origin, Secrets: response.model });
      }
    });
    cache/* lastFetchedSecretsProvider */.iF.addAll(hostEntries);
    cache/* ssoSecretsProvider */.aS.set(combined);
    sendORAutofill(combined, sender, secretUrl);
  } catch (err) {
    message_sendDataToTab("showError", errors_ERR.FETCHING_SECRETS_FAILED);
  }
}

/**
* sendORAutofill
* @param {*} secrets
* @param {*} sender
* @param {*} secretUrl
*/
async function sendORAutofill(secrets, sender, secretUrl) {
  // storage.get('Settings', (items) => {
  const settings = await cache/* settingsProvider */.Pj.get();
  if (settings && settings.exactMatchUrl) {
    const tabUrl = (0,url_helpers/* cleanUrlString */.A2)(secretUrl);
    secrets = filterSecrets(secrets, tabUrl);
  }
  const autoPopulate = settings.enableAutoPopulate;
  if (secrets.length === 1 && autoPopulate && !sender.isIconClick && !sender.isRefreshClick) {
    const result = {
      method: "contextSecretClicked",
      secretId: secrets[0].id,
      singleSecret: true,
      secrets,
    };
    ext_default().tabs.sendMessage(sender.tab.id, result);
  } else {
    ext_default().tabs.get(sender && sender.tab && sender.tab.id, (tab) => {
      checkLastError();
      if (tab) {
        if (!tab.incognito) {
          secrets = secrets.filter((x) => x.incognito !== true);
        }
        const result = {
          tabid: sender.tab.id,
          url: secretUrl,
          Secrets: secrets,
        };
        sender.selectedframeId = 0;
        sendDataToSpecificTab("GotSecrets", result, sender);
      }
    });
  }
  // });
}

/**
*  filter Secrets search
* @param {*} secrets
* @param {*} tabUrl
*/
function filterSecrets(secrets, tabUrl) {
  return secrets.filter((x) => {
    const urls = x.secretUrl.split(",");
    const match = urls.find((url) => (0,url_helpers/* cleanUrlString */.A2)(url) === tabUrl);
    if (match || !x.secretUrl) return true;
    return false;
  });
}

/**
* Helper to search for a value in an array of objects
*  @param {string} nameKey value lookup
*  @param {string} lookupValue value lookup
*  @param {Array} myArray of objects
*  @return {int} the position in the array
*/
function search(nameKey, lookupValue, myArray) {
  for (let i = 0; i < myArray.length; i++) {
    if (myArray[i][nameKey] === lookupValue) {
      return i;
    }
  }
  return -1;
}

/**
* Udpate secret password.
*  @param {object} data password value.
*  @param {int} secretId secret id.
*  @param {object} sender sender
*/
function updateSecretPassword(data, secretId, sender) {
  removePersistSecret(sender);
  sender.password = data.value;
  callAPI(
    endpoints/* default */.A.SECRETS + secretId,
    "get",
    "",
    tokens/* oauth */.o.access_token,
    constants.CONTENT && constants.CONTENT.APP_JSON,
    gotTemplateInfoEvent,
    sender,
    "",
    gotSecretUpdateErrorEvent,
  );
}

/**
* Get secret password.
*  @param {Number} secretId secret id.
*  @param {object} sender sender
*  @param {object} callback callback
*/
function getSecretPassword(secretId, sender, callback) {
  sender.callback = callback || gotPasswordEvent;
  callAPI(endpoints/* default */.A.SECRETS + secretId, "get", "", tokens/* oauth */.o.access_token, constants.CONTENT && constants.CONTENT.APP_JSON, gotSecretPasswordEvent, sender, "", gotSecretPasswordErrorEvent);
}
/**
* gotSecretPasswordEvent
* @param {*} evt
*/
function gotSecretPasswordEvent(evt) {
  const response = evt.detail.dataJson;
  if (response.sessionRecordingEnabled) {
    message_sendDataToTab("showError", errors_ERR.WIN_AD_SESSION_RECORDING_NOT_SUPPORTED);
    return;
  }
  const customResponse = {};
  response.items.forEach((x) => {
    switch (x.fieldName.toLowerCase()) {
      case "username":
        customResponse.username = x.itemValue;
        break;
      case "password":
        customResponse.password = x.itemValue;
        break;
      default:
        break;
    }
  });
  customResponse.useSessionRecording = response.sessionRecordingEnabled;
  evt.detail.dataJson.model = customResponse;
  if (!evt?.detail?.Data?.callback) return;
  dispatchCustomEvent(evt && evt.detail && evt.detail.Data && evt.detail.Data.callback, evt);
}

/**
* gotSecretPasswordError
* @param {*} evt
*/
function gotSecretPasswordErrorEvent() {

}

/**
* Event callback after Secrets By URL
* @param {string} evt event data.
*/
function gotTemplateInfoEvent(evt) {
  const jsonData = evt.detail.dataJson;
  let slugName = "";
  jsonData.items.reverse().forEach((formElement) => {
    if (formElement.isPassword) {
      slugName = formElement.slug;
    }
  });

  if (slugName.length < 1) {
    gotSecretSaveErrorEvent();
    return;
  }
  const fieldValue = { value: evt.detail.Data.password };
  const url = endpoints/* default */.A.update_secret_password(
    evt.detail.dataJson.id,
    slugName,
  );
  callAPI(
    url,
    "put",
    JSON.stringify(fieldValue),
    tokens/* oauth */.o.access_token,
    constants.CONTENT && constants.CONTENT.APP_JSON,
    gotUpdateSecretsPasswordEvent,
    "",
    "",
    gotSecretUpdateErrorEvent,
  );
}

/**
 * Event callback after Secrets By URL
  * @param {string} evt event data.
  */
async function gotSecretUserPassword(evt) {
  if (evt && evt.Data) {
    const request = evt.Data;
    const secret = evt.autoFillData.model;
    let isEdit = false;
    const item = await cache/* addSecretArrayProvider */.IR.findByTabId(request.tab.id);
    if (item) {
      const requestDomain = (0,url_helpers/* parseUrl */.Dl)(request.tab.url).domain;
      const existingEntryDomain = (0,url_helpers/* parseUrl */.Dl)(item.tabUrl).domain;
      if (requestDomain === existingEntryDomain
        || ((0,common/* checkIfMultiDomain */.FS)(existingEntryDomain).length > 0
          && (0,common/* checkIfMultiDomain */.FS)(requestDomain).length > 0)) {
        request.username = (item.data.username
          ? item.data.username : request.username);
      }
    }
    if (secret.username === request.username
      && secret.password === request.password) {
      return;
    }
    if ((request.isMappingFound && secret.password === request.password)
      || (!request.isMappingFound && secret.password === request.password)) {
      return;
    }
    if (secret.username === request.username
      && secret.password !== request.password) {
      isEdit = true;
    }
    persistSecret(request, isEdit);
  }
}

/**
* Event callback after Secrets By URL for Recent and Favorites tab.
* @param {string} result event data.
*/
async function getLastSecretEntry(result) {
  if (result) {
    let host = "";
    const response = result.model;
    if (response && response[0]) {
      host = (0,url_helpers/* parseUrl */.Dl)(response[0].secretUrl).host;
      if (host === "") {
        host = (0,url_helpers/* parseUrl */.Dl)(response[0].secretUrl).href;
      }
      const item = await cache/* lastFetchedSecretsProvider */.iF.getByHost(host);
      return {
        Secrets: response,
        url: response[0].secretUrl,
        host,
        favIconUrl: item ? item.favIconUrl : "",
      };
    }
  }
}

/**
* Event callback after Secrets By URL
* @param {string} evt event data.
*/
async function gotSecretsByURLEvent(evt) {
  if (evt && evt.detail) {
    const secretsToSend = evt.detail.dataJson.model;
    const sender = evt.detail.Data;
    const secretUrl = sender.referrer ? sender.referrer : sender.tab.url;
    gotSecretsByUrl(evt);
    sendORAutofill(secretsToSend, sender, secretUrl);
  }
}

/**
* gotSecretsByUrl
* @param {*} evt
*/
async function gotSecretsByUrl(evt) {
  if (evt && evt.detail) {
    const secretsToSend = evt.detail.dataJson.model;
    const sender = evt.detail.Data;
    const secretUrl = sender.referrer ? sender.referrer : sender.tab.url;
    await pushToLastFetchedList({
      url: secretUrl,
      Secrets: secretsToSend,
    });
  }
}

/**
* Event callback after Secrets By URL
* @param {object} response event data.
*/
async function pushToLastFetchedList(response) {
  if (!(response && response.url)) return;

  const { host, origin } = (0,url_helpers/* parseUrl */.Dl)(response.url, false);
  response.url = origin;
  response.host = host;
  cache/* lastFetchedSecretsProvider */.iF.add(response);
}

async function fetchFolders() {
  const lastCached = cache/* foldersProvider */.RV.getLastCached();
  // cached for 10 mins
  if (!lastCached
    || (Date.now() > lastCached + (10 * 60 * 1000))) {
    const personalFolder = await (0,promise.getPersonalFolder)();
    const personalFolderId = personalFolder.userPersonalFolderId;
    const foldersResponse = await (0,promise.getFolders)();
    if(personalFolderId) {
      foldersResponse.records.find((f) => f.id === personalFolderId).isPersonalFolder = true;
    }
    cache/* foldersProvider */.RV.set(foldersResponse.records);
  }
  return cache/* foldersProvider */.RV.get();
}

/**
* returns templates and folders on demand
* @param {object} sender sender
* @param {object} sendResponse callback
*/
async function getTemplatesNFolders(sender, sendResponse) {
  if (!isLoggedIn) return;
  try {
    sendMessageToSpecificWindowTab("loadingTemplates", "", sender);
    const templates = await (0,promise.getWebSecretTemplates)();
    const folders = await fetchFolders();
    const result = {
      Folders: folders,
      Templates: templates.model,
      Sites: await (0,promise.getSites)(),
    };
    if (sendResponse) {
      sendResponse(result);
    } else {
      result.fromContext = true;
      sendMessageToSpecificWindowTab(
        "GotTemplatesNFolders",
        result,
        sender,
      );
    }
  } catch (err) {
    message_sendDataToTab("showError", errors_ERR.FAILED_TO_FETCH_ADD_SECRET);
  }
}

async function removeAndUpdate(tabId) {
  await cache/* selectionHistoryProvider */.oA.remove(tabId);
}

ext_default().tabs.onActivated.addListener(() => {
  toolBarIconStateChecked = true;
  changeToolbarIcon();
  ext_default().contextMenus.removeAll();
});

ext_default().tabs.onRemoved.addListener(async (tabId, removeInfo) => {
  tabCalls[tabId] = 0;

  // removeArrayEle(selectionHistory, tabId);
  await cache/* selectionHistoryProvider */.oA.remove(tabId);
  // removeArrayEle(AddSecretArray, tabId);
  await cache/* addSecretArrayProvider */.IR.removeByTabId(tabId);
  const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  if (twoStepSecret && twoStepSecret.tab
    && twoStepSecret.tab.id === tabId) {
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
  }
  const secret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.launchedSecret);
  if (secret && secret.tabId === tabId) {
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.launchedSecret);
  }
  await cache/* windowsAdminCenterItemProvider */.q7.removeByTabId(tabId);
  if (!isLoggedIn) {
    if (ssLoginWindowId === removeInfo.windowId) {
      ext_default().runtime.sendMessage({
        method: "SamlWindowClosed",
      }, () => {
        checkLastError();
      });
    }
  }
});

ext_default().tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (isLoggedIn && changeInfo.status === "loading" && changeInfo.url) {
    const newDomain = (0,url_helpers/* parseUrl */.Dl)(changeInfo.url).domain;
    const siteList = await cache/* addSecretArrayProvider */.IR.findByTabId(tabId);
    if (siteList) {
      const previousDomain = (0,url_helpers/* parseUrl */.Dl)(siteList.tabUrl).domain;
      if (previousDomain !== newDomain
        && ((0,common/* checkIfMultiDomain */.FS)(previousDomain).length === 0
          && (0,common/* checkIfMultiDomain */.FS)(newDomain).length === 0)) {
        await cache/* addSecretArrayProvider */.IR.removeByTabId(tabId);
      }
    }

    // const removeSite = selectionHistory.find((x) => x.tabid === tabId);
    // if (removeSite && parseUrl(removeSite.url).domain !== newDomain) {
    //    removeArrayEle(selectionHistory, tabId);
    // }
    cache/* selectionHistoryProvider */.oA.get().then((selectionHistory) => {
      const removeSite = selectionHistory.find((x) => x.tabid === tabId);
      if (removeSite && (0,url_helpers/* parseUrl */.Dl)(removeSite.url).domain !== newDomain) {
        removeAndUpdate(tabId);
      }
    });
    const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
    if (twoStepSecret && twoStepSecret.SSOUrls) {
      const SSODomains = twoStepSecret.SSOUrls.map((x) => (0,url_helpers/* parseUrl */.Dl)(x).domain);
      if (!SSODomains.includes(newDomain)) {
        cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
      }
    }
    const windowsAdminCenterItem = await cache/* windowsAdminCenterItemProvider */.q7.get();
    if (windowsAdminCenterItem.find((y) => y.tabId === tabId
      && (0,url_helpers/* parseUrl */.Dl)(y.url).domain !== newDomain)) {
      await cache/* windowsAdminCenterItemProvider */.q7.removeByTabId(tabId);
    }
  } else if (changeInfo.status === "complete") {
    const url = new URL(tab.url);
    const newDomain = url.hostname;
    if (!toolBarIconStateChecked) {
      changeToolbarIcon();
      ext_default().contextMenus.removeAll();
    }
    if (sessionManager.clearStorageKey && newDomain === "myapps.microsoft.com") {
      ext_default().tabs.sendMessage(tabId, {
        method: "clearStorage",
      })
      sessionManager.clearStorageKey = false;
    }
  }
  toolBarIconStateChecked = false;
});

ext_default().windows.onFocusChanged.addListener(() => {
  ext_default().contextMenus.removeAll();
});

ext_default().windows.onRemoved.addListener(async (windowId) => {
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  if (windowId === ssLoginWindowId) {
    // ssLoginWindowId = 0;
    // platformTabId = 0;
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginWindowId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.samlTabId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.platformTabId, 0);
  }
});

ext_default().tabs.onDetached.addListener(() => {
  ext_default().contextMenus.removeAll();
});

/**
* reload context menus
* @param {object} request triggered tabId
*/
async function reloadContextMenus(request) {
  if (!((ext_default()) && (ext_default()).contextMenus)) return;
  ext_default().contextMenus.removeAll();
  if (isLoggedIn && !request.isCurrentSSTabloggedIn) {
    createContextMenu(request.isPassword);
    const settings = await cache/* settingsProvider */.Pj.get();
    const lastFetchedSecrets = await cache/* lastFetchedSecretsProvider */.iF.get();
    ext_default().tabs.query(constants.ACTIVE_TAB_QUERY, async (tabs) => {
      if (tabs && tabs.length > 0) {
        let combined = [];
        let ismultiDomain = false;
        if ((0,common/* checkIfMultiDomain */.FS)((0,url_helpers/* parseUrl */.Dl)(tabs[0].url).domain).length > 0) {
          ismultiDomain = true;
        }
        const items = lastFetchedSecrets.filter((i) => (0,url_helpers/* parseUrl */.Dl)(tabs[0].url).host === i.host
          || (ismultiDomain
            && (0,common/* checkIfMultiDomain */.FS)((0,url_helpers/* parseUrl */.Dl)(i.url).domain).length > 0));

        items.forEach((item) => {
          if (!tabs[0].incognito) {
            combined.push(...item.Secrets.filter((x) => x.incognito !== true));
          } else {
            combined.push(...item.Secrets);
          }
        });
        const tabItem = { ...await cache/* windowsAdminCenterItemProvider */.q7.findByTabId(tabs[0].id) };
        if (tabItem.itemName) {
          const winADItem = await cache/* lastFetchedWinADSecretsProvider */.dH.getByName(tabItem.itemName);
          if (winADItem && winADItem.secrets) {
            combined.push(...winADItem.secrets);
          }
        }
        if (combined) {
          // storage.get('Settings', (items) => {

          if (settings && settings.exactMatchUrl) {
            const tabUrl = (0,url_helpers/* cleanUrlString */.A2)(tabs[0].url);
            combined = filterSecrets(combined, tabUrl);
          }
          createSecretMenu(combined);
          // });
        }
      }
    });
  }
}

/**
* Parses the URL and get the different sections of URL.
* @param {Number} id element ID.
* @param {string} url Associated URL.
* @param {object} sender requester info
* @param {string} callback callback function
* @param {boolean} wpfLauncherClicked
*/
async function getAutofillDetails(
  id,
  url,
  sender,
  callback = checkRecording,
  wpfLauncherClicked = false,
) {
  if (wpfLauncherClicked == true) {
    sender.wpfLauncherClicked = true;
  }
  let secretUrl = url;
  const ssoSecrets = await cache/* ssoSecretsProvider */.aS.get();
  sender.sUrl = secretUrl;
  const secret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.launchedSecret);
  if (ssoSecrets.find((i) => i.id == id)) {
    const SSOUrls = await cache/* ssoUrlsProvider */.Tm.get();
    const ssoDomains = SSOUrls.map((j) => (0,url_helpers/* parseUrl */.Dl)(j).domain);
    if (ssoDomains.includes((0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain)) {
      const item = await cache/* lastFetchedSecretsProvider */.iF.findBySecretId(id);
      if (item) {
        secretUrl = item.url;
        sender.secretUrl = secretUrl;
      }
    }
  } else if (secret && secret.secretId === id && secret.url) {
    secretUrl = secret.url;
  }
  let isWindowsAdminCenterSecret = false;
  const tabItem = { ...await cache/* windowsAdminCenterItemProvider */.q7.findByTabId(sender.tab.id) };
  if (tabItem.itemName) {
    const item = await cache/* lastFetchedWinADSecretsProvider */.dH.getByName(tabItem.itemName);
    if (item) {
      const WACSecret = item.secrets.find((i) => i.id == id);
      if (WACSecret) {
        isWindowsAdminCenterSecret = true;
      }
    }
  }
  if (isWindowsAdminCenterSecret) {
    if (callback !== checkRecording) {
      getSecretPassword(id, sender, callback);
    } else {
      getSecretPassword(id, sender);
    }
  } else {
    sender.secretId = id;

    if (callback === gotSecretUserPassword
      || callback === checkIncognito) {
      const data = {
        secretId: id,
        url: secretUrl && secretUrl.split && secretUrl.split(",")[0],
      };
      const secretId = id;
      const isOtpPresent = sender.isGenerateOneTimePasswordPresent;
      autofillApiDetails(data, secretId, isOtpPresent)
        .then((result) => {
          result.Data = { ...data, ...sender, isOtpPresent };
          callback(result);
        })
        .catch((error) => background_handleError(error, sender));

      return;
    }
    callAPI(
      endpoints/* default */.A.SECRETS + id,
      "get",
      "",
      tokens/* oauth */.o.access_token,
      constants.CONTENT && constants.CONTENT.APP_JSON,
      callback,
      sender,
      "",
      gotPasswordErrorEvent,
    );
  }
}

/**
* convertResponse
* @param {*} data
* @return {object}
*/
function convertResponse(data) {
  if (data.items) {
    const array = data.items.map((x) => ({ [x.slug.toLowerCase()]: x.itemValue }));
    let merged = {};
    array.forEach((x) => {
      merged = { ...merged, ...x };
    });

    return {
      useSessionRecording: data.sessionRecordingEnabled,
      webLauncherRequiresIncognitoMode: data.webLauncherRequiresIncognitoMode,
      ...merged,
      items: data.items,
    };
  }
  if (data.model) {
    return data.model;
  }
}

function handleSecretActions(sender, response) {
  const isCopyPw = sender.secretAction === constants.secretAction.copyPassword;
  if (isCopyPw && (0,common/* passwordIsHidden */.Wk)(response.items)) {
    const copyMsg = (0,common/* getHiddenPassword */.Ye)(response.items);
    const copyAction = {
      secretAction: constants.secretAction.copyPassword,
      copyMsg,
    };
    if((0,common/* isSafari */.nr)()){
      navigator.clipboard.writeText(copyMsg).then(i => console.log('copied'));
    }
    sendDataToSpecificTab(
      "copyMsg",
      copyAction,
      sender,
    );
    return;
  }

  if (sender.secretAction === constants.secretAction.copyOtp) {
    (0,promise.getOneTimePassword)(sender.secretId).then((results) => {
      const copyMsg = results[0].code;
      const copyAction = {
        secretAction: constants.secretAction.copyOtp,
        copyMsg,
      };
      if((0,common/* isSafari */.nr)()){
        navigator.clipboard.writeText(copyMsg).then(i => console.log('copied'));
      }
      sendDataToSpecificTab(
        "copyMsg",
        copyAction,
        sender,
      );
    }).catch((err) => background_handleError(err, sender));
    return;
  }

  if (isCopyPw || sender.secretAction === constants.secretAction.copyUsername) {
    const data = {
      secretId: sender.secretId,
      url: sender.secretUrl.split(",")[0],
    };
    autofillApiDetails(data, sender.secretId, sender.isGenerateOneTimePasswordPresent)
      .then((result) => {
        const copyMsg = isCopyPw ? result.autoFillData.model.password : result.autoFillData.model.username;
        const copyAction = {
          secretAction: sender.secretAction,
          copyMsg,
        };
        if((0,common/* isSafari */.nr)()){
          navigator.clipboard.writeText(copyMsg).then(i => console.log('copied'));
        }
        sendDataToSpecificTab(
          "copyMsg",
          copyAction,
          sender,
        );
      })
      .catch((error) => background_handleError(error, sender));
  }
}

/**
* check if secret has recording enabled
* @param {object} evt
*/
async function checkRecording(evt) {
  const sender = evt.detail.Data;
  evt.detail.dataJson.model = convertResponse(evt.detail.dataJson);
  if (tabCalls[sender.tab.id]) {
    tabCalls[sender.tab.id] = 0;
  }
  const { secretId } = sender;
  const secretUrl = sender.referrer ? sender.referrer : sender.tab.url;
  const item = await cache/* lastFetchedSecretsProvider */.iF.findBySecretId(secretId);
  if (item && item.Secrets && item.Secrets.length > 0) {
    // take secret by Id
    const selectedSecret = item.Secrets.find((x) => x.id === secretId);
    const cachedUrl = selectedSecret ? selectedSecret.secretUrl : secretUrl;
    sender.secretUrl = cachedUrl;
  } else {
    sender.secretUrl = secretUrl;
  }
  const response = evt.detail.dataJson.model;
  const { useSessionRecording } = response;
  const incognitoEnabled = response.webLauncherRequiresIncognitoMode;

  if (useSessionRecording && !isMediaRecorderSupported()) {
    message_sendDataToTab("showError", errors_ERR.SESSION_RECORDING_NOTSUPPORTED);
    return;
  }

  if (useSessionRecording && !macVersionSupport(userAgent)) {
    message_sendDataToTab("showError", errors_ERR.SESSION_RECORDING_NOTSUPPORTED_ONSAFARI15);
    messageDisplayed = true;
    return;
  }

  if (sender.secretAction === constants.secretAction.copyPassword
    || sender.secretAction === constants.secretAction.copyUsername
    || sender.secretAction === constants.secretAction.copyOtp) {
    handleSecretActions(sender, response);
    return;
  }

  if (incognitoEnabled && !sender.tab.incognito) {
    message_sendDataToTab("showError", errors_ERR.INCOGNITO_SECRET_IN_NORMAL_WINDOW_AUTOFILL_ERROR);
    return;
  }
  setIncognitoFlag(sender, incognitoEnabled);
  if (!useSessionRecording && !sender.isIconClick) {
    const urls = sender.secretUrl.split(",");
    // eslint-disable-next-line no-restricted-syntax
    for (const url of urls) {
      sessionManager.endConflictingSessions(url, sender.tab.incognito);
    }
    gotPasswordEvent(evt);
    return;
  }
  //  pushTabToCookie(sender.tab.id);
  if (sender.secretClicked && useSessionRecording) {
    const existingSession = sessionManager.getSession(secretId, sender.tab.incognito);
    if (existingSession) {
      // dispatchCustomEvent('gotPassword', evt);
      gotPasswordEvent(evt);
      return;
    }
    // recorder.endSameURLSession(sender.secretUrl, secretId, sender);
    sessionManager.endConflictingSessions(sender.secretUrl, sender.tab.incognito);
    const SSOUrls = await cache/* ssoUrlsProvider */.Tm.get();
    const response = (0,promise.getSecretlauncherURL)(secretId);
    response.then((result) => {
      if (result.restrictedHosts) {
        const secretDomain = (0,url_helpers/* parseUrl */.Dl)((0,url_helpers/* addDefaultProtocol */.ZG)(sender.sUrl))?.domain;
        const senderDomain = secretDomain || (0,url_helpers/* parseUrl */.Dl)(sender.url)?.domain?.toLowerCase();
        const referrerDomain = (0,url_helpers/* parseUrl */.Dl)(sender.referrer)?.domain;
        const domainMatch = result.restrictedHosts.find((s) => {
          const restrictedDomain = (0,url_helpers/* parseUrl */.Dl)((0,url_helpers/* addDefaultProtocol */.ZG)(s.value))?.domain;
          return restrictedDomain?.toLowerCase() === senderDomain?.toLowerCase()
            || restrictedDomain?.toLowerCase() === referrerDomain?.toLowerCase()
            || restrictedDomain?.toLowerCase() === secretDomain?.toLowerCase();
        });

        if (domainMatch && domainMatch.value) {
          if (sender.sUrl.startsWith(domainMatch.value)) {
            // If it does, set sender.sUrl as is
            sender.sUrl = sender.sUrl; // No change needed, as it's already correct
          } else {
            // If it doesn't, concatenate the domain with the path
            sender.sUrl = domainMatch.value;
          }

        } else {
          // TODO: Not sure if this should throw an error or not
          console.warn("Could not match launch URL to domain list");
          sender.sUrl = result.secretUrl;
        }
      } else {
        sender.sUrl = result.secretUrl;
      }
      sender.SSOUrls = SSOUrls;
      initiateNewSession(secretId, evt, gotPasswordEvent);
    });
  } else {
    const result = {
      tabid: sender.tab.id,
      url: secretUrl,
      Secrets: sender.secrets,
    };
    sendDataToSpecificTab("GotSecrets", result, sender);
  }
}

/**
* check if secret has Incognito mode enabled
* @param {object} evt
*/
function checkIncognito(evt) {
  if (!((ext_default()) && (ext_default()).extension)) return;
  const data = evt.Data;
  const response = evt && evt.autoFillData && evt.autoFillData.model;
  const incognitoEnabled = response && response.webLauncherRequiresIncognitoMode;
  setIncognitoFlag(data, incognitoEnabled);
  if (incognitoEnabled) {
    ext_default().extension.isAllowedIncognitoAccess((isAllowedAccess) => {
      if (isAllowedAccess) {
        ext_default().windows.create(
          { incognito: true, url: data.secretUrl },
          async (window) => {
            if (!window) {
              sendDataToPop("showError", errors_ERR.INCOGNITO_NOT_ENABLED);
            } else {
              const secret = {
                cameFromSS: true,
                secretId: data.secretId,
                url: data.secretUrl,
                tabId: window.tabs[0].id,
              };
              await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.launchedSecret, secret);
            }
          },
        );
      } else {
        // TODO: Fix to only go to the proper place
        message_sendDataToTab("showError", errors_ERR.INCOGNITO_NOT_ENABLED);
        sendDataToPop("showError", errors_ERR.INCOGNITO_NOT_ENABLED);
      }
    });
  } else {
    ext_default().tabs.create({
      url: data && data.secretUrl,
    }, async (tab) => {
      const secret = {
        cameFromSS: true,
        secretId: data.secretId,
        url: data.secretUrl,
        tabId: tab.id,
      };
      await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.launchedSecret, secret);
    });
  }
}

/**
*  Set secret flag for webLauncherRequiresIncognitoMode in
*  LastCachedSecrets array
*  @param {object} data event data
*  @param {bool} incognitoEnabled event data
*/
async function setIncognitoFlag(data, incognitoEnabled) {
  if (data && data.secretUrl) {
    const { host } = (0,url_helpers/* parseUrl */.Dl)(data.secretUrl, false);
    const item = await cache/* lastFetchedSecretsProvider */.iF.getByHost(host);
    if (item && item.Secrets) {
      const launched = item && item.Secrets && item.Secrets.find && item.Secrets.find((s) => s.id
        == data.secretId);
      if (launched) {
        launched.incognito = incognitoEnabled;
      }
    }
    await cache/* lastFetchedSecretsProvider */.iF.add(item);
  }
}

/**
* gotTicketError
*/
function gotTicketError() {
  sendDataToTab("showError", ERR.TICKET_ERROR);
}

/**
* got PasswordError Event
* @param {object} evt event data
*/
async function gotPasswordErrorEvent(evt) {
  if (evt.detail.request && evt.detail.request.tab) {
    tabCalls[evt.detail.request.tab.id] = 0;
  }

  if (evt && evt.detail && evt.detail.Data && evt.detail.Data.message) {
    message_sendDataToTab("showError", evt.detail.Data.message);
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.launchedSecret);
  }
}

/**
 * got PasswordError Event
 * @param {object} evt event data
 */
async function gotMFAErrorEvent(mfaError) {
  if (!((ext_default()) && (ext_default()).windows)) return;
  try {
    // eslint-disable-next-line camelcase
    const { acr_values, su_token } = mfaError;
    const response = await platform_apis.getMfaDeviceCode(acr_values, su_token);
    if (response?.device_code && response?.user_code) {
      const authUrl = `${response.verification_uri}?deviceCode=${response.user_code}&app=${constants.APP_NAME}`;
      createWindow(encodeURI(authUrl), true, true);
      getPlatformToken(response, true, () => stepUpAction(mfaError));
    }
  } catch (err) {
    if (err && err.status === 410) {
      sendDataToPop('showError', errors_ERR.INVALID_SS_URL);
    } else {
      background_handleError(err);
    }
  }
}

/**
* Got password event notifies the tabs that the password was retrieved
* @param {object} e event data
*/
async function gotPasswordEvent(e) {
  const { useSessionRecording } = e.detail.dataJson.model;
  const data = e.detail.Data;
  const { secretId } = data;

  const tabDomain = (0,url_helpers/* parseUrl */.Dl)(data.url) && (0,url_helpers/* parseUrl */.Dl)(data.url).domain;
  const response = e.detail.dataJson.model;
  const incognitoEnabled = response.webLauncherRequiresIncognitoMode;
  await setIncognitoFlag(data, incognitoEnabled);
  if (incognitoEnabled) {
    logger/* default */.A.logInfo(`Incognito is enabled for secret ID ${secretId}`);
  }
  const sourceDomain = data.referrer ? data.referrer : data.url;

  const SSOUrls = await cache/* ssoUrlsProvider */.Tm.get();
  if ((0,common/* checkIfMultiDomain */.FS)(tabDomain).length > 0
    || e.detail.Data.isPasswordHiddenOnPage || e.detail.Data.isOtpHiddenOnPage) {
    if (SSOUrls.length === 0) {
      SSOUrls.push(data.tab.url);
      cache/* ssoUrlsProvider */.Tm.set(SSOUrls);
    }
    const twoStepSecret = {
      secretId,
      url: sourceDomain,
      tab: data.tab,
      SSOUrls: [...SSOUrls],
      isGenerateOneTimePasswordPresent: e.detail.Data.isGenerateOneTimePasswordPresent,
    };
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.twoStepSecret, twoStepSecret);
  }
  if (e.detail.dataJson.model) {
    const sender = e.detail.Data;
    const secretDetails = {
      ...e.detail.dataJson.model,
      sender,
    };

    const { id } = e.detail.dataJson;
    const checkedOutSecret = await cache/* checkoutSecretsStateProvider */.UY.getByID(id);
    if (!useSessionRecording && !checkedOutSecret && e.detail.dataJson.checkOutEnabled === true
      && e.detail.dataJson.checkOutMinutesRemaining > 0) {
      await cache/* checkoutSecretsStateProvider */.UY.add(e.detail.dataJson);
      // const alarmId = `checkoutTimedout_${id}`;
      // ext.alarms.create(alarmId, { delayInMinutes: e.detail.dataJson.checkOutMinutesRemaining });
      // logger.logInfo(`Alarm created with alarm id : ${alarmId} and checkout time left : ${e.detail.dataJson.checkOutMinutesRemaining}`);
      const checkInClickInterval = setInterval(() => {
        if (!isLoggedIn) {
          clearInterval(checkInClickInterval);
          // ext.alarms.clear(alarmId, () => logger.logInfo(`cleared alarm id : ${alarmId}`));
          handleCheckoutTimeout(id);
          return;
        }
        const result = (0,promise.getSecretState)(id);
        result.then((state) => {
          if (!state.isCheckedOut) {
            clearInterval(checkInClickInterval);
           //  ext.alarms.clear(alarmId, () => logger.logInfo(`Cleared alarm id : ${alarmId} after checkout time is over`));
            handleCheckoutTimeout(state.id);
          }
        }).catch(background_handleError);
      }, 30000);
    }

    const lastItem = {
      url: sender.tab.url.split("?")[0],
      secretId,
      tabid: sender.tab.id,
      useSessionRecording,
    };
    // removeArrayEle(selectionHistory, sender.tab.id);
    removeAndUpdate(sender.tab.id);
    await cache/* selectionHistoryProvider */.oA.add(lastItem);
    // selectionHistory.push(lastItem);
    if (secretId) {
      secretDetails.url = secretDetails.sender.sUrl;
      getMetadata(secretId, secretDetails, sender);
    }
  }
}

/**
* calls the API to Generate password.
* @param {object} request having templateId and slug for generating password
* @param {string} callback function name
* field if for wich password needs to be generated.
*/
function generatePassword(request, callback = passwordGeneratedEvent) {
  callAPI(
    `${endpoints/* default */.A.GENERATE_PASSWORD}/${request.templateFieldId}`,
    "post",
    "",
    tokens/* oauth */.o.access_token,
    constants.CONTENT && constants.CONTENT.APP_JSON,
    callback,
    request,
  );
}

/**
* callbacl function called after password is generated.
* @param {string} e Event Argument
*/
function passwordGeneratedEvent(e) {
  const response = {
    password: e.detail.dataJson,
  };
  if (e.detail.Data.fieldId) {
    response.fieldId = e.detail.Data.fieldId;
  }
  if((0,common/* isSafari */.nr)()){
    navigator.clipboard.writeText(response.password).then(i => console.log('copied'));
  }
  message_sendDataToTab("passwordGenerated", response);
}

/**
* User login
* @param {int} data The first number.
* @param {int} otp The first number.
*/
function userLogin(data, otp) {
  const jsonData = new URLSearchParams(data);
  callAPI(
    endpoints/* default */.A.LOGIN,
    "post",
    jsonData,
    "",
    constants.CONTENT && constants.CONTENT.APP_URL_ENCODED,
    gotTokenEvent,
    data.pincode,
    otp,
    gotLoginErrorEvent,
  );
  logger/* default */.A.logInfo(`Initiating login to ${common/* config */.$W.Url}`);
}

/**
* Get Refresh token
* @param {object} passThroughData
*/
function getRefreshToken(passThroughData) {
  const data = {
    grant_type: "refresh_token",
    refresh_token: tokens/* oauth */.o.refresh_token,
  };
  const jsonData = new URLSearchParams(data);
  callAPI(
    endpoints/* default */.A.LOGIN,
    "post",
    jsonData,
    "",
    constants.CONTENT && constants.CONTENT.APP_URL_ENCODED,
    gotRefreshTokenEvent,
    passThroughData,
    "",
    onRefreshTokenError,
    true,
  );
}

/**
* logOffUser
* @param {*} callback
*/
async function logOffUser(callback) {
  if (MFALoginWindowId > 0) {
    removeOpenedWindow(MFALoginWindowId);
  }
  sessionManager.endAllSessions();
  // recorder.stopAllSessions();
  if (tokens/* oauth */.o?.access_token) {
    callAPI(
      endpoints/* default */.A.OAUTH_EXPIRATION,
      "post",
      "",
      tokens/* oauth */.o.access_token,
      constants.CONTENT && constants.CONTENT.APP_JSON,
    );
  }
  const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
  if (serverType === constants.SERVER_TYPE.PLATFORM) {
    platform_apis.logoutPlatform();
  }
  logOff();
  const webLauncherData = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.webLauncherData);
  if (!callback || !(webLauncherData && webLauncherData.secretId)) return;
  callback(webLauncherData);
}

/**
* create secret
* @param {int} data secret data.
* @param {object} sender Sender information.
* @param {object} type type
*/
function createSecret(data, sender, type) {
  const jsonData = JSON.stringify(data);
  sender.secretTypeId = data.data.templateId;
  sender.name = data.data.name;
  if (type) {
    callAPI(
      endpoints/* default */.A.CREATE_SECRET,
      "post",
      jsonData,
      tokens/* oauth */.o.access_token,
      constants.CONTENT && constants.CONTENT.APP_JSON,
      gotSecretSaveEvent,
      sender,
      "",
      gotSecretSavePopupErrorEvent,
    );
  } else {
    callAPI(
      endpoints/* default */.A.CREATE_SECRET,
      "post",
      jsonData,
      tokens/* oauth */.o.access_token,
      constants.CONTENT && constants.CONTENT.APP_JSON,
      gotSecretSaveEvent,
      sender,
      "",
      gotSecretSaveErrorEvent,
    );
  }
}

/**
* sets the variable isLoggedIn to true and brodcast the
* message to current tab..
* max session timeout set to 2592000 (30 (days) * 24 * 60 * 60) in seconds
* @param {string} sessionTimeOut The first number.
*/
function setLoggedIn(sessionTimeOut, skipAlarm = false) {
  if (!((ext_default()) && (ext_default()).alarms)) return;
  let timeout = 0;
  let delay = 0;

  if (sessionTimeOut) {
    isLoggedIn = true;

    if(skipAlarm) return;

    if (sessionTimeOut > 2592000) {
      sessionTimeOut = 2592000;
    }
    timeout = sessionTimeOut / 60;
    delay = (timeout - 4) < (timeout * 0.5) ? timeout * 0.5 : timeout - 4;
    ext_default().alarms.create("tokenExpired", { delayInMinutes: delay });
    logger/* default */.A.logInfo(`Alarm created for token expired with ${delay}`);
  }
}

/**
 *
 */
async function handleCheckoutTimeout(secretId) {
  if (!secretId) return;
  let checkoutSecretsState = await cache/* checkoutSecretsStateProvider */.UY.get();
  if (checkoutSecretsState.length > 0) {
    const intendedSecretInfo = checkoutSecretsState.filter(
      (secretStateInfo) => secretStateInfo.id === secretId,
    ) || [];

    if (intendedSecretInfo.length === 0) return;
    ext_default().tabs.query({ url: constants.URL_PATTERN }, (tabs) => {
      for (let i = 0; i < tabs.length; i++) {
        const tabUrl = (0,url_helpers/* parseUrl */.Dl)(tabs[i].url);
        const secretUrl = (0,url_helpers/* addDefaultProtocol */.ZG)(intendedSecretInfo[0].model.url);
        if (intendedSecretInfo.length > 0
          && (0,url_helpers/* parseUrl */.Dl)(secretUrl).hostname === tabUrl.hostname) {
          remove_cookie.removeCookie(tabUrl,tabs[i].incognito);
          checkoutSecretsState = checkoutSecretsState.filter((ss) => ss.id !== secretId) || [];
          cache/* checkoutSecretsStateProvider */.UY.set(checkoutSecretsState);
          ext_default().tabs.reload(tabs[i].id);
        }
      }
    });
  }
}

ext_default().alarms.onAlarm.addListener(async (item) => {
  const webLauncherData = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.webLauncherData);
  if (item.name === "tokenExpired") {
    if (webLauncherData) {
      cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.webLauncherData);
    }
    tokenExpired();
    return;
  }
});

/**
*Toggles the ICON based on the login status.
*/
function changeToolbarIcon() {
  const action = (ext_default()).browserAction || (ext_default()).action;
  if (isLoggedIn) {
    action.setIcon({
      path: {
        16: "icons/16-icon-active.png",
        19: "icons/19-icon-active.png",
        48: "icons/48-icon-active.png",
        128: "icons/128-icon-active.png",
      },
    });
  } else {
    action.setIcon({
      path: {
        16: "icons/16-icon-inactive.png",
        19: "icons/19-icon-inactive.png",
        48: "icons/48-icon-inactive.png",
        128: "icons/128-icon-inactive.png",
      },
    });
  }
}

/**
* get token from Secret server
* @param {string} tokenValue token
* @param {string} oldToken
*/
function loginWithSS(tokenValue, oldToken) {
  let respose = {};
  if (tokenValue) {
    tokenValue = JSON.parse(tokenValue);
    respose = {
      detail: {
        dataJson: {
          token_type: "Bearer",
          access_token: tokenValue.access_token,
          refresh_token: tokenValue.refresh_token,
          expires_in: tokenValue.expires_in,
        },
      },
    };
  } else if (oldToken) {
    respose = {
      detail: {
        dataJson: {
          token_type: "Bearer",
          access_token: oldToken,
          refresh_token: "",
          expires_in: 86400,
        },
      },
    };
  } else {
    return;
  }
  gotTokenEvent(respose);
}

/**
* checkIfExists
* @param {*} request
* @param {*} sender
*/
async function checkIfExists(request, sender) {
  if (await user_permissions/* default */.A.isAddPermission()
  || await user_permissions/* default */.A.isEditPermission()) {
    const tabUrl = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url);
    const blockWebsite = await cache/* blockWebsiteProvider */.eP.get();
    const selectionHistory = await cache/* selectionHistoryProvider */.oA.get();
    if (blockWebsite.filter((site) => site === tabUrl.host).length === 0) {
      let secretId = 0;
      if (selectionHistory.length > 0) {
        const secretList = selectionHistory.filter((s) => s.tabid === sender.tab.id
          && (0,url_helpers/* parseUrl */.Dl)(s.url).domain == tabUrl.domain);
        if (secretList.length > 0) {
          secretId = parseInt(secretList[0].secretId);
        }
      }
      sender.password = request.data.password;
      sender.url = tabUrl.hostname;
      sender.reqUrl = tabUrl.origin + tabUrl.pathname + tabUrl.hash;
      sender.username = request.data.username;
      sender.secretId = secretId;
      sender.isMappingFound = request.data.isMappingFound;
      const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
      const { isUsernameChanged } = request.data;
      if (sender && twoStepSecret?.secretId === secretId) {
        sender.isGenerateOneTimePasswordPresent = twoStepSecret.isGenerateOneTimePasswordPresent;
      }
      if (secretId > 0 && !isUsernameChanged) {
        const cachedEntry = await cache/* lastFetchedSecretsProvider */.iF.findBySecretId(secretId);
        if (!cachedEntry) return;
        const item = cachedEntry.Secrets.find((p) => p.id === secretId);
        if (!item) return;
        getAutofillDetails(
          secretId,
          item.secretUrl,
          sender,
          gotSecretUserPassword,
        );
      } else {
        cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
        persistSecret(sender, false);
      }
    }
    // })
  }
}

/**
* gotUniversalToken
* @param {*} result
*/
function gotUniversalToken(json) {
  if (!(json && json.access_token)) return;
  tokens/* oauth */.o.token = json;
  getVaultInfo();
}

function stepUpAction(mfaError) {
  if (mfaError) {
    if (mfaError.fromContent === 'fromcontent') {
      const response = {
        secretId: mfaError.id,
        secretListAction: mfaError.secretListAction,
      };
      sendDataToSpecificTab('MFASecretDetails', response, mfaError.senderId);
      return;
    }
    sendDataToPop('MFASecretDetails', mfaError);
  }
}
/**
* getCommonData
* @param {*} scopeData
*/
function getCommonData(scopeData) {
  const data = {
    grant_type: "client_credentials",
    scope: scopeData || "Interactive",
  };
  return new URLSearchParams(data);
}

/**
* gotSSToken
* @param {*} result
* @param {*} vault
*/
function gotSSToken(result, vault) {
  if (!result || !vault?.connection?.url) return;
  storage/* default */.A.get("Configurations", (items) => {
    if (items && items.Configurations) {
      items.Configurations.ssUrl = (0,url_helpers/* addDefaultProtocol */.ZG)(vault?.connection?.url);
      storage/* default */.A.set({
        Configurations: items.Configurations,
      });
      common/* config */.$W.BaseURL = vault?.connection?.url;
      result.isPlatformLogin = true;
      const serverType = constants.SERVER_TYPE.PLATFORM;
      cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.serverType, serverType);
      gotTokenEvent({ detail: { dataJson: result } });
    }
  });
}

/**
* gotAllVaults
* @param {*} result
*/
function gotAllVaults(result) {
  let defaultVault = "";
  if (!(result && result.vaults)) return;
  defaultVault = result.vaults.find((x) => x.isActive && x.isDefault);
  // Throw an error vault not configured if defaultVault is undefined

  if (!defaultVault) {
    sendDataToPop("showError", errors_ERR.NO_DEFAULT_VAULT_CONFIGURED);
    return;
  }
  gotSSToken(tokens/* oauth */.o, defaultVault);
}

/**
* getVaultInfo
*/
function getVaultInfo(sender) {
  if (sender && sender.tab) {
    ext_default().tabs.remove(sender.tab.id);
  }
  platform_apis.getAllVaults()
    .then(gotAllVaults)
    .catch(background_handleError);
}

/**
* handleSwitchSS
* @param {*} request
* @param {*} sender
*/
function handleSwitchSS(request, sender) {
  setConfig(
    { url: request.appPath, ssUrl: request.appPath },
    (configurations, allowChange) => {
      if (!allowChange) return;
      common/* config */.$W.Url = request.appPath;
      request.secretServerChanged = true;
      launchSecret(request, sender);
    },
  );
}

// const isPlatform = (origin) => (origin.match(PLATFORM_DOMAIN1) || origin.match(PLATFORM_DOMAIN2));

/**
* switchLogin
*/
function switchLogin() {
  checkIfPlatformOrSS(null, (currentServerType) => {
    if (currentServerType === constants.SERVER_TYPE.PLATFORM) {
      getAutoLoginToken(common/* config */.$W.Url);
      return;
    }
    common/* config */.$W.BaseURL = common/* config */.$W.Url;
    useSecretServerLogin();
  });
}

/**
*
* @param {*} request
* @param {*} sender
*/
function launchSecret(request, sender) {
  let configUrl = "";
  const reqAppPath = new URL(request.appPath
    .replace(/\/$/, "").toLowerCase());
  if (common/* config */.$W.Url) {
    configUrl = new URL(common/* config */.$W.Url
      .replace(/\/$/, "").toLowerCase());
  }
  storage/* default */.A.get("Configurations", async (items) => {
    if (reqAppPath
      && !(reqAppPath.hostname === configUrl.hostname)
      && (items.Configurations
        && items.Configurations.fromNativeHost)) {
      return;
    }
    const urlList = request.newUrl.split(",");
    const webLauncherData = { ...request, ...sender };
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);

    if (reqAppPath
      && !(reqAppPath.hostname === configUrl.hostname) && !(request.wpfLauncherClicked)) {
         isConfigUrl = (configUrl === "") ? false : true;
      sendMessageToSpecificWindowTab(
        "confirmSwitchSecretServer",
        request,
        sender,
      );
      return;
    }
    if (urlList.length > 1) {
      request.urlList = urlList;
      sendMessageToSpecificWindowTab(
        "multipleUrl",
        request,
        sender,
      );
      return;
    }
    if (!isLoggedIn) {
      webLauncherData.loggedin = false;
      setLauncherInfo(request, webLauncherData);
      await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);
      const { origin } = configUrl;
      switchLogin(origin);
    } else {
      if (request.secretServerChanged == true) {
        webLauncherData.loggedin = false;
        setLauncherInfo(request, sender);
        await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);
        const { origin } = configUrl;
        switchLogin(origin);
        return;
      }
      messageDisplayed = false;
      const newUrl = setLauncherInfo(request, sender);
      getAutofillDetails(
        request.secretId,
        newUrl,
        sender,
        checkIncognito,
        request.wpfLauncherClicked,
      );
      if (request.Secrets && request.Secrets.length > 0) {
        pushToLastFetchedList({
          url: newUrl,
          Secrets: request.Secrets,
        });
      }
    }
  });
}

/**
* Remove the Silent SS window
* @param {*} closingwinId
*/
function removeOpenedWindow(closingwinId) {
  if (!(ext_default())?.windows?.remove) return;
  ext_default().windows.remove(closingwinId, async () => {
    checkLastError();
    // ssLoginWindowId = 0;
    // samlTabId = 0;
    // platformTabId = 0;
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginWindowId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.samlTabId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.platformTabId, 0);
    MFALoginWindowId = 0;
  });
}

/**
* Remove the Silent SS Tab
* @param {*} closingTabId
*/
function removeOpenedTab(closingTabId) {
  if (closingTabId === 0) return;
  ext_default().tabs.get(closingTabId, (tab) => {
    if (!tab) return;
  ext_default().tabs.remove(closingTabId, async () => {
    checkLastError();
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginWindowId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginTabId, 0);
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.platformTabId, 0);
    const lastFocusedTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.lastFocusedTabId);
    if (lastFocusedTabId > 0) {
      ext_default().tabs.update(lastFocusedTabId, { active: true });
    }
  });
});
}

/**
* getOtp
* @param {*} request
* @param {*} sender
*/
function getOtpDetails(request, sender, sendResponse) {
  (0,promise.getOneTimePassword)(request.secretId).then(sendResponse).catch((err) => background_handleError(err, sender));
}

/**
* getPassword
* @param {*} request
* @param {*} sender
*/
function getPassword(request, sender) {
  sender.secretId = request.secretId;
  sender.secretClicked = !request.singleSecret;
  sender.referrer = request.referrer;
  sender.selectedframeId = request.selectedframeId;
  sender.isPasswordHiddenOnPage = request.isPasswordHiddenOnPage;
  sender.isOtpHiddenOnPage = request.isOtpHiddenOnPage;
  sender.secrets = request.secrets;
  sender.secretAction = request.secretAction;
  sender.isGenerateOneTimePasswordPresent = request.isGenerateOneTimePasswordPresent;
  getAutofillDetails(request.secretId, request.url, sender);
}

/**
* Set Launcher information
* @param {object} request
* @param {object} sender
* @return {string}
*/
function setLauncherInfo(request, sender) {
  let { newUrl } = request;
  newUrl = (0,url_helpers/* addDefaultProtocol */.ZG)(newUrl);
  sender.tab = sender.tab || {};
  sender.tab.url = newUrl;
  sender.secretId = request.secretId;
  sender.secretUrl = newUrl;
  request.url = newUrl;
  return newUrl;
}

/**
* reloadOtherSSTabs
*/
async function reloadOtherSSTabs() {
  let baseUrl = common/* config */.$W.BaseURL;
  if (common/* config */.$W.BaseURL.endsWith("/")) {
    baseUrl = baseUrl.substr(0, baseUrl.length - 1);
  }
  const samlTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.samlTabId);
  ext_default().tabs.query({ url: `${baseUrl}/*` }, (tabs) => {
    tabs.forEach((tab) => {
      if (tab.id !== samlTabId) {
        if (tab.url.toLowerCase().endsWith("/samllogin.aspx")) {
          ext_default().tabs.update(tab.id, {
            url: tab.url.replace(/samllogin.aspx/ig, ""),
          }, () => {
            checkLastError();
          });
        }
      }
    });
  });
}

/**
* to change the window height and width dynamically
* @param {*} req
* @param {*} sender
*/
async function setWindowHeightWidth(req, sender) {
  const ssLoginWindowId = cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  if (sender.tab.windowId === ssLoginWindowId) {
    newWindowHeight = req.winHeight > 600 ? req.winHeight : 600;
    newWindowWidth = req.winWidth > 500 ? req.winWidth : 500;
    centerDialog(sender.tab.windowId);
  }
}

async function checkIfCurrentSSTabloggedIn(sender, sendResponse) {
  if (!(sender && sender.tab)) return;
  const tab = sender.tab;
  const urlParts = (0,url_helpers/* parseUrl */.Dl)(tab?.url);
  ext_default().cookies.getAllCookieStores((stores) => {
    stores.forEach((p) => {
      if (p.tabIds.includes(tab.id)) {
        ext_default().cookies.getAll(
          { url: urlParts?.origin, storeId: p.id  },
          (cookies) => {
            for (let i = 0; i < cookies.length; i++) {
              if (cookies[i].name === "ihawu") {
                sendResponse({
                  isCurrentSSTabloggedIn: true,
                });
              }
            }
            sendResponse({
              isCurrentSSTabloggedIn: false,
            });
        });
      }
    });
  });
}
/**
* check If SS logged In
* @param { object} tab
* @param { object} request
*/
async function checkIfSSloggedIn(tab, request) {
  if (!isLoggedIn) {
    if (!request) return;
    const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
    const urlParts = (0,url_helpers/* parseUrl */.Dl)(common/* config */.$W.BaseURL);
    ext_default().cookies.getAllCookieStores((stores) => {
      stores.forEach((p) => {
        // if (!urlParts && urlParts !== undefined && urlParts !== '') {
        if (p.tabIds.includes(tab.id)) {
          ext_default().cookies.getAll(
            { url: urlParts.origin, storeId: p.id },
            (cookies) => {
              if (!request.skipCookie) {
                for (let i = 0; i < cookies.length; i++) {
                  if (cookies[i].name === "ihawu" && cookies[i].value) {
                    let redirectUrl = common/* config */.$W.BaseURL;
                    if (urlParts.protocol.includes("https:")
                      && common/* config */.$W.BaseURL.includes("http://")) {
                      redirectUrl = common/* config */.$W.BaseURL.replace("http://", "https://");
                    }
                    useSecretServerLogin((0,url_helpers/* appendPath */.mR)(
                      redirectUrl,
                      "/AlreadyLoggedIn.aspx",
                    ));
                    return;
                  }
                }
              }
              if (tab.windowId === ssLoginWindowId) {
                setTimeout(() => {
                  centerDialog(ssLoginWindowId);
                }, 200);
              }
            },
          );
        }
      });
    });
  }
}

/**
* isTwoStepSecret
* @param {number} tabId
* @param {string} domain
* @return {bool}
*/
async function isTwoStepSecret(tabId, domain) {
  const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
  if (twoStepSecret && twoStepSecret.SSOUrls) {
    const s = twoStepSecret.SSOUrls.find((x) => (0,url_helpers/* parseUrl */.Dl)(x).domain === domain);
    if (twoStepSecret.tab.id === tabId && s) {
      return true;
    }
  }
  return false;
}

/**
* check If url exactly matches at least secret URL
* @param {object} sender
* @param { object} sendResponse
*/
async function checkExactMatch(sender, sendResponse) {
  cache/* ssoUrlsProvider */.Tm.clear();
  const tabDomain = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain;
  const SSOUrls = (0,common/* checkIfMultiDomain */.FS)(tabDomain);
  const secret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.launchedSecret);
  cache/* ssoUrlsProvider */.Tm.set(SSOUrls);
  if (secret.cameFromSS) {
    sendResponse({ urlExactMatchAvailable: true });
    return;
  }
  const tabUrl = (0,url_helpers/* cleanUrlString */.A2)(sender.tab.url);
  const urlParts = (0,url_helpers/* parseUrl */.Dl)(tabUrl);
  if (await isTwoStepSecret(sender.tab.id, urlParts.domain)
    && !sender.isContextSecretRefresh) {
    sendResponse({ urlExactMatchAvailable: true });
    return;
  }

  getSecretsByUrl(sender, (evt) => {
    gotSecretsByUrl(evt);
    const secretList = evt.detail.dataJson.model;
    const filteredList = filterSecrets(secretList, tabUrl);
    const urlExactMatchAvailable = filteredList.length > 0;
    sendResponse({ urlExactMatchAvailable });
  });
}

/**
* load Image
* @param {url} urlList url list
* @param {Callback} callback callback function
* @param {object} sender callback function
*/
async function getFavIcon(urlList, callback, sender) {
  if (sender && sender.tab) {
    // const index = search(
    //   'host',
    //   parseUrl(sender.tab.url, false).host,
    //   lastFetchedSecrets,
    // );
    const { host } = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url, false);
    const item = cache/* lastFetchedSecretsProvider */.iF.getByHost(host);
    if (!item && sender.tab.favIconUrl !== constants.ICONS.RECORDING) {
      item.favIconUrl = sender.tab.favIconUrl || urlList[0];
      await cache/* lastFetchedSecretsProvider */.iF.add(item);
      // storage.set(getCurrentContext('lastFetchedSecrets', lastFetchedSecrets));
    }
    callback.call(
      undefined,
      { success: [urlList.length > 0 ? urlList[0] : sender.tab.favIconUrl] },
    );
  } else {
    image_loader(urlList, callback);
  }
}

/**
* Align Login Dialog to Center of the screen
* @param {*} windowId
*/
async function centerDialog(windowId, newLeft, newTop) {
  if (!windowId || !(ext_default())?.windows) return;
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  ext_default().windows.getLastFocused({ windowTypes: ["normal"] }, (win) => {
    if (win.id !== ssLoginWindowId) {
      if (newWindowHeight <= 600) {
        newWindowHeight = 700;
      }
      if (newWindowWidth <= 400) {
        newWindowWidth = 900;
      }
      // const winLeft = newLeft || win.left;
      // const winTop = newTop || win.top;
      const width = Math.floor(newWindowWidth);
      const height = Math.floor(newWindowHeight);
      // const left = Math.floor(((width / 1.5)) + winLeft);
      // const top = Math.floor(((height / 1.5)) + winTop);
      ext_default().windows.get(windowId, (window) => {
        checkLastError();
        if (window) {
          ext_default().windows.update(windowId, {
            height,
            width,
            focused: true,
            state: "normal",
          });
        }
      });
    }
  });
}

/**
* use platform login
*/
function usePlatformLogin() {
  if (common/* config */.$W.Url) {
    getAutoLoginToken(common/* config */.$W.Url);
  }
}

/**
* useSecretServerLogin
* @param { string} genTokenPageUrl
*/
async function useSecretServerLogin(genTokenPageUrl) {
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  const ssLoginTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginTabId);
  if (common/* config */.$W.SamlURL && ssLoginWindowId > 0) {
    const settings = await cache/* settingsProvider */.Pj.get();
    const samlTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.samlTabId);
    ext_default().windows.get(ssLoginWindowId, (window) => {
      checkLastError();
      if (window) {
        // storage.get('Settings', (items) => {
        if (settings && settings.secretServerLoginWindow) {
          if (genTokenPageUrl) {
            ext_default().tabs.update(samlTabId, { url: genTokenPageUrl }, () => {
              checkLastError();
              setSSLoginWindow(window);
            });
          } else {
            ext_default().tabs.reload(samlTabId, () => {
              checkLastError();
              setSSLoginWindow(window);
            });
          }
        } else {
          removeOpenedWindow(ssLoginWindowId);
          createWindow(genTokenPageUrl);
        }
        // });
      } else {
        createWindow(genTokenPageUrl);
      }
    });
  } else {
    if (ssLoginTabId > 0) {
      removeOpenedTab(ssLoginTabId);
    }
    createWindow(genTokenPageUrl);
  }
}

/**
* createWindow
* @param {string} genTokenPageUrl
*/
async function createWindow(genTokenPageUrl, isPlatformWindow, isMFA) {
  const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
  // storage.get('Settings', (items) => {
  const settings = await cache/* settingsProvider */.Pj.get();
  const { width, height } = await ext_default().windows.getCurrent(); // Get current window dimensions
  if (settings && !settings.secretServerLoginWindow) {
    createTab(genTokenPageUrl);
    return;
  }
  if (ssLoginWindowId > 0) {
    return;
  }
  // ext.windows.getCurrent(function(window) {
  // console.log(window);

  const newHeight = Math.floor(height / 1.5);
  const newWidth = Math.floor(width / 1.5);
  const newTop = Math.floor((height - newHeight) / 2);
  const newLeft = Math.floor((width - newWidth) / 2);
  const windowProperty = {
    height: newHeight,
    width: newWidth,
    top: newTop,
    left: newLeft,
    url: (genTokenPageUrl
      || common/* config */.$W.SamlURL).replace(/([^:]\/)\/+/g, "$1"),
    type: "popup",
  };
  ext_default().windows.create(windowProperty, async (window) => {
    if (isPlatformWindow) {
      // platformTabId = window.tabs[0].id;
      await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.platformTabId, window.tabs[0].id);
    }
    if (isMFA) {
      setMFALoginWindow(window);
      return;
    }
    setSSLoginWindow(window, isPlatformWindow);
  });
  // });
  // });
}
/**
* createTab
* @param {*} genTokenPageUrl
*/
function createTab(genTokenPageUrl) {
  const tabProperties = {
    url: (genTokenPageUrl
      || common/* config */.$W.SamlURL).replace(/([^:]\/)\/+/g, "$1"),
  };
  ext_default().tabs.query(constants.ACTIVE_TAB_QUERY, async (tabs) => {
    if (tabs && tabs.length > 0) {
      // lastFocusedTabId = tabs[0].id;
      await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.lastFocusedTabId, tabs[0].id);
    }
    ext_default().tabs.create(
      tabProperties,
      (newTabInfo) => {
        setSSLoginTab(newTabInfo);
      },
    );
  });
}

/**
* setSSLoginWindow for new Tab
* @param {*} tab
*/
function setSSLoginTab(tab) {
  // ssLoginTabId = tab.id;
  // samlTabId = tab.id;
  cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginTabId, tab.id);
  cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.samlTabId, tab.id);
  if (!(ext_default())?.tabs?.onUpdated) return;
  ext_default().tabs.onUpdated.addListener(samlRedirect);
  sendDataToPop("removePopup", "");
}

/**
* setMFALoginWindow for new Tab
* @param {*} window
*/
function setMFALoginWindow(window) {
  MFALoginWindowId = window.id;
  const newLeft = -8;
  const newTop = -8;
  centerDialog(MFALoginWindowId, newLeft, newTop);
}

/**
* setSSLoginWindow
* @param {*} window
*/
async function setSSLoginWindow(window, isPlatformWindow) {
  await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.ssLoginWindowId, window.id);

  if (!(ext_default())?.windows) return;
  ext_default().windows.update(window.id, {
    state: "minimized",
  });
  if (window.tabs) {
    // samlTabId = window.tabs[0].id;
    cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.samlTabId, window.tabs[0].id);
    if (isPlatformWindow && window.tabs[0].windowId === window.id) {
      setTimeout(() => {
        centerDialog(window.id);
      }, 200);
      return;
    }
    checkIfSSloggedIn(window.tabs[0], { skipCookie: false });
  }
  const serverType = constants.SERVER_TYPE.SS;
  cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.serverType, serverType);
  if (!(ext_default())?.tabs?.onUpdated) return;
  ext_default().tabs.onUpdated.addListener(samlRedirect);
}

/**
* samlRedirect
* @param {*} tabId
* @param {*} changeInfo
*/
async function samlRedirect(tabId, changeInfo) {
  const samlTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.samlTabId);
  if (samlTabId === tabId && !isLoggedIn
    && changeInfo.status === "loading" && changeInfo.url) {
    const loadingUrl = changeInfo.url.toLowerCase();

    if (loadingUrl.endsWith("/samllogin.aspx")
      && common/* config */.$W.SamlPath) {
      ext_default().tabs.update(tabId, {
        url: `${changeInfo.url}?ReturnUrl=${common/* config */.$W.SamlPath}`,
      }, () => {
        checkLastError();
      });
      ext_default().tabs.onUpdated.removeListener(samlRedirect);
    } else if (loadingUrl.endsWith(twoFactorUrl)
      && common/* config */.$W.SamlPath) {
      ext_default().tabs.update(tabId, {
        url: `${changeInfo.url}&&ReturnUrl=${common/* config */.$W.SamlPath}`,
      }, () => {
        checkLastError();
      });
      ext_default().tabs.onUpdated.removeListener(samlRedirect);
    }
  }
}

const tabCalls = [];

/**
* returns true when secret are available.
* @param {object} request request
* @param {object} sender sender
* @param {object} sendResponse callback
*/
async function getSecrets(request, sender, sendResponse) {
  cache/* ssoUrlsProvider */.Tm.clear();
  const tabDomain = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain;
  let SSOUrls = (0,common/* checkIfMultiDomain */.FS)(tabDomain);

  if (request && request.justRespond) {
    getSecretsByUrl(sender, (evt) => {
      sendResponse(evt.detail.dataJson);
    });
    return;
  }

  if (request && request.referrer && SSOUrls.length > 0) {
    sender.referrer = request.referrer;
    if (!SSOUrls.includes(request.referrer)) {
      SSOUrls.push(request.referrer);
    }
    cache/* ssoUrlsProvider */.Tm.set(SSOUrls);
  }
  if ((request && request.isIconClick)
    || (request && request.isRefreshClick)
    || (request && request.isContextSecretRefresh)) {
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.launchedSecret);
  } else if (await isTwoStepSecret(sender.tab.id, tabDomain)
    && SSOUrls.length === 0) {
    const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
    SSOUrls = [...twoStepSecret.SSOUrls];
    cache/* ssoUrlsProvider */.Tm.set(SSOUrls);
  }

  // storage.get('Settings', (items) => {
  // if (items.Settings) {
  if (request && request.pageState === 1) {
   // await selectionHistoryProvider.remove(sender.tab.id);
    await cache/* addSecretArrayProvider */.IR.removeByTabId(sender.tab.id);
  }

  const isAddSecret = await isSecretCapuredInList(sender);
  const secret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.launchedSecret);
  const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
  if (secret.cameFromSS
    && secret.tabId === sender.tab.id
    && !messageDisplayed) {
    sender.secretId = secret.secretId;
    sender.secretClicked = true;
    if (!tabCalls[sender.tab.id]) {
      tabCalls[sender.tab.id] = secret.secretId;
      getAutofillDetails(secret.secretId, secret.url, sender);
    }
  } else if (SSOUrls.length > 0 && twoStepSecret?.secretId
    && !request.isUsernameChanged) {
    // for microsoft login
    twoStepSecret.tab = sender.tab;
    twoStepSecret.secretClicked = true;
    await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.twoStepSecret, twoStepSecret);
    getAutofillDetails(
      twoStepSecret.secretId,
      sender.tab.url,
      twoStepSecret,
    );
  } else if (!isAddSecret || (request && request.isIconClick)) {
    // if no secret selected, show secret list
    // if secrets > 1 else if secret = 1 autofill

    sender.showSecretPopup = request.showSecretPopup;
    sender.isCrossDomainIframe = request.isCrossDomain;
    sender.isIconClick = request.isIconClick;
    sender.isRefreshClick = request.isRefreshClick;
    sender.isUserPermission = await user_permissions/* default */.A.isAddPermission();
    sender.permissions = await user_permissions/* default */.A.getPermissions();
    if (request.eleCords) {
      sender.eleCords = request.eleCords;
    }
    const settings = await cache/* settingsProvider */.Pj.get();
    const autoPopulate = settings && (settings.set_show_popup_credential_available
      || settings.enableAutoPopulate);
    if (autoPopulate
      || request.isIconClick || request.isRefreshClick
      || request.isContextSecretRefresh) {
      if (!request.isUsernameChanged) {
        getSecretsByUrl(sender);
      }
    }
  }
  // }
  // });
  sendResponse(true);
}

/**
      * returns clears the url from the array and
      * gets the secrets again from secretserver
      * @param {object} sender sender
      * @param {object} sendResponse callback
      */
async function refreshSecretList(sender, sendResponse) {
  const { host } = (0,url_helpers/* parseUrl */.Dl)(sender.url, false);
  await cache/* lastFetchedSecretsProvider */.iF.removeByHost(host);
  const tabItem = { ...await cache/* windowsAdminCenterItemProvider */.q7.findByTabId(sender.tab.id) };
  if (tabItem.itemName) {
    await cache/* lastFetchedWinADSecretsProvider */.dH.exclude(tabItem.itemName);
  }
  if (!sendResponse) {
    removeAndUpdate(sender.tab.id);
    cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
    cache/* ssoUrlsProvider */.Tm.clear();
    getSecretsByUrl(sender, (evt) => {
      sender.isContextSecretRefresh = true;
      gotSecretsByUrl(evt);
      sendDataToSpecificTab("contextSecretRefresh", null, sender);
    });
  } else {
    sendResponse(true);
  }
}

/**
* API call for getting secrets for recent and favorites tab.
*  @param {object} request request
* @param {object} sender sender
*/
function refreshRecentAndFavorites(request, sender) {
  if (request.urls.length > 0) {
    // take last url form array and store it in variable
    // clear last fetched secrets in storage.

    const promises = [];

    for (let i = 0; i < request.urls.length; i++) {
      if (!request.urls[i]) continue;
      const urls = request.urls[i].split(",");
      for (let j = 0; j < urls.length; j++) {
        const data = JSON.stringify((0,url_helpers/* cleanUrlString */.A2)(urls[j]));
        promises.push((0,promise.searchByURL)(data));
      }
    }
    const refreshedSecrets = [];
    Promise.all(promises).then((responses) => {
      responses.forEach((response) => {
        const secretEntry = getLastSecretEntry(response);
        refreshedSecrets.push(secretEntry);
      });
      cache/* lastFetchedSecretsProvider */.iF.set(refreshedSecrets);
      sendDataToPop("refreshedSecrets", refreshedSecrets);
    }).catch((err) => {
      sendDataToPop("showError", err.message || err.error_description);
    });
  } else {
    sendDataToPop("refreshedSecrets", []);
  }
}

/**
* Remove persist Secret
* @param {object} sender
*/
function removePersistSecret(sender) {
  ext_default().tabs.get(sender && sender.tab && sender.tab.id, async (tab) => {
    checkLastError();
    if (tab) {
      await cache/* addSecretArrayProvider */.IR.removeByTabId(tab.id);
    }
  });
}

/**
* @param{string} url of main page
* when user click never
*/
async function saveForNever(url) {
  // const BlockWebSite = JSON.parse(window.localStorage.getItem('BlockWebSite') || '[]');
  // BlockWebSite.push(parseUrl(url, false).host);
  // window.localStorage.setItem('BlockWebSite', JSON.stringify(BlockWebSite));

  const blockWebsiteArray = await cache/* blockWebsiteProvider */.eP.get();
  const { host } = (0,url_helpers/* parseUrl */.Dl)(url, false);
  if (!blockWebsiteArray.includes(host)) {
    blockWebsiteArray.push(host);
    cache/* blockWebsiteProvider */.eP.set(blockWebsiteArray);
  }
}

/**
   * check whether there is secret captured in list to show
   * check if in list for Prompt to save secret
   * @param {object} sender tab details
   * @return {Boolean} true if in list else false
   */
async function isSecretCapuredInList(sender) {
  const AddSecretArray = await cache/* addSecretArrayProvider */.IR.get();
  if (AddSecretArray && AddSecretArray.length > 0) {
    const items = AddSecretArray.find((t) => {
      if (t.tabid === sender.tab.id
        && (0,url_helpers/* parseUrl */.Dl)(t.tabUrl).domain === (0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain) {
        return true;
      }
    });
    if (items) {
      return true;
    }
  }
  return false;
}

/**
   * persist data  when page redirected.
   * @param {object} request data to persist.
   * @param {Boolean} isEdit secret edit and not.
   */
async function persistSecret(request, isEdit) {
  if (!request.username || !request.password) {
    const item = await cache/* addSecretArrayProvider */.IR.findByTabId(request.tab.id);
    if (item) {
      const requestDomain = (0,url_helpers/* parseUrl */.Dl)(request.tab.url).domain;
      const existingEntryDomain = (0,url_helpers/* parseUrl */.Dl)(item.tabUrl).domain;
      if (requestDomain === existingEntryDomain
        || ((0,common/* checkIfMultiDomain */.FS)(existingEntryDomain).length > 0
          && (0,common/* checkIfMultiDomain */.FS)(requestDomain).length > 0)) {
        request.username = (request.username
          ? request.username : item.data.username);
        request.password = request.password;
      }
    }
  }
  await cache/* addSecretArrayProvider */.IR.removeByTabId(request.tab.id);
  await cache/* addSecretArrayProvider */.IR.add({
    tabid: request.tab.id,
    tabUrl: request.tab.url,
    data: request,
    isEdit,
  });
  if (request.username && request.password) {
    notifyCS(request);
  }
}

/**
* sends new secret add notification with data to contentscript.
* @param {object} sender requestor info.
*/
function notifyCS(sender) {
  ext_default().tabs.get(sender.tab.id, (tab) => {
    checkLastError();
    if (tab && tab.status !== "complete") {
      let domainChanged = false;
      if (!(ext_default())?.tabs?.onUpdated?.addListener) return;
      ext_default().tabs.onUpdated.addListener(async function listener(tabId, info) {
        if (isLoggedIn && tabId === tab.id) {
          if (info.status === "loading" && info.url) {
            if ((0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain !== (0,url_helpers/* parseUrl */.Dl)(info.url).domain) {
              domainChanged = true;
              await cache/* addSecretArrayProvider */.IR.removeByTabId(sender.tab.id);
            }
          } else if (info.status === "complete") {
            ext_default().tabs.onUpdated.removeListener(listener);
          }
        }
      });
      if (!(ext_default())?.webNavigation?.onCompleted?.addListener) return;
      ext_default().webNavigation.onCompleted.addListener(function navigate(details) {
        if (isLoggedIn && details.tabId === tab.id) {
          if (!domainChanged) {
            promptUser(tab);
          }
          ext_default().webNavigation.onCompleted.removeListener(navigate);
        }
      });
    } else {
      if (!(ext_default())?.tabs?.onUpdated?.addListener) return;
      ext_default().tabs.onUpdated.addListener(function onUrlChange(tabId, info) {
        if (isLoggedIn && info.status === "complete" && sender.tab.id === tabId) {
          promptUser(tab);
          ext_default().tabs.onUpdated.removeListener(onUrlChange);
        }
      });
      promptUser(tab);
    }
  });
}

/**
   * sends new secret add notification with data to contentscript.
   * @param {object} tab requestor info.
   */
async function promptUser(tab) {
  const secretdata = await cache/* addSecretArrayProvider */.IR.findByTabId(tab.id);
  if (secretdata && secretdata.data
    && secretdata.data.username && secretdata.data.password) {
    const tabDomain = (0,url_helpers/* parseUrl */.Dl)(tab.url).domain;
    const existingDomain = (0,url_helpers/* parseUrl */.Dl)(secretdata.tabUrl).domain;
    if (!await user_permissions/* default */.A.isAddPermission() && secretdata.isEdit === false) return;
    if (!await user_permissions/* default */.A.isEditPermission() && secretdata.isEdit === true) return;
    if (existingDomain === tabDomain
      || ((0,common/* checkIfMultiDomain */.FS)(existingDomain).length > 0
        && (0,common/* checkIfMultiDomain */.FS)(tabDomain).length > 0)) {
      const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
      ext_default().tabs.sendMessage(tab.id, {
        response: secretdata,
        method: "notify",
        serverType,
        url: common/* config */.$W.Url,
      }, { frameId: 0 }, () => {
        checkLastError();
      });
    }
  }
}

ext_default().contextMenus.onClicked.addListener((info, tab) => {
  if (tab) {
    const sender = {
      tab,
      url: tab.url,
    };
    if (info.menuItemId === "Id_AddSecret") {
      getTemplatesNFolders(sender, null);
      return;
    }
    if (info.menuItemId === "Id_RefreshSecrets") {
      refreshSecretList(sender, null);
      return;
    }
    if (info.menuItemId === "Id_GeneratePassword") {
      const pwd = generatePasswordLocally();
      if((0,common/* isSafari */.nr)()){
        navigator.clipboard.writeText(pwd).then(i => console.log('copied'));
      }
      message_sendDataToTab("passwordGenerated", { password: pwd });
      return;
    }
    ext_default().tabs.sendMessage(
      tab.id,
      {
        method: "contextSecretClicked",
        secretId: info.menuItemId,
        seretUrl: info.pageUrl,
        singleSecret: false,
      },
    );
  }
});

function getMetadataBody(mapping, sectionId) {
  const data = {
    Data: {
      metadataFieldId: null,
      metadataFieldSectionRequiresEntityEdit: false,
      metadataFieldSectionRequiresAdministerMetadata: false,
      metadataFieldName: mapping.fieldName,
      fieldDataType: "String",
      metadataFieldSectionId: sectionId || null,
      metadataFieldSectionName: constants.WPF_HINTS_SECTION,
      valueString: mapping.xpath,
      valueBit: null,
      valueDateTime: null,
      valueNumber: null,
      valueInt: null,
    },
  };

  return JSON.stringify(data);
}

/**
* insertMetadata
* @param {*} secretId
* @param {*} mappings
* @param {*} passThroughData
*/
async function insertMetadata(secretId, mappings) {
  if (!mappings?.length) return;
  try {
    const metadata = mappings.filter((x) => x.fieldName && x.xpath);
    if (metadata.length === 0) return;
    const metadataSection = await (0,promise.getMetadataFieldSections)();
    const section = getWPFHintSection(metadataSection);
    let sectionId = section?.metadataFieldSectionId;
    if (!sectionId) {
      // on the first mapping WPFHints section will be created here
      const body = getMetadataBody(metadata[0], null);
      const metadataResponse = await (0,promise.postMetadata)(secretId, body);
      sectionId = metadataResponse.metadataFieldSectionId;
      metadata.splice(0, 1);
    }
    const promises = [];
    metadata.forEach((mapping) => {
      const body = getMetadataBody(mapping, sectionId);
      promises.push((0,promise.postMetadata)(secretId, body));
    });

    await Promise.all(promises);
    logger/* default */.A.logInfo(`Metadata saved for secretId:${secretId}`);
  } catch (error) {
    logger/* default */.A.logError(error);
    message_sendDataToTab("showError", errors_ERR.METADATA_SECTION_ACCESS_DENIED);
  }
}

function getWPFHintSection(result) {
  const { records } = result;
  return records.find((x) => x.metadataFieldSectionName === constants.WPF_HINTS_SECTION);
}

/**
   * getMetadata
   * @param {number} secretId
   * @param {object} passThroughData
   * @param {object} sender
   */
async function getMetadata(secretId, passThroughData, sender, callback) {
  callAPI(
    endpoints/* default */.A.get_metadata(secretId),
    "get",
    "",
    tokens/* oauth */.o.access_token,
    constants.CONTENT.APP_JSON,
    callback ?? gotMetadata,
    passThroughData,
    "",
    gotMetadataError,
  );
}

function gotMetadataError(evt) {
  if (evt.detail.Data.error === "404") {
    const output = {
      detail: {
        Data: evt.detail.request,
        dataJson: {
          records: [],
        },
      },
    };
    gotMetadata(output);
  }
}

/**
* Create context menu  with secret
* which will for create contextm menu.
* @param {string} secretList secret list.
* @param {string} showGenPWD generated Password
*/
function createSecretMenu(secretList) {
  if (secretList && secretList.length > 0) {
    ext_default().contextMenus.create({
      type: "separator",
      id: "separator",
      title: "separator",
      contexts: ["all"],
    });
    secretList.forEach((secret) => {
      ext_default().contextMenus.create({
        id: secret.id.toString(),
        title: secret.name,
        contexts: ["all"],
      });
    });
  }
}

/**
* Create context menu  with secret
* which will for create contextm menu.
* @param {string} isPassword secret list.
*/
async function createContextMenu(isPassword) {
  if (await user_permissions/* default */.A.isAddPermission()) {
    ext_default().contextMenus.create({
      id: "Id_AddSecret",
      title: constants.PERMISSIONS.AddSecret,
      contexts: ["all"],
    });
  }
  ext_default().contextMenus.create({
    id: "Id_RefreshSecrets",
    title: "Refresh Secrets",
    contexts: ["all"],
  });
  ext_default().contextMenus.create({
    id: "Id_GeneratePassword",
    title: "Generate Password",
    contexts: ["editable"],
    visible: isPassword,
  });
}

async function checkIfPlatformLoginPage(sender, sendResponse) {
  if (sender.tab && sender.tab.url) {
    const obj= (0,url_helpers/* parseUrl */.Dl)(sender.tab.url);
    const platformLoginPagePathname = '/view/auth/';
    if(obj.pathname.startsWith(platformLoginPagePathname)) {
      sendResponse({isPlatformLoginPage : true});
    } else {
      sendResponse({isPlatformLoginPage : false});
    }
  }
}

/**
* check for Cross Domain IFrames
* @param {object} sender request url
* @return {bool}
*/
function checkForCrossDomain(sender) {
  const rootDomain = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url).domain;
  const frameDomain = (0,url_helpers/* parseUrl */.Dl)(sender.url).domain;
  let isCrossDomainRequest = false;
  if (rootDomain !== frameDomain) {
    isCrossDomainRequest = true;
  }
  const result = {};
  result.isCrossDomain = isCrossDomainRequest;
  result.rootDomain = rootDomain;
  result.frameDomain = frameDomain;
  sendMessageToSpecificWindowTab("showConfirmDialog", result, sender);
  return true;
}

/**
* openAddSecretPopup
* @param {*} method
* @param {*} result
*/
function openAddSecretPopup() {
  if (!((ext_default()) && (ext_default()).tabs)) return;
  sendDataToPop("removePopup", "");
  ext_default().tabs.query(constants.ACTIVE_TAB_QUERY, (tabs) => {
    if ((ext_default()).runtime.lastError) { /* empty */ }
    if (tabs.length > 0) {
      const sender = {
        tab: tabs[0],
        url: tabs[0].url,
      };
      getTemplatesNFolders(sender, null);
    }
  });
}

/**
* Handle Error
* @param {object} error event data
*/
function background_handleError(error, sender) {
  if (!(error && (error.message || error.error_description))) return;
  if (error && error.message && error.message.includes("expired token")) return;
  if (sender && sender.tab && !sender.wpfLauncherClicked) {
    message_sendDataToTab("showError", error.message || error.error_description);
  } else {
    sendDataToPop("showError", error.message || error.error_description);
  }
}

/**
* checkIfSSUrl
* @param {*} sendResponse
*/
function checkIfSSUrl(sendResponse) {
  (0,promise.healthCheck)(common/* config */.$W.Url + endpoints/* default */.A.CHECK_SS).then((responseJson) => {
    if ("serviceBusHealthy" in responseJson) {
      current_context/* default */.A.setCloud(true);
    } else {
      current_context/* default */.A.setCloud(false);
    }
    if (responseJson.healthy) {
      const serverType = constants.SERVER_TYPE.SS;
      cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.loggedInURLType, { url: common/* config */.$W.Url,
        server_type: serverType});
      cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.serverType, constants.SERVER_TYPE.SS);
      common/* config */.$W.BaseURL = common/* config */.$W.Url;
      setConfig(
        { url: common/* config */.$W.Url, ssUrl: common/* config */.$W.Url },
        () => sendResponse(serverType),
      );
    } else {
      sendDataToPop("showSsConfigError", "Invalid SS URL");
    }
  }).catch((err) => {
    if (err.message == "Failed to fetch") {
      sendDataToPop("showSsConfigError", "Invalid SS URL");
      return;
    }
    if (navigator.userAgent.indexOf("Safari") !== -1 && err.message == "Load failed") {
      sendDataToPop("showSsConfigError", "Safari General Error");
      return;
    }
    if (err.message == "NetworkError when attempting to fetch resource." || err.message == "Load failed") {
      sendDataToPop("showSsConfigError", "Server is not reachable");
      return;
    }
    sendDataToPop("showSsConfigError", "Invalid SS URL");
  });
}

/**
* Checks if URL is of Platform Server or Secret server
* @param {*} sender
* @param {*} sendResponse
*/
function checkIfPlatformOrSS(sender, sendResponse) {
  if (!common/* config */.$W.Url) return;
  (0,promise.platformHealthCheck)(common/* config */.$W.Url + endpoints/* default */.A.CHECK_PLATFORM)
    // .platform.getPlatformCheck(config.Url)
    .then((response) => response.text())
    .then((responseText) => {
      if (responseText === "Healthy") {
        const serverType = constants.SERVER_TYPE.PLATFORM;
        cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.loggedInURLType, { url: common/* config */.$W.Url,
          server_type: serverType});
        cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.serverType, serverType);
        // here we should have native messaging check
        current_context/* default */.A.setCloud(true);
        setConfig({ url: common/* config */.$W.Url }, () => sendResponse(serverType));
        return;
      }
      checkIfSSUrl(sendResponse);
    }).catch(() => {
      checkIfSSUrl(sendResponse);
    });
}

/**
* Checks if URL is of Platform Server or Secret server
* @param {*} sender
* @param {*} sendResponse
*/
async function checkWPFServerType(sender, sendResponse) {
  const serverType = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.serverType);
  if (sender?.tab?.url) {
    sendResponse(serverType);
  }
}

function getPlatformToken(response, isMFA, callback) {
  const pollDeviceAuth = setInterval(async () => {
    const platformTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.platformTabId);
    const ssLoginTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginTabId);
    try {
      if (isLoggedIn && !isMFA) {
        clearInterval(pollDeviceAuth);
        return;
      }
      const data = {
        grant_type: 'device_code',
        client_id: constants.CLIENT_ID,
        device_code: response.device_code,
      };
      const tokenResponse = await platform_apis.getPlatformToken(data);
      if (tokenResponse?.access_token) {
        tokens/* oauth */.o.token = tokenResponse;
        // eslint-disable-next-line no-param-reassign
        isMFA = false;
        tokens/* oauth */.o.token = tokenResponse;
        clearInterval(pollDeviceAuth);
        removeOpenedTab(platformTabId || ssLoginTabId);
        if (callback) {
          gotTokenEvent({ detail: { dataJson: tokenResponse, skipCurrent: true } });
          callback();
          return;
        }
        getVaultInfo();
      }
    } catch (ex) {
      if (ex?.error && ex.error !== 'authorization_pending') {
        clearInterval(pollDeviceAuth);
        logger/* default */.A.logError(ex.error_description);
        removeOpenedTab(platformTabId || ssLoginTabId);
      }
    }
  }, 5000);
}

/**
 * getAutoLoginToken
 *
 */
async function getAutoLoginToken() {
  if (isLoggedIn) return;
  try {
    const response = await platform_apis.getDeviceCode();
    if (response?.device_code && response?.user_code) {
      const authUrl = `${response.verification_uri}?deviceCode=${response.user_code}&app=${constants.APP_NAME}`;
      createWindow(encodeURI(authUrl), true);
      getPlatformToken(response);
    }
  } catch (err) {
    if (err && err.status === 410) {
      sendDataToPop('showError', errors_ERR.INVALID_SS_URL);
    } else {
      background_handleError(err);
    }
  }
}
/**
* getMFAChallenge
* @param {*} request
* @param {*} sender
*/
function getMFAChallenge(request, sender, sendResponse) {
  (0,promise.getSecretById)(request.secretId).then(sendResponse).catch((err) => {
    if (err && err.acr_values && err.su_token) {
      err.actionName = request.actionName;
      err.id = request.secretId;
      err.fromContent = request.fromContent;
      err.senderId = sender;
      err.secretListAction = request.secretListAction;
      gotMFAErrorEvent(err);
    } else {
      background_handleError(err, sender);
    }
  });
}

/**
* getMFAChallenge
* @param {*} request
* @param {*} sender
*/
function handlelaunchSecret(request, ls, sender) {
  let url = request.multiUrl || ls.secretUrl || ls.url;
  url = (0,url_helpers/* addDefaultProtocol */.ZG)(url);
  const newReq = {
    newUrl: url.split(",")[0],
    appPath: common/* config */.$W.Url,
    secretId: ls.id || request.secretId,
    wpfLauncherClicked: request.wpfLauncherClicked,
  };

  launchSecret(newReq, sender);
}

const methodsWithResponse = [
  "checkExactMatch",
  "DoIExcluded",
  "UserLogin",
  "checkIfSecretServer",
  "otpOnNextPage",
  "checkIfPlatformServer",
  "checkWPFServerType",
  "usePlatformLogin",
  "useSSLogin",
  "getSecretState",
  "getSecretById",
  "getFolderPath",
  "getTicketSystem",
  "getFavIcon",
  "loginMFAChallenge",
  "IsUserLoggedIn",
  "IsLoggedIn",
  "searchSecrets",
  "pageResult",
  "LogOffUser",
  "sessionTabCount",
  "checkIfPlatformOrSS",
  "getPermissions",
  "GetOtp",
  constants.secretStates.requiresComment,
  constants.secretStates.requiresCheckoutAndComment,
  constants.secretStates.requiresCheckout,
  "GetSecrets",
  "GetTemplatesNFolders",
  "refreshSecretList",
  "refreshClicked",
  "isSessionActive",
  "GetMetadata",
  "checkIfCurrentSSTabloggedIn",
  "checkIfPlatformLoginPage",
  "havingConfigUrl"
];

ext_default().runtime.onMessage.addListener(
  (request, sender, sendResponse) => {
    // console.log('background script: ', request.method, { request });
    checkLastError();
    storage/* default */.A.get("Configurations", async (items) => {
      if (items && items.Configurations && items.Configurations.url) {
        common/* config */.$W.BaseURL = items.Configurations.ssUrl;
        common/* config */.$W.Url = items.Configurations.url;
      }
      if (request.method === "checkExactMatch" && sender.tab) {
        sender.isContextSecretRefresh = request.isContextSecretRefresh;
        checkExactMatch(sender, sendResponse);
      } else if (request.method === "DoIExcluded" && sender.tab) {
        checkExcluded(sender.tab.url, sendResponse);
      } else if (request.method === "UserLogin") {
        const webLauncherData = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.webLauncherData);
        if (webLauncherData && webLauncherData.loggedin === false) {
          webLauncherData.loggedin = true;
          await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);
        }
        userLogin(request.data, request.otp);
        sendResponse(true);
      } else if (request.method === "closeSSWindow") {
        const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
        const ssLoginTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginTabId);
        if (ssLoginWindowId > 0) {
          removeOpenedWindow(ssLoginWindowId);
        }
        if (ssLoginTabId > 0) {
          removeOpenedTab(ssLoginTabId);
        }
        if (MFALoginWindowId > 0) {
          removeOpenedWindow(MFALoginWindowId);
        }
      } else if (request.method === "SSLoggedIn") {
        reloadOtherSSTabs();
      } else if (request.method === "checkIfSecretServer") {
        checkIfSecretServer(sender, sendResponse);
      } else if (request.method === "otpOnNextPage") {
        otpOnNextPage(sender, sendResponse);
      } else if (request.method === "checkIfPlatformServer") {
        checkIfPlatformServer(sender, sendResponse);
      } else if (request.method === "checkWPFServerType") {
        checkWPFServerType(sender, sendResponse);
      } else if (request.method === "checkIfCurrentSSTabloggedIn") {
        checkIfCurrentSSTabloggedIn(sender, sendResponse);
      } else if (request.method === "checkIfSSLoggedIn") {
        checkIfSSloggedIn(sender.tab, request);
      } else if (request.method === "checkIfPlatformLoginPage") {
        checkIfPlatformLoginPage(sender, sendResponse);
      } else if (request.method === "GetMetadata") {
        // debugger;
        getMetadata(request.secretId, request.passThroughData, sender, (response) => {
          sendResponse(response);
        });
      } else if (request.method === "usePlatformLogin") {
        usePlatformLogin(sender);
        sendResponse(true);
      } else if (request.method === "useSSLogin") {
        const webLauncherData = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.webLauncherData);
        if (webLauncherData && webLauncherData.loggedin === false) {
          webLauncherData.loggedin = true;
          await cache/* commonCacheProvider */.FJ.set(cache/* cacheKeys */.Xr.webLauncherData, webLauncherData);
        }
        useSecretServerLogin();
        sendResponse(true);
      } else if (request.method === "getSecretState") {
        if(request.secretId){
        (0,promise.getSecretState)(request.secretId).then(sendResponse)
          .catch((err) => background_handleError(err, sender));
        }
      } else if (request.method === "getSecretById") {
        (0,promise.getSecretById)(request.secretId).then(sendResponse).catch((err) => background_handleError(err, sender));
      } else if (request.method === "getFolderPath") {
        (0,promise.getFolderPath)(request.folderId).then(sendResponse).catch((err) => background_handleError(err, sender));
      } else if (request.method === "getTicketSystem") {
        (0,promise.getTicketSystem)().then(sendResponse).catch((err) => background_handleError(err, sender));
      } else if (request.method === "getFavIcon") {
        getFavIcon(request.urls, sendResponse, sender);
      } else if (request.method === "loginMFAChallenge") {
        if (MFALoginWindowId > 0) {
          removeOpenedWindow(MFALoginWindowId);
        }
        getMFAChallenge(request, sender, sendResponse);
      } else if (request.method === "logoutFromContent") {
        if (request.serverName === constants.SERVER_TYPE.SS) {
          onSSLogOff();
        } else {
          logOffUser();
        }
      } else if (request.method === "IsUserLoggedIn") {
        const isUserPermission = await user_permissions/* default */.A.isAddPermission();
        sendResponse({
          isLoggedIn,
          loggedInUserId,
          isUserPermission,
        });
      } else if (request.method === "IsLoggedIn") {
        sendMessage("loggedIn", isLoggedIn);
        sendResponse({ isLoggedIn });
      } else if (request.method === "searchSecrets") {
        provider.searchSecrets(request, sendResponse);
      } else if (request.method === "pageResult") {
        provider.pageResult(request, sendResponse);
      } else if (request.method === "getLogs") {
        const logs = await logger/* default */.A.getLogs();
        sendDataToPop("logs", logs);
      } else if (request.method === "setLogWhenDiagnosticLogEnable") {
        logger/* default */.A.logInfo(`Logging Enabled for: ${request.message}`);
      } else if (request.method === "login_tab") {
        launchSecret(request, sender);
      } else if (request.method === "launchSecret") {
        provider.launchSecret(request, (ls) => handlelaunchSecret(request, ls, sender));
      } else if (request.method === "LogOffUser") {
        countRecordedUrls().then((tabCount) => {
          if (tabCount > 0 && !request.checkActiveSession) {
            sendDataToPop("showLogoutDialog", tabCount);
            return;
          }
          logOffUser(sendResponse);
        });

        if (!request.isSwitchSS) {
          cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.webLauncherData);
        }
      } else if (request.method === "sessionTabCount") {
        getSessionTabCount(sendResponse);
      } else if (request.method === "havingConfigUrl") {
        sendResponse({
          isConfigUrl,
          isLoggedIn
        });
      } else if (request.method === "switch-ss") {
        logOffUser((result) => handleSwitchSS(result, sender));
      } else if (request.method === "GetGenToken") {
        loginWithSS(request.token, request.oldToken, sender);
        const ssLoginWindowId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginWindowId);
        const ssLoginTabId = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.ssLoginTabId);
        if (sender.tab.windowId === ssLoginWindowId) {
          removeOpenedWindow(sender.tab.windowId);
        } else if (sender.id && sender.tab.id === ssLoginTabId) {
          removeOpenedTab(sender.tab.id);
        }
      } else if (request.method === "getWindowWidthAndHeight") {
        setWindowHeightWidth(request, sender);
      } else if (request.method === "isSessionActive") {
        sendResponse(sessionManager.isSessionActive());
      } else if (request.method === "checkIfPlatformOrSS") {
        checkIfPlatformOrSS(sender, sendResponse);
      } else if (isLoggedIn) {
        switch (request.method) {
          case "getPermissions": {
            const permissions = await user_permissions/* default */.A.getPermissions();
            sendResponse(permissions);
            break;
          }
          case "lastClickedElement":
            reloadContextMenus(request);
            break;
          case "PageRedirect":
            promptUser(sender.tab);
            break;
          case "GetPassword":
            getPassword(request, sender);
            break;
          case "GeneratePassword":
            generatePassword(request);
            break;
          case "GetOtp":
            getOtpDetails(request, sender, sendResponse);
            break;
          case "openAddSecretPopup":
            openAddSecretPopup("showAddSecretPopup", "");
            break;
          case "createSecret":
            if (isLoggedIn) {
              sender.mappingInfo = request.mappingInfo;
              await cache/* addSecretArrayProvider */.IR.removeByTabId(sender.tab.id);
              createSecret(request.data, sender, request.type);
            }
            break;
          case constants.secretStates.requiresComment:
            state_handler.addComment(request, sender, sendResponse);
            break;
          case constants.secretStates.requiresCheckoutAndComment:
            state_handler.commentAndCheckoutSecret(request, sender, sendResponse);
            break;
          case constants.secretStates.requiresCheckout:
            state_handler.checkoutSecret(request, sender, sendResponse);
            break;
          case "GetSecrets":
            sender.iframeId = request.iframeId;
            sender.isPasswordHiddenOnPage = request.isPasswordHiddenOnPage;
            sender.isOtpHiddenOnPage = request.isOtpHiddenOnPage;
            getSecrets(request, sender, sendResponse);
            break;
          case "GetTemplatesNFolders":
            getTemplatesNFolders(sender, sendResponse);
            break;
          case "UpdateSecretPassword":
            if (isLoggedIn) {
              updateSecretPassword(request.data, request.secretId, sender);
            }
            break;
          case "CheckIfExists":
            checkIfExists(request, sender);
            break;
          case "RemovePersistedData":
            removePersistSecret(sender);
            break;
          case "SaveForNever":
            saveForNever(sender.tab.url);
            break;
          case "isCrossDomain":
            checkForCrossDomain(sender);
            break;
          case "otpSet": {
            const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
            if (twoStepSecret?.secretId) {
              cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
            }
            break; }
          case "PasswordSet": {
            const twoStepSecret = await cache/* commonCacheProvider */.FJ.get(cache/* cacheKeys */.Xr.twoStepSecret);
            if (twoStepSecret && twoStepSecret.isGenerateOneTimePasswordPresent) return;
            const { domain } = (0,url_helpers/* parseUrl */.Dl)(sender.tab.url);
            if (twoStepSecret && (0,common/* checkIfMultiDomain */.FS)(domain).length > 0) {
              cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
            } else if (await isTwoStepSecret(sender.tab.id, domain)) {
              cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.twoStepSecret);
            }
            cache/* commonCacheProvider */.FJ.clear(cache/* cacheKeys */.Xr.launchedSecret);
            break; }
          case "clearContextMenu":
            ext_default().tabs.query(constants.ACTIVE_TAB_QUERY, (tabs) => {
              ext_default().tabs.sendMessage(tabs[0].id, {
                method: "removeMouseDown",
              }, () => {
                checkLastError();
              });
              ext_default().contextMenus.removeAll();
            });
            break;
          case "lastClickedItem":
            // removeArrayEle(selectionHistory, sender.tab.id);
            removeAndUpdate(sender.tab.id);
            await cache/* windowsAdminCenterItemProvider */.q7.removeByTabId(sender.tab.id);
            cache/* windowsAdminCenterItemProvider */.q7.add({
              url: sender.tab.url,
              tabId: sender.tab.id,
              itemName: request.data,
            });
            break;
          case "showCopyToClipBoardMsg":
            sendMessageToSpecificWindowTab(
              "retshowCopyToClipBoardMsg",
              "",
              sender,
            );
            break;
          case "removeHostDiv":
            sendMessageToSpecificWindowTab("retRemoveHostDiv", "", sender);
            break;
          case "refreshSecretList":
            refreshSecretList(sender, sendResponse);
            break;
          case "refreshClicked":
            if (provider === oldWay) {
              refreshRecentAndFavorites(request, sender);
            } else {
              provider.refreshSecrets(request, sendResponse);
            }
            break;
          default:
            break;
        }
      }
    });
    if (methodsWithResponse.includes(request.method)) {
      return true;
    }
  },
);

})();

/******/ })()
;
//# sourceMappingURL=background.js.map