/*!
* M365 Moray Extensions v1.145.0
* MWF (Moray) v2.8.1
* Copyright (c) Microsoft Corporation. All rights reserved.
* Copyright 2011-2020 The Bootstrap Authors and Twitter, Inc.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.m365 = {}));
})(this, (function (exports) { 'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global$B =
// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
// eslint-disable-next-line no-new-func -- fallback
(function () { return this; })() || Function('return this')();
var objectGetOwnPropertyDescriptor = {};
var fails$J = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
var fails$I = fails$J;
// Detect IE8's incomplete defineProperty implementation
var descriptors = !fails$I(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
var fails$H = fails$J;
var functionBindNative = !fails$H(function () {
// eslint-disable-next-line es/no-function-prototype-bind -- safe
var test = (function () { /* empty */ }).bind();
// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test != 'function' || test.hasOwnProperty('prototype');
});
var NATIVE_BIND$4 = functionBindNative;
var call$q = Function.prototype.call;
var functionCall = NATIVE_BIND$4 ? call$q.bind(call$q) : function () {
return call$q.apply(call$q, arguments);
};
var objectPropertyIsEnumerable = {};
var $propertyIsEnumerable$2 = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$6 = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor$6 && !$propertyIsEnumerable$2.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor$6(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable$2;
var createPropertyDescriptor$6 = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var NATIVE_BIND$3 = functionBindNative;
var FunctionPrototype$3 = Function.prototype;
var call$p = FunctionPrototype$3.call;
var uncurryThisWithBind = NATIVE_BIND$3 && FunctionPrototype$3.bind.bind(call$p, call$p);
var functionUncurryThisRaw = NATIVE_BIND$3 ? uncurryThisWithBind : function (fn) {
return function () {
return call$p.apply(fn, arguments);
};
};
var uncurryThisRaw$1 = functionUncurryThisRaw;
var toString$m = uncurryThisRaw$1({}.toString);
var stringSlice$c = uncurryThisRaw$1(''.slice);
var classofRaw$2 = function (it) {
return stringSlice$c(toString$m(it), 8, -1);
};
var classofRaw$1 = classofRaw$2;
var uncurryThisRaw = functionUncurryThisRaw;
var functionUncurryThis = function (fn) {
// Nashorn bug:
// https://github.com/zloirock/core-js/issues/1128
// https://github.com/zloirock/core-js/issues/1130
if (classofRaw$1(fn) === 'Function') return uncurryThisRaw(fn);
};
var uncurryThis$M = functionUncurryThis;
var fails$G = fails$J;
var classof$c = classofRaw$2;
var $Object$4 = Object;
var split$3 = uncurryThis$M(''.split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails$G(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !$Object$4('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof$c(it) == 'String' ? split$3(it, '') : $Object$4(it);
} : $Object$4;
// we can't use just `it == null` since of `document.all` special case
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
var isNullOrUndefined$b = function (it) {
return it === null || it === undefined;
};
var isNullOrUndefined$a = isNullOrUndefined$b;
var $TypeError$j = TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible$d = function (it) {
if (isNullOrUndefined$a(it)) throw $TypeError$j("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var IndexedObject$4 = indexedObject;
var requireObjectCoercible$c = requireObjectCoercible$d;
var toIndexedObject$d = function (it) {
return IndexedObject$4(requireObjectCoercible$c(it));
};
var documentAll$2 = typeof document == 'object' && document.all;
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
var IS_HTMLDDA = typeof documentAll$2 == 'undefined' && documentAll$2 !== undefined;
var documentAll_1 = {
all: documentAll$2,
IS_HTMLDDA: IS_HTMLDDA
};
var $documentAll$1 = documentAll_1;
var documentAll$1 = $documentAll$1.all;
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
var isCallable$u = $documentAll$1.IS_HTMLDDA ? function (argument) {
return typeof argument == 'function' || argument === documentAll$1;
} : function (argument) {
return typeof argument == 'function';
};
var isCallable$t = isCallable$u;
var $documentAll = documentAll_1;
var documentAll = $documentAll.all;
var isObject$o = $documentAll.IS_HTMLDDA ? function (it) {
return typeof it == 'object' ? it !== null : isCallable$t(it) || it === documentAll;
} : function (it) {
return typeof it == 'object' ? it !== null : isCallable$t(it);
};
var global$A = global$B;
var isCallable$s = isCallable$u;
var aFunction = function (argument) {
return isCallable$s(argument) ? argument : undefined;
};
var getBuiltIn$d = function (namespace, method) {
return arguments.length < 2 ? aFunction(global$A[namespace]) : global$A[namespace] && global$A[namespace][method];
};
var uncurryThis$L = functionUncurryThis;
var objectIsPrototypeOf = uncurryThis$L({}.isPrototypeOf);
var getBuiltIn$c = getBuiltIn$d;
var engineUserAgent = getBuiltIn$c('navigator', 'userAgent') || '';
var global$z = global$B;
var userAgent$6 = engineUserAgent;
var process$3 = global$z.process;
var Deno$1 = global$z.Deno;
var versions = process$3 && process$3.versions || Deno$1 && Deno$1.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent$6) {
match = userAgent$6.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent$6.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
var engineV8Version = version;
/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION$3 = engineV8Version;
var fails$F = fails$J;
// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
var symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails$F(function () {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && V8_VERSION$3 && V8_VERSION$3 < 41;
});
/* eslint-disable es/no-symbol -- required for testing */
var NATIVE_SYMBOL$6 = symbolConstructorDetection;
var useSymbolAsUid = NATIVE_SYMBOL$6
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
var getBuiltIn$b = getBuiltIn$d;
var isCallable$r = isCallable$u;
var isPrototypeOf$7 = objectIsPrototypeOf;
var USE_SYMBOL_AS_UID$1 = useSymbolAsUid;
var $Object$3 = Object;
var isSymbol$5 = USE_SYMBOL_AS_UID$1 ? function (it) {
return typeof it == 'symbol';
} : function (it) {
var $Symbol = getBuiltIn$b('Symbol');
return isCallable$r($Symbol) && isPrototypeOf$7($Symbol.prototype, $Object$3(it));
};
var $String$4 = String;
var tryToString$6 = function (argument) {
try {
return $String$4(argument);
} catch (error) {
return 'Object';
}
};
var isCallable$q = isCallable$u;
var tryToString$5 = tryToString$6;
var $TypeError$i = TypeError;
// `Assert: IsCallable(argument) is true`
var aCallable$a = function (argument) {
if (isCallable$q(argument)) return argument;
throw $TypeError$i(tryToString$5(argument) + ' is not a function');
};
var aCallable$9 = aCallable$a;
var isNullOrUndefined$9 = isNullOrUndefined$b;
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
var getMethod$7 = function (V, P) {
var func = V[P];
return isNullOrUndefined$9(func) ? undefined : aCallable$9(func);
};
var call$o = functionCall;
var isCallable$p = isCallable$u;
var isObject$n = isObject$o;
var $TypeError$h = TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
var ordinaryToPrimitive$1 = function (input, pref) {
var fn, val;
if (pref === 'string' && isCallable$p(fn = input.toString) && !isObject$n(val = call$o(fn, input))) return val;
if (isCallable$p(fn = input.valueOf) && !isObject$n(val = call$o(fn, input))) return val;
if (pref !== 'string' && isCallable$p(fn = input.toString) && !isObject$n(val = call$o(fn, input))) return val;
throw $TypeError$h("Can't convert object to primitive value");
};
var shared$7 = {exports: {}};
var isPure = false;
var global$y = global$B;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty$e = Object.defineProperty;
var defineGlobalProperty$3 = function (key, value) {
try {
defineProperty$e(global$y, key, { value: value, configurable: true, writable: true });
} catch (error) {
global$y[key] = value;
} return value;
};
var global$x = global$B;
var defineGlobalProperty$2 = defineGlobalProperty$3;
var SHARED = '__core-js_shared__';
var store$3 = global$x[SHARED] || defineGlobalProperty$2(SHARED, {});
var sharedStore = store$3;
var store$2 = sharedStore;
(shared$7.exports = function (key, value) {
return store$2[key] || (store$2[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.26.0',
mode: 'global',
copyright: '© 2014-2022 Denis Pushkarev (zloirock.ru)',
license: 'https://github.com/zloirock/core-js/blob/v3.26.0/LICENSE',
source: 'https://github.com/zloirock/core-js'
});
var requireObjectCoercible$b = requireObjectCoercible$d;
var $Object$2 = Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
var toObject$d = function (argument) {
return $Object$2(requireObjectCoercible$b(argument));
};
var uncurryThis$K = functionUncurryThis;
var toObject$c = toObject$d;
var hasOwnProperty = uncurryThis$K({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es/no-object-hasown -- safe
var hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject$c(it), key);
};
var uncurryThis$J = functionUncurryThis;
var id$3 = 0;
var postfix = Math.random();
var toString$l = uncurryThis$J(1.0.toString);
var uid$4 = function (key) {
return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString$l(++id$3 + postfix, 36);
};
var global$w = global$B;
var shared$6 = shared$7.exports;
var hasOwn$m = hasOwnProperty_1;
var uid$3 = uid$4;
var NATIVE_SYMBOL$5 = symbolConstructorDetection;
var USE_SYMBOL_AS_UID = useSymbolAsUid;
var WellKnownSymbolsStore$1 = shared$6('wks');
var Symbol$3 = global$w.Symbol;
var symbolFor = Symbol$3 && Symbol$3['for'];
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol$3 : Symbol$3 && Symbol$3.withoutSetter || uid$3;
var wellKnownSymbol$t = function (name) {
if (!hasOwn$m(WellKnownSymbolsStore$1, name) || !(NATIVE_SYMBOL$5 || typeof WellKnownSymbolsStore$1[name] == 'string')) {
var description = 'Symbol.' + name;
if (NATIVE_SYMBOL$5 && hasOwn$m(Symbol$3, name)) {
WellKnownSymbolsStore$1[name] = Symbol$3[name];
} else if (USE_SYMBOL_AS_UID && symbolFor) {
WellKnownSymbolsStore$1[name] = symbolFor(description);
} else {
WellKnownSymbolsStore$1[name] = createWellKnownSymbol(description);
}
} return WellKnownSymbolsStore$1[name];
};
var call$n = functionCall;
var isObject$m = isObject$o;
var isSymbol$4 = isSymbol$5;
var getMethod$6 = getMethod$7;
var ordinaryToPrimitive = ordinaryToPrimitive$1;
var wellKnownSymbol$s = wellKnownSymbol$t;
var $TypeError$g = TypeError;
var TO_PRIMITIVE = wellKnownSymbol$s('toPrimitive');
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
var toPrimitive$2 = function (input, pref) {
if (!isObject$m(input) || isSymbol$4(input)) return input;
var exoticToPrim = getMethod$6(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = 'default';
result = call$n(exoticToPrim, input, pref);
if (!isObject$m(result) || isSymbol$4(result)) return result;
throw $TypeError$g("Can't convert object to primitive value");
}
if (pref === undefined) pref = 'number';
return ordinaryToPrimitive(input, pref);
};
var toPrimitive$1 = toPrimitive$2;
var isSymbol$3 = isSymbol$5;
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
var toPropertyKey$4 = function (argument) {
var key = toPrimitive$1(argument, 'string');
return isSymbol$3(key) ? key : key + '';
};
var global$v = global$B;
var isObject$l = isObject$o;
var document$3 = global$v.document;
// typeof document.createElement is 'object' in old IE
var EXISTS$1 = isObject$l(document$3) && isObject$l(document$3.createElement);
var documentCreateElement$2 = function (it) {
return EXISTS$1 ? document$3.createElement(it) : {};
};
var DESCRIPTORS$p = descriptors;
var fails$E = fails$J;
var createElement$1 = documentCreateElement$2;
// Thanks to IE8 for its funny defineProperty
var ie8DomDefine = !DESCRIPTORS$p && !fails$E(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(createElement$1('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var DESCRIPTORS$o = descriptors;
var call$m = functionCall;
var propertyIsEnumerableModule$2 = objectPropertyIsEnumerable;
var createPropertyDescriptor$5 = createPropertyDescriptor$6;
var toIndexedObject$c = toIndexedObject$d;
var toPropertyKey$3 = toPropertyKey$4;
var hasOwn$l = hasOwnProperty_1;
var IE8_DOM_DEFINE$1 = ie8DomDefine;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor$2 = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
objectGetOwnPropertyDescriptor.f = DESCRIPTORS$o ? $getOwnPropertyDescriptor$2 : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject$c(O);
P = toPropertyKey$3(P);
if (IE8_DOM_DEFINE$1) try {
return $getOwnPropertyDescriptor$2(O, P);
} catch (error) { /* empty */ }
if (hasOwn$l(O, P)) return createPropertyDescriptor$5(!call$m(propertyIsEnumerableModule$2.f, O, P), O[P]);
};
var objectDefineProperty = {};
var DESCRIPTORS$n = descriptors;
var fails$D = fails$J;
// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
var v8PrototypeDefineBug = DESCRIPTORS$n && fails$D(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(function () { /* empty */ }, 'prototype', {
value: 42,
writable: false
}).prototype != 42;
});
var isObject$k = isObject$o;
var $String$3 = String;
var $TypeError$f = TypeError;
// `Assert: Type(argument) is Object`
var anObject$l = function (argument) {
if (isObject$k(argument)) return argument;
throw $TypeError$f($String$3(argument) + ' is not an object');
};
var DESCRIPTORS$m = descriptors;
var IE8_DOM_DEFINE = ie8DomDefine;
var V8_PROTOTYPE_DEFINE_BUG$1 = v8PrototypeDefineBug;
var anObject$k = anObject$l;
var toPropertyKey$2 = toPropertyKey$4;
var $TypeError$e = TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty$1 = Object.defineProperty;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
var ENUMERABLE = 'enumerable';
var CONFIGURABLE$1 = 'configurable';
var WRITABLE = 'writable';
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
objectDefineProperty.f = DESCRIPTORS$m ? V8_PROTOTYPE_DEFINE_BUG$1 ? function defineProperty(O, P, Attributes) {
anObject$k(O);
P = toPropertyKey$2(P);
anObject$k(Attributes);
if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
var current = $getOwnPropertyDescriptor$1(O, P);
if (current && current[WRITABLE]) {
O[P] = Attributes.value;
Attributes = {
configurable: CONFIGURABLE$1 in Attributes ? Attributes[CONFIGURABLE$1] : current[CONFIGURABLE$1],
enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
writable: false
};
}
} return $defineProperty$1(O, P, Attributes);
} : $defineProperty$1 : function defineProperty(O, P, Attributes) {
anObject$k(O);
P = toPropertyKey$2(P);
anObject$k(Attributes);
if (IE8_DOM_DEFINE) try {
return $defineProperty$1(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw $TypeError$e('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var DESCRIPTORS$l = descriptors;
var definePropertyModule$6 = objectDefineProperty;
var createPropertyDescriptor$4 = createPropertyDescriptor$6;
var createNonEnumerableProperty$7 = DESCRIPTORS$l ? function (object, key, value) {
return definePropertyModule$6.f(object, key, createPropertyDescriptor$4(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var makeBuiltIn$3 = {exports: {}};
var DESCRIPTORS$k = descriptors;
var hasOwn$k = hasOwnProperty_1;
var FunctionPrototype$2 = Function.prototype;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS$k && Object.getOwnPropertyDescriptor;
var EXISTS = hasOwn$k(FunctionPrototype$2, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE = EXISTS && (!DESCRIPTORS$k || (DESCRIPTORS$k && getDescriptor(FunctionPrototype$2, 'name').configurable));
var functionName = {
EXISTS: EXISTS,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE
};
var uncurryThis$I = functionUncurryThis;
var isCallable$o = isCallable$u;
var store$1 = sharedStore;
var functionToString$1 = uncurryThis$I(Function.toString);
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable$o(store$1.inspectSource)) {
store$1.inspectSource = function (it) {
return functionToString$1(it);
};
}
var inspectSource$3 = store$1.inspectSource;
var global$u = global$B;
var isCallable$n = isCallable$u;
var WeakMap$1 = global$u.WeakMap;
var weakMapBasicDetection = isCallable$n(WeakMap$1) && /native code/.test(String(WeakMap$1));
var shared$5 = shared$7.exports;
var uid$2 = uid$4;
var keys$2 = shared$5('keys');
var sharedKey$4 = function (key) {
return keys$2[key] || (keys$2[key] = uid$2(key));
};
var hiddenKeys$6 = {};
var NATIVE_WEAK_MAP$1 = weakMapBasicDetection;
var global$t = global$B;
var isObject$j = isObject$o;
var createNonEnumerableProperty$6 = createNonEnumerableProperty$7;
var hasOwn$j = hasOwnProperty_1;
var shared$4 = sharedStore;
var sharedKey$3 = sharedKey$4;
var hiddenKeys$5 = hiddenKeys$6;
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError$6 = global$t.TypeError;
var WeakMap = global$t.WeakMap;
var set$1, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set$1(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject$j(it) || (state = get(it)).type !== TYPE) {
throw TypeError$6('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP$1 || shared$4.state) {
var store = shared$4.state || (shared$4.state = new WeakMap());
/* eslint-disable no-self-assign -- prototype methods protection */
store.get = store.get;
store.has = store.has;
store.set = store.set;
/* eslint-enable no-self-assign -- prototype methods protection */
set$1 = function (it, metadata) {
if (store.has(it)) throw TypeError$6(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
store.set(it, metadata);
return metadata;
};
get = function (it) {
return store.get(it) || {};
};
has = function (it) {
return store.has(it);
};
} else {
var STATE = sharedKey$3('state');
hiddenKeys$5[STATE] = true;
set$1 = function (it, metadata) {
if (hasOwn$j(it, STATE)) throw TypeError$6(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty$6(it, STATE, metadata);
return metadata;
};
get = function (it) {
return hasOwn$j(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return hasOwn$j(it, STATE);
};
}
var internalState = {
set: set$1,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
var fails$C = fails$J;
var isCallable$m = isCallable$u;
var hasOwn$i = hasOwnProperty_1;
var DESCRIPTORS$j = descriptors;
var CONFIGURABLE_FUNCTION_NAME$1 = functionName.CONFIGURABLE;
var inspectSource$2 = inspectSource$3;
var InternalStateModule$8 = internalState;
var enforceInternalState$2 = InternalStateModule$8.enforce;
var getInternalState$4 = InternalStateModule$8.get;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty$d = Object.defineProperty;
var CONFIGURABLE_LENGTH = DESCRIPTORS$j && !fails$C(function () {
return defineProperty$d(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
});
var TEMPLATE = String(String).split('String');
var makeBuiltIn$2 = makeBuiltIn$3.exports = function (value, name, options) {
if (String(name).slice(0, 7) === 'Symbol(') {
name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
}
if (options && options.getter) name = 'get ' + name;
if (options && options.setter) name = 'set ' + name;
if (!hasOwn$i(value, 'name') || (CONFIGURABLE_FUNCTION_NAME$1 && value.name !== name)) {
if (DESCRIPTORS$j) defineProperty$d(value, 'name', { value: name, configurable: true });
else value.name = name;
}
if (CONFIGURABLE_LENGTH && options && hasOwn$i(options, 'arity') && value.length !== options.arity) {
defineProperty$d(value, 'length', { value: options.arity });
}
try {
if (options && hasOwn$i(options, 'constructor') && options.constructor) {
if (DESCRIPTORS$j) defineProperty$d(value, 'prototype', { writable: false });
// in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
} else if (value.prototype) value.prototype = undefined;
} catch (error) { /* empty */ }
var state = enforceInternalState$2(value);
if (!hasOwn$i(state, 'source')) {
state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
} return value;
};
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
// eslint-disable-next-line no-extend-native -- required
Function.prototype.toString = makeBuiltIn$2(function toString() {
return isCallable$m(this) && getInternalState$4(this).source || inspectSource$2(this);
}, 'toString');
var isCallable$l = isCallable$u;
var definePropertyModule$5 = objectDefineProperty;
var makeBuiltIn$1 = makeBuiltIn$3.exports;
var defineGlobalProperty$1 = defineGlobalProperty$3;
var defineBuiltIn$i = function (O, key, value, options) {
if (!options) options = {};
var simple = options.enumerable;
var name = options.name !== undefined ? options.name : key;
if (isCallable$l(value)) makeBuiltIn$1(value, name, options);
if (options.global) {
if (simple) O[key] = value;
else defineGlobalProperty$1(key, value);
} else {
try {
if (!options.unsafe) delete O[key];
else if (O[key]) simple = true;
} catch (error) { /* empty */ }
if (simple) O[key] = value;
else definePropertyModule$5.f(O, key, {
value: value,
enumerable: false,
configurable: !options.nonConfigurable,
writable: !options.nonWritable
});
} return O;
};
var objectGetOwnPropertyNames = {};
var ceil$1 = Math.ceil;
var floor$6 = Math.floor;
// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es/no-math-trunc -- safe
var mathTrunc = Math.trunc || function trunc(x) {
var n = +x;
return (n > 0 ? floor$6 : ceil$1)(n);
};
var trunc = mathTrunc;
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
var toIntegerOrInfinity$8 = function (argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- NaN check
return number !== number || number === 0 ? 0 : trunc(number);
};
var toIntegerOrInfinity$7 = toIntegerOrInfinity$8;
var max$5 = Math.max;
var min$5 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex$4 = function (index, length) {
var integer = toIntegerOrInfinity$7(index);
return integer < 0 ? max$5(integer + length, 0) : min$5(integer, length);
};
var toIntegerOrInfinity$6 = toIntegerOrInfinity$8;
var min$4 = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
var toLength$5 = function (argument) {
return argument > 0 ? min$4(toIntegerOrInfinity$6(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var toLength$4 = toLength$5;
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
var lengthOfArrayLike$b = function (obj) {
return toLength$4(obj.length);
};
var toIndexedObject$b = toIndexedObject$d;
var toAbsoluteIndex$3 = toAbsoluteIndex$4;
var lengthOfArrayLike$a = lengthOfArrayLike$b;
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod$6 = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject$b($this);
var length = lengthOfArrayLike$a(O);
var index = toAbsoluteIndex$3(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod$6(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod$6(false)
};
var uncurryThis$H = functionUncurryThis;
var hasOwn$h = hasOwnProperty_1;
var toIndexedObject$a = toIndexedObject$d;
var indexOf$2 = arrayIncludes.indexOf;
var hiddenKeys$4 = hiddenKeys$6;
var push$9 = uncurryThis$H([].push);
var objectKeysInternal = function (object, names) {
var O = toIndexedObject$a(object);
var i = 0;
var result = [];
var key;
for (key in O) !hasOwn$h(hiddenKeys$4, key) && hasOwn$h(O, key) && push$9(result, key);
// Don't enum bug & hidden keys
while (names.length > i) if (hasOwn$h(O, key = names[i++])) {
~indexOf$2(result, key) || push$9(result, key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys$3 = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var internalObjectKeys$1 = objectKeysInternal;
var enumBugKeys$2 = enumBugKeys$3;
var hiddenKeys$3 = enumBugKeys$2.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys$1(O, hiddenKeys$3);
};
var objectGetOwnPropertySymbols = {};
// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
var getBuiltIn$a = getBuiltIn$d;
var uncurryThis$G = functionUncurryThis;
var getOwnPropertyNamesModule$2 = objectGetOwnPropertyNames;
var getOwnPropertySymbolsModule$3 = objectGetOwnPropertySymbols;
var anObject$j = anObject$l;
var concat$3 = uncurryThis$G([].concat);
// all object keys, includes non-enumerable and symbols
var ownKeys$9 = getBuiltIn$a('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule$2.f(anObject$j(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule$3.f;
return getOwnPropertySymbols ? concat$3(keys, getOwnPropertySymbols(it)) : keys;
};
var hasOwn$g = hasOwnProperty_1;
var ownKeys$8 = ownKeys$9;
var getOwnPropertyDescriptorModule$2 = objectGetOwnPropertyDescriptor;
var definePropertyModule$4 = objectDefineProperty;
var copyConstructorProperties$2 = function (target, source, exceptions) {
var keys = ownKeys$8(source);
var defineProperty = definePropertyModule$4.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$2.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!hasOwn$g(target, key) && !(exceptions && hasOwn$g(exceptions, key))) {
defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
}
};
var fails$B = fails$J;
var isCallable$k = isCallable$u;
var replacement = /#|\.prototype\./;
var isForced$5 = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: isCallable$k(detection) ? fails$B(detection)
: !!detection;
};
var normalize = isForced$5.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced$5.data = {};
var NATIVE = isForced$5.NATIVE = 'N';
var POLYFILL = isForced$5.POLYFILL = 'P';
var isForced_1 = isForced$5;
var global$s = global$B;
var getOwnPropertyDescriptor$5 = objectGetOwnPropertyDescriptor.f;
var createNonEnumerableProperty$5 = createNonEnumerableProperty$7;
var defineBuiltIn$h = defineBuiltIn$i;
var defineGlobalProperty = defineGlobalProperty$3;
var copyConstructorProperties$1 = copyConstructorProperties$2;
var isForced$4 = isForced_1;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.dontCallGetSet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global$s;
} else if (STATIC) {
target = global$s[TARGET] || defineGlobalProperty(TARGET, {});
} else {
target = (global$s[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.dontCallGetSet) {
descriptor = getOwnPropertyDescriptor$5(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced$4(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty == typeof targetProperty) continue;
copyConstructorProperties$1(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty$5(sourceProperty, 'sham', true);
}
defineBuiltIn$h(target, key, sourceProperty, options);
}
};
var uncurryThis$F = functionUncurryThis;
var aCallable$8 = aCallable$a;
var NATIVE_BIND$2 = functionBindNative;
var bind$b = uncurryThis$F(uncurryThis$F.bind);
// optional / simple context binding
var functionBindContext = function (fn, that) {
aCallable$8(fn);
return that === undefined ? fn : NATIVE_BIND$2 ? bind$b(fn, that) : function (/* ...args */) {
return fn.apply(that, arguments);
};
};
var classof$b = classofRaw$2;
// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
var isArray$6 = Array.isArray || function isArray(argument) {
return classof$b(argument) == 'Array';
};
var wellKnownSymbol$r = wellKnownSymbol$t;
var TO_STRING_TAG$3 = wellKnownSymbol$r('toStringTag');
var test$1 = {};
test$1[TO_STRING_TAG$3] = 'z';
var toStringTagSupport = String(test$1) === '[object z]';
var TO_STRING_TAG_SUPPORT$2 = toStringTagSupport;
var isCallable$j = isCallable$u;
var classofRaw = classofRaw$2;
var wellKnownSymbol$q = wellKnownSymbol$t;
var TO_STRING_TAG$2 = wellKnownSymbol$q('toStringTag');
var $Object$1 = Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
var classof$a = TO_STRING_TAG_SUPPORT$2 ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = $Object$1(it), TO_STRING_TAG$2)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && isCallable$j(O.callee) ? 'Arguments' : result;
};
var uncurryThis$E = functionUncurryThis;
var fails$A = fails$J;
var isCallable$i = isCallable$u;
var classof$9 = classof$a;
var getBuiltIn$9 = getBuiltIn$d;
var inspectSource$1 = inspectSource$3;
var noop = function () { /* empty */ };
var empty = [];
var construct$1 = getBuiltIn$9('Reflect', 'construct');
var constructorRegExp = /^\s*(?:class|function)\b/;
var exec$6 = uncurryThis$E(constructorRegExp.exec);
var INCORRECT_TO_STRING = !constructorRegExp.exec(noop);
var isConstructorModern = function isConstructor(argument) {
if (!isCallable$i(argument)) return false;
try {
construct$1(noop, empty, argument);
return true;
} catch (error) {
return false;
}
};
var isConstructorLegacy = function isConstructor(argument) {
if (!isCallable$i(argument)) return false;
switch (classof$9(argument)) {
case 'AsyncFunction':
case 'GeneratorFunction':
case 'AsyncGeneratorFunction': return false;
}
try {
// we can't check .prototype since constructors produced by .bind haven't it
// `Function#toString` throws on some built-it function in some legacy engines
// (for example, `DOMQuad` and similar in FF41-)
return INCORRECT_TO_STRING || !!exec$6(constructorRegExp, inspectSource$1(argument));
} catch (error) {
return true;
}
};
isConstructorLegacy.sham = true;
// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
var isConstructor$4 = !construct$1 || fails$A(function () {
var called;
return isConstructorModern(isConstructorModern.call)
|| !isConstructorModern(Object)
|| !isConstructorModern(function () { called = true; })
|| called;
}) ? isConstructorLegacy : isConstructorModern;
var isArray$5 = isArray$6;
var isConstructor$3 = isConstructor$4;
var isObject$i = isObject$o;
var wellKnownSymbol$p = wellKnownSymbol$t;
var SPECIES$6 = wellKnownSymbol$p('species');
var $Array$3 = Array;
// a part of `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesConstructor$1 = function (originalArray) {
var C;
if (isArray$5(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (isConstructor$3(C) && (C === $Array$3 || isArray$5(C.prototype))) C = undefined;
else if (isObject$i(C)) {
C = C[SPECIES$6];
if (C === null) C = undefined;
}
} return C === undefined ? $Array$3 : C;
};
var arraySpeciesConstructor = arraySpeciesConstructor$1;
// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate$3 = function (originalArray, length) {
return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
};
var bind$a = functionBindContext;
var uncurryThis$D = functionUncurryThis;
var IndexedObject$3 = indexedObject;
var toObject$b = toObject$d;
var lengthOfArrayLike$9 = lengthOfArrayLike$b;
var arraySpeciesCreate$2 = arraySpeciesCreate$3;
var push$8 = uncurryThis$D([].push);
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
var createMethod$5 = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var IS_FILTER_REJECT = TYPE == 7;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject$b($this);
var self = IndexedObject$3(O);
var boundFunction = bind$a(callbackfn, that);
var length = lengthOfArrayLike$9(self);
var index = 0;
var create = specificCreate || arraySpeciesCreate$2;
var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push$8(target, value); // filter
} else switch (TYPE) {
case 4: return false; // every
case 7: push$8(target, value); // filterReject
}
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
var arrayIteration = {
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
forEach: createMethod$5(0),
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map: createMethod$5(1),
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter: createMethod$5(2),
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some: createMethod$5(3),
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every: createMethod$5(4),
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find: createMethod$5(5),
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod$5(6),
// `Array.prototype.filterReject` method
// https://github.com/tc39/proposal-array-filtering
filterReject: createMethod$5(7)
};
var fails$z = fails$J;
var arrayMethodIsStrict$8 = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails$z(function () {
// eslint-disable-next-line no-useless-call -- required for testing
method.call(null, argument || function () { return 1; }, 1);
});
};
var $forEach$1 = arrayIteration.forEach;
var arrayMethodIsStrict$7 = arrayMethodIsStrict$8;
var STRICT_METHOD$7 = arrayMethodIsStrict$7('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.foreach
var arrayForEach = !STRICT_METHOD$7 ? function forEach(callbackfn /* , thisArg */) {
return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
// eslint-disable-next-line es/no-array-prototype-foreach -- safe
} : [].forEach;
var $$_ = _export;
var forEach$1 = arrayForEach;
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
// eslint-disable-next-line es/no-array-prototype-foreach -- safe
$$_({ target: 'Array', proto: true, forced: [].forEach != forEach$1 }, {
forEach: forEach$1
});
var TO_STRING_TAG_SUPPORT$1 = toStringTagSupport;
var classof$8 = classof$a;
// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
var objectToString = TO_STRING_TAG_SUPPORT$1 ? {}.toString : function toString() {
return '[object ' + classof$8(this) + ']';
};
var TO_STRING_TAG_SUPPORT = toStringTagSupport;
var defineBuiltIn$g = defineBuiltIn$i;
var toString$k = objectToString;
// `Object.prototype.toString` method
// https://tc39.es/ecma262/#sec-object.prototype.tostring
if (!TO_STRING_TAG_SUPPORT) {
defineBuiltIn$g(Object.prototype, 'toString', toString$k, { unsafe: true });
}
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
var domIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
// in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList`
var documentCreateElement$1 = documentCreateElement$2;
var classList = documentCreateElement$1('span').classList;
var DOMTokenListPrototype$2 = classList && classList.constructor && classList.constructor.prototype;
var domTokenListPrototype = DOMTokenListPrototype$2 === Object.prototype ? undefined : DOMTokenListPrototype$2;
var global$r = global$B;
var DOMIterables$1 = domIterables;
var DOMTokenListPrototype$1 = domTokenListPrototype;
var forEach = arrayForEach;
var createNonEnumerableProperty$4 = createNonEnumerableProperty$7;
var handlePrototype$1 = function (CollectionPrototype) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
createNonEnumerableProperty$4(CollectionPrototype, 'forEach', forEach);
} catch (error) {
CollectionPrototype.forEach = forEach;
}
};
for (var COLLECTION_NAME$1 in DOMIterables$1) {
if (DOMIterables$1[COLLECTION_NAME$1]) {
handlePrototype$1(global$r[COLLECTION_NAME$1] && global$r[COLLECTION_NAME$1].prototype);
}
}
handlePrototype$1(DOMTokenListPrototype$1);
var fails$y = fails$J;
var wellKnownSymbol$o = wellKnownSymbol$t;
var V8_VERSION$2 = engineV8Version;
var SPECIES$5 = wellKnownSymbol$o('species');
var arrayMethodHasSpeciesSupport$5 = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return V8_VERSION$2 >= 51 || !fails$y(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$5] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var $$Z = _export;
var $map = arrayIteration.map;
var arrayMethodHasSpeciesSupport$4 = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport$4('map');
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
// with adding support of @@species
$$Z({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, {
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var objectDefineProperties = {};
var internalObjectKeys = objectKeysInternal;
var enumBugKeys$1 = enumBugKeys$3;
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
var objectKeys$4 = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys$1);
};
var DESCRIPTORS$i = descriptors;
var V8_PROTOTYPE_DEFINE_BUG = v8PrototypeDefineBug;
var definePropertyModule$3 = objectDefineProperty;
var anObject$i = anObject$l;
var toIndexedObject$9 = toIndexedObject$d;
var objectKeys$3 = objectKeys$4;
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
objectDefineProperties.f = DESCRIPTORS$i && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
anObject$i(O);
var props = toIndexedObject$9(Properties);
var keys = objectKeys$3(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule$3.f(O, key = keys[index++], props[key]);
return O;
};
var getBuiltIn$8 = getBuiltIn$d;
var html$2 = getBuiltIn$8('document', 'documentElement');
/* global ActiveXObject -- old IE, WSH */
var anObject$h = anObject$l;
var definePropertiesModule$1 = objectDefineProperties;
var enumBugKeys = enumBugKeys$3;
var hiddenKeys$2 = hiddenKeys$6;
var html$1 = html$2;
var documentCreateElement = documentCreateElement$2;
var sharedKey$2 = sharedKey$4;
var GT = '>';
var LT = '<';
var PROTOTYPE$1 = 'prototype';
var SCRIPT = 'script';
var IE_PROTO$1 = sharedKey$2('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html$1.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
activeXDocument = new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = typeof document != 'undefined'
? document.domain && activeXDocument
? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame()
: NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE$1][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys$2[IE_PROTO$1] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es/no-object-create -- safe
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE$1] = anObject$h(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE$1] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO$1] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : definePropertiesModule$1.f(result, Properties);
};
var wellKnownSymbol$n = wellKnownSymbol$t;
var create$6 = objectCreate;
var defineProperty$c = objectDefineProperty.f;
var UNSCOPABLES = wellKnownSymbol$n('unscopables');
var ArrayPrototype$1 = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype$1[UNSCOPABLES] == undefined) {
defineProperty$c(ArrayPrototype$1, UNSCOPABLES, {
configurable: true,
value: create$6(null)
});
}
// add a key to Array.prototype[@@unscopables]
var addToUnscopables$4 = function (key) {
ArrayPrototype$1[UNSCOPABLES][key] = true;
};
var $$Y = _export;
var $find = arrayIteration.find;
var addToUnscopables$3 = addToUnscopables$4;
var FIND = 'find';
var SKIPS_HOLES$1 = true;
// Shouldn't skip holes
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES$1 = false; });
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
$$Y({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables$3(FIND);
var toPropertyKey$1 = toPropertyKey$4;
var definePropertyModule$2 = objectDefineProperty;
var createPropertyDescriptor$3 = createPropertyDescriptor$6;
var createProperty$6 = function (object, key, value) {
var propertyKey = toPropertyKey$1(key);
if (propertyKey in object) definePropertyModule$2.f(object, propertyKey, createPropertyDescriptor$3(0, value));
else object[propertyKey] = value;
};
var uncurryThis$C = functionUncurryThis;
var arraySlice$8 = uncurryThis$C([].slice);
var $$X = _export;
var isArray$4 = isArray$6;
var isConstructor$2 = isConstructor$4;
var isObject$h = isObject$o;
var toAbsoluteIndex$2 = toAbsoluteIndex$4;
var lengthOfArrayLike$8 = lengthOfArrayLike$b;
var toIndexedObject$8 = toIndexedObject$d;
var createProperty$5 = createProperty$6;
var wellKnownSymbol$m = wellKnownSymbol$t;
var arrayMethodHasSpeciesSupport$3 = arrayMethodHasSpeciesSupport$5;
var nativeSlice = arraySlice$8;
var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport$3('slice');
var SPECIES$4 = wellKnownSymbol$m('species');
var $Array$2 = Array;
var max$4 = Math.max;
// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
$$X({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, {
slice: function slice(start, end) {
var O = toIndexedObject$8(this);
var length = lengthOfArrayLike$8(O);
var k = toAbsoluteIndex$2(start, length);
var fin = toAbsoluteIndex$2(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray$4(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (isConstructor$2(Constructor) && (Constructor === $Array$2 || isArray$4(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject$h(Constructor)) {
Constructor = Constructor[SPECIES$4];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === $Array$2 || Constructor === undefined) {
return nativeSlice(O, k, fin);
}
}
result = new (Constructor === undefined ? $Array$2 : Constructor)(max$4(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty$5(result, n, O[k]);
result.length = n;
return result;
}
});
/* eslint-disable es/no-array-prototype-indexof -- required for testing */
var $$W = _export;
var uncurryThis$B = functionUncurryThis;
var $indexOf = arrayIncludes.indexOf;
var arrayMethodIsStrict$6 = arrayMethodIsStrict$8;
var nativeIndexOf = uncurryThis$B([].indexOf);
var NEGATIVE_ZERO$1 = !!nativeIndexOf && 1 / nativeIndexOf([1], 1, -0) < 0;
var STRICT_METHOD$6 = arrayMethodIsStrict$6('indexOf');
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
$$W({ target: 'Array', proto: true, forced: NEGATIVE_ZERO$1 || !STRICT_METHOD$6 }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
var fromIndex = arguments.length > 1 ? arguments[1] : undefined;
return NEGATIVE_ZERO$1
// convert -0 to +0
? nativeIndexOf(this, searchElement, fromIndex) || 0
: $indexOf(this, searchElement, fromIndex);
}
});
var uncurryThis$A = functionUncurryThis;
var aCallable$7 = aCallable$a;
var isObject$g = isObject$o;
var hasOwn$f = hasOwnProperty_1;
var arraySlice$7 = arraySlice$8;
var NATIVE_BIND$1 = functionBindNative;
var $Function = Function;
var concat$2 = uncurryThis$A([].concat);
var join$3 = uncurryThis$A([].join);
var factories = {};
var construct = function (C, argsLength, args) {
if (!hasOwn$f(factories, argsLength)) {
for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
factories[argsLength] = $Function('C,a', 'return new C(' + join$3(list, ',') + ')');
} return factories[argsLength](C, args);
};
// `Function.prototype.bind` method implementation
// https://tc39.es/ecma262/#sec-function.prototype.bind
var functionBind = NATIVE_BIND$1 ? $Function.bind : function bind(that /* , ...args */) {
var F = aCallable$7(this);
var Prototype = F.prototype;
var partArgs = arraySlice$7(arguments, 1);
var boundFunction = function bound(/* args... */) {
var args = concat$2(partArgs, arraySlice$7(arguments));
return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
};
if (isObject$g(Prototype)) boundFunction.prototype = Prototype;
return boundFunction;
};
// TODO: Remove from `core-js@4`
var $$V = _export;
var bind$9 = functionBind;
// `Function.prototype.bind` method
// https://tc39.es/ecma262/#sec-function.prototype.bind
$$V({ target: 'Function', proto: true, forced: Function.bind !== bind$9 }, {
bind: bind$9
});
var DESCRIPTORS$h = descriptors;
var isArray$3 = isArray$6;
var $TypeError$d = TypeError;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$4 = Object.getOwnPropertyDescriptor;
// Safari < 13 does not throw an error in this case
var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS$h && !function () {
// makes no sense without proper strict mode support
if (this !== undefined) return true;
try {
// eslint-disable-next-line es/no-object-defineproperty -- safe
Object.defineProperty([], 'length', { writable: false }).length = 1;
} catch (error) {
return error instanceof TypeError;
}
}();
var arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
if (isArray$3(O) && !getOwnPropertyDescriptor$4(O, 'length').writable) {
throw $TypeError$d('Cannot set read only .length');
} return O.length = length;
} : function (O, length) {
return O.length = length;
};
var $TypeError$c = TypeError;
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
var doesNotExceedSafeInteger$2 = function (it) {
if (it > MAX_SAFE_INTEGER) throw $TypeError$c('Maximum allowed index exceeded');
return it;
};
var tryToString$4 = tryToString$6;
var $TypeError$b = TypeError;
var deletePropertyOrThrow$2 = function (O, P) {
if (!delete O[P]) throw $TypeError$b('Cannot delete property ' + tryToString$4(P) + ' of ' + tryToString$4(O));
};
var $$U = _export;
var toObject$a = toObject$d;
var toAbsoluteIndex$1 = toAbsoluteIndex$4;
var toIntegerOrInfinity$5 = toIntegerOrInfinity$8;
var lengthOfArrayLike$7 = lengthOfArrayLike$b;
var setArrayLength = arraySetLength;
var doesNotExceedSafeInteger$1 = doesNotExceedSafeInteger$2;
var arraySpeciesCreate$1 = arraySpeciesCreate$3;
var createProperty$4 = createProperty$6;
var deletePropertyOrThrow$1 = deletePropertyOrThrow$2;
var arrayMethodHasSpeciesSupport$2 = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport$2('splice');
var max$3 = Math.max;
var min$3 = Math.min;
// `Array.prototype.splice` method
// https://tc39.es/ecma262/#sec-array.prototype.splice
// with adding support of @@species
$$U({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject$a(this);
var len = lengthOfArrayLike$7(O);
var actualStart = toAbsoluteIndex$1(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min$3(max$3(toIntegerOrInfinity$5(deleteCount), 0), len - actualStart);
}
doesNotExceedSafeInteger$1(len + insertCount - actualDeleteCount);
A = arraySpeciesCreate$1(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty$4(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else deletePropertyOrThrow$1(O, to);
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) deletePropertyOrThrow$1(O, k - 1);
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else deletePropertyOrThrow$1(O, to);
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
setArrayLength(O, len - actualDeleteCount + insertCount);
return A;
}
});
var DESCRIPTORS$g = descriptors;
var uncurryThis$z = functionUncurryThis;
var call$l = functionCall;
var fails$x = fails$J;
var objectKeys$2 = objectKeys$4;
var getOwnPropertySymbolsModule$2 = objectGetOwnPropertySymbols;
var propertyIsEnumerableModule$1 = objectPropertyIsEnumerable;
var toObject$9 = toObject$d;
var IndexedObject$2 = indexedObject;
// eslint-disable-next-line es/no-object-assign -- safe
var $assign = Object.assign;
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
var defineProperty$b = Object.defineProperty;
var concat$1 = uncurryThis$z([].concat);
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
var objectAssign = !$assign || fails$x(function () {
// should have correct order of operations (Edge bug)
if (DESCRIPTORS$g && $assign({ b: 1 }, $assign(defineProperty$b({}, 'a', {
enumerable: true,
get: function () {
defineProperty$b(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line es/no-symbol -- safe
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return $assign({}, A)[symbol] != 7 || objectKeys$2($assign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
var T = toObject$9(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = getOwnPropertySymbolsModule$2.f;
var propertyIsEnumerable = propertyIsEnumerableModule$1.f;
while (argumentsLength > index) {
var S = IndexedObject$2(arguments[index++]);
var keys = getOwnPropertySymbols ? concat$1(objectKeys$2(S), getOwnPropertySymbols(S)) : objectKeys$2(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS$g || call$l(propertyIsEnumerable, S, key)) T[key] = S[key];
}
} return T;
} : $assign;
var $$T = _export;
var assign$1 = objectAssign;
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es/no-object-assign -- required for testing
$$T({ target: 'Object', stat: true, arity: 2, forced: Object.assign !== assign$1 }, {
assign: assign$1
});
var classof$7 = classof$a;
var $String$2 = String;
var toString$j = function (argument) {
if (classof$7(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
return $String$2(argument);
};
var anObject$g = anObject$l;
// `RegExp.prototype.flags` getter implementation
// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
var regexpFlags$1 = function () {
var that = anObject$g(this);
var result = '';
if (that.hasIndices) result += 'd';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.dotAll) result += 's';
if (that.unicode) result += 'u';
if (that.unicodeSets) result += 'v';
if (that.sticky) result += 'y';
return result;
};
var fails$w = fails$J;
var global$q = global$B;
// babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
var $RegExp$2 = global$q.RegExp;
var UNSUPPORTED_Y$2 = fails$w(function () {
var re = $RegExp$2('a', 'y');
re.lastIndex = 2;
return re.exec('abcd') != null;
});
// UC Browser bug
// https://github.com/zloirock/core-js/issues/1008
var MISSED_STICKY$1 = UNSUPPORTED_Y$2 || fails$w(function () {
return !$RegExp$2('a', 'y').sticky;
});
var BROKEN_CARET = UNSUPPORTED_Y$2 || fails$w(function () {
// https://bugzilla.mozilla.org/show_bug.cgi?id=773687
var re = $RegExp$2('^r', 'gy');
re.lastIndex = 2;
return re.exec('str') != null;
});
var regexpStickyHelpers = {
BROKEN_CARET: BROKEN_CARET,
MISSED_STICKY: MISSED_STICKY$1,
UNSUPPORTED_Y: UNSUPPORTED_Y$2
};
var fails$v = fails$J;
var global$p = global$B;
// babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError
var $RegExp$1 = global$p.RegExp;
var regexpUnsupportedDotAll = fails$v(function () {
var re = $RegExp$1('.', 's');
return !(re.dotAll && re.exec('\n') && re.flags === 's');
});
var fails$u = fails$J;
var global$o = global$B;
// babel-minify and Closure Compiler transpiles RegExp('(?b)', 'g') -> /(?b)/g and it causes SyntaxError
var $RegExp = global$o.RegExp;
var regexpUnsupportedNcg = fails$u(function () {
var re = $RegExp('(?b)', 'g');
return re.exec('b').groups.a !== 'b' ||
'b'.replace(re, '$c') !== 'bc';
});
/* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */
/* eslint-disable regexp/no-useless-quantifier -- testing */
var call$k = functionCall;
var uncurryThis$y = functionUncurryThis;
var toString$i = toString$j;
var regexpFlags = regexpFlags$1;
var stickyHelpers$1 = regexpStickyHelpers;
var shared$3 = shared$7.exports;
var create$5 = objectCreate;
var getInternalState$3 = internalState.get;
var UNSUPPORTED_DOT_ALL$1 = regexpUnsupportedDotAll;
var UNSUPPORTED_NCG$1 = regexpUnsupportedNcg;
var nativeReplace = shared$3('native-string-replace', String.prototype.replace);
var nativeExec = RegExp.prototype.exec;
var patchedExec = nativeExec;
var charAt$9 = uncurryThis$y(''.charAt);
var indexOf$1 = uncurryThis$y(''.indexOf);
var replace$9 = uncurryThis$y(''.replace);
var stringSlice$b = uncurryThis$y(''.slice);
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/;
var re2 = /b*/g;
call$k(nativeExec, re1, 'a');
call$k(nativeExec, re2, 'a');
return re1.lastIndex !== 0 || re2.lastIndex !== 0;
})();
var UNSUPPORTED_Y$1 = stickyHelpers$1.BROKEN_CARET;
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1 || UNSUPPORTED_DOT_ALL$1 || UNSUPPORTED_NCG$1;
if (PATCH) {
patchedExec = function exec(string) {
var re = this;
var state = getInternalState$3(re);
var str = toString$i(string);
var raw = state.raw;
var result, reCopy, lastIndex, match, i, object, group;
if (raw) {
raw.lastIndex = re.lastIndex;
result = call$k(patchedExec, raw, str);
re.lastIndex = raw.lastIndex;
return result;
}
var groups = state.groups;
var sticky = UNSUPPORTED_Y$1 && re.sticky;
var flags = call$k(regexpFlags, re);
var source = re.source;
var charsAdded = 0;
var strCopy = str;
if (sticky) {
flags = replace$9(flags, 'y', '');
if (indexOf$1(flags, 'g') === -1) {
flags += 'g';
}
strCopy = stringSlice$b(str, re.lastIndex);
// Support anchored sticky behavior.
if (re.lastIndex > 0 && (!re.multiline || re.multiline && charAt$9(str, re.lastIndex - 1) !== '\n')) {
source = '(?: ' + source + ')';
strCopy = ' ' + strCopy;
charsAdded++;
}
// ^(? + rx + ) is needed, in combination with some str slicing, to
// simulate the 'y' flag.
reCopy = new RegExp('^(?:' + source + ')', flags);
}
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + source + '$(?!\\s)', flags);
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
match = call$k(nativeExec, sticky ? reCopy : re, strCopy);
if (sticky) {
if (match) {
match.input = stringSlice$b(match.input, charsAdded);
match[0] = stringSlice$b(match[0], charsAdded);
match.index = re.lastIndex;
re.lastIndex += match[0].length;
} else re.lastIndex = 0;
} else if (UPDATES_LAST_INDEX_WRONG && match) {
re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn't work for /(.?)?/
call$k(nativeReplace, match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
if (match && groups) {
match.groups = object = create$5(null);
for (i = 0; i < groups.length; i++) {
group = groups[i];
object[group[0]] = match[group[1]];
}
}
return match;
};
}
var regexpExec$2 = patchedExec;
var $$S = _export;
var exec$5 = regexpExec$2;
// `RegExp.prototype.exec` method
// https://tc39.es/ecma262/#sec-regexp.prototype.exec
$$S({ target: 'RegExp', proto: true, forced: /./.exec !== exec$5 }, {
exec: exec$5
});
var ViewPort = {
XS: 0,
SM: 540,
MD: 860,
LG: 1084,
XL: 1400
};
var DetectionUtil = {
/* eslint-disable no-useless-escape, unicorn/better-regex */detectMobile: function detectMobile(includeTabletCheck) {
if (includeTabletCheck === void 0) {
includeTabletCheck = false;
}
/**
* detect if mobile and/or tablet device
* returns bool
*/
var check = false;
if (includeTabletCheck) {
(function (a) {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.slice(0, 4))) {
check = true;
}
})(navigator.userAgent || navigator.vendor || window.opera);
} else {
(function (a) {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.slice(0, 4))) {
check = true;
}
})(navigator.userAgent || navigator.vendor || window.opera);
}
return check;
},
/**
* Gets viewport based on brower's window width.
* @returns {string} viewport
*/
detectViewport: function detectViewport() {
var windowWidth = window.innerWidth;
if (windowWidth >= ViewPort.XS && windowWidth < ViewPort.SM) {
return 'xs';
}
if (windowWidth < ViewPort.MD && windowWidth >= ViewPort.SM) {
return 'sm';
}
if (windowWidth < ViewPort.LG && windowWidth >= ViewPort.MD) {
return 'md';
}
if (windowWidth < ViewPort.XL && windowWidth >= ViewPort.LG) {
return 'lg';
}
if (windowWidth >= ViewPort.XL) {
return 'xl';
}
},
/* eslint-enable no-useless-escape */isBiDirectional: function isBiDirectional(el) {
if (!el) {
el = document.querySelector('html');
}
return el.getAttribute('dir') === 'rtl';
},
/**
* Detects whether a user has enabled the prefers reduced motion setting
* @returns {boolean}
*/
prefersReducedMotion: function prefersReducedMotion() {
var preference = window.matchMedia('(prefers-reduced-motion: reduce)');
return preference.matches;
}
};
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return exports;
};
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function (obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function () {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function (exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function (record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperties$3(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass$3(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
if (staticProps) _defineProperties$3(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf$1(subClass, superClass);
}
function _getPrototypeOf$1(o) {
_getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf$1(o);
}
function _setPrototypeOf$1(o, p) {
_setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf$1(o, p);
}
function _isNativeReflectConstruct$1() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct$1(Parent, args, Class) {
if (_isNativeReflectConstruct$1()) {
_construct$1 = Reflect.construct.bind();
} else {
_construct$1 = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf$1(instance, Class.prototype);
return instance;
};
}
return _construct$1.apply(null, arguments);
}
function _isNativeFunction$1(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper$1(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper$1 = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction$1(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct$1(Class, arguments, _getPrototypeOf$1(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf$1(Wrapper, Class);
};
return _wrapNativeSuper$1(Class);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _assertThisInitialized$1(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _unsupportedIterableToArray$7(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$7(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$7(o, minLen);
}
function _arrayLikeToArray$7(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose$6(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray$7(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var id$2 = 0;
function _classPrivateFieldLooseKey(name) {
return "__private_" + id$2++ + "_" + name;
}
function _classPrivateFieldLooseBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
// TODO: Remove from `core-js@4`
var uncurryThis$x = functionUncurryThis;
var defineBuiltIn$f = defineBuiltIn$i;
var DatePrototype$1 = Date.prototype;
var INVALID_DATE = 'Invalid Date';
var TO_STRING$1 = 'toString';
var nativeDateToString = uncurryThis$x(DatePrototype$1[TO_STRING$1]);
var thisTimeValue$2 = uncurryThis$x(DatePrototype$1.getTime);
// `Date.prototype.toString` method
// https://tc39.es/ecma262/#sec-date.prototype.tostring
if (String(new Date(NaN)) != INVALID_DATE) {
defineBuiltIn$f(DatePrototype$1, TO_STRING$1, function toString() {
var value = thisTimeValue$2(this);
// eslint-disable-next-line no-self-compare -- NaN check
return value === value ? nativeDateToString(this) : INVALID_DATE;
});
}
var call$j = functionCall;
var hasOwn$e = hasOwnProperty_1;
var isPrototypeOf$6 = objectIsPrototypeOf;
var regExpFlags = regexpFlags$1;
var RegExpPrototype$3 = RegExp.prototype;
var regexpGetFlags = function (R) {
var flags = R.flags;
return flags === undefined && !('flags' in RegExpPrototype$3) && !hasOwn$e(R, 'flags') && isPrototypeOf$6(RegExpPrototype$3, R)
? call$j(regExpFlags, R) : flags;
};
var PROPER_FUNCTION_NAME$2 = functionName.PROPER;
var defineBuiltIn$e = defineBuiltIn$i;
var anObject$f = anObject$l;
var $toString$3 = toString$j;
var fails$t = fails$J;
var getRegExpFlags$2 = regexpGetFlags;
var TO_STRING = 'toString';
var RegExpPrototype$2 = RegExp.prototype;
var nativeToString = RegExpPrototype$2[TO_STRING];
var NOT_GENERIC = fails$t(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
// FF44- RegExp#toString has a wrong name
var INCORRECT_NAME = PROPER_FUNCTION_NAME$2 && nativeToString.name != TO_STRING;
// `RegExp.prototype.toString` method
// https://tc39.es/ecma262/#sec-regexp.prototype.tostring
if (NOT_GENERIC || INCORRECT_NAME) {
defineBuiltIn$e(RegExp.prototype, TO_STRING, function toString() {
var R = anObject$f(this);
var pattern = $toString$3(R.source);
var flags = $toString$3(getRegExpFlags$2(R));
return '/' + pattern + '/' + flags;
}, { unsafe: true });
}
var $$R = _export;
var isArray$2 = isArray$6;
// `Array.isArray` method
// https://tc39.es/ecma262/#sec-array.isarray
$$R({ target: 'Array', stat: true }, {
isArray: isArray$2
});
var InitializationUtil = {
/**
* Initialize a component after DOM is loaded
* @param {string} selector - DOM selector for component
* @param {Function} init - Callback function to initialize the component
*/
initializeComponent: function initializeComponent(selector, init) {
document.querySelectorAll(selector).forEach(function (node) {
return init(node);
});
},
/**
* Iterate over list to add event listeners
* @param {Array.<{
* el: Element | Document | Window,
* handler: Function,
* type: String,
* options?: Object
* }>} eventList - List of event maps
*/
addEvents: function addEvents(eventList) {
for (var _iterator = _createForOfIteratorHelperLoose$6(eventList), _step; !(_step = _iterator()).done;) {
var obj = _step.value;
if (typeof obj.options === 'undefined') {
obj.options = {};
}
if (typeof obj.el.addEventListener === 'function') {
obj.el.addEventListener(obj.type, obj.handler, obj.options);
} else if (obj.el.toString() === '[object MediaQueryList]' && typeof obj.el.addListener === 'function') {
obj.el.addListener(obj.handler); // for Safari <14
}
}
},
/**
* Iterate over list to remove event listeners
* @param {array} eventList - List of event maps
*/
removeEvents: function removeEvents(eventList) {
for (var _iterator2 = _createForOfIteratorHelperLoose$6(eventList), _step2; !(_step2 = _iterator2()).done;) {
var obj = _step2.value;
if (typeof obj.el.removeEventListener === 'function') {
obj.el.removeEventListener(obj.type, obj.handler);
} else if (obj.el.toString() === '[object MediaQueryList]' && typeof obj.el.removeListener === 'function') {
obj.el.removeListener(obj.handler); // for Safari <14
}
}
},
/**
* Tears down each in a list of mwf component instances
* @param {Array} componentList an array of mwf component instance
*/
tearDownComponentList: function tearDownComponentList(componentList) {
if (Array.isArray(componentList)) {
var component;
while (componentList.length > 0) {
component = componentList.pop();
if (typeof component.remove === 'function') {
component.remove();
}
}
}
}
};
var $$Q = _export;
var fails$s = fails$J;
var isArray$1 = isArray$6;
var isObject$f = isObject$o;
var toObject$8 = toObject$d;
var lengthOfArrayLike$6 = lengthOfArrayLike$b;
var doesNotExceedSafeInteger = doesNotExceedSafeInteger$2;
var createProperty$3 = createProperty$6;
var arraySpeciesCreate = arraySpeciesCreate$3;
var arrayMethodHasSpeciesSupport$1 = arrayMethodHasSpeciesSupport$5;
var wellKnownSymbol$l = wellKnownSymbol$t;
var V8_VERSION$1 = engineV8Version;
var IS_CONCAT_SPREADABLE = wellKnownSymbol$l('isConcatSpreadable');
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION$1 >= 51 || !fails$s(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport$1('concat');
var isConcatSpreadable = function (O) {
if (!isObject$f(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray$1(O);
};
var FORCED$8 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.es/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
$$Q({ target: 'Array', proto: true, arity: 1, forced: FORCED$8 }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
concat: function concat(arg) {
var O = toObject$8(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = lengthOfArrayLike$6(E);
doesNotExceedSafeInteger(n + len);
for (k = 0; k < len; k++, n++) if (k in E) createProperty$3(A, n, E[k]);
} else {
doesNotExceedSafeInteger(n + 1);
createProperty$3(A, n++, E);
}
}
A.length = n;
return A;
}
});
var call$i = functionCall;
var anObject$e = anObject$l;
var getMethod$5 = getMethod$7;
var iteratorClose$2 = function (iterator, kind, value) {
var innerResult, innerError;
anObject$e(iterator);
try {
innerResult = getMethod$5(iterator, 'return');
if (!innerResult) {
if (kind === 'throw') throw value;
return value;
}
innerResult = call$i(innerResult, iterator);
} catch (error) {
innerError = true;
innerResult = error;
}
if (kind === 'throw') throw value;
if (innerError) throw innerResult;
anObject$e(innerResult);
return value;
};
var anObject$d = anObject$l;
var iteratorClose$1 = iteratorClose$2;
// call something on iterator step with safe closing on error
var callWithSafeIterationClosing$1 = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject$d(value)[0], value[1]) : fn(value);
} catch (error) {
iteratorClose$1(iterator, 'throw', error);
}
};
var iterators = {};
var wellKnownSymbol$k = wellKnownSymbol$t;
var Iterators$4 = iterators;
var ITERATOR$9 = wellKnownSymbol$k('iterator');
var ArrayPrototype = Array.prototype;
// check on default Array iterator
var isArrayIteratorMethod$2 = function (it) {
return it !== undefined && (Iterators$4.Array === it || ArrayPrototype[ITERATOR$9] === it);
};
var classof$6 = classof$a;
var getMethod$4 = getMethod$7;
var isNullOrUndefined$8 = isNullOrUndefined$b;
var Iterators$3 = iterators;
var wellKnownSymbol$j = wellKnownSymbol$t;
var ITERATOR$8 = wellKnownSymbol$j('iterator');
var getIteratorMethod$4 = function (it) {
if (!isNullOrUndefined$8(it)) return getMethod$4(it, ITERATOR$8)
|| getMethod$4(it, '@@iterator')
|| Iterators$3[classof$6(it)];
};
var call$h = functionCall;
var aCallable$6 = aCallable$a;
var anObject$c = anObject$l;
var tryToString$3 = tryToString$6;
var getIteratorMethod$3 = getIteratorMethod$4;
var $TypeError$a = TypeError;
var getIterator$3 = function (argument, usingIterator) {
var iteratorMethod = arguments.length < 2 ? getIteratorMethod$3(argument) : usingIterator;
if (aCallable$6(iteratorMethod)) return anObject$c(call$h(iteratorMethod, argument));
throw $TypeError$a(tryToString$3(argument) + ' is not iterable');
};
var bind$8 = functionBindContext;
var call$g = functionCall;
var toObject$7 = toObject$d;
var callWithSafeIterationClosing = callWithSafeIterationClosing$1;
var isArrayIteratorMethod$1 = isArrayIteratorMethod$2;
var isConstructor$1 = isConstructor$4;
var lengthOfArrayLike$5 = lengthOfArrayLike$b;
var createProperty$2 = createProperty$6;
var getIterator$2 = getIterator$3;
var getIteratorMethod$2 = getIteratorMethod$4;
var $Array$1 = Array;
// `Array.from` method implementation
// https://tc39.es/ecma262/#sec-array.from
var arrayFrom$1 = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject$7(arrayLike);
var IS_CONSTRUCTOR = isConstructor$1(this);
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
if (mapping) mapfn = bind$8(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
var iteratorMethod = getIteratorMethod$2(O);
var index = 0;
var length, result, step, iterator, next, value;
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod && !(this === $Array$1 && isArrayIteratorMethod$1(iteratorMethod))) {
iterator = getIterator$2(O, iteratorMethod);
next = iterator.next;
result = IS_CONSTRUCTOR ? new this() : [];
for (;!(step = call$g(next, iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty$2(result, index, value);
}
} else {
length = lengthOfArrayLike$5(O);
result = IS_CONSTRUCTOR ? new this(length) : $Array$1(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty$2(result, index, value);
}
}
result.length = index;
return result;
};
var wellKnownSymbol$i = wellKnownSymbol$t;
var ITERATOR$7 = wellKnownSymbol$i('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR$7] = function () {
return this;
};
// eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing
Array.from(iteratorWithReturn, function () { throw 2; });
} catch (error) { /* empty */ }
var checkCorrectnessOfIteration$3 = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR$7] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
var $$P = _export;
var from = arrayFrom$1;
var checkCorrectnessOfIteration$2 = checkCorrectnessOfIteration$3;
var INCORRECT_ITERATION = !checkCorrectnessOfIteration$2(function (iterable) {
// eslint-disable-next-line es/no-array-from -- required for testing
Array.from(iterable);
});
// `Array.from` method
// https://tc39.es/ecma262/#sec-array.from
$$P({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: from
});
var uncurryThis$w = functionUncurryThis;
var toIntegerOrInfinity$4 = toIntegerOrInfinity$8;
var toString$h = toString$j;
var requireObjectCoercible$a = requireObjectCoercible$d;
var charAt$8 = uncurryThis$w(''.charAt);
var charCodeAt$3 = uncurryThis$w(''.charCodeAt);
var stringSlice$a = uncurryThis$w(''.slice);
var createMethod$4 = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = toString$h(requireObjectCoercible$a($this));
var position = toIntegerOrInfinity$4(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = charCodeAt$3(S, position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = charCodeAt$3(S, position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING
? charAt$8(S, position)
: first
: CONVERT_TO_STRING
? stringSlice$a(S, position, position + 2)
: (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
var stringMultibyte = {
// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod$4(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod$4(true)
};
var fails$r = fails$J;
var correctPrototypeGetter = !fails$r(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
var hasOwn$d = hasOwnProperty_1;
var isCallable$h = isCallable$u;
var toObject$6 = toObject$d;
var sharedKey$1 = sharedKey$4;
var CORRECT_PROTOTYPE_GETTER$1 = correctPrototypeGetter;
var IE_PROTO = sharedKey$1('IE_PROTO');
var $Object = Object;
var ObjectPrototype$2 = $Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
// eslint-disable-next-line es/no-object-getprototypeof -- safe
var objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER$1 ? $Object.getPrototypeOf : function (O) {
var object = toObject$6(O);
if (hasOwn$d(object, IE_PROTO)) return object[IE_PROTO];
var constructor = object.constructor;
if (isCallable$h(constructor) && object instanceof constructor) {
return constructor.prototype;
} return object instanceof $Object ? ObjectPrototype$2 : null;
};
var fails$q = fails$J;
var isCallable$g = isCallable$u;
var isObject$e = isObject$o;
var getPrototypeOf$1 = objectGetPrototypeOf;
var defineBuiltIn$d = defineBuiltIn$i;
var wellKnownSymbol$h = wellKnownSymbol$t;
var ITERATOR$6 = wellKnownSymbol$h('iterator');
var BUGGY_SAFARI_ITERATORS$1 = false;
// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype$2, PrototypeOfArrayIteratorPrototype, arrayIterator;
/* eslint-disable es/no-array-prototype-keys -- safe */
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS$1 = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf$1(getPrototypeOf$1(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = !isObject$e(IteratorPrototype$2) || fails$q(function () {
var test = {};
// FF44- legacy iterators case
return IteratorPrototype$2[ITERATOR$6].call(test) !== test;
});
if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype$2 = {};
// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if (!isCallable$g(IteratorPrototype$2[ITERATOR$6])) {
defineBuiltIn$d(IteratorPrototype$2, ITERATOR$6, function () {
return this;
});
}
var iteratorsCore = {
IteratorPrototype: IteratorPrototype$2,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1
};
var defineProperty$a = objectDefineProperty.f;
var hasOwn$c = hasOwnProperty_1;
var wellKnownSymbol$g = wellKnownSymbol$t;
var TO_STRING_TAG$1 = wellKnownSymbol$g('toStringTag');
var setToStringTag$7 = function (target, TAG, STATIC) {
if (target && !STATIC) target = target.prototype;
if (target && !hasOwn$c(target, TO_STRING_TAG$1)) {
defineProperty$a(target, TO_STRING_TAG$1, { configurable: true, value: TAG });
}
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var create$4 = objectCreate;
var createPropertyDescriptor$2 = createPropertyDescriptor$6;
var setToStringTag$6 = setToStringTag$7;
var Iterators$2 = iterators;
var returnThis$1 = function () { return this; };
var iteratorCreateConstructor = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create$4(IteratorPrototype$1, { next: createPropertyDescriptor$2(+!ENUMERABLE_NEXT, next) });
setToStringTag$6(IteratorConstructor, TO_STRING_TAG, false);
Iterators$2[TO_STRING_TAG] = returnThis$1;
return IteratorConstructor;
};
var isCallable$f = isCallable$u;
var $String$1 = String;
var $TypeError$9 = TypeError;
var aPossiblePrototype$1 = function (argument) {
if (typeof argument == 'object' || isCallable$f(argument)) return argument;
throw $TypeError$9("Can't set " + $String$1(argument) + ' as a prototype');
};
/* eslint-disable no-proto -- safe */
var uncurryThis$v = functionUncurryThis;
var anObject$b = anObject$l;
var aPossiblePrototype = aPossiblePrototype$1;
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
setter = uncurryThis$v(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set);
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject$b(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var $$O = _export;
var call$f = functionCall;
var FunctionName = functionName;
var isCallable$e = isCallable$u;
var createIteratorConstructor$1 = iteratorCreateConstructor;
var getPrototypeOf = objectGetPrototypeOf;
var setPrototypeOf$3 = objectSetPrototypeOf;
var setToStringTag$5 = setToStringTag$7;
var createNonEnumerableProperty$3 = createNonEnumerableProperty$7;
var defineBuiltIn$c = defineBuiltIn$i;
var wellKnownSymbol$f = wellKnownSymbol$t;
var Iterators$1 = iterators;
var IteratorsCore = iteratorsCore;
var PROPER_FUNCTION_NAME$1 = FunctionName.PROPER;
var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR$5 = wellKnownSymbol$f('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis = function () { return this; };
var iteratorDefine = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor$1(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR$5]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf$3) {
setPrototypeOf$3(CurrentIteratorPrototype, IteratorPrototype);
} else if (!isCallable$e(CurrentIteratorPrototype[ITERATOR$5])) {
defineBuiltIn$c(CurrentIteratorPrototype, ITERATOR$5, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag$5(CurrentIteratorPrototype, TO_STRING_TAG, true);
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (PROPER_FUNCTION_NAME$1 && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
if (CONFIGURABLE_FUNCTION_NAME) {
createNonEnumerableProperty$3(IterablePrototype, 'name', VALUES);
} else {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return call$f(nativeIterator, this); };
}
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
defineBuiltIn$c(IterablePrototype, KEY, methods[KEY]);
}
} else $$O({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
// define iterator
if (IterablePrototype[ITERATOR$5] !== defaultIterator) {
defineBuiltIn$c(IterablePrototype, ITERATOR$5, defaultIterator, { name: DEFAULT });
}
Iterators$1[NAME] = defaultIterator;
return methods;
};
// `CreateIterResultObject` abstract operation
// https://tc39.es/ecma262/#sec-createiterresultobject
var createIterResultObject$3 = function (value, done) {
return { value: value, done: done };
};
var charAt$7 = stringMultibyte.charAt;
var toString$g = toString$j;
var InternalStateModule$7 = internalState;
var defineIterator$2 = iteratorDefine;
var createIterResultObject$2 = createIterResultObject$3;
var STRING_ITERATOR = 'String Iterator';
var setInternalState$7 = InternalStateModule$7.set;
var getInternalState$2 = InternalStateModule$7.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator$2(String, 'String', function (iterated) {
setInternalState$7(this, {
type: STRING_ITERATOR,
string: toString$g(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState$2(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return createIterResultObject$2(undefined, true);
point = charAt$7(string, index);
state.index += point.length;
return createIterResultObject$2(point, false);
});
var $$N = _export;
var uncurryThis$u = functionUncurryThis;
var IndexedObject$1 = indexedObject;
var toIndexedObject$7 = toIndexedObject$d;
var arrayMethodIsStrict$5 = arrayMethodIsStrict$8;
var nativeJoin = uncurryThis$u([].join);
var ES3_STRINGS = IndexedObject$1 != Object;
var STRICT_METHOD$5 = arrayMethodIsStrict$5('join', ',');
// `Array.prototype.join` method
// https://tc39.es/ecma262/#sec-array.prototype.join
$$N({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$5 }, {
join: function join(separator) {
return nativeJoin(toIndexedObject$7(this), separator === undefined ? ',' : separator);
}
});
var $$M = _export;
var $includes = arrayIncludes.includes;
var fails$p = fails$J;
var addToUnscopables$2 = addToUnscopables$4;
// FF99+ bug
var BROKEN_ON_SPARSE = fails$p(function () {
return !Array(1).includes();
});
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
$$M({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables$2('includes');
var isObject$d = isObject$o;
var classof$5 = classofRaw$2;
var wellKnownSymbol$e = wellKnownSymbol$t;
var MATCH$2 = wellKnownSymbol$e('match');
// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
var isRegexp = function (it) {
var isRegExp;
return isObject$d(it) && ((isRegExp = it[MATCH$2]) !== undefined ? !!isRegExp : classof$5(it) == 'RegExp');
};
var isRegExp$2 = isRegexp;
var $TypeError$8 = TypeError;
var notARegexp = function (it) {
if (isRegExp$2(it)) {
throw $TypeError$8("The method doesn't accept regular expressions");
} return it;
};
var wellKnownSymbol$d = wellKnownSymbol$t;
var MATCH$1 = wellKnownSymbol$d('match');
var correctIsRegexpLogic = function (METHOD_NAME) {
var regexp = /./;
try {
'/./'[METHOD_NAME](regexp);
} catch (error1) {
try {
regexp[MATCH$1] = false;
return '/./'[METHOD_NAME](regexp);
} catch (error2) { /* empty */ }
} return false;
};
var $$L = _export;
var uncurryThis$t = functionUncurryThis;
var notARegExp$1 = notARegexp;
var requireObjectCoercible$9 = requireObjectCoercible$d;
var toString$f = toString$j;
var correctIsRegExpLogic$1 = correctIsRegexpLogic;
var stringIndexOf$3 = uncurryThis$t(''.indexOf);
// `String.prototype.includes` method
// https://tc39.es/ecma262/#sec-string.prototype.includes
$$L({ target: 'String', proto: true, forced: !correctIsRegExpLogic$1('includes') }, {
includes: function includes(searchString /* , position = 0 */) {
return !!~stringIndexOf$3(
toString$f(requireObjectCoercible$9(this)),
toString$f(notARegExp$1(searchString)),
arguments.length > 1 ? arguments[1] : undefined
);
}
});
// a string of all valid unicode whitespaces
var whitespaces$4 = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
'\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
var uncurryThis$s = functionUncurryThis;
var requireObjectCoercible$8 = requireObjectCoercible$d;
var toString$e = toString$j;
var whitespaces$3 = whitespaces$4;
var replace$8 = uncurryThis$s(''.replace);
var whitespace = '[' + whitespaces$3 + ']';
var ltrim = RegExp('^' + whitespace + whitespace + '*');
var rtrim = RegExp(whitespace + whitespace + '*$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod$3 = function (TYPE) {
return function ($this) {
var string = toString$e(requireObjectCoercible$8($this));
if (TYPE & 1) string = replace$8(string, ltrim, '');
if (TYPE & 2) string = replace$8(string, rtrim, '');
return string;
};
};
var stringTrim = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimstart
start: createMethod$3(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimend
end: createMethod$3(2),
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
trim: createMethod$3(3)
};
var global$n = global$B;
var fails$o = fails$J;
var uncurryThis$r = functionUncurryThis;
var toString$d = toString$j;
var trim$2 = stringTrim.trim;
var whitespaces$2 = whitespaces$4;
var $parseInt$1 = global$n.parseInt;
var Symbol$2 = global$n.Symbol;
var ITERATOR$4 = Symbol$2 && Symbol$2.iterator;
var hex = /^[+-]?0x/i;
var exec$4 = uncurryThis$r(hex.exec);
var FORCED$7 = $parseInt$1(whitespaces$2 + '08') !== 8 || $parseInt$1(whitespaces$2 + '0x16') !== 22
// MS Edge 18- broken with boxed symbols
|| (ITERATOR$4 && !fails$o(function () { $parseInt$1(Object(ITERATOR$4)); }));
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
var numberParseInt = FORCED$7 ? function parseInt(string, radix) {
var S = trim$2(toString$d(string));
return $parseInt$1(S, (radix >>> 0) || (exec$4(hex, S) ? 16 : 10));
} : $parseInt$1;
var $$K = _export;
var $parseInt = numberParseInt;
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
$$K({ global: true, forced: parseInt != $parseInt }, {
parseInt: $parseInt
});
var toIndexedObject$6 = toIndexedObject$d;
var addToUnscopables$1 = addToUnscopables$4;
var Iterators = iterators;
var InternalStateModule$6 = internalState;
var defineProperty$9 = objectDefineProperty.f;
var defineIterator$1 = iteratorDefine;
var createIterResultObject$1 = createIterResultObject$3;
var DESCRIPTORS$f = descriptors;
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState$6 = InternalStateModule$6.set;
var getInternalState$1 = InternalStateModule$6.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
var es_array_iterator = defineIterator$1(Array, 'Array', function (iterated, kind) {
setInternalState$6(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject$6(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState$1(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return createIterResultObject$1(undefined, true);
}
if (kind == 'keys') return createIterResultObject$1(index, false);
if (kind == 'values') return createIterResultObject$1(target[index], false);
return createIterResultObject$1([index, target[index]], false);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values = Iterators.Arguments = Iterators.Array;
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables$1('keys');
addToUnscopables$1('values');
addToUnscopables$1('entries');
// V8 ~ Chrome 45- bug
if (DESCRIPTORS$f && values.name !== 'values') try {
defineProperty$9(values, 'name', { value: 'values' });
} catch (error) { /* empty */ }
var global$m = global$B;
var DOMIterables = domIterables;
var DOMTokenListPrototype = domTokenListPrototype;
var ArrayIteratorMethods = es_array_iterator;
var createNonEnumerableProperty$2 = createNonEnumerableProperty$7;
var wellKnownSymbol$c = wellKnownSymbol$t;
var ITERATOR$3 = wellKnownSymbol$c('iterator');
var TO_STRING_TAG = wellKnownSymbol$c('toStringTag');
var ArrayValues = ArrayIteratorMethods.values;
var handlePrototype = function (CollectionPrototype, COLLECTION_NAME) {
if (CollectionPrototype) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[ITERATOR$3] !== ArrayValues) try {
createNonEnumerableProperty$2(CollectionPrototype, ITERATOR$3, ArrayValues);
} catch (error) {
CollectionPrototype[ITERATOR$3] = ArrayValues;
}
if (!CollectionPrototype[TO_STRING_TAG]) {
createNonEnumerableProperty$2(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
}
if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
createNonEnumerableProperty$2(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
} catch (error) {
CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
}
}
}
};
for (var COLLECTION_NAME in DOMIterables) {
handlePrototype(global$m[COLLECTION_NAME] && global$m[COLLECTION_NAME].prototype, COLLECTION_NAME);
}
handlePrototype(DOMTokenListPrototype, 'DOMTokenList');
var PROPER_FUNCTION_NAME = functionName.PROPER;
var fails$n = fails$J;
var whitespaces$1 = whitespaces$4;
var non = '\u200B\u0085\u180E';
// check that a method works with the correct list
// of whitespaces and has a correct name
var stringTrimForced = function (METHOD_NAME) {
return fails$n(function () {
return !!whitespaces$1[METHOD_NAME]()
|| non[METHOD_NAME]() !== non
|| (PROPER_FUNCTION_NAME && whitespaces$1[METHOD_NAME].name !== METHOD_NAME);
});
};
var $$J = _export;
var $trim = stringTrim.trim;
var forcedStringTrimMethod = stringTrimForced;
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
$$J({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {
trim: function trim() {
return $trim(this);
}
});
var selectors = ['input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'a[href]', 'button:not([disabled])', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])'];
var tabSelectors = [].concat(selectors, ['[tabindex]:not([tabindex^="-"]):not([disabled])']);
var focusSelectors = [].concat(selectors, ['[tabindex]:not([disabled])']);
var HelpersUtil = {
/**
* Returns array of tabbable elements
* @param {HTMLElement} node container to search, default is document
* @returns {Array} returns elements that can be tabbed to using the keyboard
*/
getTabbableElements: function getTabbableElements(node) {
if (node === void 0) {
node = document;
}
return Array.from(node.querySelectorAll(tabSelectors.join(', ')));
},
/**
* Checks if a node is a tabbable element
* @param {HTMLElement} node the node to compare
* @returns {boolean} returns true or false depending on whether the node is considered tabbable or not
*/
isElementTabbable: function isElementTabbable(node) {
return node.matches(tabSelectors.join(', '));
},
getUid: function getUid() {
// Convert random number to base 36 (numbers + letters),
// and grab the first 9 characters after the decimal.
return Math.random().toString(36).slice(2, 9);
},
/**
* Returns array of focusable elements
* @param {HTMLElement} node container to search, default is document
* @returns {Array} returns elements that can receive focus
*/
getFocusableElements: function getFocusableElements(node) {
if (node === void 0) {
node = document;
}
return Array.from(node.querySelectorAll(focusSelectors.join(', ')));
},
/**
* Returns outer height of element, includes element offsetHeight
* @param {HTMLElement} node container to search
* @param {object} options
* @param {string[]} options.cssSelectors array of css properties
* @example
* const options = { cssSelectors: ['margin', 'padding'] };
* const options = { cssSelectors: ['marginTop'] };
* @returns {number} returns height value
*/
getElementOuterHeight: function getElementOuterHeight(node, options) {
if (options === void 0) {
options = null;
}
var computedNodeStyles = getComputedStyle(node);
if (!options) {
return computedNodeStyles.offsetHeight;
}
var outerHeight = node.offsetHeight;
options.cssSelectors.forEach(function (selector) {
// if no values are specified, calculate spacing for the top and bottom
if (!selector.toLowerCase().includes('top') && !selector.toLowerCase().includes('bottom')) {
outerHeight += parseInt(computedNodeStyles[selector + 'Top'], 10) + parseInt(computedNodeStyles[selector + 'Bottom'], 10);
} else if (selector.values.length > 0) {
outerHeight += parseInt(computedNodeStyles[selector], 10);
}
});
return outerHeight;
},
/**
* Returns outer width of element, includes element offsetWidth
* @param {HTMLElement} node container to search
* @param {object} options
* @param {string[]} options.cssSelectors array of css properties
* @example
* const options = { cssSelectors: ['margin', 'padding'] };
* const options = { cssSelectors: ['marginLeft'] };
* @returns {number} returns width value
*/
getElementOuterWidth: function getElementOuterWidth(node, options) {
if (options === void 0) {
options = null;
}
var computedNodeStyles = getComputedStyle(node);
if (!options) {
return computedNodeStyles.offsetWidth;
}
var outerWidth = node.offsetWidth;
options.cssSelectors.forEach(function (selector) {
// if no values are specifed, calculate spacing for the left and right
if (!selector.toLowerCase().includes('left') && !selector.toLowerCase().includes('right')) {
outerWidth += parseInt(computedNodeStyles[selector + 'Left'], 10) + parseInt(computedNodeStyles[selector + 'Right'], 10);
} else if (selector.values.length > 0) {
outerWidth += parseInt(computedNodeStyles[selector], 10);
}
});
return outerWidth;
},
/**
* Returns the value of the data-target attribute or null
* @param {HTMLElement} element element with the data-target attribute
* @returns {HTMLElement} returns the value of the data-target attribute or null
*/
getSelectorFromElement: function getSelectorFromElement(element) {
try {
var selector = element.getAttribute('data-target');
if (!selector || selector === '#') {
var hrefAttr = element.getAttribute('href');
selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : '';
}
return selector;
} catch (_unused) {
return null;
}
},
/**
* Gets the offset height of the element
* @param {HTMLElement} element the element
* @returns {number} returns the offset height
*/
reflow: function reflow(element) {
return element.offsetHeight;
},
/**
* Gets the full height of the document
* May be a little dated but this seems to be an established approach
* https://javascript.info/size-and-scroll-window#width-height-of-the-document
* @returns {number} the full height of the document
*/
getDocumentHeight: function getDocumentHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight);
}
};
// TODO: Remove from `core-js@4` since it's moved to entry points
var uncurryThis$q = functionUncurryThis;
var defineBuiltIn$b = defineBuiltIn$i;
var regexpExec$1 = regexpExec$2;
var fails$m = fails$J;
var wellKnownSymbol$b = wellKnownSymbol$t;
var createNonEnumerableProperty$1 = createNonEnumerableProperty$7;
var SPECIES$3 = wellKnownSymbol$b('species');
var RegExpPrototype$1 = RegExp.prototype;
var fixRegexpWellKnownSymbolLogic = function (KEY, exec, FORCED, SHAM) {
var SYMBOL = wellKnownSymbol$b(KEY);
var DELEGATES_TO_SYMBOL = !fails$m(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails$m(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
if (KEY === 'split') {
// We can't use real regex here since it causes deoptimization
// and serious performance degradation in V8
// https://github.com/zloirock/core-js/issues/306
re = {};
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES$3] = function () { return re; };
re.flags = '';
re[SYMBOL] = /./[SYMBOL];
}
re.exec = function () { execCalled = true; return null; };
re[SYMBOL]('');
return !execCalled;
});
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
FORCED
) {
var uncurriedNativeRegExpMethod = uncurryThis$q(/./[SYMBOL]);
var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
var uncurriedNativeMethod = uncurryThis$q(nativeMethod);
var $exec = regexp.exec;
if ($exec === regexpExec$1 || $exec === RegExpPrototype$1.exec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: uncurriedNativeRegExpMethod(regexp, str, arg2) };
}
return { done: true, value: uncurriedNativeMethod(str, regexp, arg2) };
}
return { done: false };
});
defineBuiltIn$b(String.prototype, KEY, methods[0]);
defineBuiltIn$b(RegExpPrototype$1, SYMBOL, methods[1]);
}
if (SHAM) createNonEnumerableProperty$1(RegExpPrototype$1[SYMBOL], 'sham', true);
};
var charAt$6 = stringMultibyte.charAt;
// `AdvanceStringIndex` abstract operation
// https://tc39.es/ecma262/#sec-advancestringindex
var advanceStringIndex$2 = function (S, index, unicode) {
return index + (unicode ? charAt$6(S, index).length : 1);
};
var call$e = functionCall;
var anObject$a = anObject$l;
var isCallable$d = isCallable$u;
var classof$4 = classofRaw$2;
var regexpExec = regexpExec$2;
var $TypeError$7 = TypeError;
// `RegExpExec` abstract operation
// https://tc39.es/ecma262/#sec-regexpexec
var regexpExecAbstract = function (R, S) {
var exec = R.exec;
if (isCallable$d(exec)) {
var result = call$e(exec, R, S);
if (result !== null) anObject$a(result);
return result;
}
if (classof$4(R) === 'RegExp') return call$e(regexpExec, R, S);
throw $TypeError$7('RegExp#exec called on incompatible receiver');
};
var call$d = functionCall;
var fixRegExpWellKnownSymbolLogic$2 = fixRegexpWellKnownSymbolLogic;
var anObject$9 = anObject$l;
var isNullOrUndefined$7 = isNullOrUndefined$b;
var toLength$3 = toLength$5;
var toString$c = toString$j;
var requireObjectCoercible$7 = requireObjectCoercible$d;
var getMethod$3 = getMethod$7;
var advanceStringIndex$1 = advanceStringIndex$2;
var regExpExec$3 = regexpExecAbstract;
// @@match logic
fixRegExpWellKnownSymbolLogic$2('match', function (MATCH, nativeMatch, maybeCallNative) {
return [
// `String.prototype.match` method
// https://tc39.es/ecma262/#sec-string.prototype.match
function match(regexp) {
var O = requireObjectCoercible$7(this);
var matcher = isNullOrUndefined$7(regexp) ? undefined : getMethod$3(regexp, MATCH);
return matcher ? call$d(matcher, regexp, O) : new RegExp(regexp)[MATCH](toString$c(O));
},
// `RegExp.prototype[@@match]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@match
function (string) {
var rx = anObject$9(this);
var S = toString$c(string);
var res = maybeCallNative(nativeMatch, rx, S);
if (res.done) return res.value;
if (!rx.global) return regExpExec$3(rx, S);
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
var A = [];
var n = 0;
var result;
while ((result = regExpExec$3(rx, S)) !== null) {
var matchStr = toString$c(result[0]);
A[n] = matchStr;
if (matchStr === '') rx.lastIndex = advanceStringIndex$1(S, toLength$3(rx.lastIndex), fullUnicode);
n++;
}
return n === 0 ? null : A;
}
];
});
var ColorUtil = {
/**
* Calculates the YIQ of the color
* @param {object} rgb The RGB notation of the color
* @returns {number}
*/
getYiq: function getYiq(_ref) {
var r = _ref.r,
g = _ref.g,
b = _ref.b;
return (r * 299 + g * 587 + b * 114) / 1000;
},
/**
* Gets the RGB object notation for a string
* @param {string} str a string representing a css rgb value
* @returns {object} an object for rgb notation
*/
getRGB: function getRGB(str) {
var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d\.\d?)\))?/);
return match ? {
r: match[1],
g: match[2],
b: match[3]
} : {};
}
};
// https://keycode.info/table-of-all-keycodes
var KeyboardUtil = {
keyCodes: {
ARROW_DOWN: 40,
ARROW_LEFT: 37,
ARROW_RIGHT: 39,
ARROW_UP: 38,
BACKSPACE: 8,
CLEAR: 12,
END: 35,
ENTER: 13,
ESC: 27,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
SPACE: 32,
TAB: 9
},
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
keys: {
ARROW_DOWN: 'ArrowDown',
ARROW_LEFT: 'ArrowLeft',
ARROW_RIGHT: 'ArrowRight',
ARROW_UP: 'ArrowUp',
BACKSPACE: 'Backspace',
CLEAR: 'Clear',
END: 'End',
ENTER: 'Enter',
ESC: 'Escape',
HOME: 'Home',
PAGE_DOWN: 'PageDown',
PAGE_UP: 'PageUp',
SPACE: ' ',
TAB: 'Tab'
},
getKeyCode: function getKeyCode(e) {
return e.which || e.keyCode || 0;
}
};
var NATIVE_BIND = functionBindNative;
var FunctionPrototype$1 = Function.prototype;
var apply$6 = FunctionPrototype$1.apply;
var call$c = FunctionPrototype$1.call;
// eslint-disable-next-line es/no-reflect -- safe
var functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call$c.bind(apply$6) : function () {
return call$c.apply(apply$6, arguments);
});
var uncurryThis$p = functionUncurryThis;
var toObject$5 = toObject$d;
var floor$5 = Math.floor;
var charAt$5 = uncurryThis$p(''.charAt);
var replace$7 = uncurryThis$p(''.replace);
var stringSlice$9 = uncurryThis$p(''.slice);
var SUBSTITUTION_SYMBOLS = /$([$&'`]|\d{1,2}|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /$([$&'`]|\d{1,2})/g;
// `GetSubstitution` abstract operation
// https://tc39.es/ecma262/#sec-getsubstitution
var getSubstitution$2 = function (matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject$5(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return replace$7(replacement, symbols, function (match, ch) {
var capture;
switch (charAt$5(ch, 0)) {
case '$': return '$';
case '&': return matched;
case '`': return stringSlice$9(str, 0, position);
case "'": return stringSlice$9(str, tailPos);
case '<':
capture = namedCaptures[stringSlice$9(ch, 1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor$5(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? charAt$5(ch, 1) : captures[f - 1] + charAt$5(ch, 1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
};
var apply$5 = functionApply;
var call$b = functionCall;
var uncurryThis$o = functionUncurryThis;
var fixRegExpWellKnownSymbolLogic$1 = fixRegexpWellKnownSymbolLogic;
var fails$l = fails$J;
var anObject$8 = anObject$l;
var isCallable$c = isCallable$u;
var isNullOrUndefined$6 = isNullOrUndefined$b;
var toIntegerOrInfinity$3 = toIntegerOrInfinity$8;
var toLength$2 = toLength$5;
var toString$b = toString$j;
var requireObjectCoercible$6 = requireObjectCoercible$d;
var advanceStringIndex = advanceStringIndex$2;
var getMethod$2 = getMethod$7;
var getSubstitution$1 = getSubstitution$2;
var regExpExec$2 = regexpExecAbstract;
var wellKnownSymbol$a = wellKnownSymbol$t;
var REPLACE$1 = wellKnownSymbol$a('replace');
var max$2 = Math.max;
var min$2 = Math.min;
var concat = uncurryThis$o([].concat);
var push$7 = uncurryThis$o([].push);
var stringIndexOf$2 = uncurryThis$o(''.indexOf);
var stringSlice$8 = uncurryThis$o(''.slice);
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// IE <= 11 replaces $0 with the whole match, as if it was $&
// https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
var REPLACE_KEEPS_$0 = (function () {
// eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing
return 'a'.replace(/./, '$0') === '$0';
})();
// Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () {
if (/./[REPLACE$1]) {
return /./[REPLACE$1]('a', '$0') === '';
}
return false;
})();
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails$l(function () {
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
// eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive
return ''.replace(re, '$') !== '7';
});
// @@replace logic
fixRegExpWellKnownSymbolLogic$1('replace', function (_, nativeReplace, maybeCallNative) {
var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';
return [
// `String.prototype.replace` method
// https://tc39.es/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = requireObjectCoercible$6(this);
var replacer = isNullOrUndefined$6(searchValue) ? undefined : getMethod$2(searchValue, REPLACE$1);
return replacer
? call$b(replacer, searchValue, O, replaceValue)
: call$b(nativeReplace, toString$b(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
function (string, replaceValue) {
var rx = anObject$8(this);
var S = toString$b(string);
if (
typeof replaceValue == 'string' &&
stringIndexOf$2(replaceValue, UNSAFE_SUBSTITUTE) === -1 &&
stringIndexOf$2(replaceValue, '$<') === -1
) {
var res = maybeCallNative(nativeReplace, rx, S, replaceValue);
if (res.done) return res.value;
}
var functionalReplace = isCallable$c(replaceValue);
if (!functionalReplace) replaceValue = toString$b(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regExpExec$2(rx, S);
if (result === null) break;
push$7(results, result);
if (!global) break;
var matchStr = toString$b(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength$2(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = toString$b(result[0]);
var position = max$2(min$2(toIntegerOrInfinity$3(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) push$7(captures, maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = concat([matched], captures, position, S);
if (namedCaptures !== undefined) push$7(replacerArgs, namedCaptures);
var replacement = toString$b(apply$5(replaceValue, undefined, replacerArgs));
} else {
replacement = getSubstitution$1(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += stringSlice$8(S, nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + stringSlice$8(S, nextSourcePosition);
}
];
}, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);
var StringUtil = {
/**
* Interpolate a string.
* @param {string} template - The template string to interpolate, with keys in the format %{key}.
* @param {object} data - An object containing the keys and values to replace in the template.
* @returns {string} - The interpolated string.
*/
interpolateString: function interpolateString(template, data) {
return template.replace(/%{(\w+)}/g, function (match, key) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
return data[key];
}
// %{key} not found, show a warning in the console and return an empty string
// eslint-disable-next-line no-console
console.warn("Template error, %{" + key + "} not found:", template);
return '';
});
}
};
var EventName$C = {
ON_REMOVE: 'onRemove'
};
var focusControls = [];
/**
* Class representing Focus Controls.
* Solve for Firefox bug where following on-page anchor links loses focus:
* https://bugzilla.mozilla.org/show_bug.cgi?id=308064
* https://bugzilla.mozilla.org/show_bug.cgi?id=277178
*/
var FocusControls = /*#__PURE__*/function () {
/**
* Create a FocusControls instance
* @param {Object} opts - The focus control options.
* @param {HTMLElement} opts.el - The anchor element node, must have href attribute with fragment identifier.
*/
function FocusControls(opts) {
var _this = this;
this.el = opts.el;
this.target = document.querySelector(this.el.getAttribute('href'));
this.events = [{
el: this.el,
type: 'click',
handler: function handler(e) {
_this.onClick(e);
}
}];
// Add event handlers.
InitializationUtil.addEvents(this.events);
focusControls.push(this);
}
/**
* Click event.
* @param {Event} e - The event object.
*/
var _proto = FocusControls.prototype;
_proto.onClick = function onClick(e) {
e.preventDefault();
// removes focus if target element is already focused (for voiceover on mobile)
if (document.activeElement === this.target) {
document.activeElement.blur();
}
this.target.focus();
this.target.scrollIntoView();
}
/**
* Remove the focus controls and events.
*/;
_proto.remove = function remove() {
// Remove event handlers
InitializationUtil.removeEvents(this.events);
// Remove this focus controls reference from array of instances
var index = focusControls.indexOf(this);
focusControls.splice(index, 1);
// Create and dispatch custom event
this[EventName$C.ON_REMOVE] = new CustomEvent(EventName$C.ON_REMOVE, {
bubbles: true
});
this.el.dispatchEvent(this[EventName$C.ON_REMOVE]);
}
/**
* Get an array of focus controls instances.
* @returns {Object[]} Array of focus controls instances.
*/;
FocusControls.getInstances = function getInstances() {
return focusControls;
};
return FocusControls;
}();
var global$l = global$B;
var fails$k = fails$J;
var uncurryThis$n = functionUncurryThis;
var toString$a = toString$j;
var trim$1 = stringTrim.trim;
var whitespaces = whitespaces$4;
var charAt$4 = uncurryThis$n(''.charAt);
var $parseFloat$1 = global$l.parseFloat;
var Symbol$1 = global$l.Symbol;
var ITERATOR$2 = Symbol$1 && Symbol$1.iterator;
var FORCED$6 = 1 / $parseFloat$1(whitespaces + '-0') !== -Infinity
// MS Edge 18- broken with boxed symbols
|| (ITERATOR$2 && !fails$k(function () { $parseFloat$1(Object(ITERATOR$2)); }));
// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
var numberParseFloat = FORCED$6 ? function parseFloat(string) {
var trimmedString = trim$1(toString$a(string));
var result = $parseFloat$1(trimmedString);
return result === 0 && charAt$4(trimmedString, 0) == '-' ? -0 : result;
} : $parseFloat$1;
var $$I = _export;
var $parseFloat = numberParseFloat;
// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
$$I({ global: true, forced: parseFloat != $parseFloat }, {
parseFloat: $parseFloat
});
var $TypeError$6 = TypeError;
var validateArgumentsLength$4 = function (passed, required) {
if (passed < required) throw $TypeError$6('Not enough arguments');
return passed;
};
var global$k = global$B;
var apply$4 = functionApply;
var isCallable$b = isCallable$u;
var userAgent$5 = engineUserAgent;
var arraySlice$6 = arraySlice$8;
var validateArgumentsLength$3 = validateArgumentsLength$4;
var MSIE = /MSIE .\./.test(userAgent$5); // <- dirty ie9- check
var Function$2 = global$k.Function;
var wrap$1 = function (scheduler) {
return MSIE ? function (handler, timeout /* , ...arguments */) {
var boundArgs = validateArgumentsLength$3(arguments.length, 1) > 2;
var fn = isCallable$b(handler) ? handler : Function$2(handler);
var args = boundArgs ? arraySlice$6(arguments, 2) : undefined;
return scheduler(boundArgs ? function () {
apply$4(fn, this, args);
} : fn, timeout);
} : scheduler;
};
// ie9- setTimeout & setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
var schedulersFix = {
// `setTimeout` method
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
setTimeout: wrap$1(global$k.setTimeout),
// `setInterval` method
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
setInterval: wrap$1(global$k.setInterval)
};
var $$H = _export;
var global$j = global$B;
var setInterval$1 = schedulersFix.setInterval;
// ie9- setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
$$H({ global: true, bind: true, forced: global$j.setInterval !== setInterval$1 }, {
setInterval: setInterval$1
});
var $$G = _export;
var global$i = global$B;
var setTimeout$1 = schedulersFix.setTimeout;
// ie9- setTimeout additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
$$G({ global: true, bind: true, forced: global$i.setTimeout !== setTimeout$1 }, {
setTimeout: setTimeout$1
});
var TRANSITION_END = 'transitionend';
/**
* Gets the transition duration from an element's styles
* @param {HTMLElement} element - element
* @returns {number} - transition duration in milliseconds
*/
var getTransitionDurationFromElement = function getTransitionDurationFromElement(element) {
var MILLISECONDS_MULTIPLIER = 1000;
if (!element) {
return 0;
}
// Get transition-duration of the element
var transitionDuration = getComputedStyle(element)['transition-duration'];
var transitionDelay = getComputedStyle(element)['transition-delay'];
var floatTransitionDuration = parseFloat(transitionDuration);
var floatTransitionDelay = parseFloat(transitionDelay);
// Return 0 if element or transition duration is not found
if (!floatTransitionDuration && !floatTransitionDelay) {
return 0;
}
// If multiple durations are defined, take the first
transitionDuration = transitionDuration.split(',')[0];
transitionDelay = transitionDelay.split(',')[0];
return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
};
/**
* Dispatches a transition-end event.
* @param {HTMLElement} element - element on which to dispatch event
*/
var triggerTransitionEnd = function triggerTransitionEnd(element) {
element.dispatchEvent(new Event(TRANSITION_END));
};
/**
* Ensures transition-end is triggered on an element.
* @param {HTMLElement} element - element on which transition occurs
* @param {number} duration - transition duration in milliseconds
*/
var emulateTransitionEnd = function emulateTransitionEnd(element, duration) {
if (duration === void 0) {
duration = 0;
}
var called = false;
var durationPadding = 5;
var emulatedDuration = duration + durationPadding;
function listener() {
called = true;
element.removeEventListener(TRANSITION_END, listener);
}
element.addEventListener(TRANSITION_END, listener);
setTimeout(function () {
if (!called) {
triggerTransitionEnd(element);
}
}, emulatedDuration);
};
var TransitionUtil = {
TRANSITION_END: TRANSITION_END,
getTransitionDurationFromElement: getTransitionDurationFromElement,
triggerTransitionEnd: triggerTransitionEnd,
emulateTransitionEnd: emulateTransitionEnd
};
var Util$1 = Object.assign({}, DetectionUtil, HelpersUtil, InitializationUtil, ColorUtil, KeyboardUtil, StringUtil, {
FocusControls: FocusControls
}, TransitionUtil);
// TODO: Remove from `core-js@4`
var $$F = _export;
var uncurryThis$m = functionUncurryThis;
var $Date = Date;
var thisTimeValue$1 = uncurryThis$m($Date.prototype.getTime);
// `Date.now` method
// https://tc39.es/ecma262/#sec-date.now
$$F({ target: 'Date', stat: true }, {
now: function now() {
return thisTimeValue$1(new $Date());
}
});
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
* as-is, to `callback` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* `delay` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
* false (at end), schedule `callback` to execute after `delay` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle(delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* `callback` is executed at the proper times in `throttle` and `end`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time `callback` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec
function cancel(options) {
var _ref2 = options || {},
_ref2$upcomingOnly = _ref2.upcomingOnly,
upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
/*
* The `wrapper` function encapsulates all of the throttling / debouncing
* functionality and when executed will limit the rate at which `callback`
* is executed.
*/
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
} // Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
/*
* If `debounceMode` is true (at begin) this is used to clear the flag
* to allow future `callback` executions.
*/
function clear() {
timeoutID = undefined;
}
if (!noLeading && debounceMode && !timeoutID) {
/*
* Since `wrapper` is being called for the first time and
* `debounceMode` is true (at begin), execute `callback`
* and noLeading != true.
*/
exec();
}
clearExistingTimeout();
if (debounceMode === undefined && elapsed > delay) {
if (noLeading) {
/*
* In throttle mode with noLeading, if `delay` time has
* been exceeded, update `lastExec` and schedule `callback`
* to execute after `delay` ms.
*/
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
/*
* In throttle mode without noLeading, if `delay` time has been exceeded, execute
* `callback`.
*/
exec();
}
} else if (noTrailing !== true) {
/*
* In trailing throttle mode, since `delay` time has not been
* exceeded, schedule `callback` to execute `delay` ms after most
* recent execution.
*
* If `debounceMode` is true (at begin), schedule `clear` to execute
* after `delay` ms.
*
* If `debounceMode` is false (at end), schedule `callback` to
* execute after `delay` ms.
*/
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel; // Return the wrapper function.
return wrapper;
}
/* eslint-disable no-undefined */
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
* to `callback` when the debounced-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
* after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
* (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
*
* @returns {Function} A new, debounced function.
*/
function debounce(delay, callback, options) {
var _ref = options || {},
_ref$atBegin = _ref.atBegin,
atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
return throttle(delay, callback, {
debounceMode: atBegin !== false
});
}
var instances$s = [];
var Selector$B = {
DATA_MOUNT: '[data-mount="accordion-extension"]',
COLLAPSE_BUTTON: '[data-mount="collapse"]'
};
var EventName$B = {
ON_REMOVE: 'onRemove'
};
var ClassName$r = {
LIST_ITEM_SHOW: 'accordion-list-show',
ENABLE_COLLAPSE_MOBILE: 'enable-collapse-mobile',
COLLAPSE_SHOW: 'show',
COLLAPSED: 'collapsed',
COLLAPSE: 'collapse'
};
function _click(collapse) {
this.el.querySelectorAll('li').forEach(function (listItem) {
listItem.classList.remove(ClassName$r.LIST_ITEM_SHOW);
});
// expanding - add classname to active trigger's list item
if (!collapse.classList.contains(ClassName$r.COLLAPSED)) {
collapse.closest('li').classList.add(ClassName$r.LIST_ITEM_SHOW);
var collapseEle = collapse.closest('li').querySelector(ClassName$r.COLLAPSE);
if (collapseEle) {
collapseEle.classList.add(ClassName$r.COLLAPSE_SHOW);
}
}
}
function _enableMultiSelectMobile() {
var _this = this;
if (this.disableMobileGroupManagement) {
var collapseInstances = window.mwf.Collapse.getInstances();
var accordionList = Array.prototype.map.call(this.collapseBtnList, function (btn) {
return collapseInstances.find(function (collapse) {
return collapse.triggerElement === btn;
});
});
accordionList.forEach(function (collapse, index) {
if (_this.inMobileViewport()) {
collapse.parent = '';
} else {
collapse.parent = collapse.el.getAttribute('data-parent');
if (_this.intialShowIndex === index) {
collapse.show();
} else {
collapse.hide();
}
}
});
}
}
var AccordionExtension = /*#__PURE__*/function () {
function AccordionExtension(opts) {
var _this2 = this;
this.el = opts.el;
this.collapseBtnList = this.el.querySelectorAll(Selector$B.COLLAPSE_BUTTON);
this.intialShowIndex = 0;
this.disableMobileGroupManagement = this.el.dataset.disableMobileGroupManagement;
this.customViewports = opts.customViewports || ['md', 'lg', 'xl'];
this.mobileViewports = opts.mobileViewports || ['xs', 'sm'];
_enableMultiSelectMobile.call(this);
// find index of intial show accordion
[].slice.call(this.collapseBtnList).forEach(function (btn, i) {
if (btn.className.indexOf('collapsed') === -1) {
_this2.intialShowIndex = i;
}
});
this[EventName$B.ON_REMOVE] = new CustomEvent(EventName$B.ON_REMOVE, {
bubbles: true,
cancelable: true
});
this.events = [];
this.collapseBtnList.forEach(function (collapse) {
_this2.events.push({
el: collapse,
type: 'click',
handler: _click.bind(_this2, collapse)
});
});
if (this.disableMobileGroupManagement) {
this.events.push({
el: window,
type: 'resize',
handler: debounce(300, _enableMultiSelectMobile.bind(this))
});
}
_click.bind(this, this.collapseBtnList[this.intialShowIndex])();
Util$1.addEvents(this.events);
instances$s.push(this);
}
var _proto = AccordionExtension.prototype;
_proto.inMobileViewport = function inMobileViewport() {
var viewport = Util$1.detectViewport();
return this.mobileViewports.indexOf(viewport) > -1;
}
/**
* Remove the instance
*/;
_proto.remove = function remove() {
Util$1.removeEvents(this.events);
this.el.dispatchEvent(this[EventName$B.ON_REMOVE]);
var index = instances$s.indexOf(this);
instances$s.splice(index, 1);
}
/**
* Get alert instances.
* @returns {Object[]} An array of alert instances
*/;
AccordionExtension.getInstances = function getInstances() {
return instances$s;
};
return AccordionExtension;
}();
var $$E = _export;
var toObject$4 = toObject$d;
var nativeKeys = objectKeys$4;
var fails$j = fails$J;
var FAILS_ON_PRIMITIVES$3 = fails$j(function () { nativeKeys(1); });
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
$$E({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$3 }, {
keys: function keys(it) {
return nativeKeys(toObject$4(it));
}
});
var $$D = _export;
var DESCRIPTORS$e = descriptors;
var defineProperty$8 = objectDefineProperty.f;
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
// eslint-disable-next-line es/no-object-defineproperty -- safe
$$D({ target: 'Object', stat: true, forced: Object.defineProperty !== defineProperty$8, sham: !DESCRIPTORS$e }, {
defineProperty: defineProperty$8
});
var $$C = _export;
var $filter = arrayIteration.filter;
var arrayMethodHasSpeciesSupport = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter');
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
$$C({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var classof$3 = classofRaw$2;
var global$h = global$B;
var engineIsNode = classof$3(global$h.process) == 'process';
var getBuiltIn$7 = getBuiltIn$d;
var definePropertyModule$1 = objectDefineProperty;
var wellKnownSymbol$9 = wellKnownSymbol$t;
var DESCRIPTORS$d = descriptors;
var SPECIES$2 = wellKnownSymbol$9('species');
var setSpecies$3 = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn$7(CONSTRUCTOR_NAME);
var defineProperty = definePropertyModule$1.f;
if (DESCRIPTORS$d && Constructor && !Constructor[SPECIES$2]) {
defineProperty(Constructor, SPECIES$2, {
configurable: true,
get: function () { return this; }
});
}
};
var isPrototypeOf$5 = objectIsPrototypeOf;
var $TypeError$5 = TypeError;
var anInstance$6 = function (it, Prototype) {
if (isPrototypeOf$5(Prototype, it)) return it;
throw $TypeError$5('Incorrect invocation');
};
var isConstructor = isConstructor$4;
var tryToString$2 = tryToString$6;
var $TypeError$4 = TypeError;
// `Assert: IsConstructor(argument) is true`
var aConstructor$2 = function (argument) {
if (isConstructor(argument)) return argument;
throw $TypeError$4(tryToString$2(argument) + ' is not a constructor');
};
var anObject$7 = anObject$l;
var aConstructor$1 = aConstructor$2;
var isNullOrUndefined$5 = isNullOrUndefined$b;
var wellKnownSymbol$8 = wellKnownSymbol$t;
var SPECIES$1 = wellKnownSymbol$8('species');
// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
var speciesConstructor$2 = function (O, defaultConstructor) {
var C = anObject$7(O).constructor;
var S;
return C === undefined || isNullOrUndefined$5(S = anObject$7(C)[SPECIES$1]) ? defaultConstructor : aConstructor$1(S);
};
var userAgent$4 = engineUserAgent;
var engineIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent$4);
var global$g = global$B;
var apply$3 = functionApply;
var bind$7 = functionBindContext;
var isCallable$a = isCallable$u;
var hasOwn$b = hasOwnProperty_1;
var fails$i = fails$J;
var html = html$2;
var arraySlice$5 = arraySlice$8;
var createElement = documentCreateElement$2;
var validateArgumentsLength$2 = validateArgumentsLength$4;
var IS_IOS$1 = engineIsIos;
var IS_NODE$4 = engineIsNode;
var set = global$g.setImmediate;
var clear = global$g.clearImmediate;
var process$2 = global$g.process;
var Dispatch = global$g.Dispatch;
var Function$1 = global$g.Function;
var MessageChannel = global$g.MessageChannel;
var String$1 = global$g.String;
var counter = 0;
var queue$1 = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var $location, defer, channel, port;
try {
// Deno throws a ReferenceError on `location` access without `--location` flag
$location = global$g.location;
} catch (error) { /* empty */ }
var run = function (id) {
if (hasOwn$b(queue$1, id)) {
var fn = queue$1[id];
delete queue$1[id];
fn();
}
};
var runner = function (id) {
return function () {
run(id);
};
};
var listener = function (event) {
run(event.data);
};
var post = function (id) {
// old engines have not location.origin
global$g.postMessage(String$1(id), $location.protocol + '//' + $location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set || !clear) {
set = function setImmediate(handler) {
validateArgumentsLength$2(arguments.length, 1);
var fn = isCallable$a(handler) ? handler : Function$1(handler);
var args = arraySlice$5(arguments, 1);
queue$1[++counter] = function () {
apply$3(fn, undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue$1[id];
};
// Node.js 0.8-
if (IS_NODE$4) {
defer = function (id) {
process$2.nextTick(runner(id));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(runner(id));
};
// Browsers with MessageChannel, includes WebWorkers
// except iOS - https://github.com/zloirock/core-js/issues/624
} else if (MessageChannel && !IS_IOS$1) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = bind$7(port.postMessage, port);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global$g.addEventListener &&
isCallable$a(global$g.postMessage) &&
!global$g.importScripts &&
$location && $location.protocol !== 'file:' &&
!fails$i(post)
) {
defer = post;
global$g.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in createElement('script')) {
defer = function (id) {
html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(runner(id), 0);
};
}
}
var task$1 = {
set: set,
clear: clear
};
var userAgent$3 = engineUserAgent;
var global$f = global$B;
var engineIsIosPebble = /ipad|iphone|ipod/i.test(userAgent$3) && global$f.Pebble !== undefined;
var userAgent$2 = engineUserAgent;
var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(userAgent$2);
var global$e = global$B;
var bind$6 = functionBindContext;
var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f;
var macrotask = task$1.set;
var IS_IOS = engineIsIos;
var IS_IOS_PEBBLE = engineIsIosPebble;
var IS_WEBOS_WEBKIT = engineIsWebosWebkit;
var IS_NODE$3 = engineIsNode;
var MutationObserver$1 = global$e.MutationObserver || global$e.WebKitMutationObserver;
var document$2 = global$e.document;
var process$1 = global$e.process;
var Promise$1 = global$e.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor$3(global$e, 'queueMicrotask');
var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
var flush, head, last, notify$1, toggle, node, promise, then;
// modern engines have queueMicrotask method
if (!queueMicrotask) {
flush = function () {
var parent, fn;
if (IS_NODE$3 && (parent = process$1.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (error) {
if (head) notify$1();
else last = undefined;
throw error;
}
} last = undefined;
if (parent) parent.enter();
};
// browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
// also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
if (!IS_IOS && !IS_NODE$3 && !IS_WEBOS_WEBKIT && MutationObserver$1 && document$2) {
toggle = true;
node = document$2.createTextNode('');
new MutationObserver$1(flush).observe(node, { characterData: true });
notify$1 = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (!IS_IOS_PEBBLE && Promise$1 && Promise$1.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
promise = Promise$1.resolve(undefined);
// workaround of WebKit ~ iOS Safari 10.1 bug
promise.constructor = Promise$1;
then = bind$6(promise.then, promise);
notify$1 = function () {
then(flush);
};
// Node.js without promises
} else if (IS_NODE$3) {
notify$1 = function () {
process$1.nextTick(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessage
// - onreadystatechange
// - setTimeout
} else {
// strange IE + webpack dev server bug - use .bind(global)
macrotask = bind$6(macrotask, global$e);
notify$1 = function () {
macrotask(flush);
};
}
}
var microtask$1 = queueMicrotask || function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify$1();
} last = task;
};
var global$d = global$B;
var hostReportErrors$1 = function (a, b) {
var console = global$d.console;
if (console && console.error) {
arguments.length == 1 ? console.error(a) : console.error(a, b);
}
};
var perform$3 = function (exec) {
try {
return { error: false, value: exec() };
} catch (error) {
return { error: true, value: error };
}
};
var Queue$1 = function () {
this.head = null;
this.tail = null;
};
Queue$1.prototype = {
add: function (item) {
var entry = { item: item, next: null };
if (this.head) this.tail.next = entry;
else this.head = entry;
this.tail = entry;
},
get: function () {
var entry = this.head;
if (entry) {
this.head = entry.next;
if (this.tail === entry) this.tail = null;
return entry.item;
}
}
};
var queue = Queue$1;
var global$c = global$B;
var promiseNativeConstructor = global$c.Promise;
/* global Deno -- Deno case */
var engineIsDeno = typeof Deno == 'object' && Deno && typeof Deno.version == 'object';
var IS_DENO$1 = engineIsDeno;
var IS_NODE$2 = engineIsNode;
var engineIsBrowser = !IS_DENO$1 && !IS_NODE$2
&& typeof window == 'object'
&& typeof document == 'object';
var global$b = global$B;
var NativePromiseConstructor$4 = promiseNativeConstructor;
var isCallable$9 = isCallable$u;
var isForced$3 = isForced_1;
var inspectSource = inspectSource$3;
var wellKnownSymbol$7 = wellKnownSymbol$t;
var IS_BROWSER = engineIsBrowser;
var IS_DENO = engineIsDeno;
var V8_VERSION = engineV8Version;
NativePromiseConstructor$4 && NativePromiseConstructor$4.prototype;
var SPECIES = wellKnownSymbol$7('species');
var SUBCLASSING = false;
var NATIVE_PROMISE_REJECTION_EVENT$1 = isCallable$9(global$b.PromiseRejectionEvent);
var FORCED_PROMISE_CONSTRUCTOR$5 = isForced$3('Promise', function () {
var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor$4);
var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor$4);
// V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// We can't detect it synchronously, so just check versions
if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
// We can't use @@species feature detection in V8 since it causes
// deoptimization and performance degradation
// https://github.com/zloirock/core-js/issues/679
if (!V8_VERSION || V8_VERSION < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) {
// Detect correctness of subclassing with @@species support
var promise = new NativePromiseConstructor$4(function (resolve) { resolve(1); });
var FakePromise = function (exec) {
exec(function () { /* empty */ }, function () { /* empty */ });
};
var constructor = promise.constructor = {};
constructor[SPECIES] = FakePromise;
SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
if (!SUBCLASSING) return true;
// Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
} return !GLOBAL_CORE_JS_PROMISE && (IS_BROWSER || IS_DENO) && !NATIVE_PROMISE_REJECTION_EVENT$1;
});
var promiseConstructorDetection = {
CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR$5,
REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT$1,
SUBCLASSING: SUBCLASSING
};
var newPromiseCapability$2 = {};
var aCallable$5 = aCallable$a;
var $TypeError$3 = TypeError;
var PromiseCapability = function (C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw $TypeError$3('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aCallable$5(resolve);
this.reject = aCallable$5(reject);
};
// `NewPromiseCapability` abstract operation
// https://tc39.es/ecma262/#sec-newpromisecapability
newPromiseCapability$2.f = function (C) {
return new PromiseCapability(C);
};
var $$B = _export;
var IS_NODE$1 = engineIsNode;
var global$a = global$B;
var call$a = functionCall;
var defineBuiltIn$a = defineBuiltIn$i;
var setPrototypeOf$2 = objectSetPrototypeOf;
var setToStringTag$4 = setToStringTag$7;
var setSpecies$2 = setSpecies$3;
var aCallable$4 = aCallable$a;
var isCallable$8 = isCallable$u;
var isObject$c = isObject$o;
var anInstance$5 = anInstance$6;
var speciesConstructor$1 = speciesConstructor$2;
var task = task$1.set;
var microtask = microtask$1;
var hostReportErrors = hostReportErrors$1;
var perform$2 = perform$3;
var Queue = queue;
var InternalStateModule$5 = internalState;
var NativePromiseConstructor$3 = promiseNativeConstructor;
var PromiseConstructorDetection = promiseConstructorDetection;
var newPromiseCapabilityModule$3 = newPromiseCapability$2;
var PROMISE = 'Promise';
var FORCED_PROMISE_CONSTRUCTOR$4 = PromiseConstructorDetection.CONSTRUCTOR;
var NATIVE_PROMISE_REJECTION_EVENT = PromiseConstructorDetection.REJECTION_EVENT;
var NATIVE_PROMISE_SUBCLASSING = PromiseConstructorDetection.SUBCLASSING;
var getInternalPromiseState = InternalStateModule$5.getterFor(PROMISE);
var setInternalState$5 = InternalStateModule$5.set;
var NativePromisePrototype$2 = NativePromiseConstructor$3 && NativePromiseConstructor$3.prototype;
var PromiseConstructor = NativePromiseConstructor$3;
var PromisePrototype = NativePromisePrototype$2;
var TypeError$5 = global$a.TypeError;
var document$1 = global$a.document;
var process = global$a.process;
var newPromiseCapability$1 = newPromiseCapabilityModule$3.f;
var newGenericPromiseCapability = newPromiseCapability$1;
var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && global$a.dispatchEvent);
var UNHANDLED_REJECTION = 'unhandledrejection';
var REJECTION_HANDLED = 'rejectionhandled';
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
// helpers
var isThenable = function (it) {
var then;
return isObject$c(it) && isCallable$8(then = it.then) ? then : false;
};
var callReaction = function (reaction, state) {
var value = state.value;
var ok = state.state == FULFILLED;
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (state.rejection === UNHANDLED) onHandleUnhandled(state);
state.rejection = HANDLED;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // can throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError$5('Promise-chain cycle'));
} else if (then = isThenable(result)) {
call$a(then, result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
};
var notify = function (state, isReject) {
if (state.notified) return;
state.notified = true;
microtask(function () {
var reactions = state.reactions;
var reaction;
while (reaction = reactions.get()) {
callReaction(reaction, state);
}
state.notified = false;
if (isReject && !state.rejection) onUnhandled(state);
});
};
var dispatchEvent = function (name, promise, reason) {
var event, handler;
if (DISPATCH_EVENT) {
event = document$1.createEvent('Event');
event.promise = promise;
event.reason = reason;
event.initEvent(name, false, true);
global$a.dispatchEvent(event);
} else event = { promise: promise, reason: reason };
if (!NATIVE_PROMISE_REJECTION_EVENT && (handler = global$a['on' + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
};
var onUnhandled = function (state) {
call$a(task, global$a, function () {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform$2(function () {
if (IS_NODE$1) {
process.emit('unhandledRejection', value, promise);
} else dispatchEvent(UNHANDLED_REJECTION, promise, value);
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
state.rejection = IS_NODE$1 || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function (state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function (state) {
call$a(task, global$a, function () {
var promise = state.facade;
if (IS_NODE$1) {
process.emit('rejectionHandled', promise);
} else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind$5 = function (fn, state, unwrap) {
return function (value) {
fn(state, value, unwrap);
};
};
var internalReject = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
state.value = value;
state.state = REJECTED;
notify(state, true);
};
var internalResolve = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
try {
if (state.facade === value) throw TypeError$5("Promise can't be resolved itself");
var then = isThenable(value);
if (then) {
microtask(function () {
var wrapper = { done: false };
try {
call$a(then, value,
bind$5(internalResolve, wrapper, state),
bind$5(internalReject, wrapper, state)
);
} catch (error) {
internalReject(wrapper, error, state);
}
});
} else {
state.value = value;
state.state = FULFILLED;
notify(state, false);
}
} catch (error) {
internalReject({ done: false }, error, state);
}
};
// constructor polyfill
if (FORCED_PROMISE_CONSTRUCTOR$4) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise(executor) {
anInstance$5(this, PromisePrototype);
aCallable$4(executor);
call$a(Internal, this);
var state = getInternalPromiseState(this);
try {
executor(bind$5(internalResolve, state), bind$5(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
PromisePrototype = PromiseConstructor.prototype;
// eslint-disable-next-line no-unused-vars -- required for `.length`
Internal = function Promise(executor) {
setInternalState$5(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: new Queue(),
rejection: false,
state: PENDING,
value: undefined
});
};
// `Promise.prototype.then` method
// https://tc39.es/ecma262/#sec-promise.prototype.then
Internal.prototype = defineBuiltIn$a(PromisePrototype, 'then', function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability$1(speciesConstructor$1(this, PromiseConstructor));
state.parent = true;
reaction.ok = isCallable$8(onFulfilled) ? onFulfilled : true;
reaction.fail = isCallable$8(onRejected) && onRejected;
reaction.domain = IS_NODE$1 ? process.domain : undefined;
if (state.state == PENDING) state.reactions.add(reaction);
else microtask(function () {
callReaction(reaction, state);
});
return reaction.promise;
});
OwnPromiseCapability = function () {
var promise = new Internal();
var state = getInternalPromiseState(promise);
this.promise = promise;
this.resolve = bind$5(internalResolve, state);
this.reject = bind$5(internalReject, state);
};
newPromiseCapabilityModule$3.f = newPromiseCapability$1 = function (C) {
return C === PromiseConstructor || C === PromiseWrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
if (isCallable$8(NativePromiseConstructor$3) && NativePromisePrototype$2 !== Object.prototype) {
nativeThen = NativePromisePrototype$2.then;
if (!NATIVE_PROMISE_SUBCLASSING) {
// make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
defineBuiltIn$a(NativePromisePrototype$2, 'then', function then(onFulfilled, onRejected) {
var that = this;
return new PromiseConstructor(function (resolve, reject) {
call$a(nativeThen, that, resolve, reject);
}).then(onFulfilled, onRejected);
// https://github.com/zloirock/core-js/issues/640
}, { unsafe: true });
}
// make `.constructor === Promise` work for native promise-based APIs
try {
delete NativePromisePrototype$2.constructor;
} catch (error) { /* empty */ }
// make `instanceof Promise` work for native promise-based APIs
if (setPrototypeOf$2) {
setPrototypeOf$2(NativePromisePrototype$2, PromisePrototype);
}
}
}
$$B({ global: true, constructor: true, wrap: true, forced: FORCED_PROMISE_CONSTRUCTOR$4 }, {
Promise: PromiseConstructor
});
setToStringTag$4(PromiseConstructor, PROMISE, false);
setSpecies$2(PROMISE);
var bind$4 = functionBindContext;
var call$9 = functionCall;
var anObject$6 = anObject$l;
var tryToString$1 = tryToString$6;
var isArrayIteratorMethod = isArrayIteratorMethod$2;
var lengthOfArrayLike$4 = lengthOfArrayLike$b;
var isPrototypeOf$4 = objectIsPrototypeOf;
var getIterator$1 = getIterator$3;
var getIteratorMethod$1 = getIteratorMethod$4;
var iteratorClose = iteratorClose$2;
var $TypeError$2 = TypeError;
var Result = function (stopped, result) {
this.stopped = stopped;
this.result = result;
};
var ResultPrototype = Result.prototype;
var iterate$5 = function (iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_RECORD = !!(options && options.IS_RECORD);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = bind$4(unboundFunction, that);
var iterator, iterFn, index, length, result, next, step;
var stop = function (condition) {
if (iterator) iteratorClose(iterator, 'normal', condition);
return new Result(true, condition);
};
var callFn = function (value) {
if (AS_ENTRIES) {
anObject$6(value);
return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
} return INTERRUPTED ? fn(value, stop) : fn(value);
};
if (IS_RECORD) {
iterator = iterable.iterator;
} else if (IS_ITERATOR) {
iterator = iterable;
} else {
iterFn = getIteratorMethod$1(iterable);
if (!iterFn) throw $TypeError$2(tryToString$1(iterable) + ' is not iterable');
// optimisation for array iterators
if (isArrayIteratorMethod(iterFn)) {
for (index = 0, length = lengthOfArrayLike$4(iterable); length > index; index++) {
result = callFn(iterable[index]);
if (result && isPrototypeOf$4(ResultPrototype, result)) return result;
} return new Result(false);
}
iterator = getIterator$1(iterable, iterFn);
}
next = IS_RECORD ? iterable.next : iterator.next;
while (!(step = call$9(next, iterator)).done) {
try {
result = callFn(step.value);
} catch (error) {
iteratorClose(iterator, 'throw', error);
}
if (typeof result == 'object' && result && isPrototypeOf$4(ResultPrototype, result)) return result;
} return new Result(false);
};
var NativePromiseConstructor$2 = promiseNativeConstructor;
var checkCorrectnessOfIteration$1 = checkCorrectnessOfIteration$3;
var FORCED_PROMISE_CONSTRUCTOR$3 = promiseConstructorDetection.CONSTRUCTOR;
var promiseStaticsIncorrectIteration = FORCED_PROMISE_CONSTRUCTOR$3 || !checkCorrectnessOfIteration$1(function (iterable) {
NativePromiseConstructor$2.all(iterable).then(undefined, function () { /* empty */ });
});
var $$A = _export;
var call$8 = functionCall;
var aCallable$3 = aCallable$a;
var newPromiseCapabilityModule$2 = newPromiseCapability$2;
var perform$1 = perform$3;
var iterate$4 = iterate$5;
var PROMISE_STATICS_INCORRECT_ITERATION$1 = promiseStaticsIncorrectIteration;
// `Promise.all` method
// https://tc39.es/ecma262/#sec-promise.all
$$A({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION$1 }, {
all: function all(iterable) {
var C = this;
var capability = newPromiseCapabilityModule$2.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform$1(function () {
var $promiseResolve = aCallable$3(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate$4(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
call$8($promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var $$z = _export;
var FORCED_PROMISE_CONSTRUCTOR$2 = promiseConstructorDetection.CONSTRUCTOR;
var NativePromiseConstructor$1 = promiseNativeConstructor;
var getBuiltIn$6 = getBuiltIn$d;
var isCallable$7 = isCallable$u;
var defineBuiltIn$9 = defineBuiltIn$i;
var NativePromisePrototype$1 = NativePromiseConstructor$1 && NativePromiseConstructor$1.prototype;
// `Promise.prototype.catch` method
// https://tc39.es/ecma262/#sec-promise.prototype.catch
$$z({ target: 'Promise', proto: true, forced: FORCED_PROMISE_CONSTRUCTOR$2, real: true }, {
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
// makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
if (isCallable$7(NativePromiseConstructor$1)) {
var method$1 = getBuiltIn$6('Promise').prototype['catch'];
if (NativePromisePrototype$1['catch'] !== method$1) {
defineBuiltIn$9(NativePromisePrototype$1, 'catch', method$1, { unsafe: true });
}
}
var $$y = _export;
var call$7 = functionCall;
var aCallable$2 = aCallable$a;
var newPromiseCapabilityModule$1 = newPromiseCapability$2;
var perform = perform$3;
var iterate$3 = iterate$5;
var PROMISE_STATICS_INCORRECT_ITERATION = promiseStaticsIncorrectIteration;
// `Promise.race` method
// https://tc39.es/ecma262/#sec-promise.race
$$y({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
race: function race(iterable) {
var C = this;
var capability = newPromiseCapabilityModule$1.f(C);
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aCallable$2(C.resolve);
iterate$3(iterable, function (promise) {
call$7($promiseResolve, C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var $$x = _export;
var call$6 = functionCall;
var newPromiseCapabilityModule = newPromiseCapability$2;
var FORCED_PROMISE_CONSTRUCTOR$1 = promiseConstructorDetection.CONSTRUCTOR;
// `Promise.reject` method
// https://tc39.es/ecma262/#sec-promise.reject
$$x({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR$1 }, {
reject: function reject(r) {
var capability = newPromiseCapabilityModule.f(this);
call$6(capability.reject, undefined, r);
return capability.promise;
}
});
var anObject$5 = anObject$l;
var isObject$b = isObject$o;
var newPromiseCapability = newPromiseCapability$2;
var promiseResolve$2 = function (C, x) {
anObject$5(C);
if (isObject$b(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
var $$w = _export;
var getBuiltIn$5 = getBuiltIn$d;
var FORCED_PROMISE_CONSTRUCTOR = promiseConstructorDetection.CONSTRUCTOR;
var promiseResolve$1 = promiseResolve$2;
getBuiltIn$5('Promise');
// `Promise.resolve` method
// https://tc39.es/ecma262/#sec-promise.resolve
$$w({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR }, {
resolve: function resolve(x) {
return promiseResolve$1(this, x);
}
});
var toIntegerOrInfinity$2 = toIntegerOrInfinity$8;
var toString$9 = toString$j;
var requireObjectCoercible$5 = requireObjectCoercible$d;
var $RangeError$3 = RangeError;
// `String.prototype.repeat` method implementation
// https://tc39.es/ecma262/#sec-string.prototype.repeat
var stringRepeat = function repeat(count) {
var str = toString$9(requireObjectCoercible$5(this));
var result = '';
var n = toIntegerOrInfinity$2(count);
if (n < 0 || n == Infinity) throw $RangeError$3('Wrong number of repetitions');
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
return result;
};
// https://github.com/tc39/proposal-string-pad-start-end
var uncurryThis$l = functionUncurryThis;
var toLength$1 = toLength$5;
var toString$8 = toString$j;
var $repeat$1 = stringRepeat;
var requireObjectCoercible$4 = requireObjectCoercible$d;
var repeat$1 = uncurryThis$l($repeat$1);
var stringSlice$7 = uncurryThis$l(''.slice);
var ceil = Math.ceil;
// `String.prototype.{ padStart, padEnd }` methods implementation
var createMethod$2 = function (IS_END) {
return function ($this, maxLength, fillString) {
var S = toString$8(requireObjectCoercible$4($this));
var intMaxLength = toLength$1(maxLength);
var stringLength = S.length;
var fillStr = fillString === undefined ? ' ' : toString$8(fillString);
var fillLen, stringFiller;
if (intMaxLength <= stringLength || fillStr == '') return S;
fillLen = intMaxLength - stringLength;
stringFiller = repeat$1(fillStr, ceil(fillLen / fillStr.length));
if (stringFiller.length > fillLen) stringFiller = stringSlice$7(stringFiller, 0, fillLen);
return IS_END ? S + stringFiller : stringFiller + S;
};
};
var stringPad = {
// `String.prototype.padStart` method
// https://tc39.es/ecma262/#sec-string.prototype.padstart
start: createMethod$2(false),
// `String.prototype.padEnd` method
// https://tc39.es/ecma262/#sec-string.prototype.padend
end: createMethod$2(true)
};
var uncurryThis$k = functionUncurryThis;
var fails$h = fails$J;
var padStart = stringPad.start;
var $RangeError$2 = RangeError;
var $isFinite = isFinite;
var abs$1 = Math.abs;
var DatePrototype = Date.prototype;
var nativeDateToISOString = DatePrototype.toISOString;
var thisTimeValue = uncurryThis$k(DatePrototype.getTime);
var getUTCDate = uncurryThis$k(DatePrototype.getUTCDate);
var getUTCFullYear = uncurryThis$k(DatePrototype.getUTCFullYear);
var getUTCHours = uncurryThis$k(DatePrototype.getUTCHours);
var getUTCMilliseconds = uncurryThis$k(DatePrototype.getUTCMilliseconds);
var getUTCMinutes = uncurryThis$k(DatePrototype.getUTCMinutes);
var getUTCMonth = uncurryThis$k(DatePrototype.getUTCMonth);
var getUTCSeconds = uncurryThis$k(DatePrototype.getUTCSeconds);
// `Date.prototype.toISOString` method implementation
// https://tc39.es/ecma262/#sec-date.prototype.toisostring
// PhantomJS / old WebKit fails here:
var dateToIsoString = (fails$h(function () {
return nativeDateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
}) || !fails$h(function () {
nativeDateToISOString.call(new Date(NaN));
})) ? function toISOString() {
if (!$isFinite(thisTimeValue(this))) throw $RangeError$2('Invalid time value');
var date = this;
var year = getUTCFullYear(date);
var milliseconds = getUTCMilliseconds(date);
var sign = year < 0 ? '-' : year > 9999 ? '+' : '';
return sign + padStart(abs$1(year), sign ? 6 : 4, 0) +
'-' + padStart(getUTCMonth(date) + 1, 2, 0) +
'-' + padStart(getUTCDate(date), 2, 0) +
'T' + padStart(getUTCHours(date), 2, 0) +
':' + padStart(getUTCMinutes(date), 2, 0) +
':' + padStart(getUTCSeconds(date), 2, 0) +
'.' + padStart(milliseconds, 3, 0) +
'Z';
} : nativeDateToISOString;
var $$v = _export;
var toISOString = dateToIsoString;
// `Date.prototype.toISOString` method
// https://tc39.es/ecma262/#sec-date.prototype.toisostring
// PhantomJS / old WebKit has a broken implementations
$$v({ target: 'Date', proto: true, forced: Date.prototype.toISOString !== toISOString }, {
toISOString: toISOString
});
var $$u = _export;
var NativePromiseConstructor = promiseNativeConstructor;
var fails$g = fails$J;
var getBuiltIn$4 = getBuiltIn$d;
var isCallable$6 = isCallable$u;
var speciesConstructor = speciesConstructor$2;
var promiseResolve = promiseResolve$2;
var defineBuiltIn$8 = defineBuiltIn$i;
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
// Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
var NON_GENERIC = !!NativePromiseConstructor && fails$g(function () {
// eslint-disable-next-line unicorn/no-thenable -- required for testing
NativePromisePrototype['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });
});
// `Promise.prototype.finally` method
// https://tc39.es/ecma262/#sec-promise.prototype.finally
$$u({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {
'finally': function (onFinally) {
var C = speciesConstructor(this, getBuiltIn$4('Promise'));
var isFunction = isCallable$6(onFinally);
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
}
});
// makes sure that native promise-based APIs `Promise#finally` properly works with patched `Promise#then`
if (isCallable$6(NativePromiseConstructor)) {
var method = getBuiltIn$4('Promise').prototype['finally'];
if (NativePromisePrototype['finally'] !== method) {
defineBuiltIn$8(NativePromisePrototype, 'finally', method, { unsafe: true });
}
}
var $$t = _export;
var $some = arrayIteration.some;
var arrayMethodIsStrict$4 = arrayMethodIsStrict$8;
var STRICT_METHOD$4 = arrayMethodIsStrict$4('some');
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
$$t({ target: 'Array', proto: true, forced: !STRICT_METHOD$4 }, {
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var $$s = _export;
var uncurryThis$j = functionUncurryThis;
var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
var toLength = toLength$5;
var toString$7 = toString$j;
var notARegExp = notARegexp;
var requireObjectCoercible$3 = requireObjectCoercible$d;
var correctIsRegExpLogic = correctIsRegexpLogic;
// eslint-disable-next-line es/no-string-prototype-startswith -- safe
var nativeStartsWith = uncurryThis$j(''.startsWith);
var stringSlice$6 = uncurryThis$j(''.slice);
var min$1 = Math.min;
var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith');
// https://github.com/zloirock/core-js/pull/702
var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () {
var descriptor = getOwnPropertyDescriptor$2(String.prototype, 'startsWith');
return descriptor && !descriptor.writable;
}();
// `String.prototype.startsWith` method
// https://tc39.es/ecma262/#sec-string.prototype.startswith
$$s({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = toString$7(requireObjectCoercible$3(this));
notARegExp(searchString);
var index = toLength(min$1(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = toString$7(searchString);
return nativeStartsWith
? nativeStartsWith(that, search, index)
: stringSlice$6(that, index, index + search.length) === search;
}
});
var DESCRIPTORS$c = descriptors;
var FUNCTION_NAME_EXISTS = functionName.EXISTS;
var uncurryThis$i = functionUncurryThis;
var defineProperty$7 = objectDefineProperty.f;
var FunctionPrototype = Function.prototype;
var functionToString = uncurryThis$i(FunctionPrototype.toString);
var nameRE = /function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/;
var regExpExec$1 = uncurryThis$i(nameRE.exec);
var NAME = 'name';
// Function instances `.name` property
// https://tc39.es/ecma262/#sec-function-instances-name
if (DESCRIPTORS$c && !FUNCTION_NAME_EXISTS) {
defineProperty$7(FunctionPrototype, NAME, {
configurable: true,
get: function () {
try {
return regExpExec$1(nameRE, functionToString(this))[1];
} catch (error) {
return '';
}
}
});
}
/* eslint-disable es/no-array-prototype-lastindexof -- safe */
var apply$2 = functionApply;
var toIndexedObject$5 = toIndexedObject$d;
var toIntegerOrInfinity$1 = toIntegerOrInfinity$8;
var lengthOfArrayLike$3 = lengthOfArrayLike$b;
var arrayMethodIsStrict$3 = arrayMethodIsStrict$8;
var min = Math.min;
var $lastIndexOf = [].lastIndexOf;
var NEGATIVE_ZERO = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
var STRICT_METHOD$3 = arrayMethodIsStrict$3('lastIndexOf');
var FORCED$5 = NEGATIVE_ZERO || !STRICT_METHOD$3;
// `Array.prototype.lastIndexOf` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
var arrayLastIndexOf = FORCED$5 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return apply$2($lastIndexOf, this, arguments) || 0;
var O = toIndexedObject$5(this);
var length = lengthOfArrayLike$3(O);
var index = length - 1;
if (arguments.length > 1) index = min(index, toIntegerOrInfinity$1(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
return -1;
} : $lastIndexOf;
var $$r = _export;
var lastIndexOf = arrayLastIndexOf;
// `Array.prototype.lastIndexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
// eslint-disable-next-line es/no-array-prototype-lastindexof -- required for testing
$$r({ target: 'Array', proto: true, forced: lastIndexOf !== [].lastIndexOf }, {
lastIndexOf: lastIndexOf
});
var fails$f = fails$J;
var wellKnownSymbol$6 = wellKnownSymbol$t;
var IS_PURE = isPure;
var ITERATOR$1 = wellKnownSymbol$6('iterator');
var urlConstructorDetection = !fails$f(function () {
// eslint-disable-next-line unicorn/relative-url-style -- required for testing
var url = new URL('b?a=1&b=2&c=3', 'http://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return (IS_PURE && !url.toJSON)
|| !searchParams.sort
|| url.href !== 'http://a/c%20d?a=1&c=3'
|| searchParams.get('c') !== '3'
|| String(new URLSearchParams('?a=1')) !== 'a=1'
|| !searchParams[ITERATOR$1]
// throws in Edge
|| new URL('https://a@b').username !== 'a'
|| new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
// not punycoded in Edge
|| new URL('http://тест').host !== 'xn--e1aybc'
// not escaped in Chrome 62-
|| new URL('http://a#б').hash !== '#%D0%B1'
// fails in Chrome 66-
|| result !== 'a1c3'
// throws in Safari
|| new URL('http://x', undefined).host !== 'x';
});
var makeBuiltIn = makeBuiltIn$3.exports;
var defineProperty$6 = objectDefineProperty;
var defineBuiltInAccessor$1 = function (target, name, descriptor) {
if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
return defineProperty$6.f(target, name, descriptor);
};
var toAbsoluteIndex = toAbsoluteIndex$4;
var lengthOfArrayLike$2 = lengthOfArrayLike$b;
var createProperty$1 = createProperty$6;
var $Array = Array;
var max$1 = Math.max;
var arraySliceSimple = function (O, start, end) {
var length = lengthOfArrayLike$2(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
var result = $Array(max$1(fin - k, 0));
for (var n = 0; k < fin; k++, n++) createProperty$1(result, n, O[k]);
result.length = n;
return result;
};
// based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
var uncurryThis$h = functionUncurryThis;
var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'
var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
var baseMinusTMin = base - tMin;
var $RangeError$1 = RangeError;
var exec$3 = uncurryThis$h(regexSeparators.exec);
var floor$4 = Math.floor;
var fromCharCode = String.fromCharCode;
var charCodeAt$2 = uncurryThis$h(''.charCodeAt);
var join$2 = uncurryThis$h([].join);
var push$6 = uncurryThis$h([].push);
var replace$6 = uncurryThis$h(''.replace);
var split$2 = uncurryThis$h(''.split);
var toLowerCase$1 = uncurryThis$h(''.toLowerCase);
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
*/
var ucs2decode = function (string) {
var output = [];
var counter = 0;
var length = string.length;
while (counter < length) {
var value = charCodeAt$2(string, counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = charCodeAt$2(string, counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
push$6(output, ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
push$6(output, value);
counter--;
}
} else {
push$6(output, value);
}
}
return output;
};
/**
* Converts a digit/integer into a basic code point.
*/
var digitToBasic = function (digit) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
*/
var adapt = function (delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor$4(delta / damp) : delta >> 1;
delta += floor$4(delta / numPoints);
while (delta > baseMinusTMin * tMax >> 1) {
delta = floor$4(delta / baseMinusTMin);
k += base;
}
return floor$4(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
*/
var encode = function (input) {
var output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
var inputLength = input.length;
// Initialize the state.
var n = initialN;
var delta = 0;
var bias = initialBias;
var i, currentValue;
// Handle the basic code points.
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < 0x80) {
push$6(output, fromCharCode(currentValue));
}
}
var basicLength = output.length; // number of basic code points.
var handledCPCount = basicLength; // number of code points that have been handled;
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
push$6(output, delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next larger one:
var m = maxInt;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's state to , but guard against overflow.
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor$4((maxInt - delta) / handledCPCountPlusOne)) {
throw $RangeError$1(OVERFLOW_ERROR);
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < n && ++delta > maxInt) {
throw $RangeError$1(OVERFLOW_ERROR);
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
var q = delta;
var k = base;
while (true) {
var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) break;
var qMinusT = q - t;
var baseMinusT = base - t;
push$6(output, fromCharCode(digitToBasic(t + qMinusT % baseMinusT)));
q = floor$4(qMinusT / baseMinusT);
k += base;
}
push$6(output, fromCharCode(digitToBasic(q)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
handledCPCount++;
}
}
delta++;
n++;
}
return join$2(output, '');
};
var stringPunycodeToAscii = function (input) {
var encoded = [];
var labels = split$2(replace$6(toLowerCase$1(input), regexSeparators, '\u002E'), '.');
var i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
push$6(encoded, exec$3(regexNonASCII, label) ? 'xn--' + encode(label) : label);
}
return join$2(encoded, '.');
};
var defineBuiltIn$7 = defineBuiltIn$i;
var defineBuiltIns$4 = function (target, src, options) {
for (var key in src) defineBuiltIn$7(target, key, src[key], options);
return target;
};
var arraySlice$4 = arraySliceSimple;
var floor$3 = Math.floor;
var mergeSort = function (array, comparefn) {
var length = array.length;
var middle = floor$3(length / 2);
return length < 8 ? insertionSort(array, comparefn) : merge(
array,
mergeSort(arraySlice$4(array, 0, middle), comparefn),
mergeSort(arraySlice$4(array, middle), comparefn),
comparefn
);
};
var insertionSort = function (array, comparefn) {
var length = array.length;
var i = 1;
var element, j;
while (i < length) {
j = i;
element = array[i];
while (j && comparefn(array[j - 1], element) > 0) {
array[j] = array[--j];
}
if (j !== i++) array[j] = element;
} return array;
};
var merge = function (array, left, right, comparefn) {
var llength = left.length;
var rlength = right.length;
var lindex = 0;
var rindex = 0;
while (lindex < llength || rindex < rlength) {
array[lindex + rindex] = (lindex < llength && rindex < rlength)
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
: lindex < llength ? left[lindex++] : right[rindex++];
} return array;
};
var arraySort$1 = mergeSort;
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var $$q = _export;
var global$9 = global$B;
var call$5 = functionCall;
var uncurryThis$g = functionUncurryThis;
var DESCRIPTORS$b = descriptors;
var USE_NATIVE_URL$1 = urlConstructorDetection;
var defineBuiltIn$6 = defineBuiltIn$i;
var defineBuiltIns$3 = defineBuiltIns$4;
var setToStringTag$3 = setToStringTag$7;
var createIteratorConstructor = iteratorCreateConstructor;
var InternalStateModule$4 = internalState;
var anInstance$4 = anInstance$6;
var isCallable$5 = isCallable$u;
var hasOwn$a = hasOwnProperty_1;
var bind$3 = functionBindContext;
var classof$2 = classof$a;
var anObject$4 = anObject$l;
var isObject$a = isObject$o;
var $toString$2 = toString$j;
var create$3 = objectCreate;
var createPropertyDescriptor$1 = createPropertyDescriptor$6;
var getIterator = getIterator$3;
var getIteratorMethod = getIteratorMethod$4;
var validateArgumentsLength$1 = validateArgumentsLength$4;
var wellKnownSymbol$5 = wellKnownSymbol$t;
var arraySort = arraySort$1;
var ITERATOR = wellKnownSymbol$5('iterator');
var URL_SEARCH_PARAMS = 'URLSearchParams';
var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
var setInternalState$4 = InternalStateModule$4.set;
var getInternalParamsState = InternalStateModule$4.getterFor(URL_SEARCH_PARAMS);
var getInternalIteratorState = InternalStateModule$4.getterFor(URL_SEARCH_PARAMS_ITERATOR);
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
// Avoid NodeJS experimental warning
var safeGetBuiltIn = function (name) {
if (!DESCRIPTORS$b) return global$9[name];
var descriptor = getOwnPropertyDescriptor$1(global$9, name);
return descriptor && descriptor.value;
};
var nativeFetch = safeGetBuiltIn('fetch');
var NativeRequest = safeGetBuiltIn('Request');
var Headers$1 = safeGetBuiltIn('Headers');
var RequestPrototype = NativeRequest && NativeRequest.prototype;
var HeadersPrototype = Headers$1 && Headers$1.prototype;
var RegExp$1 = global$9.RegExp;
var TypeError$4 = global$9.TypeError;
var decodeURIComponent$1 = global$9.decodeURIComponent;
var encodeURIComponent$1 = global$9.encodeURIComponent;
var charAt$3 = uncurryThis$g(''.charAt);
var join$1 = uncurryThis$g([].join);
var push$5 = uncurryThis$g([].push);
var replace$5 = uncurryThis$g(''.replace);
var shift$1 = uncurryThis$g([].shift);
var splice$1 = uncurryThis$g([].splice);
var split$1 = uncurryThis$g(''.split);
var stringSlice$5 = uncurryThis$g(''.slice);
var plus = /\+/g;
var sequences = Array(4);
var percentSequence = function (bytes) {
return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp$1('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
};
var percentDecode = function (sequence) {
try {
return decodeURIComponent$1(sequence);
} catch (error) {
return sequence;
}
};
var deserialize = function (it) {
var result = replace$5(it, plus, ' ');
var bytes = 4;
try {
return decodeURIComponent$1(result);
} catch (error) {
while (bytes) {
result = replace$5(result, percentSequence(bytes--), percentDecode);
}
return result;
}
};
var find$1 = /[!'()~]|%20/g;
var replacements = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
var replacer = function (match) {
return replacements[match];
};
var serialize = function (it) {
return replace$5(encodeURIComponent$1(it), find$1, replacer);
};
var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
setInternalState$4(this, {
type: URL_SEARCH_PARAMS_ITERATOR,
iterator: getIterator(getInternalParamsState(params).entries),
kind: kind
});
}, 'Iterator', function next() {
var state = getInternalIteratorState(this);
var kind = state.kind;
var step = state.iterator.next();
var entry = step.value;
if (!step.done) {
step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
} return step;
}, true);
var URLSearchParamsState = function (init) {
this.entries = [];
this.url = null;
if (init !== undefined) {
if (isObject$a(init)) this.parseObject(init);
else this.parseQuery(typeof init == 'string' ? charAt$3(init, 0) === '?' ? stringSlice$5(init, 1) : init : $toString$2(init));
}
};
URLSearchParamsState.prototype = {
type: URL_SEARCH_PARAMS,
bindURL: function (url) {
this.url = url;
this.update();
},
parseObject: function (object) {
var iteratorMethod = getIteratorMethod(object);
var iterator, next, step, entryIterator, entryNext, first, second;
if (iteratorMethod) {
iterator = getIterator(object, iteratorMethod);
next = iterator.next;
while (!(step = call$5(next, iterator)).done) {
entryIterator = getIterator(anObject$4(step.value));
entryNext = entryIterator.next;
if (
(first = call$5(entryNext, entryIterator)).done ||
(second = call$5(entryNext, entryIterator)).done ||
!call$5(entryNext, entryIterator).done
) throw TypeError$4('Expected sequence with length 2');
push$5(this.entries, { key: $toString$2(first.value), value: $toString$2(second.value) });
}
} else for (var key in object) if (hasOwn$a(object, key)) {
push$5(this.entries, { key: key, value: $toString$2(object[key]) });
}
},
parseQuery: function (query) {
if (query) {
var attributes = split$1(query, '&');
var index = 0;
var attribute, entry;
while (index < attributes.length) {
attribute = attributes[index++];
if (attribute.length) {
entry = split$1(attribute, '=');
push$5(this.entries, {
key: deserialize(shift$1(entry)),
value: deserialize(join$1(entry, '='))
});
}
}
}
},
serialize: function () {
var entries = this.entries;
var result = [];
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
push$5(result, serialize(entry.key) + '=' + serialize(entry.value));
} return join$1(result, '&');
},
update: function () {
this.entries.length = 0;
this.parseQuery(this.url.query);
},
updateURL: function () {
if (this.url) this.url.update();
}
};
// `URLSearchParams` constructor
// https://url.spec.whatwg.org/#interface-urlsearchparams
var URLSearchParamsConstructor = function URLSearchParams(/* init */) {
anInstance$4(this, URLSearchParamsPrototype);
var init = arguments.length > 0 ? arguments[0] : undefined;
setInternalState$4(this, new URLSearchParamsState(init));
};
var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
defineBuiltIns$3(URLSearchParamsPrototype, {
// `URLSearchParams.prototype.append` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append: function append(name, value) {
validateArgumentsLength$1(arguments.length, 2);
var state = getInternalParamsState(this);
push$5(state.entries, { key: $toString$2(name), value: $toString$2(value) });
state.updateURL();
},
// `URLSearchParams.prototype.delete` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
'delete': function (name) {
validateArgumentsLength$1(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var key = $toString$2(name);
var index = 0;
while (index < entries.length) {
if (entries[index].key === key) splice$1(entries, index, 1);
else index++;
}
state.updateURL();
},
// `URLSearchParams.prototype.get` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get: function get(name) {
validateArgumentsLength$1(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString$2(name);
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) return entries[index].value;
}
return null;
},
// `URLSearchParams.prototype.getAll` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll: function getAll(name) {
validateArgumentsLength$1(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString$2(name);
var result = [];
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) push$5(result, entries[index].value);
}
return result;
},
// `URLSearchParams.prototype.has` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has: function has(name) {
validateArgumentsLength$1(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString$2(name);
var index = 0;
while (index < entries.length) {
if (entries[index++].key === key) return true;
}
return false;
},
// `URLSearchParams.prototype.set` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set: function set(name, value) {
validateArgumentsLength$1(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var found = false;
var key = $toString$2(name);
var val = $toString$2(value);
var index = 0;
var entry;
for (; index < entries.length; index++) {
entry = entries[index];
if (entry.key === key) {
if (found) splice$1(entries, index--, 1);
else {
found = true;
entry.value = val;
}
}
}
if (!found) push$5(entries, { key: key, value: val });
state.updateURL();
},
// `URLSearchParams.prototype.sort` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
sort: function sort() {
var state = getInternalParamsState(this);
arraySort(state.entries, function (a, b) {
return a.key > b.key ? 1 : -1;
});
state.updateURL();
},
// `URLSearchParams.prototype.forEach` method
forEach: function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = bind$3(callback, arguments.length > 1 ? arguments[1] : undefined);
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
boundFunction(entry.value, entry.key, this);
}
},
// `URLSearchParams.prototype.keys` method
keys: function keys() {
return new URLSearchParamsIterator(this, 'keys');
},
// `URLSearchParams.prototype.values` method
values: function values() {
return new URLSearchParamsIterator(this, 'values');
},
// `URLSearchParams.prototype.entries` method
entries: function entries() {
return new URLSearchParamsIterator(this, 'entries');
}
}, { enumerable: true });
// `URLSearchParams.prototype[@@iterator]` method
defineBuiltIn$6(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries, { name: 'entries' });
// `URLSearchParams.prototype.toString` method
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
defineBuiltIn$6(URLSearchParamsPrototype, 'toString', function toString() {
return getInternalParamsState(this).serialize();
}, { enumerable: true });
setToStringTag$3(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
$$q({ global: true, constructor: true, forced: !USE_NATIVE_URL$1 }, {
URLSearchParams: URLSearchParamsConstructor
});
// Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams`
if (!USE_NATIVE_URL$1 && isCallable$5(Headers$1)) {
var headersHas = uncurryThis$g(HeadersPrototype.has);
var headersSet = uncurryThis$g(HeadersPrototype.set);
var wrapRequestOptions = function (init) {
if (isObject$a(init)) {
var body = init.body;
var headers;
if (classof$2(body) === URL_SEARCH_PARAMS) {
headers = init.headers ? new Headers$1(init.headers) : new Headers$1();
if (!headersHas(headers, 'content-type')) {
headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
return create$3(init, {
body: createPropertyDescriptor$1(0, $toString$2(body)),
headers: createPropertyDescriptor$1(0, headers)
});
}
} return init;
};
if (isCallable$5(nativeFetch)) {
$$q({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, {
fetch: function fetch(input /* , init */) {
return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
}
});
}
if (isCallable$5(NativeRequest)) {
var RequestConstructor = function Request(input /* , init */) {
anInstance$4(this, RequestPrototype);
return new NativeRequest(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
};
RequestPrototype.constructor = RequestConstructor;
RequestConstructor.prototype = RequestPrototype;
$$q({ global: true, constructor: true, dontCallGetSet: true, forced: true }, {
Request: RequestConstructor
});
}
}
var web_urlSearchParams_constructor = {
URLSearchParams: URLSearchParamsConstructor,
getState: getInternalParamsState
};
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var $$p = _export;
var DESCRIPTORS$a = descriptors;
var USE_NATIVE_URL = urlConstructorDetection;
var global$8 = global$B;
var bind$2 = functionBindContext;
var uncurryThis$f = functionUncurryThis;
var defineBuiltIn$5 = defineBuiltIn$i;
var defineBuiltInAccessor = defineBuiltInAccessor$1;
var anInstance$3 = anInstance$6;
var hasOwn$9 = hasOwnProperty_1;
var assign = objectAssign;
var arrayFrom = arrayFrom$1;
var arraySlice$3 = arraySliceSimple;
var codeAt = stringMultibyte.codeAt;
var toASCII = stringPunycodeToAscii;
var $toString$1 = toString$j;
var setToStringTag$2 = setToStringTag$7;
var validateArgumentsLength = validateArgumentsLength$4;
var URLSearchParamsModule = web_urlSearchParams_constructor;
var InternalStateModule$3 = internalState;
var setInternalState$3 = InternalStateModule$3.set;
var getInternalURLState = InternalStateModule$3.getterFor('URL');
var URLSearchParams$1 = URLSearchParamsModule.URLSearchParams;
var getInternalSearchParamsState = URLSearchParamsModule.getState;
var NativeURL = global$8.URL;
var TypeError$3 = global$8.TypeError;
var parseInt$1 = global$8.parseInt;
var floor$2 = Math.floor;
var pow$1 = Math.pow;
var charAt$2 = uncurryThis$f(''.charAt);
var exec$2 = uncurryThis$f(/./.exec);
var join = uncurryThis$f([].join);
var numberToString$1 = uncurryThis$f(1.0.toString);
var pop = uncurryThis$f([].pop);
var push$4 = uncurryThis$f([].push);
var replace$4 = uncurryThis$f(''.replace);
var shift = uncurryThis$f([].shift);
var split = uncurryThis$f(''.split);
var stringSlice$4 = uncurryThis$f(''.slice);
var toLowerCase = uncurryThis$f(''.toLowerCase);
var unshift = uncurryThis$f([].unshift);
var INVALID_AUTHORITY = 'Invalid authority';
var INVALID_SCHEME = 'Invalid scheme';
var INVALID_HOST = 'Invalid host';
var INVALID_PORT = 'Invalid port';
var ALPHA = /[a-z]/i;
// eslint-disable-next-line regexp/no-obscure-range -- safe
var ALPHANUMERIC = /[\d+-.a-z]/i;
var DIGIT = /\d/;
var HEX_START = /^0x/i;
var OCT = /^[0-7]+$/;
var DEC = /^\d+$/;
var HEX = /^[\da-f]+$/i;
/* eslint-disable regexp/no-control-character -- safe */
var FORBIDDEN_HOST_CODE_POINT = /[\0\t\n\r #%/:<>?@[\\\]^|]/;
var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\0\t\n\r #/:<>?@[\\\]^|]/;
var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u0020]+|[\u0000-\u0020]+$/g;
var TAB_AND_NEW_LINE = /[\t\n\r]/g;
/* eslint-enable regexp/no-control-character -- safe */
var EOF;
// https://url.spec.whatwg.org/#ipv4-number-parser
var parseIPv4 = function (input) {
var parts = split(input, '.');
var partsLength, numbers, index, part, radix, number, ipv4;
if (parts.length && parts[parts.length - 1] == '') {
parts.length--;
}
partsLength = parts.length;
if (partsLength > 4) return input;
numbers = [];
for (index = 0; index < partsLength; index++) {
part = parts[index];
if (part == '') return input;
radix = 10;
if (part.length > 1 && charAt$2(part, 0) == '0') {
radix = exec$2(HEX_START, part) ? 16 : 8;
part = stringSlice$4(part, radix == 8 ? 1 : 2);
}
if (part === '') {
number = 0;
} else {
if (!exec$2(radix == 10 ? DEC : radix == 8 ? OCT : HEX, part)) return input;
number = parseInt$1(part, radix);
}
push$4(numbers, number);
}
for (index = 0; index < partsLength; index++) {
number = numbers[index];
if (index == partsLength - 1) {
if (number >= pow$1(256, 5 - partsLength)) return null;
} else if (number > 255) return null;
}
ipv4 = pop(numbers);
for (index = 0; index < numbers.length; index++) {
ipv4 += numbers[index] * pow$1(256, 3 - index);
}
return ipv4;
};
// https://url.spec.whatwg.org/#concept-ipv6-parser
// eslint-disable-next-line max-statements -- TODO
var parseIPv6 = function (input) {
var address = [0, 0, 0, 0, 0, 0, 0, 0];
var pieceIndex = 0;
var compress = null;
var pointer = 0;
var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
var chr = function () {
return charAt$2(input, pointer);
};
if (chr() == ':') {
if (charAt$2(input, 1) != ':') return;
pointer += 2;
pieceIndex++;
compress = pieceIndex;
}
while (chr()) {
if (pieceIndex == 8) return;
if (chr() == ':') {
if (compress !== null) return;
pointer++;
pieceIndex++;
compress = pieceIndex;
continue;
}
value = length = 0;
while (length < 4 && exec$2(HEX, chr())) {
value = value * 16 + parseInt$1(chr(), 16);
pointer++;
length++;
}
if (chr() == '.') {
if (length == 0) return;
pointer -= length;
if (pieceIndex > 6) return;
numbersSeen = 0;
while (chr()) {
ipv4Piece = null;
if (numbersSeen > 0) {
if (chr() == '.' && numbersSeen < 4) pointer++;
else return;
}
if (!exec$2(DIGIT, chr())) return;
while (exec$2(DIGIT, chr())) {
number = parseInt$1(chr(), 10);
if (ipv4Piece === null) ipv4Piece = number;
else if (ipv4Piece == 0) return;
else ipv4Piece = ipv4Piece * 10 + number;
if (ipv4Piece > 255) return;
pointer++;
}
address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
numbersSeen++;
if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
}
if (numbersSeen != 4) return;
break;
} else if (chr() == ':') {
pointer++;
if (!chr()) return;
} else if (chr()) return;
address[pieceIndex++] = value;
}
if (compress !== null) {
swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex != 0 && swaps > 0) {
swap = address[pieceIndex];
address[pieceIndex--] = address[compress + swaps - 1];
address[compress + --swaps] = swap;
}
} else if (pieceIndex != 8) return;
return address;
};
var findLongestZeroSequence = function (ipv6) {
var maxIndex = null;
var maxLength = 1;
var currStart = null;
var currLength = 0;
var index = 0;
for (; index < 8; index++) {
if (ipv6[index] !== 0) {
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
currStart = null;
currLength = 0;
} else {
if (currStart === null) currStart = index;
++currLength;
}
}
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
return maxIndex;
};
// https://url.spec.whatwg.org/#host-serializing
var serializeHost = function (host) {
var result, index, compress, ignore0;
// ipv4
if (typeof host == 'number') {
result = [];
for (index = 0; index < 4; index++) {
unshift(result, host % 256);
host = floor$2(host / 256);
} return join(result, '.');
// ipv6
} else if (typeof host == 'object') {
result = '';
compress = findLongestZeroSequence(host);
for (index = 0; index < 8; index++) {
if (ignore0 && host[index] === 0) continue;
if (ignore0) ignore0 = false;
if (compress === index) {
result += index ? ':' : '::';
ignore0 = true;
} else {
result += numberToString$1(host[index], 16);
if (index < 7) result += ':';
}
}
return '[' + result + ']';
} return host;
};
var C0ControlPercentEncodeSet = {};
var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, {
' ': 1, '"': 1, '<': 1, '>': 1, '`': 1
});
var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, {
'#': 1, '?': 1, '{': 1, '}': 1
});
var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, {
'/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1
});
var percentEncode = function (chr, set) {
var code = codeAt(chr, 0);
return code > 0x20 && code < 0x7F && !hasOwn$9(set, chr) ? chr : encodeURIComponent(chr);
};
// https://url.spec.whatwg.org/#special-scheme
var specialSchemes = {
ftp: 21,
file: null,
http: 80,
https: 443,
ws: 80,
wss: 443
};
// https://url.spec.whatwg.org/#windows-drive-letter
var isWindowsDriveLetter = function (string, normalized) {
var second;
return string.length == 2 && exec$2(ALPHA, charAt$2(string, 0))
&& ((second = charAt$2(string, 1)) == ':' || (!normalized && second == '|'));
};
// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
var startsWithWindowsDriveLetter = function (string) {
var third;
return string.length > 1 && isWindowsDriveLetter(stringSlice$4(string, 0, 2)) && (
string.length == 2 ||
((third = charAt$2(string, 2)) === '/' || third === '\\' || third === '?' || third === '#')
);
};
// https://url.spec.whatwg.org/#single-dot-path-segment
var isSingleDot = function (segment) {
return segment === '.' || toLowerCase(segment) === '%2e';
};
// https://url.spec.whatwg.org/#double-dot-path-segment
var isDoubleDot = function (segment) {
segment = toLowerCase(segment);
return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
};
// States:
var SCHEME_START = {};
var SCHEME = {};
var NO_SCHEME = {};
var SPECIAL_RELATIVE_OR_AUTHORITY = {};
var PATH_OR_AUTHORITY = {};
var RELATIVE = {};
var RELATIVE_SLASH = {};
var SPECIAL_AUTHORITY_SLASHES = {};
var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
var AUTHORITY = {};
var HOST = {};
var HOSTNAME = {};
var PORT = {};
var FILE = {};
var FILE_SLASH = {};
var FILE_HOST = {};
var PATH_START = {};
var PATH = {};
var CANNOT_BE_A_BASE_URL_PATH = {};
var QUERY = {};
var FRAGMENT = {};
var URLState = function (url, isBase, base) {
var urlString = $toString$1(url);
var baseState, failure, searchParams;
if (isBase) {
failure = this.parse(urlString);
if (failure) throw TypeError$3(failure);
this.searchParams = null;
} else {
if (base !== undefined) baseState = new URLState(base, true);
failure = this.parse(urlString, null, baseState);
if (failure) throw TypeError$3(failure);
searchParams = getInternalSearchParamsState(new URLSearchParams$1());
searchParams.bindURL(this);
this.searchParams = searchParams;
}
};
URLState.prototype = {
type: 'URL',
// https://url.spec.whatwg.org/#url-parsing
// eslint-disable-next-line max-statements -- TODO
parse: function (input, stateOverride, base) {
var url = this;
var state = stateOverride || SCHEME_START;
var pointer = 0;
var buffer = '';
var seenAt = false;
var seenBracket = false;
var seenPasswordToken = false;
var codePoints, chr, bufferCodePoints, failure;
input = $toString$1(input);
if (!stateOverride) {
url.scheme = '';
url.username = '';
url.password = '';
url.host = null;
url.port = null;
url.path = [];
url.query = null;
url.fragment = null;
url.cannotBeABaseURL = false;
input = replace$4(input, LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, '');
}
input = replace$4(input, TAB_AND_NEW_LINE, '');
codePoints = arrayFrom(input);
while (pointer <= codePoints.length) {
chr = codePoints[pointer];
switch (state) {
case SCHEME_START:
if (chr && exec$2(ALPHA, chr)) {
buffer += toLowerCase(chr);
state = SCHEME;
} else if (!stateOverride) {
state = NO_SCHEME;
continue;
} else return INVALID_SCHEME;
break;
case SCHEME:
if (chr && (exec$2(ALPHANUMERIC, chr) || chr == '+' || chr == '-' || chr == '.')) {
buffer += toLowerCase(chr);
} else if (chr == ':') {
if (stateOverride && (
(url.isSpecial() != hasOwn$9(specialSchemes, buffer)) ||
(buffer == 'file' && (url.includesCredentials() || url.port !== null)) ||
(url.scheme == 'file' && !url.host)
)) return;
url.scheme = buffer;
if (stateOverride) {
if (url.isSpecial() && specialSchemes[url.scheme] == url.port) url.port = null;
return;
}
buffer = '';
if (url.scheme == 'file') {
state = FILE;
} else if (url.isSpecial() && base && base.scheme == url.scheme) {
state = SPECIAL_RELATIVE_OR_AUTHORITY;
} else if (url.isSpecial()) {
state = SPECIAL_AUTHORITY_SLASHES;
} else if (codePoints[pointer + 1] == '/') {
state = PATH_OR_AUTHORITY;
pointer++;
} else {
url.cannotBeABaseURL = true;
push$4(url.path, '');
state = CANNOT_BE_A_BASE_URL_PATH;
}
} else if (!stateOverride) {
buffer = '';
state = NO_SCHEME;
pointer = 0;
continue;
} else return INVALID_SCHEME;
break;
case NO_SCHEME:
if (!base || (base.cannotBeABaseURL && chr != '#')) return INVALID_SCHEME;
if (base.cannotBeABaseURL && chr == '#') {
url.scheme = base.scheme;
url.path = arraySlice$3(base.path);
url.query = base.query;
url.fragment = '';
url.cannotBeABaseURL = true;
state = FRAGMENT;
break;
}
state = base.scheme == 'file' ? FILE : RELATIVE;
continue;
case SPECIAL_RELATIVE_OR_AUTHORITY:
if (chr == '/' && codePoints[pointer + 1] == '/') {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
pointer++;
} else {
state = RELATIVE;
continue;
} break;
case PATH_OR_AUTHORITY:
if (chr == '/') {
state = AUTHORITY;
break;
} else {
state = PATH;
continue;
}
case RELATIVE:
url.scheme = base.scheme;
if (chr == EOF) {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySlice$3(base.path);
url.query = base.query;
} else if (chr == '/' || (chr == '\\' && url.isSpecial())) {
state = RELATIVE_SLASH;
} else if (chr == '?') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySlice$3(base.path);
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySlice$3(base.path);
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySlice$3(base.path);
url.path.length--;
state = PATH;
continue;
} break;
case RELATIVE_SLASH:
if (url.isSpecial() && (chr == '/' || chr == '\\')) {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
} else if (chr == '/') {
state = AUTHORITY;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
state = PATH;
continue;
} break;
case SPECIAL_AUTHORITY_SLASHES:
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
if (chr != '/' || charAt$2(buffer, pointer + 1) != '/') continue;
pointer++;
break;
case SPECIAL_AUTHORITY_IGNORE_SLASHES:
if (chr != '/' && chr != '\\') {
state = AUTHORITY;
continue;
} break;
case AUTHORITY:
if (chr == '@') {
if (seenAt) buffer = '%40' + buffer;
seenAt = true;
bufferCodePoints = arrayFrom(buffer);
for (var i = 0; i < bufferCodePoints.length; i++) {
var codePoint = bufferCodePoints[i];
if (codePoint == ':' && !seenPasswordToken) {
seenPasswordToken = true;
continue;
}
var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
if (seenPasswordToken) url.password += encodedCodePoints;
else url.username += encodedCodePoints;
}
buffer = '';
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial())
) {
if (seenAt && buffer == '') return INVALID_AUTHORITY;
pointer -= arrayFrom(buffer).length + 1;
buffer = '';
state = HOST;
} else buffer += chr;
break;
case HOST:
case HOSTNAME:
if (stateOverride && url.scheme == 'file') {
state = FILE_HOST;
continue;
} else if (chr == ':' && !seenBracket) {
if (buffer == '') return INVALID_HOST;
failure = url.parseHost(buffer);
if (failure) return failure;
buffer = '';
state = PORT;
if (stateOverride == HOSTNAME) return;
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial())
) {
if (url.isSpecial() && buffer == '') return INVALID_HOST;
if (stateOverride && buffer == '' && (url.includesCredentials() || url.port !== null)) return;
failure = url.parseHost(buffer);
if (failure) return failure;
buffer = '';
state = PATH_START;
if (stateOverride) return;
continue;
} else {
if (chr == '[') seenBracket = true;
else if (chr == ']') seenBracket = false;
buffer += chr;
} break;
case PORT:
if (exec$2(DIGIT, chr)) {
buffer += chr;
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial()) ||
stateOverride
) {
if (buffer != '') {
var port = parseInt$1(buffer, 10);
if (port > 0xFFFF) return INVALID_PORT;
url.port = (url.isSpecial() && port === specialSchemes[url.scheme]) ? null : port;
buffer = '';
}
if (stateOverride) return;
state = PATH_START;
continue;
} else return INVALID_PORT;
break;
case FILE:
url.scheme = 'file';
if (chr == '/' || chr == '\\') state = FILE_SLASH;
else if (base && base.scheme == 'file') {
if (chr == EOF) {
url.host = base.host;
url.path = arraySlice$3(base.path);
url.query = base.query;
} else if (chr == '?') {
url.host = base.host;
url.path = arraySlice$3(base.path);
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.host = base.host;
url.path = arraySlice$3(base.path);
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
if (!startsWithWindowsDriveLetter(join(arraySlice$3(codePoints, pointer), ''))) {
url.host = base.host;
url.path = arraySlice$3(base.path);
url.shortenPath();
}
state = PATH;
continue;
}
} else {
state = PATH;
continue;
} break;
case FILE_SLASH:
if (chr == '/' || chr == '\\') {
state = FILE_HOST;
break;
}
if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(join(arraySlice$3(codePoints, pointer), ''))) {
if (isWindowsDriveLetter(base.path[0], true)) push$4(url.path, base.path[0]);
else url.host = base.host;
}
state = PATH;
continue;
case FILE_HOST:
if (chr == EOF || chr == '/' || chr == '\\' || chr == '?' || chr == '#') {
if (!stateOverride && isWindowsDriveLetter(buffer)) {
state = PATH;
} else if (buffer == '') {
url.host = '';
if (stateOverride) return;
state = PATH_START;
} else {
failure = url.parseHost(buffer);
if (failure) return failure;
if (url.host == 'localhost') url.host = '';
if (stateOverride) return;
buffer = '';
state = PATH_START;
} continue;
} else buffer += chr;
break;
case PATH_START:
if (url.isSpecial()) {
state = PATH;
if (chr != '/' && chr != '\\') continue;
} else if (!stateOverride && chr == '?') {
url.query = '';
state = QUERY;
} else if (!stateOverride && chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
state = PATH;
if (chr != '/') continue;
} break;
case PATH:
if (
chr == EOF || chr == '/' ||
(chr == '\\' && url.isSpecial()) ||
(!stateOverride && (chr == '?' || chr == '#'))
) {
if (isDoubleDot(buffer)) {
url.shortenPath();
if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
push$4(url.path, '');
}
} else if (isSingleDot(buffer)) {
if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
push$4(url.path, '');
}
} else {
if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
if (url.host) url.host = '';
buffer = charAt$2(buffer, 0) + ':'; // normalize windows drive letter
}
push$4(url.path, buffer);
}
buffer = '';
if (url.scheme == 'file' && (chr == EOF || chr == '?' || chr == '#')) {
while (url.path.length > 1 && url.path[0] === '') {
shift(url.path);
}
}
if (chr == '?') {
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.fragment = '';
state = FRAGMENT;
}
} else {
buffer += percentEncode(chr, pathPercentEncodeSet);
} break;
case CANNOT_BE_A_BASE_URL_PATH:
if (chr == '?') {
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
url.path[0] += percentEncode(chr, C0ControlPercentEncodeSet);
} break;
case QUERY:
if (!stateOverride && chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
if (chr == "'" && url.isSpecial()) url.query += '%27';
else if (chr == '#') url.query += '%23';
else url.query += percentEncode(chr, C0ControlPercentEncodeSet);
} break;
case FRAGMENT:
if (chr != EOF) url.fragment += percentEncode(chr, fragmentPercentEncodeSet);
break;
}
pointer++;
}
},
// https://url.spec.whatwg.org/#host-parsing
parseHost: function (input) {
var result, codePoints, index;
if (charAt$2(input, 0) == '[') {
if (charAt$2(input, input.length - 1) != ']') return INVALID_HOST;
result = parseIPv6(stringSlice$4(input, 1, -1));
if (!result) return INVALID_HOST;
this.host = result;
// opaque host
} else if (!this.isSpecial()) {
if (exec$2(FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT, input)) return INVALID_HOST;
result = '';
codePoints = arrayFrom(input);
for (index = 0; index < codePoints.length; index++) {
result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
}
this.host = result;
} else {
input = toASCII(input);
if (exec$2(FORBIDDEN_HOST_CODE_POINT, input)) return INVALID_HOST;
result = parseIPv4(input);
if (result === null) return INVALID_HOST;
this.host = result;
}
},
// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
cannotHaveUsernamePasswordPort: function () {
return !this.host || this.cannotBeABaseURL || this.scheme == 'file';
},
// https://url.spec.whatwg.org/#include-credentials
includesCredentials: function () {
return this.username != '' || this.password != '';
},
// https://url.spec.whatwg.org/#is-special
isSpecial: function () {
return hasOwn$9(specialSchemes, this.scheme);
},
// https://url.spec.whatwg.org/#shorten-a-urls-path
shortenPath: function () {
var path = this.path;
var pathSize = path.length;
if (pathSize && (this.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
path.length--;
}
},
// https://url.spec.whatwg.org/#concept-url-serializer
serialize: function () {
var url = this;
var scheme = url.scheme;
var username = url.username;
var password = url.password;
var host = url.host;
var port = url.port;
var path = url.path;
var query = url.query;
var fragment = url.fragment;
var output = scheme + ':';
if (host !== null) {
output += '//';
if (url.includesCredentials()) {
output += username + (password ? ':' + password : '') + '@';
}
output += serializeHost(host);
if (port !== null) output += ':' + port;
} else if (scheme == 'file') output += '//';
output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + join(path, '/') : '';
if (query !== null) output += '?' + query;
if (fragment !== null) output += '#' + fragment;
return output;
},
// https://url.spec.whatwg.org/#dom-url-href
setHref: function (href) {
var failure = this.parse(href);
if (failure) throw TypeError$3(failure);
this.searchParams.update();
},
// https://url.spec.whatwg.org/#dom-url-origin
getOrigin: function () {
var scheme = this.scheme;
var port = this.port;
if (scheme == 'blob') try {
return new URLConstructor(scheme.path[0]).origin;
} catch (error) {
return 'null';
}
if (scheme == 'file' || !this.isSpecial()) return 'null';
return scheme + '://' + serializeHost(this.host) + (port !== null ? ':' + port : '');
},
// https://url.spec.whatwg.org/#dom-url-protocol
getProtocol: function () {
return this.scheme + ':';
},
setProtocol: function (protocol) {
this.parse($toString$1(protocol) + ':', SCHEME_START);
},
// https://url.spec.whatwg.org/#dom-url-username
getUsername: function () {
return this.username;
},
setUsername: function (username) {
var codePoints = arrayFrom($toString$1(username));
if (this.cannotHaveUsernamePasswordPort()) return;
this.username = '';
for (var i = 0; i < codePoints.length; i++) {
this.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
},
// https://url.spec.whatwg.org/#dom-url-password
getPassword: function () {
return this.password;
},
setPassword: function (password) {
var codePoints = arrayFrom($toString$1(password));
if (this.cannotHaveUsernamePasswordPort()) return;
this.password = '';
for (var i = 0; i < codePoints.length; i++) {
this.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
},
// https://url.spec.whatwg.org/#dom-url-host
getHost: function () {
var host = this.host;
var port = this.port;
return host === null ? ''
: port === null ? serializeHost(host)
: serializeHost(host) + ':' + port;
},
setHost: function (host) {
if (this.cannotBeABaseURL) return;
this.parse(host, HOST);
},
// https://url.spec.whatwg.org/#dom-url-hostname
getHostname: function () {
var host = this.host;
return host === null ? '' : serializeHost(host);
},
setHostname: function (hostname) {
if (this.cannotBeABaseURL) return;
this.parse(hostname, HOSTNAME);
},
// https://url.spec.whatwg.org/#dom-url-port
getPort: function () {
var port = this.port;
return port === null ? '' : $toString$1(port);
},
setPort: function (port) {
if (this.cannotHaveUsernamePasswordPort()) return;
port = $toString$1(port);
if (port == '') this.port = null;
else this.parse(port, PORT);
},
// https://url.spec.whatwg.org/#dom-url-pathname
getPathname: function () {
var path = this.path;
return this.cannotBeABaseURL ? path[0] : path.length ? '/' + join(path, '/') : '';
},
setPathname: function (pathname) {
if (this.cannotBeABaseURL) return;
this.path = [];
this.parse(pathname, PATH_START);
},
// https://url.spec.whatwg.org/#dom-url-search
getSearch: function () {
var query = this.query;
return query ? '?' + query : '';
},
setSearch: function (search) {
search = $toString$1(search);
if (search == '') {
this.query = null;
} else {
if ('?' == charAt$2(search, 0)) search = stringSlice$4(search, 1);
this.query = '';
this.parse(search, QUERY);
}
this.searchParams.update();
},
// https://url.spec.whatwg.org/#dom-url-searchparams
getSearchParams: function () {
return this.searchParams.facade;
},
// https://url.spec.whatwg.org/#dom-url-hash
getHash: function () {
var fragment = this.fragment;
return fragment ? '#' + fragment : '';
},
setHash: function (hash) {
hash = $toString$1(hash);
if (hash == '') {
this.fragment = null;
return;
}
if ('#' == charAt$2(hash, 0)) hash = stringSlice$4(hash, 1);
this.fragment = '';
this.parse(hash, FRAGMENT);
},
update: function () {
this.query = this.searchParams.serialize() || null;
}
};
// `URL` constructor
// https://url.spec.whatwg.org/#url-class
var URLConstructor = function URL(url /* , base */) {
var that = anInstance$3(this, URLPrototype);
var base = validateArgumentsLength(arguments.length, 1) > 1 ? arguments[1] : undefined;
var state = setInternalState$3(that, new URLState(url, false, base));
if (!DESCRIPTORS$a) {
that.href = state.serialize();
that.origin = state.getOrigin();
that.protocol = state.getProtocol();
that.username = state.getUsername();
that.password = state.getPassword();
that.host = state.getHost();
that.hostname = state.getHostname();
that.port = state.getPort();
that.pathname = state.getPathname();
that.search = state.getSearch();
that.searchParams = state.getSearchParams();
that.hash = state.getHash();
}
};
var URLPrototype = URLConstructor.prototype;
var accessorDescriptor = function (getter, setter) {
return {
get: function () {
return getInternalURLState(this)[getter]();
},
set: setter && function (value) {
return getInternalURLState(this)[setter](value);
},
configurable: true,
enumerable: true
};
};
if (DESCRIPTORS$a) {
// `URL.prototype.href` accessors pair
// https://url.spec.whatwg.org/#dom-url-href
defineBuiltInAccessor(URLPrototype, 'href', accessorDescriptor('serialize', 'setHref'));
// `URL.prototype.origin` getter
// https://url.spec.whatwg.org/#dom-url-origin
defineBuiltInAccessor(URLPrototype, 'origin', accessorDescriptor('getOrigin'));
// `URL.prototype.protocol` accessors pair
// https://url.spec.whatwg.org/#dom-url-protocol
defineBuiltInAccessor(URLPrototype, 'protocol', accessorDescriptor('getProtocol', 'setProtocol'));
// `URL.prototype.username` accessors pair
// https://url.spec.whatwg.org/#dom-url-username
defineBuiltInAccessor(URLPrototype, 'username', accessorDescriptor('getUsername', 'setUsername'));
// `URL.prototype.password` accessors pair
// https://url.spec.whatwg.org/#dom-url-password
defineBuiltInAccessor(URLPrototype, 'password', accessorDescriptor('getPassword', 'setPassword'));
// `URL.prototype.host` accessors pair
// https://url.spec.whatwg.org/#dom-url-host
defineBuiltInAccessor(URLPrototype, 'host', accessorDescriptor('getHost', 'setHost'));
// `URL.prototype.hostname` accessors pair
// https://url.spec.whatwg.org/#dom-url-hostname
defineBuiltInAccessor(URLPrototype, 'hostname', accessorDescriptor('getHostname', 'setHostname'));
// `URL.prototype.port` accessors pair
// https://url.spec.whatwg.org/#dom-url-port
defineBuiltInAccessor(URLPrototype, 'port', accessorDescriptor('getPort', 'setPort'));
// `URL.prototype.pathname` accessors pair
// https://url.spec.whatwg.org/#dom-url-pathname
defineBuiltInAccessor(URLPrototype, 'pathname', accessorDescriptor('getPathname', 'setPathname'));
// `URL.prototype.search` accessors pair
// https://url.spec.whatwg.org/#dom-url-search
defineBuiltInAccessor(URLPrototype, 'search', accessorDescriptor('getSearch', 'setSearch'));
// `URL.prototype.searchParams` getter
// https://url.spec.whatwg.org/#dom-url-searchparams
defineBuiltInAccessor(URLPrototype, 'searchParams', accessorDescriptor('getSearchParams'));
// `URL.prototype.hash` accessors pair
// https://url.spec.whatwg.org/#dom-url-hash
defineBuiltInAccessor(URLPrototype, 'hash', accessorDescriptor('getHash', 'setHash'));
}
// `URL.prototype.toJSON` method
// https://url.spec.whatwg.org/#dom-url-tojson
defineBuiltIn$5(URLPrototype, 'toJSON', function toJSON() {
return getInternalURLState(this).serialize();
}, { enumerable: true });
// `URL.prototype.toString` method
// https://url.spec.whatwg.org/#URL-stringification-behavior
defineBuiltIn$5(URLPrototype, 'toString', function toString() {
return getInternalURLState(this).serialize();
}, { enumerable: true });
if (NativeURL) {
var nativeCreateObjectURL = NativeURL.createObjectURL;
var nativeRevokeObjectURL = NativeURL.revokeObjectURL;
// `URL.createObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
if (nativeCreateObjectURL) defineBuiltIn$5(URLConstructor, 'createObjectURL', bind$2(nativeCreateObjectURL, NativeURL));
// `URL.revokeObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
if (nativeRevokeObjectURL) defineBuiltIn$5(URLConstructor, 'revokeObjectURL', bind$2(nativeRevokeObjectURL, NativeURL));
}
setToStringTag$2(URLConstructor, 'URL');
$$p({ global: true, constructor: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS$a }, {
URL: URLConstructor
});
var uncurryThis$e = functionUncurryThis;
var requireObjectCoercible$2 = requireObjectCoercible$d;
var toString$6 = toString$j;
var quot = /"/g;
var replace$3 = uncurryThis$e(''.replace);
// `CreateHTML` abstract operation
// https://tc39.es/ecma262/#sec-createhtml
var createHtml = function (string, tag, attribute, value) {
var S = toString$6(requireObjectCoercible$2(string));
var p1 = '<' + tag;
if (attribute !== '') p1 += ' ' + attribute + '="' + replace$3(toString$6(value), quot, '"') + '"';
return p1 + '>' + S + '' + tag + '>';
};
var fails$e = fails$J;
// check the existence of a method, lowercase
// of a tag and escaping quotes in arguments
var stringHtmlForced = function (METHOD_NAME) {
return fails$e(function () {
var test = ''[METHOD_NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
});
};
var $$o = _export;
var createHTML$1 = createHtml;
var forcedStringHTMLMethod$1 = stringHtmlForced;
// `String.prototype.sub` method
// https://tc39.es/ecma262/#sec-string.prototype.sub
$$o({ target: 'String', proto: true, forced: forcedStringHTMLMethod$1('sub') }, {
sub: function sub() {
return createHTML$1(this, 'sub', '', '');
}
});
// import DetectionUtil from './util/detection';
// const Util = {
// ...DetectionUtil
// };
var Util = {
/**
* Loads a script file by adding it to the DOM. Returns a promise that resolves when the script has loaded.
* @param {string} url URL of the script file to load
* @param {string} appendLocation Where to append the script tag. Options: 'body' or 'head'
* @param {boolean} async If true, the script will be loaded asynchronously
* @param {boolean} defer If true, the script will be deferred
* @returns {Promise} A promise that resolves with the script element when the script has loaded
*/
loadScript: function loadScript(url, appendLocation, async, defer) {
if (appendLocation === void 0) {
appendLocation = 'body';
}
if (async === void 0) {
async = true;
}
if (defer === void 0) {
defer = false;
}
return new Promise(function (resolve, reject) {
if (!['body', 'head'].includes(appendLocation)) {
reject(new Error("Invalid appendLocation: " + appendLocation + ". Use 'body' or 'head'."));
return;
}
// Check if the script is already loaded
var existingScript = Array.from(document.getElementsByTagName('script')).find(function (script) {
return script.src === url;
});
if (existingScript) {
resolve(existingScript);
return;
}
var script = document.createElement('script');
script.src = url;
script.async = async;
script.defer = defer;
script.addEventListener('load', function () {
return resolve(script);
});
script.addEventListener('error', function () {
return reject(new Error("Failed to load script: " + url));
});
document[appendLocation].append(script);
});
},
/**
* Normalizes text for comparison by converting smart quotes to straight quotes
* and normalizing other special characters and whitespace
*
* @param {string} text The text to normalize
* @returns {string} The normalized text
*/
normalizeText: function normalizeText(text) {
if (typeof text !== 'string' || !text) return '';
return text
// Western quotes (keep separate for single vs double quote differentiation)
.replace(/[\u2018\u2019]/g, "'") // Smart single quotes to straight quotes
// All other quotes (combined for efficiency based on ESLint suggestions)
.replace(/[\u00AB-\u00BB\u201A-\u201F\u3008\u3009\u300C-\u300F\u301D-\u301F]/g, '"')
// Dashes (using range)
.replace(/[\u2012-\u2015]/g, '-')
// All whitespace in one operation
.replace(/\s+/g, ' ').trim();
},
/**
* Toggles the inert attribute on the siblings of the provided element
*
* This function is useful for modal dialogs, as it allows you to disable
* all elements outside the modal, ensuring that screen readers
* only interact with the modal content.
*
* @param {HTMLElement} element modal dialog element whose siblings will be affected
* @param {boolean} isInert If true, adds the 'inert' attribute. If false, removes it.
*/
toggleSiblingsInert: function toggleSiblingsInert(element, isInert) {
if (!element || !element.parentElement) {
// eslint-disable-next-line no-console
console.warn('toggleSiblingsInert: Invalid element or no parent element found.');
return;
}
// get all siblings of the element
var siblings = Array.from(element.parentElement.children);
siblings.forEach(function (sibling) {
// check if the sibling is an element and not a script, style, or link tag
if (sibling !== element && sibling.nodeType === Node.ELEMENT_NODE && !['SCRIPT', 'STYLE', 'LINK'].includes(sibling.tagName)) {
if (isInert) {
sibling.setAttribute('inert', '');
} else if (sibling.hasAttribute('inert')) {
sibling.removeAttribute('inert');
}
}
});
}
};
// Send the getClock request every 30 seconds of inactivity
var livePersonGetClockInterval = 30000;
// Error types
var LPErrorTypes = {
GET_JWT_TIMEOUT: 'GET_JWT_TIMEOUT',
INIT_WS_TIMEOUT: 'INIT_WS_TIMEOUT',
ACCEPT_STATUS_TIMEOUT: 'ACCEPT_STATUS_TIMEOUT',
INIT_CONNECTION_TIMEOUT: 'INIT_CONNECTION_TIMEOUT',
SUBSCRIBE_EX_CONVERSATIONS_TIMEOUT: 'SUBSCRIBE_EX_CONVERSATIONS_TIMEOUT',
UNSUBSCRIBE_EX_CONVERSATIONS_TIMEOUT: 'UNSUBSCRIBE_EX_CONVERSATIONS_TIMEOUT',
CONSUMER_REQUEST_CONVERSATION_TIMEOUT: 'CONSUMER_REQUEST_CONVERSATION_TIMEOUT',
USER_CLOSE_CONVERSATION_TIMEOUT: 'USER_CLOSE_CONVERSATION_TIMEOUT',
SEND_MESSAGE_TIMEOUT: 'SEND_MESSAGE_TIMEOUT',
WEBSOCKET_NOT_OPEN: 'WEBSOCKET_NOT_OPEN'
};
/**
* LivePerson library
* Forked from https://codepen.io/liveperson/pen/oYyLJr
*/
var LPUtils = {
conversationStateTypes: {
OPEN: 'OPEN',
CLOSE: 'CLOSE'
},
conversationStageTypes: {
OPEN: 'OPEN',
CLOSE: 'CLOSE'
},
acceptStatusTypes: {
ACCEPT: 'ACCEPT',
READ: 'READ',
ACCESS: 'ACCESS',
NACK: 'NACK',
ACTION: 'ACTION'
},
getDomain: function getDomain(account, name) {
var domains = account.startsWith('le') ? 'hc1n.dev.lprnd.net' : 'adminlogin.liveperson.net';
var url = "https://" + domains + "/csdr/account/" + account + "/service/" + name + "/baseURI.lpCsds?version=1.0&cb=domainCallback";
return new Promise(function (res, rej) {
// Remove existing script tag if it exists
var existingScript = document.querySelector("script[src=\"" + url + "\"]");
if (existingScript) {
existingScript.remove();
}
var script = document.createElement('script');
script.src = url;
script.async = true;
script.addEventListener('error', function () {
return rej(new Error('Network error getting LivePerson domain'));
});
window.domainCallback = function (data) {
if (data.ResultSet && data.ResultSet.lpData && data.ResultSet.lpData[0] && data.ResultSet.lpData[0].lpServer) {
res(data.ResultSet.lpData[0].lpServer);
} else {
rej(new Error('Invalid response'));
}
};
document.body.append(script);
});
},
signup: function signup(account) {
return this.getDomain(account, 'idp').then(function (idpDomain) {
var url = "https://" + idpDomain + "/api/account/" + account + "/signup.jsonp?callback=callback";
return new Promise(function (res, rej) {
var script = document.createElement('script');
script.src = url;
script.async = true;
script.addEventListener('error', function () {
return rej(new Error('Network error'));
});
window.callback = function (idpResp) {
if (idpResp && idpResp.jwt) {
res(idpResp.jwt);
} else {
rej(new Error('Invalid response'));
}
};
document.body.append(script);
});
});
},
// fetch jwt from cookie object or create one
getJWT: function getJWT(account, cookieObject, cookieKey) {
var localJWT = cookieObject[cookieKey];
if (!localJWT) {
return this.signup(account).then(function (newJWT) {
return newJWT;
});
}
return localJWT;
},
engagement: {
buildSessionRequestBody: function buildSessionRequestBody(country, topic, leadId, ipAddress, pageId) {
var sessionRequestBody = {
appType: 'EXTERNAL'
};
if (pageId) {
sessionRequestBody = {
pageId: pageId
};
}
if (ipAddress) {
sessionRequestBody.appDetails = {
ipAddress: ipAddress
};
}
if (country || topic || leadId || ipAddress) {
sessionRequestBody.engagementAttributes = [];
}
if (!ipAddress && country) {
sessionRequestBody.engagementAttributes.push({
type: 'personal',
personal: {
language: country
}
});
}
if (topic || leadId) {
var leadAttribute = {
type: 'lead',
lead: {}
};
if (topic) {
leadAttribute.lead.topic = topic;
}
if (leadId) {
leadAttribute.lead.leadId = leadId;
}
sessionRequestBody.engagementAttributes.push(leadAttribute);
}
return sessionRequestBody;
},
createSession: function createSession(requestData) {
var account = requestData.account,
country = requestData.country,
topic = requestData.topic,
leadId = requestData.leadId,
ipAddress = requestData.ipAddress,
_requestData$visitorI = requestData.visitorId,
visitorId = _requestData$visitorI === void 0 ? null : _requestData$visitorI,
_requestData$sessionI = requestData.sessionId,
sessionId = _requestData$sessionI === void 0 ? null : _requestData$sessionI;
return new Promise(function (resolve, reject) {
LPUtils.getDomain(account, 'msdkgw').then(function (engagementDomain) {
var visitorIdPathParam = visitorId ? "/" + visitorId : '';
var sessionIdQueryParam = sessionId ? "&sid=" + sessionId : '';
var url = "https://" + engagementDomain + "/api/account/" + account + "/app/engagement/visitors" + visitorIdPathParam + "?v=1.0" + sessionIdQueryParam;
var requestBody = LPUtils.engagement.buildSessionRequestBody(country, topic, leadId, ipAddress);
fetch(url, {
body: JSON.stringify(requestBody),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.json();
}).then(function (result) {
return resolve(result);
})["catch"](function (error) {
return reject(error);
});
});
});
},
updateSession: function updateSession(requestData) {
var account = requestData.account,
pageId = requestData.pageId,
visitorId = requestData.visitorId,
sessionId = requestData.sessionId,
country = requestData.country,
topic = requestData.topic,
leadId = requestData.leadId,
ipAddress = requestData.ipAddress;
if (!pageId || !visitorId || !sessionId) {
throw new Error('Required parameters are missing.');
}
return new Promise(function (resolve, reject) {
LPUtils.getDomain(account, 'msdkgw').then(function (engagementDomain) {
var url = "https://" + engagementDomain + "/api/account/" + account + "/app/engagement/visitors/" + visitorId + "?v=1.0&sid=" + sessionId;
var requestBody = LPUtils.engagement.buildSessionRequestBody(country, topic, leadId, ipAddress);
fetch(url, {
body: JSON.stringify(requestBody),
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return resolve(response.status);
})["catch"](function (error) {
return reject(error);
});
});
});
}
},
waitFor: function waitFor(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
},
/* eslint-disable no-unmodified-loop-condition */
/* eslint-disable no-await-in-loop */
/**
* Executes a polling function with exponential backoff retry strategy.
*
* @param {Function} pollingFunction - The function to be executed. Should return a promise.
* @param {Function} retryCondition - A function that determines whether to retry based on the response and error. Should return a boolean or a promise that resolves to a boolean.
* @param {Object} [options] - Optional settings.
* @param {Array} [options.args] - Arguments to pass to the polling function.
* @param {number} [options.maxRetries=3] - Maximum number of retry attempts.
* @param {number} [options.delayInSeconds=5] - Initial delay between retries in seconds.
* @param {number} [options.attemptNumber] - The current attempt number (used internally).
* @param {number} [options.nextInterval] - The next interval for retry (used internally).
* @param {number} [options.attemptsLeft] - The number of attempts left (used internally).
* @param {number} [options.pollingInterval] - The current polling interval (used internally).
* @returns {Promise<*>} - The response from the polling function if successful.
* @throws {Error} - Throws the last encountered error if all retries fail.
*/
exponentialBackoff: function exponentialBackoff(pollingFunction, retryCondition, options) {
return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var maxRetries, delayInSeconds, attemptNumber, response, error, retry, args, retryFunction;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
maxRetries = 3;
delayInSeconds = 5;
attemptNumber = 0;
response = null;
error = null;
retry = false;
args = [];
if (!options) {
options = {};
}
if (!options.args) {
options.args = [];
}
args = options.args;
maxRetries = options.maxRetries || maxRetries;
delayInSeconds = options.delayInSeconds || delayInSeconds;
retryFunction = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
attemptNumber++;
_context.next = 4;
return pollingFunction.apply(void 0, args);
case 4:
response = _context.sent;
_context.next = 10;
break;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](0);
error = _context.t0;
case 10:
options.attemptNumber = attemptNumber;
options.nextInterval = delayInSeconds;
options.attemptsLeft = maxRetries;
if (!retryCondition) {
_context.next = 19;
break;
}
_context.next = 16;
return retryCondition(response, error, options);
case 16:
_context.t1 = _context.sent;
_context.next = 20;
break;
case 19:
_context.t1 = !response || error;
case 20:
retry = _context.t1;
args = options.args || [];
case 22:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 7]]);
}));
return function retryFunction() {
return _ref.apply(this, arguments);
};
}();
_context2.next = 15;
return retryFunction();
case 15:
if (!(maxRetries > 0 && retry)) {
_context2.next = 27;
break;
}
response = null;
error = null;
options.pollingInterval = delayInSeconds;
_context2.next = 21;
return LPUtils.waitFor(delayInSeconds * 1000);
case 21:
delayInSeconds *= 2; // Exponential backoff
maxRetries--;
_context2.next = 25;
return retryFunction();
case 25:
_context2.next = 15;
break;
case 27:
if (!response) {
_context2.next = 29;
break;
}
return _context2.abrupt("return", response);
case 29:
throw error;
case 30:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))();
}
/* eslint-enable no-unmodified-loop-condition */
/* eslint-enable no-await-in-loop */
};
var LPWs = /*#__PURE__*/function () {
LPWs.connect = function connect(url) {
return new LPWs(url)._connect();
};
LPWs.connectDebug = function connectDebug(url) {
return new LPWs(url, true)._connect();
};
function LPWs(url, debug) {
var _this = this;
this.getClockRequest = debounce(livePersonGetClockInterval, function () {
if (_this.debug && !_this.ws) {
console.log("[" + new Date().toLocaleString() + "] WebSocket is either not open yet or already closed.\n");
}
_this.getClock().then(function (resp) {
if (_this.debug) {
console.log("[" + new Date().toLocaleString() + "] WebSocket connection pong response: " + resp.code + "\n");
}
});
});
this.reqs = {};
this.subs = [];
this.publishContentCallbacks = [];
this.url = url;
this.debug = debug;
}
var _proto = LPWs.prototype;
_proto._connect = function _connect() {
var _this2 = this;
return new Promise(function (resolve, reject) {
var ws = new WebSocket(_this2.url);
_this2.ws = ws;
ws.addEventListener('open', function () {
return resolve(_this2);
});
ws.addEventListener('message', function (msg) {
return _this2.onmessage(msg);
});
ws.addEventListener('close', function (evt) {
return reject(evt);
});
});
};
_proto.request = function request(type, body, headers) {
var _this3 = this;
return new Promise(function (resolve, reject) {
var _obj$body$event, _obj$body$event2, _obj$body$event2$mess;
if (!_this3.ws) {
reject(new LPError(LPErrorTypes.WEBSOCKET_NOT_OPEN, 'LivePerson WebSocket connection is not open'));
}
var obj = {
kind: 'req',
type: type,
body: body || {},
id: (body == null ? void 0 : body.messageId) || Math.floor(Math.random() * 1e9),
headers: headers
};
_this3.reqs[obj.id] = function (type, code, body) {
return resolve({
type: type,
code: code,
body: body,
reqId: obj.id
});
};
var str = JSON.stringify(obj);
if (_this3.debug) console.log('sending: ' + str);
var timestampString = new Date().toISOString();
// If user is sending a message to LivePerson, notify handlers about the message object
if (obj.type === 'ms.PublishEvent' && ((_obj$body$event = obj.body.event) == null ? void 0 : _obj$body$event.type) === 'ContentEvent' && (_obj$body$event2 = obj.body.event) != null && (_obj$body$event2$mess = _obj$body$event2.message) != null && _obj$body$event2$mess.length) {
Promise.all(_this3.publishContentCallbacks.map(function (callback) {
return callback(obj, timestampString);
})).then(function () {
_this3.ws.send(str);
})["catch"](function (error) {
console.error('Error in publishContentCallbacks:', error);
reject(error);
});
} else {
_this3.ws.send(str);
}
});
};
_proto.onNotification = function onNotification(filterFunc, _onNotification) {
this.subs.push({
filter: filterFunc,
cb: _onNotification
});
};
_proto.onPublishContent = function onPublishContent(callback) {
this.publishContentCallbacks.push(callback);
};
_proto.toFuncName = function toFuncName(reqType) {
var str = reqType.slice(1 + reqType.lastIndexOf('.'));
return str.charAt(0).toLowerCase() + str.slice(1);
};
_proto.registerRequests = function registerRequests(arr) {
var _this4 = this;
arr.forEach(function (reqType) {
_this4[_this4.toFuncName(reqType)] = function (body, headers, id) {
return _this4.request(reqType, body, headers, id);
};
});
};
_proto.onmessage = function onmessage(msg) {
if (this.debug) console.log('recieved: ' + msg.data);
var obj = JSON.parse(msg.data);
if (obj.kind === 'resp') {
var id = obj.reqId;
delete obj.reqId;
delete obj.kind;
this.reqs[id].call(this, obj.type, obj.code, obj.body);
delete this.reqs[id];
} else if (obj.kind === 'notification') {
this.subs.forEach(function (sub) {
if (sub.filter.call(this, obj)) {
sub.cb.call(this, obj.body);
}
});
}
// Start the clock interval
this.getClockRequest();
};
return LPWs;
}();
var LPError = /*#__PURE__*/function (_Error) {
_inheritsLoose(LPError, _Error);
function LPError(type, message, data) {
var _this5;
if (data === void 0) {
data = {};
}
_this5 = _Error.call(this, message) || this;
_this5.type = type;
_this5.data = data;
return _this5;
}
return LPError;
}( /*#__PURE__*/_wrapNativeSuper$1(Error));
/**
* Private variables
*/
var aiChatDrawers = [];
var uhfHeaderMarginBottomVal = 2;
var azureWebsitesDomain = '.azurewebsites.net';
var aemCloudDomain = '.adobeaemcloud.com';
var isRunningLocally = window.location.port === '9002' || window.location.port === '4502' || window.location.port === '4503';
var isAzureWebsites = window.location.hostname.includes(azureWebsitesDomain);
var isAemCloud = window.location.hostname.includes(aemCloudDomain);
var livePersonApiRequestTypes = ['GetClock', 'cqm.SubscribeExConversations', 'cqm.UnsubscribeExConversations', 'ms.PublishEvent', 'cm.ConsumerRequestConversation', 'ms.SubscribeMessagingEvents', 'InitConnection', 'cm.UpdateConversationField'];
var livePersonChatStateTypes = {
DEFAULT: 0,
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
GONE: 'GONE',
COMPOSING: 'COMPOSING',
PAUSE: 'PAUSE'
};
var livePersonUserComposingDelay = 3000; // User starts composing again after 3 seconds of inactivity
var livePersonUserPauseDelay = 3000; // User state will be set to PAUSE after 3 seconds of inactivity
var livePersonResponseTimeout = 5000; // Wait 5 seconds before retrying a request to LP
// Wait a second before user can click a chat link again to avoid chat with sales button/link spamming
var debouncedChatActionTypeLinkClickDelay = 1000;
// JsonPollock script source for LivePerson post-chat survey rendering
var jsonPollockScriptSrc = 'https://www.microsoft.com/msonecloudapi/assets/json-pollock.bundle.min.js';
/**
* Private functions
*/
/**
* Get the domain for the cookie.
* @returns {string} The domain for the cookie.
*/
function getCookieDomain() {
// If on localhost or your IP, or on extensions PROD, or on Azure Websites or AEM Cloud, use the hostname.
if (isRunningLocally || isAzureWebsites || isAemCloud) {
return window.location.hostname;
}
// PROD
return '.microsoft.com';
}
/**
* Get the base endpoint for the data connector for communicating with Microsoft OneCloud API.
*
* @param {string} protocol The protocol to use for the endpoint. Examples: 'https:' or 'wss:'
* @returns {string} The base endpoint for the data connector.
*/
function getDataConnectorBaseEndpoint(protocol) {
if (isRunningLocally) {
return protocol + "//webassistant-dev.microsoft.com"; // Dev endpoint
}
if (isAzureWebsites) {
return protocol + "//webassistant-ppe.microsoft.com"; // PPE endpoint
}
return protocol + "//webassistant-prod.microsoft.com"; // PROD endpoint
}
/**
* LivePerson private functions
*/
function withSubscriptionID(subscriptionID) {
return function (notif) {
return notif.body.subscriptionId === subscriptionID;
};
}
function withType(type) {
return function (notif) {
return notif.type.includes(type);
};
}
/**
* Selectors
*/
var Selector$A = {
DATA_MOUNT: '[data-mount="ai-chat-drawer"]',
AI_CHAT_BUTTON: '.ai-chat-button',
AI_CHAT_BUTTON_TEXT: '.ai-chat-button__text',
AI_CHAT_BUTTON_HEADER_TEXT: '.ai-chat-button .ai-chat-button__text span',
AI_CHAT_BUTTON_ANCHOR: '.ai-chat-button a',
AI_CHAT_BUTTON_DATA_MOUNT: '[data-mount="ai-chat-button"]',
ARTICLE: 'article',
BLOCK_FEATURE_TITLE: '.block-feature__title',
CHAT_ACTION_TYPE_LINK: '[data-oc-chat]',
CLOSE_BUTTON: '.ai-chat-drawer__close',
DEFLECTION_FLOW_ELEMENT: '[id^="deflection-"]',
FEEDBACK_BUTTON: '.action--ai-feedback',
FOCUSABLE_ELEMENTS: 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]',
TAG_BUTTON: 'button.ai-chat-message--tag',
WEB_CHAT_CONTAINER: '.ai-chat-drawer__body__content__messages',
WEB_CHAT_SEND_BOX: '.webchat__send-box',
WEB_CHAT_SEND_BUTTON: '.webchat__send-button',
WEB_CHAT_ACTION_SET_BUTTONS: '.ac-actionSet button',
WEB_CHAT_TRANSCRIPT: '.webchat__basic-transcript',
WEB_CHAT_BUBBLE: '.webchat__bubble',
WEB_CHAT_BUBBLE_FROM_BOT: '.webchat__bubble:not(.webchat__bubble--from-user)',
WEB_CHAT_BUBBLE_FROM_USER: '.webchat__bubble--from-user',
WEB_CHAT_BUBBLE_CONTENT: '.webchat__bubble__content',
WEB_CHAT_STATUS: '.webchat__activity-status',
WEB_CHAT_TRANSCRIPT_TRANSCRIPT: '.webchat__basic-transcript__transcript',
UHF_HEADER: 'header',
UHF_HEADER_CONTAINER: '.universalheader, #headerArea',
UHF_MENU_NAV_EXPAND_ELEM: '#uhfCatLogoButton',
UHF_FOOTER: '.universalfooter, #footerArea',
SEND_TRANSCRIPT_CHECKBOX_CONTAINER: '[id^="sendTranscript"]',
STICKY_NAV: '#sticky-nav',
STICKY: '.sticky',
SURVEY_RESPONSE_STAR_SVG: '.survey-response-button-star',
POST_SURVEY_JSON_POLLOCK_BUTTON: 'div.lp-json-pollock-element-button button',
HEADER_CONTROLS: '.ai-chat-drawer__header__control'
};
/**
* Event names
*/
var EventName$A = {
CHANGE: 'change',
CLICK: 'click',
CLOSE: 'close',
INPUT: 'input',
KEYDOWN: 'keydown',
SCROLL: 'scroll',
SUBMIT: 'submit',
RESIZE: 'resize',
TRANSITION_END: 'transitionend',
WEBCHAT_CONNECT_INITIATED: 'webchatconnectinitiated',
WEBCHAT_CONNECT_FULFILLED: 'webchatconnectfulfilled',
WEBCHAT_MESSAGE_RECEIVED: 'webchatmessagereceived',
START_CONVERSATION_FULFILLED: 'startconversationfulfilled',
FEEDBACK_SENT: 'feedbackRequestSent',
LIVEPERSON_CHAT_START: 'startLPChat',
LIVEPERSON_MESSAGE_RENDERED: 'livePersonMessageRendered',
LIVEPERSON_SAVE_IDS: 'saveLPIDs',
GENERATE_REIMAGINE_UMP: 'generateReimagineUMP',
INSTANTIATED_BY_PROACTIVE_CHAT: 'instantiatedByProactiveChatEvent'
};
/**
* CSS classes
*/
var ClassName$q = {
AI_DISCLAIMER: 'ai-chat-drawer__disclaimer',
DISABLED: 'disabled',
DISPLAY_NONE: 'd-none',
FEEDBACK_BUTTON: 'action--ai-feedback',
GET_HEIGHT: 'get-height',
LP_SURVEY_QUESTIONNAIRE: 'lp-pcs-questionnaire',
LP_SURVEY_RICH_CONTENT: 'lp-pcs-richContent',
OVERFLOW_HIDDEN: 'overflow-hidden',
RETURN_TO_AI_CHAT: 'return-to-ai-chat',
SCREEN_READER_ONLY: 'sr-only',
SHOW: 'show',
STUCK: 'stuck',
SURVEY_RESPONSE_BUTTON_STAR: 'survey-response-button-star',
WEBCHAT_BUBBLE_CONTENT_FOLLOW_UP: 'webchat__bubble__content--follow-up',
WEBCHAT_BUBBLE_LP_SYSTEM_MESSAGE: 'webchat__bubble--lp-system-message'
};
/**
* Custom Attributes
*/
var Attributes$5 = {
AI_CHAT_ACTION_TYPE_LINK: 'data-oc-ai-chat',
CHAT_ACTION_TYPE_LINK: 'data-oc-chat',
IS_HIDDEN: 'data-is-hidden'
};
/**
* Style options for WebChat
*/
var AIChatDrawerStyleOptions = {
// Basic styling
backgroundColor: 'var(--theme-background-neutral-fade)',
fontSizeSmall: '0.75rem',
monospaceFont: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace',
primaryFont: 'inherit',
transitionDuration: '.3s',
// Bubble
bubbleBorderRadius: 'var(--root-radii-s)',
bubbleBorderWidth: 0,
bubbleFromUserBackground: 'var(--root-color-brilliant-blue-100)',
bubbleFromUserBorderRadius: 'var(--root-radii-s)',
bubbleFromUserBorderWidth: 0,
bubbleFromUserTextColor: 'var(--root-color-dark-slate-900)',
bubbleTextColor: 'var(--theme-foreground-base-subtle)',
// Send box
hideUploadButton: true,
sendBoxBackground: 'var(--theme-background-card-normal);',
sendBoxButtonColor: 'var(--theme-foreground-accent-subtle-normal)',
sendBoxButtonShadeColorOnActive: 'transparent',
sendBoxButtonKeyboardFocusIndicatorBorderColor: 'currentColor',
sendBoxButtonKeyboardFocusIndicatorBorderRadius: '0.5rem',
sendBoxButtonKeyboardFocusIndicatorBorderStyle: 'dotted',
sendBoxButtonKeyboardFocusIndicatorBorderWidth: '0.1875rem',
sendBoxButtonKeyboardFocusIndicatorInset: '0.375rem',
sendBoxDisabledTextColor: '#d2d2d2',
sendBoxButtonColorOnDisabled: '#d2d2d2',
sendBoxButtonShadeColorOnDisabled: 'transparent',
sendBoxHeight: 64,
sendBoxMaxHeight: 72,
sendBoxTextColor: 'Black',
sendBoxPlaceholderColor: 'var(--theme-foreground-base-subtle)',
sendBoxTextWrap: true,
// Timestamp
timestampColor: 'var(--root-color-dark-slate-400)'
};
/**
* Keys for cookies
*/
var StorageKeys = {
cookieName: 'ocrAIChat',
token: 'ocrAIChatToken',
tokenCreated: 'ocrAIChatTokenCreated',
tuid: 'tuid',
chatDrawerState: 'ocrAIChatDrawerState',
sourceSite: 'ocrAIChatDrawerSourceSite',
lpJWT: 'lpJWT',
lpOpenConvs: 'lpOpenConvs',
startLPChatActivityIds: 'startLPChatActivityIds',
lpSession: 'lpEngagementSession'
};
/**
* Constants for cookies
*/
var CookieConstants = {
domain: getCookieDomain(),
expiryDays: -1,
// Session cookie
secure: !isRunningLocally,
sameSite: 'Strict',
path: '/'
};
/**
* Feedback icon SVG constants
*/
var FEEDBACK_ICON_SVGS = {
POSITIVE_FILLED: "data:image/svg+xml,%3Csvg class='image is-down is-filled ___12fm75w f1w7gpdv fez10in fg4l7m0' fill='%230067b8' aria-hidden='true' width='16' height='16' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M9.58 1.05c-.75-.2-1.34.35-1.55.87-.24.6-.45 1.02-.7 1.53-.16.3-.33.65-.53 1.09-.48 1-.95 1.65-1.3 2.04a4.06 4.06 0 0 1-.5.49h-.02L3.11 8.19a2 2 0 0 0-.86 2.43l.52 1.38a2 2 0 0 0 1.28 1.2l5.35 1.69a2.5 2.5 0 0 0 3.15-1.68l1.36-4.65A2 2 0 0 0 12 6h-1.38l.2-.74c.13-.56.24-1.2.23-1.74-.01-.5-.06-1.02-.27-1.46-.22-.48-.6-.83-1.19-1Zm-4.6 6.03Z' %3E%3C/path%3E%3C/svg%3E",
NEGATIVE_FILLED: "data:image/svg+xml,%3Csvg class='image is-down is-filled ___12fm75w f1w7gpdv fez10in fg4l7m0' fill='%230067b8' aria-hidden='true' width='16' height='16' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M13.1 4.62a3.5 3.5 0 0 0-4.38-2.73L3.77 3.27a2 2 0 0 0-1.43 1.56l-.23 1.2c-.16.87.46 1.64 1.16 1.93.25.1.55.25.85.46a8.22 8.22 0 0 1 3.02 3.92l.28.7c.14.38.28.73.41 1 .11.23.25.46.42.63.19.19.44.33.75.33.36 0 .67-.12.91-.34.24-.2.4-.48.5-.76.22-.55.29-1.25.3-1.9a14.73 14.73 0 0 0-.13-2h.51a2.5 2.5 0 0 0 2.46-2.96l-.46-2.42Z' %3E%3C/path%3E%3C/svg%3E",
FILLED_STAR_SVG: "data:image/svg+xml,%3Csvg class='image star-rating' width='24' height='24' viewBox='0 0 24 24' fill='%230078D4' stroke='%230078D4' stroke-width='2' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 .587l3.668 7.57 8.332 1.228-6.038 5.938 1.425 8.283L12 18.617l-7.387 4.012 1.425-8.283-6.038-5.938 8.332-1.228z'/%3E%3C/svg%3E",
UNFILLED_STAR_SVG: "data:image/svg+xml,%3Csvg class='image star-rating' width='24' height='24' viewBox='0 0 24 24' fill='white' stroke='%230078D4' stroke-width='2' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 .587l3.668 7.57 8.332 1.228-6.038 5.938 1.425 8.283L12 18.617l-7.387 4.012 1.425-8.283-6.038-5.938 8.332-1.228z'/%3E%3C/svg%3E"
};
/**
* BotFramework-WebChat notification levels
*/
var NotificationLevel = {
ERROR: 'error',
WARN: 'warn',
INFO: 'info',
SUCCESS: 'success'
};
/**
* Gets all set cookie values, if available.
* @returns {Record | null} All cookie values.
*/
var getAllCookies = function getAllCookies() {
/** @type {Record} */
var cookies = {};
document.cookie.split('; ').forEach(function (pair) {
var separatorIndex = pair.indexOf('=');
if (separatorIndex !== -1) {
var key = pair.slice(0, separatorIndex);
var value;
try {
value = decodeURIComponent(pair.slice(separatorIndex + 1));
} catch (error) {
console.error("Error decoding cookie value: " + error);
return;
}
cookies[key] = value;
}
});
if (Object.keys(cookies).length > 0) {
return cookies;
}
return null;
};
/**
* Gets a set cookie value for the key provided, if available.
* @param {string} key Cookie key.
* @returns {string | null} Cookie value, or null.
*/
var getCookie = function getCookie(key) {
var cookies;
try {
cookies = getAllCookies();
} catch (error) {
console.error("Error getting all cookies: " + error);
return null;
}
if (cookies && typeof cookies === 'object') {
var value = cookies[key];
if (value !== undefined) {
return value;
}
}
return null;
};
/**
* Sets a cookie with the provided key and value.
* @param {string} key Cookie key.
* @param {string} value Cookie value.
* @param {number} [expiryDays] Number of days before the cookie expires.
* @param {string} [domain] Domain for the cookie.
* @param {boolean} [secure] Whether the cookie is secure.
* @param {boolean} [httpOnly] Whether the cookie is HTTP only.
* @param {string} [sameSite] SameSite attribute for the cookie.
*/
var setCookie = function setCookie(key, value, expiryDays, domain, secure, httpOnly, sameSite, path) {
if (secure === void 0) {
secure = CookieConstants.secure;
}
if (httpOnly === void 0) {
httpOnly = false;
}
if (sameSite === void 0) {
sameSite = CookieConstants.sameSite;
}
if (path === void 0) {
path = CookieConstants.path;
}
if (typeof key !== 'string' || typeof value !== 'string' || typeof expiryDays !== 'number' || domain && typeof domain !== 'string') {
throw new Error('Error setting cookie: Invalid parameters.');
}
var expiryDate = null;
if (expiryDays > -1) {
expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + expiryDays * 24 * 60 * 60 * 1000);
}
var cookieValue = key + "=" + encodeURIComponent(value);
var expiryString = expiryDate ? ";expires=" + expiryDate.toUTCString() : '';
var domainString = domain ? ";domain=" + domain : '';
var secureString = secure ? ';secure' : '';
var httpOnlyString = httpOnly ? ';httponly' : '';
var sameSiteString = ";samesite=" + sameSite;
var pathString = ";path=" + path;
// eslint-disable-next-line unicorn/no-document-cookie
document.cookie = cookieValue + expiryString + domainString + secureString + httpOnlyString + sameSiteString + pathString;
};
/**
* AI Chat Drawer
*/
var _UMP_HTML_TEMPLATE = /*#__PURE__*/_classPrivateFieldLooseKey("UMP_HTML_TEMPLATE");
var _setDefaultValuesInMarkup = /*#__PURE__*/_classPrivateFieldLooseKey("setDefaultValuesInMarkup");
var _setDefaultValuesAiChatButton = /*#__PURE__*/_classPrivateFieldLooseKey("setDefaultValuesAiChatButton");
var _addEventHandlers = /*#__PURE__*/_classPrivateFieldLooseKey("addEventHandlers");
var _initUhfIntersectionObserver = /*#__PURE__*/_classPrivateFieldLooseKey("initUhfIntersectionObserver");
var _initStickyNavMutationObserver = /*#__PURE__*/_classPrivateFieldLooseKey("initStickyNavMutationObserver");
var _initWebChatTranscriptObserver = /*#__PURE__*/_classPrivateFieldLooseKey("initWebChatTranscriptObserver");
var _positionAiChatButton = /*#__PURE__*/_classPrivateFieldLooseKey("positionAiChatButton");
var _positionAiChatDrawer = /*#__PURE__*/_classPrivateFieldLooseKey("positionAiChatDrawer");
var _resetSourceSiteUpdatePromise = /*#__PURE__*/_classPrivateFieldLooseKey("resetSourceSiteUpdatePromise");
var _regenerateAIChatDrawerToken = /*#__PURE__*/_classPrivateFieldLooseKey("regenerateAIChatDrawerToken");
var _generateDirectLineToken = /*#__PURE__*/_classPrivateFieldLooseKey("generateDirectLineToken");
var _refreshDirectLineToken = /*#__PURE__*/_classPrivateFieldLooseKey("refreshDirectLineToken");
var _setRefreshTimer = /*#__PURE__*/_classPrivateFieldLooseKey("setRefreshTimer");
var _getLocale = /*#__PURE__*/_classPrivateFieldLooseKey("getLocale");
var _initializeJsonPollock = /*#__PURE__*/_classPrivateFieldLooseKey("initializeJsonPollock");
var _handlePageOpenState = /*#__PURE__*/_classPrivateFieldLooseKey("handlePageOpenState");
var _getSourceSite = /*#__PURE__*/_classPrivateFieldLooseKey("getSourceSite");
var _getLPEndpoint = /*#__PURE__*/_classPrivateFieldLooseKey("getLPEndpoint");
var _getLivePersonIdFromJWT = /*#__PURE__*/_classPrivateFieldLooseKey("getLivePersonIdFromJWT");
var AIChatDrawer = /*#__PURE__*/function () {
/**
* Create an AIChatDrawer instance
* @param {Object} opts - The AI Chat Drawer options.
* @param {HTMLElement} opts.el - The chat drawer element.
*/
function AIChatDrawer(_ref) {
var _this = this,
_this$aiChatButton,
_this$getAIChatDrawer,
_this$getAIChatDrawer2,
_this$getAIChatDrawer3,
_this$getAIChatDrawer4;
var _el = _ref.el,
styleOptions = _ref.styleOptions;
Object.defineProperty(this, _getLivePersonIdFromJWT, {
value: _getLivePersonIdFromJWT2
});
Object.defineProperty(this, _getLPEndpoint, {
value: _getLPEndpoint2
});
Object.defineProperty(this, _getSourceSite, {
value: _getSourceSite2
});
Object.defineProperty(this, _handlePageOpenState, {
value: _handlePageOpenState2
});
Object.defineProperty(this, _initializeJsonPollock, {
value: _initializeJsonPollock2
});
Object.defineProperty(this, _getLocale, {
value: _getLocale2
});
Object.defineProperty(this, _setRefreshTimer, {
value: _setRefreshTimer2
});
Object.defineProperty(this, _refreshDirectLineToken, {
value: _refreshDirectLineToken2
});
Object.defineProperty(this, _generateDirectLineToken, {
value: _generateDirectLineToken2
});
Object.defineProperty(this, _regenerateAIChatDrawerToken, {
value: _regenerateAIChatDrawerToken2
});
Object.defineProperty(this, _resetSourceSiteUpdatePromise, {
value: _resetSourceSiteUpdatePromise2
});
Object.defineProperty(this, _positionAiChatDrawer, {
value: _positionAiChatDrawer2
});
Object.defineProperty(this, _positionAiChatButton, {
value: _positionAiChatButton2
});
Object.defineProperty(this, _initWebChatTranscriptObserver, {
value: _initWebChatTranscriptObserver2
});
Object.defineProperty(this, _initStickyNavMutationObserver, {
value: _initStickyNavMutationObserver2
});
Object.defineProperty(this, _initUhfIntersectionObserver, {
value: _initUhfIntersectionObserver2
});
Object.defineProperty(this, _addEventHandlers, {
value: _addEventHandlers2
});
Object.defineProperty(this, _setDefaultValuesAiChatButton, {
value: _setDefaultValuesAiChatButton2
});
Object.defineProperty(this, _setDefaultValuesInMarkup, {
value: _setDefaultValuesInMarkup2
});
Object.defineProperty(this, _UMP_HTML_TEMPLATE, {
writable: true,
value: "\n \n \n
"
});
this.replaceButtonContentWithStarSvg = function (el) {
var button = el.querySelector('button');
if (!button) return;
el.classList.add(ClassName$q.SURVEY_RESPONSE_BUTTON_STAR);
button.innerHTML = '';
var img = document.createElement('img');
img.src = FEEDBACK_ICON_SVGS.UNFILLED_STAR_SVG;
img.alt = 'Star';
button.append(img);
button.addEventListener(EventName$A.CLICK, _this.handleStarClick);
};
this.handleStarClick = function (event) {
event.preventDefault();
// Get all star buttons within the closest WEB_CHAT_BUBBLE_CONTENT parent
var parent = event.currentTarget.closest(Selector$A.WEB_CHAT_BUBBLE_CONTENT);
if (!parent) return;
var starDivs = Array.from(parent.querySelectorAll(Selector$A.SURVEY_RESPONSE_STAR_SVG));
// Get the index of the clicked star
var clickedStar = event.currentTarget.closest(Selector$A.SURVEY_RESPONSE_STAR_SVG);
var clickedIndex = starDivs.indexOf(clickedStar);
// Update the star ratings visually
starDivs.forEach(function (div, index) {
var btn = div.querySelector('button');
var img = btn.querySelector('img');
if (img) {
img.src = index <= clickedIndex ? FEEDBACK_ICON_SVGS.FILLED_STAR_SVG : FEEDBACK_ICON_SVGS.UNFILLED_STAR_SVG;
}
});
};
this.tryAddSurveyButtonTelemetry = function (el, attempts, forStarButtons) {
if (attempts === void 0) {
attempts = 0;
}
if (forStarButtons === void 0) {
forStarButtons = false;
}
var button = el.querySelector('button');
var parentBubble = el.closest(Selector$A.WEB_CHAT_BUBBLE_CONTENT);
var text = parentBubble == null ? void 0 : parentBubble.querySelector('.webchat__text-content p');
if (text && button) {
var buttonValue = button.getAttribute('title');
button.dataset.biHn = text.textContent;
button.dataset.biCN = forStarButtons ? buttonValue + " star rating button" : "" + buttonValue;
button.dataset.biId = 'ai-chat-drawer';
} else if (attempts < 3) {
setTimeout(function () {
return _this.tryAddSurveyButtonTelemetry(el, attempts + 1, forStarButtons);
}, 100);
}
};
this.tryReplaceButtonwithStarSVG = function (el, attempts) {
if (attempts === void 0) {
attempts = 0;
}
var parent = el.closest(Selector$A.WEB_CHAT_BUBBLE_CONTENT);
if (parent) {
var requiresStarReplacement = parent.dataset.requiresStarReplacement === 'true';
if (requiresStarReplacement) {
_this.replaceButtonContentWithStarSvg(el);
_this.tryAddSurveyButtonTelemetry(el, 0, true);
}
} else if (attempts < 3) {
setTimeout(function () {
return _this.tryReplaceButtonwithStarSVG(el, attempts + 1);
}, 100);
}
};
this.onAfterElementRenderedHandler = function (element, template) {
// If the element is a button and post-survey is enabled, process it
if (template.type === window.JsonPollock.TEMPLATE_TYPES.BUTTON && _this.isPostSurveyEnabled) {
_this.tryAddSurveyButtonTelemetry(element, 0, false);
_this.tryReplaceButtonwithStarSVG(element);
}
return element;
};
this.el = _el;
this.styleOptions = styleOptions || AIChatDrawerStyleOptions;
this.closeButton = this.el.querySelector(Selector$A.CLOSE_BUTTON);
this.webChatContainer = this.el.querySelector(Selector$A.WEB_CHAT_CONTAINER);
this.aiChatButton = document.querySelector(Selector$A.AI_CHAT_BUTTON);
this.aiChatButtonHeader = document.querySelector(Selector$A.AI_CHAT_BUTTON_HEADER_TEXT);
this.aiChatButtonAnchor = document.querySelector(Selector$A.AI_CHAT_BUTTON_ANCHOR);
this.aiChatButtonDataMount = (_this$aiChatButton = this.aiChatButton) == null ? void 0 : _this$aiChatButton.querySelector(Selector$A.AI_CHAT_BUTTON_DATA_MOUNT);
this.headerControls = this.el.querySelector(Selector$A.HEADER_CONTROLS);
this.aiDisclaimerDiv = null;
this.previouslyFocusedElem = null;
this.firstFocusableElem = this.closeButton;
this.lastFocusableElem = null;
this.webChatTextAreaHadFocus = false;
this.chatInitialized = false;
this.refreshBefore = 120; // Refresh 2 minutes before token expires
this.refreshAfter = 3480; // Refresh if token is older than 58 minutes
this.tokenEndpoint = this.el.dataset.tokenEndpoint;
this.tokenEndpointV2 = this.el.dataset.tokenEndpointV2;
this.botEnvironmentParameter = this.el.dataset.botEnvironmentParameter;
this.v2PagePaths = (this.el.dataset.v2PagePaths || '').split(',').map(function (s) {
return s.trim();
}).filter(Boolean);
this.refreshTokenUrl = this.el.dataset.refreshTokenUrl;
this.sourceSite = _classPrivateFieldLooseBase(this, _getSourceSite)[_getSourceSite]();
this.tuid = null;
this.initialChatTextDelay = 2000; // 2 seconds
this.messageWaitTimeout = null;
this.messageWaitTimeoutDuration = 100000; // 100 seconds
// Promise that will be resolved when the sourceSite update is detected
this.resolveSourceSiteUpdate = null;
this.sourceSiteUpdatePromise = null;
_classPrivateFieldLooseBase(this, _resetSourceSiteUpdatePromise)[_resetSourceSiteUpdatePromise]();
this.textInputPlaceholder = this.el.dataset.textInputPlaceholder || 'Ask a work question or make a request...';
this.isChatPersistEnabled = this.el.dataset.isChatPersistEnabled === 'true';
this.isInstantiatedByProactiveChat = false;
this.drawerTitleText = this.el.querySelector(Selector$A.BLOCK_FEATURE_TITLE).textContent || 'AI-powered assistant';
this.drawerLivePersonTitleText = this.el.dataset.drawerLivePersonTitleText || '[Live Agent] AI-powered assistant';
this.buttonTitleText = this.aiChatButton.querySelector(Selector$A.AI_CHAT_BUTTON_TEXT + " span").textContent || 'AI-powered assistant'; // button and drawer currently have same text, including for flexibility.
this.buttonLivePersonTitleText = this.el.dataset.buttonLivePersonTitleText || '[Live Agent] AI-powered assistant';
this.connectivityStatusAltFatalString = this.el.dataset.connectivityStatusAltFatal || 'Please refresh the page.';
this.livePersonInQueueText = this.el.dataset.livePersonInQueueText || 'Connecting you to a live agent. Please wait.';
this.livePersonUserClosedConversationText = this.el.dataset.livePersonUserClosedConversationText || 'Conversation closed by you';
this.livePersonAgentClosedConversationText = this.el.dataset.livePersonAgentClosedConversationText || 'Conversation closed by agent';
this.livePersonSystemClosedConversationText = this.el.dataset.livePersonSystemClosedConversationText || 'Conversation closed by idle system';
this.livePersonDisclaimerText = this.el.dataset.livePersonDisclaimerText || 'You are now chatting with a live agent.';
this.livePersonGenericErrorText = this.el.dataset.livePersonGenericErrorText || 'An error occurred. Please try again later.';
this.surveyBotDisclaimerText = this.el.dataset.surveyBotDisclaimerText || 'You are now chatting with a survey bot.';
this.livePersonNoAgentsText = this.el.dataset.noAgentsText || 'No agents are available to chat.';
this.livePersonSurveyCloseMessage = this.el.dataset.livePersonSurveyCloseMessage || 'Thank you for your time';
this.livePersonReadText = this.el.dataset.readText || 'Read';
this.returnToAiChatText = this.el.dataset.returnToAiChatText || 'End live chat';
this.livePersonDisconnectedReconnectingText = this.el.dataset.livePersonDisconnectedReconnectingText || 'You have been disconnected from live agent. Attempting to reconnect...';
this.livePersonReconnectedText = this.el.dataset.livePersonReconnectedText || 'Reconnected to live agent. You can continue your conversation.';
this.livePersonSendingMessageText = this.el.dataset.livePersonSendingMessageText || 'Sending';
this.livePersonSendFailedText = this.el.dataset.livePersonSendFailedText || 'Send failed.';
this.retryButtonText = this.el.dataset.retryButtonText || 'Retry';
this.transcriptIntroText = this.el.dataset.livePersonTranscriptIntroText || '**FULL CONVERSATION TRANSCRIPT:**';
this.transcriptContinuedText = this.el.dataset.livePersonTranscriptContinuedText || '**FULL CONVERSATION TRANSCRIPT (CONTINUED):**';
this.transcriptFromUserText = this.el.dataset.livePersonTranscriptFromUserText || '**User:**';
this.transcriptFromAssistantText = this.el.dataset.livePersonTranscriptFromAssistantText || '**Assistant:**';
this.aiDisclaimerText = this.el.dataset.aiDisclaimer || 'AI-generated content may be incorrect';
this.closeButtonAriaLabel = this.headerControls ? this.headerControls.getAttribute('aria-label') : 'Close Dialog';
this.chatDrawerAriaLabel = this.el.getAttribute('aria-label') || 'Chatbot Window';
this.livePersonMessageCharLimit = 8000; // LivePerson message character limit
this.store = null;
this.webChatInstance = null;
this.webChatSendBox = null;
this.webChatForm = null;
this.webChatTextarea = null;
this.webChatSendButton = null;
this.webChatMaximumCharacters = 250; // Maximum number of chars user can type in web chat
this.uhfHeaderElem = document.querySelector(Selector$A.UHF_HEADER);
this.uhfNavMenuExpandElem = document.querySelector(Selector$A.UHF_MENU_NAV_EXPAND_ELEM);
this.uhfHeaderIntersectionObserver = null;
this.uhfHeaderIsVisible = true; // Flag to check if the UHF header is visible
this.hideChatBelowHeight = 349.9; // Hide chat below 350px height
this.mediaQueryListChatHidden = window.matchMedia("(max-height: " + this.hideChatBelowHeight + "px)");
this.modalDialogBelowWidth = 599.9; // Chat drawer becomes modal dialog below this width
this.mediaQueryListModalDialog = window.matchMedia("(max-width: " + this.modalDialogBelowWidth + "px)");
this.uhfFooterElem = document.querySelector(Selector$A.UHF_FOOTER);
this.uhfFooterOriginalPadding = this.uhfFooterElem ? window.getComputedStyle(this.uhfFooterElem, null).getPropertyValue('padding-bottom') : '';
this.debouncedResizeDelay = 250;
this.stickyNavElem = document.querySelector(Selector$A.STICKY_NAV);
this.stickyNavMutationObserver = null;
this.botGeneratingResponseText = this.el.dataset.botGeneratingResponseText || 'Generating a response';
this.botFeedbackPositiveAriaLabel = this.el.dataset.botFeedbackPositiveAriaLabel || 'Thumbs up';
this.botFeedbackNegativeAriaLabel = this.el.dataset.botFeedbackNegativeAriaLabel || 'Thumbs down';
this.chatActionTypeLinks = document.querySelectorAll(Selector$A.CHAT_ACTION_TYPE_LINK);
this.chatActionTypeLinkText = this.el.dataset.chatActionTypeLinkText || 'Chat with sales';
// LivePerson
this.dataConnectorBaseEndpoint = getDataConnectorBaseEndpoint('https:');
this.accountId = null;
this.skillId = null;
this.isSendTranscript = false;
this.corsBypassQueryStringObj = null; // Only applies to local and preview environments
this.lpJWT = null;
this.lpSession = null;
this.lpMessages = {};
this.startLPChatActivityIds = (_this$getAIChatDrawer = (_this$getAIChatDrawer2 = this.getAIChatDrawerCookieObject()) == null ? void 0 : _this$getAIChatDrawer2[StorageKeys.startLPChatActivityIds]) != null ? _this$getAIChatDrawer : [];
this.lpOpenConvs = (_this$getAIChatDrawer3 = (_this$getAIChatDrawer4 = this.getAIChatDrawerCookieObject()) == null ? void 0 : _this$getAIChatDrawer4[StorageKeys.lpOpenConvs]) != null ? _this$getAIChatDrawer3 : {};
this.lpSubscriptionId = null;
this.lpSubscribedToMessagingEvents = false; // Flag to check if subscribed to messaging events
this.curLpChangeSequence = 0; // Keep track of the current change sequence
this.lpWebsocket = null;
this.isLivePersonChatActive = false;
this.isLivePersonAgentAssigned = false;
this.isSurveyTextActionPublished = false;
this.isPostSurveyEnabled = false;
this.isLivePersonChatFeatureEnabled = this.el.dataset.isLPEnabled || false;
this.lpSurveyForcedClosed = false;
this.debouncedChatStateToComposing = debounce(livePersonUserComposingDelay, this.chatStateToComposing.bind(this), {
atBegin: true
});
this.debouncedChatStateToPause = debounce(livePersonUserPauseDelay, this.chatStateToPause.bind(this));
this.handleLpUserInput = this.handleLpUserInput.bind(this);
this.debouncedOnChatActionTypeLinkClick = debounce(debouncedChatActionTypeLinkClickDelay, this.onChatActionTypeLinkClick.bind(this), {
atBegin: true
});
_classPrivateFieldLooseBase(this, _addEventHandlers)[_addEventHandlers]();
_classPrivateFieldLooseBase(this, _initUhfIntersectionObserver)[_initUhfIntersectionObserver]();
_classPrivateFieldLooseBase(this, _initStickyNavMutationObserver)[_initStickyNavMutationObserver]();
_classPrivateFieldLooseBase(this, _positionAiChatButton)[_positionAiChatButton]();
_classPrivateFieldLooseBase(this, _positionAiChatDrawer)[_positionAiChatDrawer]();
this.onMediaQueryListChatHiddenChange(this.mediaQueryListChatHidden);
this.onMediaQueryListModalDialogChange(this.mediaQueryListModalDialog);
_classPrivateFieldLooseBase(this, _handlePageOpenState)[_handlePageOpenState]();
// These text areas will have their text content adjusted during Live Person connection/disconnection events. During these events, we already
// push screen-reader accessible messages, so we want to turn off the aria-live regions for these two elements to avoid "double speaking".
this.aiChatButton.querySelector(Selector$A.AI_CHAT_BUTTON_TEXT + " span").setAttribute('aria-live', 'off');
this.el.querySelector(Selector$A.BLOCK_FEATURE_TITLE).setAttribute('aria-live', 'off');
aiChatDrawers.push(this);
_classPrivateFieldLooseBase(this, _setDefaultValuesInMarkup)[_setDefaultValuesInMarkup]();
}
/**
* Universal Media Player Template
*/
var _proto = AIChatDrawer.prototype;
/**
* Pushes click handlers to events array for each chat action type link. This is used to add event handlers
* to the chat action type links in the markup. Returns the added events list.
*
* @returns {Array.<{
* el: Element | Document | Window,
* handler: Function,
* type: String,
* options?: Object
* }>} The events added to events array of the component.
*/
_proto.addChatActionTypeLinkEvents = function addChatActionTypeLinkEvents() {
var _this2 = this;
var eventsToAdd = [];
this.chatActionTypeLinks.forEach(function (element) {
var _this2$events;
// Clone the element so legacy event handlers are not bound to it
var newNode = element.cloneNode(true);
// remove data-oc-chat which is used by legacy chat script
newNode.removeAttribute(Attributes$5.CHAT_ACTION_TYPE_LINK);
// add data-oc-ai-chat to identify this as an AI chat button
newNode.setAttribute(Attributes$5.AI_CHAT_ACTION_TYPE_LINK, '');
newNode.setAttribute('aria-controls', 'ai-chat-drawer');
// legacy chat script sets style display none until chat is initialized
if (newNode.style.display === 'none') {
newNode.style.removeProperty('display');
}
eventsToAdd.push({
el: newNode,
handler: _this2.debouncedOnChatActionTypeLinkClick,
type: EventName$A.CLICK
});
if (newNode.tagName !== 'BUTTON') {
eventsToAdd.push({
el: newNode,
handler: _this2.debouncedOnChatActionTypeLinkClick,
type: EventName$A.KEYDOWN
});
}
(_this2$events = _this2.events).push.apply(_this2$events, eventsToAdd);
element.replaceWith(newNode);
});
return eventsToAdd;
}
/** Check if the Direct Line token is valid.
* @returns {boolean} Whether the Direct Line token is valid.
*/;
_proto.hasValidToken = function hasValidToken() {
var cookieObj = this.getAIChatDrawerCookieObject();
if (typeof cookieObj !== 'object' || cookieObj === null) {
return false;
}
var token = cookieObj[StorageKeys.token];
var tokenCreated = cookieObj[StorageKeys.tokenCreated];
var currentTime = Date.now() / 1000;
if (isNaN(tokenCreated)) {
return false;
}
// I used OR logic here to check for bad cases, but it could be easily flipped to AND logic.
return !(!token || token === 'undefined' || currentTime - tokenCreated > this.refreshAfter);
}
/*
* Deletes the Chat Drawer Cookie and calls the generate Direct Line token to
* Re-establish the cookie. Used when a cookie needs to be force-refreshed.
*/;
/**
* Handle click on AI Chat Button
* @param {Event} event Click or keydown event on AI Chat Button
*/
_proto.onAiChatButtonClick = function onAiChatButtonClick(event) {
// return if event type is keydown and key is not enter or space bar
if (event.type === EventName$A.KEYDOWN && Util$1.getKeyCode(event) !== Util$1.keyCodes.ENTER && Util$1.getKeyCode(event) !== Util$1.keyCodes.SPACE) {
return;
}
event.preventDefault();
event.stopPropagation();
this.chatOpenOrInit();
}
/**
* Handle keydown event on the AI Chat Drawer. If the tab key is pressed, loop focus between the first and last focusable
* elements in the drawer. Note this will not work for mobile screen readers, a different approach will be needed.
* @param {KeyboardEvent} event Keydown event on the AI Chat Drawer
* @returns {void}
*/;
_proto.onKeyDown = function onKeyDown(event) {
if (!this.el.contains(document.activeElement) || Util$1.getKeyCode(event) !== Util$1.keyCodes.TAB) {
return;
}
if ((document.activeElement === this.firstFocusableElem || document.activeElement === this.el) && event.shiftKey) {
event.preventDefault();
this.lastFocusableElem.focus();
return;
}
if (document.activeElement === this.lastFocusableElem && !event.shiftKey) {
event.preventDefault();
this.firstFocusableElem.focus();
}
}
/**
* Handles the keydown event on the document.
* If the key combination is Ctrl + F6 and the element is not hidden, it performs the necessary focus actions.
* If the active element is within the component, it focuses on the search input or the first focusable element in the main content.
* If the active element is outside the component, it restores the previously focused element.
* @param {KeyboardEvent} event The keydown event on the document
*/;
_proto.onDocumentKeyDown = function onDocumentKeyDown(event) {
if (!(event.ctrlKey && event.key === 'F6') || this.el.hidden) {
return;
}
if (this.el.contains(document.activeElement)) {
var _this$previouslyFocus;
if (this.previouslyFocusedElem === document.body || ((_this$previouslyFocus = this.previouslyFocusedElem) == null ? void 0 : _this$previouslyFocus.offsetParent) === null) {
var main = document.querySelector(Selector$A.MAIN_CONTENT);
var firstFocusableElemInMain = main == null ? void 0 : main.querySelector(Selector$A.FOCUSABLE_ELEMENTS);
firstFocusableElemInMain == null ? void 0 : firstFocusableElemInMain.focus();
} else {
this.previouslyFocusedElem.focus();
}
} else {
this.previouslyFocusedElem = document.activeElement;
this.webChatTextarea.focus();
}
}
/**
* Handles the click event on a chat action type link.
* Prevents the default action and initializes or opens the chat based on its current state.
* If the event type is 'keydown', it only proceeds if the key pressed is 'Enter' or 'Space'.
*
* @param {Event} event - The event object representing the click or keydown event.
*/;
_proto.onChatActionTypeLinkClick = function onChatActionTypeLinkClick(event) {
// return if event type is keydown and key is not enter or space bar
if (event.type === EventName$A.KEYDOWN && Util$1.getKeyCode(event) !== Util$1.keyCodes.ENTER && Util$1.getKeyCode(event) !== Util$1.keyCodes.SPACE) {
return;
}
event.preventDefault();
this.chatOpenOrInit(this.chatActionTypeLinkText);
}
/**
* Render the BotFramework Web Chat.
*/;
_proto.renderWebChat = function renderWebChat() {
window.WebChat.renderWebChat({
locale: _classPrivateFieldLooseBase(this, _getLocale)[_getLocale](),
directLine: this.directLine,
sendTypingIndicator: true,
store: this.store,
styleOptions: this.styleOptions,
overrideLocalizedStrings: {
TEXT_INPUT_PLACEHOLDER: this.textInputPlaceholder,
CONNECTIVITY_STATUS_ALT_FATAL: this.connectivityStatusAltFatalString
}
}, this.webChatContainer);
}
/**
* Display or update a toast style notification at the top of the chat drawer.
* Documentation for BotFramework-WebChat notifications:
* https://github.com/microsoft/BotFramework-WebChat/blob/main/docs/NOTIFICATION.md
*
* @param {string} messageText The text to display in the notification
* @param {string} notificationLevel The level of the notification (error, warn, info, success. Default is 'info')
* @param {string} notificationId The ID of the notification (optional)
* @param {string} altText The alternative text for the notification (optional. Use if the message contains HTML)
*
* @returns {string} The notification ID
*/;
_proto.setNotification = function setNotification(messageText, notificationLevel, notificationId, altText) {
if (notificationLevel === void 0) {
notificationLevel = NotificationLevel.INFO;
}
if (notificationId === void 0) {
notificationId = '';
}
if (altText === void 0) {
altText = '';
}
if (!this.store) {
console.error('Unable to display notification. BotFramework-WebChat store not found.');
return;
}
notificationId = notificationId || window.crypto.randomUUID();
var notificationObj = {
type: 'WEB_CHAT/SET_NOTIFICATION',
payload: {
id: notificationId,
level: notificationLevel,
message: messageText
}
};
if (altText) {
notificationObj.payload.alt = altText;
}
this.store.dispatch(notificationObj);
return notificationId;
}
/**
* Dismisses a notification by its ID.
*
* This method dispatches an action to the BotFramework-WebChat store to remove a notification.
* If the store is not available, it logs an error message.
*
* @param {string} id - The ID of the notification to dismiss.
*/;
_proto.dismissNotification = function dismissNotification(id) {
if (!this.store) {
console.error('Unable to dismiss notification. BotFramework-WebChat store not found.');
return;
}
this.store.dispatch({
type: 'WEB_CHAT/DISMISS_NOTIFICATION',
payload: {
id: id
}
});
}
/**
* Check for LivePerson agent availability
*
* @returns {Promise} Response from the fetch call
*/
/* eslint-disable no-await-in-loop */;
_proto.checkLivePersonAgentAvailability =
/*#__PURE__*/
function () {
var _checkLivePersonAgentAvailability = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(retries, delay) {
var checkAgentAvailabilityEndpoint, headers, options, attempt, response, jsonResponse;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (retries === void 0) {
retries = 3;
}
if (delay === void 0) {
delay = 1000;
}
checkAgentAvailabilityEndpoint = _classPrivateFieldLooseBase(this, _getLPEndpoint)[_getLPEndpoint](this.dataConnectorBaseEndpoint, 'liveperson/v1/check');
headers = new Headers();
headers.append('Content-Type', 'application/json');
options = {
method: 'POST',
headers: headers,
body: JSON.stringify({
metadata: {
skillId: this.skillId
}
})
};
attempt = 1;
case 7:
if (!(attempt <= retries)) {
_context.next = 34;
break;
}
_context.prev = 8;
_context.next = 11;
return fetch(checkAgentAvailabilityEndpoint, options);
case 11:
response = _context.sent;
if (response.ok) {
_context.next = 14;
break;
}
throw new Error("Error checking LivePerson agent availability. Response status: " + response.status);
case 14:
_context.next = 16;
return response.json();
case 16:
jsonResponse = _context.sent;
return _context.abrupt("return", jsonResponse.availability);
case 20:
_context.prev = 20;
_context.t0 = _context["catch"](8);
console.error("Attempt " + attempt + " failed: " + _context.t0.message);
if (!(attempt < retries)) {
_context.next = 28;
break;
}
_context.next = 26;
return new Promise(function (resolve) {
return setTimeout(resolve, delay);
});
case 26:
_context.next = 31;
break;
case 28:
this.setNotification(this.livePersonGenericErrorText, NotificationLevel.ERROR);
console.error('All retry attempts failed.');
throw _context.t0;
case 31:
attempt++;
_context.next = 7;
break;
case 34:
case "end":
return _context.stop();
}
}
}, _callee, this, [[8, 20]]);
}));
function checkLivePersonAgentAvailability(_x, _x2) {
return _checkLivePersonAgentAvailability.apply(this, arguments);
}
return checkLivePersonAgentAvailability;
}()
/* eslint-enable no-await-in-loop */
/**
* Get the lead ID based on the current page's origin and pathname.
* @returns {string} The generated lead ID.
*/
;
_proto.getLeadId = function getLeadId() {
return window.location.origin + window.location.pathname;
}
/**
* Creates or updates a live-person engagement session for current client
* @returns live-person engagement session create response
*/;
_proto.createLivePersonSession =
/*#__PURE__*/
function () {
var _createLivePersonSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _window$oc$geo$countr, _window$oc, _window$oc$geo, _document$querySelect, _window$oc$lp$topic, _window$oc2, _window$oc2$lp;
var country, topic, leadId, ipAddress, cookieObject, localSession, isCreatingSession, requestData, callOptions, isSessionUpdated, result, _result, _this$updateAIChatDra;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
country = (_window$oc$geo$countr = (_window$oc = window.oc) == null ? void 0 : (_window$oc$geo = _window$oc.geo) == null ? void 0 : _window$oc$geo.country) != null ? _window$oc$geo$countr : (_document$querySelect = document.querySelector('[data-geo-country]')) == null ? void 0 : _document$querySelect.getAttribute('data-geo-country');
topic = (_window$oc$lp$topic = (_window$oc2 = window.oc) == null ? void 0 : (_window$oc2$lp = _window$oc2.lp) == null ? void 0 : _window$oc2$lp.topic) != null ? _window$oc$lp$topic : '';
leadId = this.getLeadId();
ipAddress = ''; // TODO - Get ip-address
cookieObject = this.getAIChatDrawerCookieObject();
localSession = cookieObject[StorageKeys.lpSession];
isCreatingSession = false;
requestData = {
account: this.accountId,
country: country,
topic: topic,
leadId: leadId,
ipAddress: ipAddress,
pageId: null,
visitorId: null,
sessionId: null
}; // Check if session already exists and matches with current
if (!(localSession && localSession.pageId && localSession.visitorId && localSession.sessionId)) {
_context2.next = 16;
break;
}
if (!(localSession.topic === topic && localSession.leadId === leadId && localSession.country === country)) {
_context2.next = 11;
break;
}
return _context2.abrupt("return", localSession);
case 11:
requestData.pageId = localSession.pageId;
requestData.visitorId = localSession.visitorId;
requestData.sessionId = localSession.sessionId;
_context2.next = 17;
break;
case 16:
isCreatingSession = true;
case 17:
callOptions = {
// Arguments must be in order of the calling function
args: [requestData]
};
_context2.prev = 18;
isSessionUpdated = false;
if (isCreatingSession) {
_context2.next = 25;
break;
}
_context2.next = 23;
return LPUtils.exponentialBackoff(LPUtils.engagement.updateSession, function (response) {
if (response > 499) {
// Retry in case of server-side issue from live-person
return true;
}
return false;
}, callOptions);
case 23:
result = _context2.sent;
isSessionUpdated = result === 200;
case 25:
if (isSessionUpdated) {
_context2.next = 33;
break;
}
// Clear out any existing session data
requestData.pageId = null;
requestData.visitorId = null;
requestData.sessionId = null;
_context2.next = 31;
return LPUtils.exponentialBackoff(LPUtils.engagement.createSession, function (response, error, options) {
if (!response && !error) {
// Set retry flag to true
return true;
}
// Check if current response contains the session id and visitor id
if (response.sessionId && response.visitorId) {
// Set retry flag to false as we have received the success response
return false; // this will return the create session results back via `exponentialBackoff`
}
var errorMessage = (error == null ? void 0 : error.message) || (response == null ? void 0 : response.message);
if (errorMessage) {
// Extract the visitor id and retry
var _errorMessage$split = errorMessage.split('vid: '),
vid = _errorMessage$split[1];
if (vid) {
// Update the args - need to add the visitor id if it is provided when retrying a 5xx response
requestData.visitorId = vid;
options.args = [requestData];
}
console.warn('[LP] received error while trying to create session:', error || response, vid);
}
// Set retry flag to true
return true;
}, callOptions);
case 31:
_result = _context2.sent;
if (_result.visitorId && _result.sessionId) {
requestData.pageId = _result.pageId;
requestData.visitorId = _result.visitorId;
requestData.sessionId = _result.sessionId;
// Update cookie with the LivePerson session
this.updateAIChatDrawerCookie((_this$updateAIChatDra = {}, _this$updateAIChatDra[StorageKeys.lpSession] = requestData, _this$updateAIChatDra));
}
case 33:
_context2.next = 38;
break;
case 35:
_context2.prev = 35;
_context2.t0 = _context2["catch"](18);
console.error('[LP] failed to create lp-engagement session:', _context2.t0);
case 38:
return _context2.abrupt("return", requestData);
case 39:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[18, 35]]);
}));
function createLivePersonSession() {
return _createLivePersonSession.apply(this, arguments);
}
return createLivePersonSession;
}()
/**
* Get the LivePerson JWT
*
* @param {number} retryCount The number of retries
*
* @returns {Promise} The LivePerson JWT
*/
;
_proto.getLivePersonJWT =
/*#__PURE__*/
function () {
var _getLivePersonJWT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(retryCount) {
var _this3 = this;
var timeoutPromise;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (retryCount === void 0) {
retryCount = 0;
}
timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.GET_JWT_TIMEOUT, 'Getting JWT for LivePerson timed out'));
}, ms);
});
};
return _context3.abrupt("return", Promise.race([LPUtils.getJWT(this.accountId, this.getAIChatDrawerCookieObject(), StorageKeys.lpJWT), timeoutPromise(livePersonResponseTimeout)])["catch"](function (error) {
_this3.handleLivePersonError(error, function (newRetryCount) {
return _this3.getLivePersonJWT(newRetryCount);
}, retryCount);
}));
case 3:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function getLivePersonJWT(_x3) {
return _getLivePersonJWT.apply(this, arguments);
}
return getLivePersonJWT;
}()
/**
* Get the LivePerson UMS domain
*
* @returns {Promise} The LivePerson UMS domain
*/
;
_proto.getLivePersonUmsDomain =
/*#__PURE__*/
function () {
var _getLivePersonUmsDomain = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
return _context4.abrupt("return", LPUtils.getDomain(this.accountId, 'asyncMessagingEnt'));
case 4:
_context4.prev = 4;
_context4.t0 = _context4["catch"](0);
console.error('Error fetching UMS domain:', _context4.t0);
// Handle the error appropriately, e.g., show an error message to the user or retry the operation
return _context4.abrupt("return", null);
case 8:
case "end":
return _context4.stop();
}
}
}, _callee4, this, [[0, 4]]);
}));
function getLivePersonUmsDomain() {
return _getLivePersonUmsDomain.apply(this, arguments);
}
return getLivePersonUmsDomain;
}()
/**
* Initialize the LivePerson websocket
*
* @param {string} umsDomain The LivePerson UMS domain
* @param {number} retryCount The number of retries
*
* @returns {Promise} The LivePerson websocket instance
*/
;
_proto.initLivePersonWebsocket =
/*#__PURE__*/
function () {
var _initLivePersonWebsocket = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(umsDomain, retryCount) {
var _this4 = this;
var timeoutPromise;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (retryCount === void 0) {
retryCount = 0;
}
timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.INIT_WS_TIMEOUT, 'Initializing LivePerson websocket timed out'));
}, ms);
});
};
return _context5.abrupt("return", Promise.race([LPWs.connect("wss://" + umsDomain + "/ws_api/account/" + this.accountId + "/messaging/consumer?v=3"), timeoutPromise(livePersonResponseTimeout)])["catch"](function (error) {
_this4.handleLivePersonError(error, function (newRetryCount) {
return _this4.initLivePersonWebsocket(umsDomain, newRetryCount);
}, retryCount);
}));
case 3:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function initLivePersonWebsocket(_x4, _x5) {
return _initLivePersonWebsocket.apply(this, arguments);
}
return initLivePersonWebsocket;
}()
/**
* Get LivePerson Id from JWT
*
* @returns {string | null} The LivePerson Id
*/
;
/**
* Update the LivePerson agent state in the UI
*
* @param {string} state The agent state
*/
_proto.updateAgentState = function updateAgentState(state) {
// Designs do not have all states here. We may remove states if not needed.
switch (state) {
case livePersonChatStateTypes.ACTIVE:
{
// is in the chat
break;
}
case livePersonChatStateTypes.INACTIVE:
{
// navigated away but application is still open
break;
}
case livePersonChatStateTypes.GONE:
{
// closed the chat application
break;
}
case livePersonChatStateTypes.COMPOSING:
{
// is typing
// Dispatch bot typing activity to the store so it renders in the WebChat
this.store.dispatch({
type: 'DIRECT_LINE/INCOMING_ACTIVITY',
payload: {
activity: {
type: 'typing',
from: {
role: 'bot'
},
timestamp: new Date().toISOString()
}
}
});
break;
}
}
}
/**
* Subscribe to LivePerson messaging events
*
* @param {string} dialogId The dialogId to subscribe to
* @param {string} conversationId The conversationId to subscribe to. For main dialog, conversationId and dialogId
* are the same. For survey dialog, conversationId and dialogId are different
* @param {number} fromSeq The sequence number to start from
* @param {number} retryCount The number of retries
*/;
_proto.subscribeToLivePersonMessagingEvents = function subscribeToLivePersonMessagingEvents(dialogId, conversationId, fromSeq, retryCount) {
var _this5 = this;
if (fromSeq === void 0) {
fromSeq = 0;
}
if (retryCount === void 0) {
retryCount = 0;
}
this.lpWebsocket.subscribeMessagingEvents({
fromSeq: fromSeq,
dialogId: dialogId,
conversationId: conversationId
}).then(function (response) {
return _this5.handleLivePersonResponse(response);
})["catch"](function (error) {
return _this5.handleLivePersonError(error, function (newRetryCount) {
return _this5.subscribeToLivePersonMessagingEvents(dialogId, conversationId, fromSeq, newRetryCount);
}, retryCount);
});
}
/**
* Handle response from LivePerson websocket. Throw an error if the response code is an error code.
*
* @param {Response} response The response from the LivePerson API
*
* @returns {Response} The response from the LivePerson API
*/;
_proto.handleLivePersonResponse = function handleLivePersonResponse(response) {
if (response.code >= 400 && response.code < 600) {
throw Object.assign(new Error(response.body), {
code: response.code
});
} else {
return response;
}
}
/**
* Handles errors from LivePerson API calls with retry logic.
* LivePerson Retry Policy Recommendations: https://developers.liveperson.com/retry-policy-recommendations.html
*
* @param {Object} error - The error object returned from the LivePerson API.
* @param {Function} retryCallback - The callback function to retry the API call.
* @param {number} [retryCount=0] - The current retry attempt count.
* @param {number} [maxRetries=3] - The maximum number of retry attempts.
*/;
_proto.handleLivePersonError = function handleLivePersonError(error, retryCallback, retryCount, maxRetries) {
var _this6 = this;
if (retryCount === void 0) {
retryCount = 0;
}
if (maxRetries === void 0) {
maxRetries = 3;
}
// Max number of retries hit
if (retryCount >= maxRetries) {
console.error("Max retries reached for error type " + error.type + ":", error);
if (error.type === LPErrorTypes.SEND_MESSAGE_TIMEOUT) {
this.handleLivePersonSendMessageTimeout(error.data.messageId);
}
if (error.type === LPErrorTypes.USER_CLOSE_CONVERSATION_TIMEOUT) {
// User atttempted to close conversation, but the request to LP timed out.
// Return user to AI Chat so they are not stuck
this.returnUIToAIChatBot();
}
return;
}
if (!error.code || error.code >= 400 && error.code < 500) {
if (error.code === 429 && typeof retryCallback === 'function') {
// Request is being throttled due to rate-limiting
// Too many requests, retry after at least 1 second (or 5 seconds for login requests), avoid bursts of requests
var retryInterval = 1000;
setTimeout(function () {
retryCallback(retryCount + 1).then(function (response) {
return _this6.handleLivePersonResponse(response);
})["catch"](function (error) {
return _this6.handleLivePersonError(error, retryCallback, retryCount + 1, maxRetries);
});
}, retryInterval);
} else {
// Handle other types of errors
switch (error.type) {
case LPErrorTypes.SEND_MESSAGE_TIMEOUT:
{
// Retry sending the message
retryCallback(error.data.messageId, retryCount + 1);
break;
}
case LPErrorTypes.USER_CLOSE_CONVERSATION_TIMEOUT:
{
// Retry closing the conversation
retryCallback(retryCount + 1);
break;
}
case LPErrorTypes.WEBSOCKET_NOT_OPEN:
{
console.error('LivePerson websocket not open:', error);
// Display a generic error message to the user
this.setNotification(this.livePersonGenericErrorText, NotificationLevel.ERROR);
break;
}
case LPErrorTypes.ACCEPT_STATUS_TIMEOUT:
{
// Retry updating the message accept status
retryCallback(error.data.sequence, error.data.status, error.data.dialogId, retryCount + 1);
break;
}
default:
{
console.error('Client-side error:', error);
// Display a generic error message to the user
this.setNotification(this.livePersonGenericErrorText, NotificationLevel.ERROR);
break;
}
}
}
} else if (error.code >= 500 && error.code < 600) {
// Server error, retry 3 times with 5, 10, 15 second pause between retries
var retryDelays = [5000, 10000, 15000];
var delay = retryDelays[Math.min(retryCount, retryDelays.length - 1)];
setTimeout(function () {
retryCallback(retryCount + 1).then(function (response) {
return _this6.handleLivePersonResponse(response);
})["catch"](function (error) {
return _this6.handleLivePersonError(error, retryCallback, retryCount + 1, maxRetries);
});
}, delay);
}
}
/**
* Update the status of a LivePerson message in the chat. For example, "Read" text will appear after
* timestamp when the message is read by LivePerson.
*
* @param {number} sequence The sequence number of the message
* @param {string} status The status of the message
* @param {string} dialogId The dialogId of the message
*/;
_proto.updateLivePersonMessageStatus = function updateLivePersonMessageStatus(sequence, status, dialogId) {
// Get message element
var messageElement = this.lpMessages[dialogId + "-" + sequence];
// Return if message element does not exist
if (!messageElement) {
return;
}
// Update the accept status
messageElement.dataset.acceptStatus = status;
switch (status) {
case 'ACCEPT':
{
break;
}
case 'READ':
{
this.markMessageAsRead(messageElement);
break;
}
}
}
/**
* Handle LivePerson conversation notifications
*
* @param {Object} notificationBody The notification body
*/;
_proto.handleLivePersonConversationNotification = function handleLivePersonConversationNotification(notificationBody) {
var _this7 = this;
notificationBody.changes.forEach(function (change) {
var _this7$updateAIChatDr5;
// Check if there are no active dialogs open
var isConversationOpen = change.result.conversationDetails.state !== LPUtils.conversationStateTypes.CLOSE || change.result.conversationDetails.stage !== LPUtils.conversationStateTypes.CLOSE;
// Get active dialog
var activeDialog = change.result.conversationDetails.dialogs.find(function (d) {
return d.state === LPUtils.conversationStateTypes.OPEN;
});
// Check if post survey is enabled
_this7.isPostSurveyEnabled = change.result.conversationDetails.state === LPUtils.conversationStateTypes.CLOSE && change.result.conversationDetails.stage === LPUtils.conversationStateTypes.OPEN;
// Conversation is closed or there is no active dialog
if (!isConversationOpen || !activeDialog) {
if (Object.hasOwn(_this7.lpOpenConvs, change.result.convId)) {
var _this7$lpWebsocket;
// Only show the message if the survey was completed fully by the user
if (!_this7.lpSurveyForcedClosed) {
var _change$result, _change$result$conver;
_this7.webChatSendMessage(_this7.livePersonSurveyCloseMessage, new Date((_change$result = change.result) == null ? void 0 : (_change$result$conver = _change$result.conversationDetails) == null ? void 0 : _change$result$conver.endTs).toISOString(), 'lp-system', null, null, null);
}
// Cancel the get clock interval
(_this7$lpWebsocket = _this7.lpWebsocket) == null ? void 0 : _this7$lpWebsocket.getClockRequest.cancel();
// Cancel debounced chat states
_this7.debouncedChatStateToComposing.cancel({
upcomingOnly: true
});
_this7.debouncedChatStateToPause.cancel({
upcomingOnly: true
});
// Reset the agent state
_this7.updateAgentState(livePersonChatStateTypes.DEFAULT);
// Unsubscribe from conversation metadata for this subscriptionId
_this7.livePersonUnsubscribeExConversations(notificationBody.subscriptionId)["finally"](function () {
var _this7$updateAIChatDr;
// Reset subscribed to messaging events flag
_this7.lpSubscribedToMessagingEvents = false;
// Reset the current change sequence
_this7.curLpChangeSequence = 0;
// Return the UI to AI chat bot
_this7.returnUIToAIChatBot();
// Delete the conversation from open conversations metadata object
delete _this7.lpOpenConvs[change.result.convId];
// Update the cookie
_this7.updateAIChatDrawerCookie((_this7$updateAIChatDr = {}, _this7$updateAIChatDr[StorageKeys.lpOpenConvs] = _this7.lpOpenConvs, _this7$updateAIChatDr));
});
}
return;
}
// Check if this is a notification for a new conversation
if (!_this7.lpOpenConvs[change.result.convId]) {
var _this7$updateAIChatDr2;
// Create and store conversation metadata
_this7.lpOpenConvs[change.result.convId] = {
result: {
convId: change.result.convId,
dialogs: change.result.conversationDetails.dialogs.map(function (dialog) {
return {
dialogId: dialog.dialogId,
dialogType: dialog.dialogType
};
})
},
activeDialogId: activeDialog.dialogId,
chatState: livePersonChatStateTypes.DEFAULT,
closeMsgSent: false
};
// Update cookie
_this7.updateAIChatDrawerCookie((_this7$updateAIChatDr2 = {}, _this7$updateAIChatDr2[StorageKeys.lpOpenConvs] = _this7.lpOpenConvs, _this7$updateAIChatDr2));
// Send event to PVA to record the new Live Person conversation ID to cosmos DB
var eventValue = {
skillId: _this7.skillId,
LPConversationID: change.result.convId
};
_this7.webChatSendEvent(EventName$A.LIVEPERSON_SAVE_IDS, eventValue);
// Send transcript to LivePerson if user has elected to do so
if (_this7.isSendTranscript) {
_this7.sendTranscriptToLivePerson();
}
// Subscribe to messaging events with active dialog id
_this7.subscribeToLivePersonMessagingEvents(activeDialog.dialogId, change.result.convId);
_this7.lpSubscribedToMessagingEvents = true;
}
// Check if there are new dialogs added to this conversation
if (change.result.conversationDetails.dialogs.length !== _this7.lpOpenConvs[change.result.convId].result.dialogs.length) {
var _this7$updateAIChatDr4;
// if the new dialog is a survey dialog, post the conversation closed message
if (change.result.conversationDetails.dialogs.some(function (dialog) {
return dialog.dialogType === 'POST_SURVEY';
}) &&
// Check if the close message has already been sent in this conversation
_this7.lpOpenConvs[change.result.convId] && !_this7.lpOpenConvs[change.result.convId].closeMsgSent) {
var _change$result2, _change$result2$conve, _this7$updateAIChatDr3;
var closeMessage = '';
// Show a message based on who closed the chat
if (change.result.conversationDetails && change.result.conversationDetails.closeReason === 'CONSUMER') {
closeMessage = _this7.livePersonUserClosedConversationText;
} else if (change.result.conversationDetails && change.result.conversationDetails.closeReason === 'AGENT') {
closeMessage = _this7.livePersonAgentClosedConversationText;
} else {
closeMessage = _this7.livePersonSystemClosedConversationText;
}
var timestamp = new Date().toISOString();
if (change.serverTimestamp) {
// If serverTimestamp is available, use it
timestamp = new Date(change.serverTimestamp).toISOString();
} else if ((_change$result2 = change.result) != null && (_change$result2$conve = _change$result2.conversationDetails) != null && _change$result2$conve.dialogs) {
// If serverTimestamp is not available, use the end timestamp of the main dialog
var mainDialog = change.result.conversationDetails.dialogs.find(function (dialog) {
return dialog.dialogType === 'MAIN' && dialog.state === 'CLOSE';
});
if (mainDialog && mainDialog.endTs) {
timestamp = new Date(mainDialog.endTs).toISOString();
}
}
_this7.webChatSendMessage(closeMessage, timestamp, 'lp-system', null, null, null);
// Update the lpOpenConvs object to track the close message
_this7.lpOpenConvs[change.result.convId].closeMsgSent = true;
// Update the lpOpenConvs in the cookie
_this7.updateAIChatDrawerCookie((_this7$updateAIChatDr3 = {}, _this7$updateAIChatDr3[StorageKeys.lpOpenConvs] = _this7.lpOpenConvs, _this7$updateAIChatDr3));
// Disable the chat message box
_this7.toggleWebChatUserTextBoxDisabled(true);
}
// Track the active dialog
// Update the dialog id in case the dialogs have switched
_this7.lpOpenConvs[change.result.convId].activeDialogId = activeDialog.dialogId;
// Update the cookie
_this7.updateAIChatDrawerCookie((_this7$updateAIChatDr4 = {}, _this7$updateAIChatDr4[StorageKeys.lpOpenConvs] = _this7.lpOpenConvs, _this7$updateAIChatDr4));
// Subscribe to messaging events of the new active dialog id
_this7.subscribeToLivePersonMessagingEvents(activeDialog.dialogId, change.result.convId);
_this7.lpSubscribedToMessagingEvents = true;
}
// Check if we need to subscribe to messaging events for an existing conversation
if (!_this7.lpSubscribedToMessagingEvents) {
// Subscribe to messaging events with active dialog id, from the current change sequence
_this7.subscribeToLivePersonMessagingEvents(activeDialog.dialogId, change.result.convId, _this7.curLpChangeSequence);
_this7.lpSubscribedToMessagingEvents = true;
}
// Update the current conversation result details in open conversations metadata object
_this7.lpOpenConvs[change.result.convId].result = {
convId: change.result.convId,
dialogs: change.result.conversationDetails.dialogs.map(function (dialog) {
return {
dialogId: dialog.dialogId,
dialogType: dialog.dialogType
};
})
};
// Update the cookie
_this7.updateAIChatDrawerCookie((_this7$updateAIChatDr5 = {}, _this7$updateAIChatDr5[StorageKeys.lpOpenConvs] = _this7.lpOpenConvs, _this7$updateAIChatDr5));
if (change.type === 'UPSERT') {
if (_this7.isPostSurveyEnabled) {
_this7.toggleLivePersonDisclaimer(true, _this7.surveyBotDisclaimerText);
return;
}
// Check for agent assignment
var hasAgentAssigned = change.result.conversationDetails.participants.some(function (p) {
return p.role === 'ASSIGNED_AGENT';
});
if (hasAgentAssigned) {
if (!_this7.isLivePersonAgentAssigned) {
// Change the disclaimer text to the Speaking With LivePerson disclaimer text
_this7.toggleLivePersonDisclaimer(true, _this7.livePersonDisclaimerText);
// Re-enable the chat message box, but not any other action-set buttons
_this7.toggleWebChatUserTextBoxDisabled(false);
// Keep track of agent assigned state
_this7.isLivePersonAgentAssigned = true;
}
_this7.updateAgentState(livePersonChatStateTypes.ACTIVE);
} else {
_this7.updateAgentState(livePersonChatStateTypes.INACTIVE);
}
}
});
}
/**
* Publish a message to LivePerson websocket
*
* @param {string} messageText The message text
* @param {string} messageId The message ID
* @returns {Promise} A promise that resolves when the message is published
*/;
_proto.publishToLivePersonWebsocket = function publishToLivePersonWebsocket(messageText, messageId) {
if (messageId === void 0) {
messageId = null;
}
return this.lpWebsocket.publishEvent({
dialogId: this.lpOpenConvs[Object.keys(this.lpOpenConvs)[0]].activeDialogId,
conversationId: Object.keys(this.lpOpenConvs)[0],
event: {
type: 'ContentEvent',
contentType: 'text/plain',
message: messageText
},
messageId: messageId || Math.floor(Math.random() * 1e9)
});
}
/**
* Send accept status to LivePerson websocket
*
* @param {string} status The status to send
* @param {number} sequence The sequence number
* @param {number} retryCount The number of retries
*/;
_proto.acceptStatusToLivePersonWebsocket = function acceptStatusToLivePersonWebsocket(status, sequence, retryCount) {
var _this8 = this;
if (retryCount === void 0) {
retryCount = 0;
}
var timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.ACCEPT_STATUS_TIMEOUT, 'Accept status to LivePerson timed out', {
status: status,
sequence: sequence
}));
}, ms);
});
};
Promise.race([this.lpWebsocket.publishEvent({
dialogId: this.lpOpenConvs[Object.keys(this.lpOpenConvs)[0]].activeDialogId,
conversationId: Object.keys(this.lpOpenConvs)[0],
event: {
type: 'AcceptStatusEvent',
status: status,
sequenceList: [sequence]
}
}), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this8.handleLivePersonResponse(response);
})["catch"](function (error) {
_this8.handleLivePersonError(error, function (newRetryCount) {
return _this8.acceptStatusToLivePersonWebsocket(status, sequence, newRetryCount);
}, retryCount);
});
}
/**
* On close LivePerson websocket
*
* @param {Event} event The close event
*/;
_proto.onCloseLivePersonWebsocket =
/*#__PURE__*/
function () {
var _onCloseLivePersonWebsocket = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(event) {
var _this9 = this;
var notificationId, pollingFunction, retryCondition;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
if (this.isLivePersonChatActive) {
_context8.next = 4;
break;
}
console.warn('LivePerson websocket closed. event:', event);
// Return the UI to the AI Chat Bot
this.returnUIToAIChatBot();
return _context8.abrupt("return");
case 4:
if (!(event.code === 4401 || event.code === 4407)) {
_context8.next = 12;
break;
}
console.warn('LivePerson websocket closed - API token expired. event:', event);
// LivePerson API token expired
// From LivePerson documentation - The client should return to the initation step, issue a fresh token, and reestablish the connection.
// Display a message to the user that the connection to LivePerson was closed
this.setNotification(this.livePersonSystemClosedConversationText, NotificationLevel.ERROR);
this.lpWebsocket.ws = null;
this.lpWebsocket = null;
this.returnUIToAIChatBot();
_context8.next = 35;
break;
case 12:
// From LivePerson documentation - For any other closeReason, the client should wait a few seconds and then try reconnecting.
console.warn('LivePerson websocket closed - unknown reason. event:', event);
this.isLivePersonAgentAssigned = false;
// If there is an open conversation, try to reconnect after 3 seconds, then back off exponentially
if (!(Object.keys(this.lpOpenConvs).length > 0)) {
_context8.next = 31;
break;
}
notificationId = null;
pollingFunction = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
// eslint-disable-next-line no-console
console.log('Attempting to reconnect to LivePerson...');
if (!notificationId) {
// Display a warning notification to the user that they were disconnected, and trying to reconnect
notificationId = _this9.setNotification(_this9.livePersonDisconnectedReconnectingText, NotificationLevel.WARN);
}
// Exit early if LivePerson chat is no longer active
if (_this9.isLivePersonChatActive) {
_context6.next = 7;
break;
}
console.warn('LivePerson chat is no longer active. Returning UI to AI Chat Bot.');
_this9.dismissNotification(notificationId);
_this9.returnUIToAIChatBot();
return _context6.abrupt("return", {
success: false
});
case 7:
_context6.prev = 7;
_context6.next = 10;
return _this9.initLivePersonChat();
case 10:
// Reconnected successfully. Update the notification and return a success response, and close the notification
// after 10 seconds
// eslint-disable-next-line no-console
console.log('Reconnected to LivePerson successfully.');
_this9.setNotification(_this9.livePersonReconnectedText, NotificationLevel.SUCCESS, notificationId);
setTimeout(function () {
return _this9.dismissNotification(notificationId);
}, 10000);
return _context6.abrupt("return", {
success: true
});
case 16:
_context6.prev = 16;
_context6.t0 = _context6["catch"](7);
// Did not reconnect successfully. Log the error and return a failure response
console.error('Error reconnecting to LivePerson:', _context6.t0);
return _context6.abrupt("return", {
success: false
});
case 20:
case "end":
return _context6.stop();
}
}
}, _callee6, null, [[7, 16]]);
}));
return function pollingFunction() {
return _ref2.apply(this, arguments);
};
}();
retryCondition = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(response, error, _options) {
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (_this9.isLivePersonChatActive) {
_context7.next = 2;
break;
}
return _context7.abrupt("return", false);
case 2:
return _context7.abrupt("return", Boolean(error) || response && !response.success);
case 3:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
return function retryCondition(_x7, _x8, _x9) {
return _ref3.apply(this, arguments);
};
}();
_context8.prev = 18;
_context8.next = 21;
return LPUtils.exponentialBackoff(pollingFunction, retryCondition, {
maxRetries: 7,
// Maximum number of retries
delayInSeconds: 3 // Initial delay in seconds
});
case 21:
_context8.next = 29;
break;
case 23:
_context8.prev = 23;
_context8.t0 = _context8["catch"](18);
// All attempts to reconnect failed. Log the error and return the UI to the AI Chat Bot
console.error('Failed to reconnect to LivePerson:', _context8.t0);
this.lpWebsocket.ws = null;
this.lpWebsocket = null;
this.returnUIToAIChatBot();
case 29:
_context8.next = 35;
break;
case 31:
// If there are no open conversations, return the UI to the AI Chat Bot
console.warn('No open LivePerson conversations. Returning UI to AI Chat Bot.');
this.lpWebsocket.ws = null;
this.lpWebsocket = null;
this.returnUIToAIChatBot();
case 35:
case "end":
return _context8.stop();
}
}
}, _callee8, this, [[18, 23]]);
}));
function onCloseLivePersonWebsocket(_x6) {
return _onCloseLivePersonWebsocket.apply(this, arguments);
}
return onCloseLivePersonWebsocket;
}()
/**
* Sends an event activity to the bot framework store.
*
* @param {string} eventName The name of the event
* @param {Object} eventValue The value for the event (typically an object)
*/
;
_proto.webChatSendEvent = function webChatSendEvent(eventName, eventValue) {
if (!this.store) {
console.error('Error sending event to bot. WebChat store is not defined.');
return;
}
this.store.dispatch({
type: 'DIRECT_LINE/POST_ACTIVITY',
meta: {
method: 'keyboard'
},
payload: {
activity: {
channelData: {
postBack: true
},
name: eventName,
type: 'event',
value: eventValue
}
}
});
}
/**
* Dispatch an incoming-activity message to the bot framework store.
* The 'store' adds the message bubble to the transcript window, using the 'role' to style the message as 'bot', 'user', or
* our custom 'lp-system' message.
* Only used when connected to a Live Person conversation, and for post Live Person conversation's survey messages.
*
* @params {string} message The message to dispatch
* @param {string} timestamp The timestamp of the message
* @param {string} role The role of the message sender: "bot", "user", or "lp-system"
* @param {string} originatorId The originator id of the message sender
* @param {string} messageId The id of the message. If not provided, a random id is generated
* @param {number} messageSequence The sequence number of the message (only applies when rendering a message received from
* LivePerson websocket)
*/;
_proto.webChatSendMessage = function webChatSendMessage(message, timestampForWebChat, roleForWebChat, originatorId, messageId, messageSequence) {
if (messageId === void 0) {
messageId = null;
}
if (messageSequence === void 0) {
messageSequence = null;
}
var processedMessage = message.replace(/#\/?md#/g, '');
// Removes all HTML tags from the message to avoid HTML injection into the WebStore
processedMessage = new DOMParser().parseFromString(processedMessage, 'text/html').body.textContent;
// If id is not provided, generate a random id
if (!messageId) {
messageId = Math.floor(Math.random() * 1e9);
}
// Ensure messageId is a string
messageId = String(messageId);
// Dispatch message to WebChat store so it renders in the WebChat UI
this.store.dispatch({
type: 'DIRECT_LINE/INCOMING_ACTIVITY',
payload: {
activity: {
type: 'message',
text: processedMessage,
from: {
id: originatorId,
role: roleForWebChat
},
id: messageId,
sequence: messageSequence,
timestamp: timestampForWebChat
}
}
});
}
/**
* Replaces the button content with an SVG star icon.
*
* @param {HTMLElement} el - The element containing the button to replace.
*/;
/**
* Initialize the LivePerson connection
*
* @param {number} retryCount The number of retries
*/
_proto.initLivePersonConnection = function initLivePersonConnection(retryCount) {
var _this10 = this;
if (retryCount === void 0) {
retryCount = 0;
}
var timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.INIT_CONNECTION_TIMEOUT, 'Initializing LivePerson connection timed out'));
}, ms);
});
};
// Resolve the promise that completes first
Promise.race([this.lpWebsocket.initConnection({}, [{
type: '.ams.headers.ConsumerAuthentication',
jwt: this.lpJWT
}, {
type: '.ams.headers.ClientProperties',
features: ['AUTO_MESSAGES', 'RICH_CONTENT', 'QUICK_REPLIES', 'MULTI_DIALOG', 'MARKDOWN_HYPERLINKS']
}]), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this10.handleLivePersonResponse(response);
})["catch"](function (error) {
_this10.handleLivePersonError(error, function (newRetryCount) {
return _this10.initLivePersonConnection(newRetryCount);
}, retryCount);
});
}
/**
* Subscribe to LivePerson open conversations metadata
*
* @param {number} retryCount The number of retries
*
* @returns {Promise} A promise that resolves when the LivePerson websocket is subscribed to conversations metadata.
* Existing conversations that match the filter will also be sent. The promise rejects if the
* request times out.
*/;
_proto.livePersonSubscribeExConversations =
/*#__PURE__*/
function () {
var _livePersonSubscribeExConversations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(retryCount) {
var _this11 = this;
var timeoutPromise;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (retryCount === void 0) {
retryCount = 0;
}
timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.SUBSCRIBE_CONVERSATION_TIMEOUT, 'Subscribing to LivePerson conversation metadata timed out'));
}, ms);
});
};
return _context9.abrupt("return", Promise.race([this.lpWebsocket.subscribeExConversations({
stage: [LPUtils.conversationStageTypes.OPEN, LPUtils.conversationStageTypes.CLOSE],
convState: [LPUtils.conversationStateTypes.OPEN, LPUtils.conversationStateTypes.CLOSE]
}), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this11.handleLivePersonResponse(response);
})["catch"](function (error) {
_this11.handleLivePersonError(error, function (newRetryCount) {
return _this11.livePersonSubscribeExConversations(newRetryCount);
}, retryCount);
}));
case 3:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function livePersonSubscribeExConversations(_x10) {
return _livePersonSubscribeExConversations.apply(this, arguments);
}
return livePersonSubscribeExConversations;
}()
/**
* Unsubscribe from LivePerson conversation
*
* @param {string} subscriptionId The subscriptionId to unsubscribe from
* @param {number} retryCount The number of retries
*
* @returns {Promise} A promise that resolves when the LivePerson websocket is unsubscribed from the conversation
*/
;
_proto.livePersonUnsubscribeExConversations =
/*#__PURE__*/
function () {
var _livePersonUnsubscribeExConversations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(subscriptionId, retryCount) {
var _this12 = this;
var timeoutPromise;
return _regeneratorRuntime().wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (retryCount === void 0) {
retryCount = 0;
}
timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.UNSUBSCRIBE_CONVERSATION_TIMEOUT, 'Unsubscribing from LivePerson conversation metadata timed out'));
}, ms);
});
};
return _context10.abrupt("return", Promise.race([this.lpWebsocket.unsubscribeExConversations({
subscriptionId: subscriptionId
}), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this12.handleLivePersonResponse(response);
})["catch"](function (error) {
_this12.handleLivePersonError(error, function (newRetryCount) {
return _this12.livePersonUnsubscribeExConversations(subscriptionId, newRetryCount);
}, retryCount);
}));
case 3:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function livePersonUnsubscribeExConversations(_x11, _x12) {
return _livePersonUnsubscribeExConversations.apply(this, arguments);
}
return livePersonUnsubscribeExConversations;
}()
/**
* Disables all survey response buttons in the last message to prevent further interaction.
*
*/
;
_proto.disablePreviousQuestionSurveyResponseButtons = function disablePreviousQuestionSurveyResponseButtons() {
if (!this.isPostSurveyEnabled) return;
// Get all survey messages except the last one (current question awaiting a response)
var surveyMessages = Array.from(this.el.querySelectorAll("section" + Selector$A.WEB_CHAT_TRANSCRIPT_TRANSCRIPT + " " + Selector$A.ARTICLE)).slice(0, -1);
// Iterate over the survey messages and disable buttons
surveyMessages.forEach(function (message) {
var buttons = message.querySelectorAll(Selector$A.POST_SURVEY_JSON_POLLOCK_BUTTON);
buttons.forEach(function (button) {
button.disabled = true;
});
});
}
/**
* Consumer request conversation to LivePerson
*
* @param {number} retryCount The number of retries
*/;
_proto.livePersonConsumerRequestConversation = function livePersonConsumerRequestConversation(retryCount) {
var _this13 = this;
if (retryCount === void 0) {
retryCount = 0;
}
var timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.CONSUMER_REQUEST_CONVERSATION_TIMEOUT, 'Consumer request conversation to LivePerson timed out'));
}, ms);
});
};
Promise.race([this.lpWebsocket.consumerRequestConversation({
skillId: this.skillId,
conversationContext: {
visitorId: this.lpSession.visitorId,
sessionId: this.lpSession.sessionId,
lang: document.documentElement.lang,
type: 'SharkContext',
features: ['AUTO_MESSAGES', 'RICH_CONTENT', 'QUICK_REPLIES', 'MULTI_DIALOG', 'MARKDOWN_HYPERLINKS']
}
}), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this13.handleLivePersonResponse(response);
})["catch"](function (error) {
_this13.handleLivePersonError(error, function (newRetryCount) {
return _this13.livePersonConsumerRequestConversation(newRetryCount);
}, retryCount);
});
}
/**
* Updates or waits for a LivePerson message element in the DOM, setting its originator and optionally updating its timestamp.
*
* - If the message element already exists, updates its `originator` dataset property.
* - If the element has a `data-lp-message-id` attribute, calls `webChatSendMessage` to update the message with the server timestamp.
* - If the element does not exist, observes the DOM for its appearance, updates its `originator`, and resolves when found or after a timeout.
*
* @async
* @param {string} messageText - The text content of the message.
* @param {string} dialogId - The dialog ID associated with the message.
* @param {string|number} sequence - The sequence number of the message within the dialog.
* @param {string} originatorId - The ID of the message originator.
* @param {string} roleForWebChat - The role (e.g., 'user', 'agent') for the web chat.
* @param {string} timestampFromServerString - The timestamp string from the server.
* @returns {Promise} Resolves with the message element when found or updated, or `null` if not found within the timeout.
*/;
_proto.updateLivePersonMessageInDOM =
/*#__PURE__*/
function () {
var _updateLivePersonMessageInDOM = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(messageText, dialogId, sequence, originatorId, roleForWebChat, timestampFromServerString) {
var _this14 = this;
return _regeneratorRuntime().wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
return _context11.abrupt("return", new Promise(function (resolve) {
// Check if element already exists
var messageElem = _this14.webChatTranscriptElem.querySelector("[data-lp-message-dialog-id=\"" + dialogId + "\"][data-lp-message-sequence=\"" + sequence + "\"]");
if (messageElem) {
messageElem.dataset.originator = roleForWebChat;
// If message has an has a data-lp-message-id attribute, it was already rendered from a user message send. Call webChatSendMessage to
// update the message in the transcript with the timestamp from the server to ensure that the message is rendered
// in the correct order
var messageId = messageElem.dataset.lpMessageId;
if (messageId) {
_this14.webChatSendMessage(messageText, timestampFromServerString, roleForWebChat, originatorId, messageId, sequence);
resolve(messageElem);
return;
}
resolve(messageElem);
return;
}
// Set up observer to wait for the element to appear
var observer = new MutationObserver(function () {
var messageElem = _this14.webChatTranscriptElem.querySelector("[data-lp-message-dialog-id=\"" + dialogId + "\"][data-lp-message-sequence=\"" + sequence + "\"]");
if (messageElem) {
messageElem.dataset.originator = roleForWebChat;
observer.disconnect();
clearTimeout(observerTimeout);
resolve(messageElem);
}
});
// Start observing the transcript for changes
observer.observe(_this14.webChatTranscriptElem, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['data-lp-message-dialog-id', 'data-lp-message-sequence']
});
// Set a timeout to avoid hanging indefinitely
var observerTimeout = setTimeout(function () {
observer.disconnect();
console.warn("Message element for dialogId=" + dialogId + ", sequence=" + sequence + " not found within timeout period");
resolve(null);
}, 5000);
}));
case 1:
case "end":
return _context11.stop();
}
}
}, _callee11);
}));
function updateLivePersonMessageInDOM(_x13, _x14, _x15, _x16, _x17, _x18) {
return _updateLivePersonMessageInDOM.apply(this, arguments);
}
return updateLivePersonMessageInDOM;
}()
/**
* Renders quick reply options inside a LivePerson survey chat message element using JsonPollock.
*
* @param {Object} quickRepliesData - The data object representing quick replies to render.
* @param {HTMLElement} messageElem - The DOM element representing the chat message bubble.
* @param {boolean} [requiresStarReplacement=false] - Indicates if rating star replacement is required for the survey.
*
* @throws {Error} Logs an error if rendering fails or required elements are not found.
*/
;
_proto.renderQuickReplies = function renderQuickReplies(quickRepliesData, messageElem, requiresStarReplacement) {
if (requiresStarReplacement === void 0) {
requiresStarReplacement = false;
}
if (!quickRepliesData || !messageElem) return;
try {
var container = window.JsonPollock.render(quickRepliesData);
var bubbleContent = messageElem.querySelector(Selector$A.WEB_CHAT_BUBBLE_CONTENT);
if (!bubbleContent) {
console.error('webchat__bubble__content element not found in the messageElem');
return;
}
// Append the rendered container
bubbleContent.append(container);
// If post-survey is enabled
if (this.isPostSurveyEnabled) {
// Set data attribute based on requiresStarReplacement flag
bubbleContent.dataset.requiresStarReplacement = requiresStarReplacement.toString();
// Add class to distinguish survey questions
bubbleContent.classList.add(ClassName$q.LP_SURVEY_QUESTIONNAIRE);
// If requiresStarReplacement is false, add 'lp-pcs-richContent' class for styling rich content
if (!requiresStarReplacement) {
bubbleContent.classList.add(ClassName$q.LP_SURVEY_RICH_CONTENT);
}
}
} catch (error) {
console.error('Error rendering quick replies:', error);
}
}
/**
* Accepts a message via the LivePerson WebSocket if the role is not 'user'.
*
* @param {string} roleForWebChat - The role associated with the web chat message.
* @param {number} sequence - The sequence number for the message.
*/;
_proto.acceptMessageIfNotUser = function acceptMessageIfNotUser(roleForWebChat, sequence) {
if (roleForWebChat !== 'user') {
this.acceptStatusToLivePersonWebsocket(LPUtils.acceptStatusTypes.ACCEPT, sequence);
}
}
/**
* Handle LivePerson opened websocket
*
* @returns {Promise} A promise that resolves when the LivePerson websocket is opened
*/;
_proto.handleLivePersonOpenedSocket =
/*#__PURE__*/
function () {
var _handleLivePersonOpenedSocket = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
var _this15 = this,
_subscribeExConversat;
var userId, subscribeExConversationsResponse;
return _regeneratorRuntime().wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
this.lpWebsocket.registerRequests(livePersonApiRequestTypes);
userId = _classPrivateFieldLooseBase(this, _getLivePersonIdFromJWT)[_getLivePersonIdFromJWT]();
if (userId) {
_context12.next = 6;
break;
}
console.error('No LivePerson userId found');
this.setNotification(NotificationLevel.ERROR, this.livePersonGenericErrorText);
return _context12.abrupt("return");
case 6:
this.initLivePersonConnection();
this.lpWebsocket.onNotification(withType('MessagingEvent'), function (body) {
var _body$changes;
return (_body$changes = body.changes) == null ? void 0 : _body$changes.forEach(function (change) {
var originatorId = change.originatorMetadata.id;
var roleForWebChat = change.originatorId === userId ? 'user' : 'bot';
if (change.sequence) {
_this15.curLpChangeSequence = change.sequence;
}
// publish the survey response to LivePerson Chat
if (!_this15.isSurveyTextActionPublished && change.sequence) {
window.JsonPollock.registerAction('publishText', function (data) {
_this15.acceptStatusToLivePersonWebsocket(LPUtils.acceptStatusTypes.ACTION, change.sequence);
_this15.handleLivePersonSendMessage(data.actionData.text);
});
_this15.isSurveyTextActionPublished = true;
}
switch (change.event.type) {
case 'RichContentEvent':
{
// Extract message text from the first element of content
var messageTextElement = change.event.content.elements.find(function (el) {
return el.type === 'text';
});
var messageText = messageTextElement ? messageTextElement.text : '';
var serverTimestampString = new Date(change.serverTimestamp).toISOString();
_this15.webChatSendMessage(messageText, serverTimestampString, roleForWebChat, originatorId, null, change.sequence);
// Update message in DOM
_this15.updateLivePersonMessageInDOM(messageText, change.dialogId, change.sequence, originatorId, roleForWebChat, serverTimestampString).then(function (messageElem) {
_this15.lpMessages[change.dialogId + "-" + change.sequence] = messageElem;
// Prepare buttons data for JSON-Pollock rendering
var buttonElements = change.event.content.elements.filter(function (el) {
return el.type === 'button';
});
if (buttonElements.length > 0) {
var quickRepliesData = {
type: change.event.content.type,
elements: buttonElements.map(function (button) {
return {
type: button.type,
title: button.title,
tooltip: button.tooltip,
click: {
actions: button.click.actions
}
};
})
};
_this15.renderQuickReplies(quickRepliesData, messageElem, false);
}
});
break;
}
case 'ContentEvent':
{
var _serverTimestampString = new Date(change.serverTimestamp).toISOString();
if (roleForWebChat === 'user' && (change.event.message.startsWith(_this15.transcriptIntroText) || change.event.message.startsWith(_this15.transcriptContinuedText))) {
// Don't render transcript messages the user sent to LivePerson in the WebChat UI
break;
}
// If the transcript does not already contain the message, render it in the WebChat UI
if (!_this15.webChatTranscriptElem.querySelector("[data-lp-message-dialog-id=\"" + change.dialogId + "\"][data-lp-message-sequence=\"" + change.sequence + "\"]")) {
_this15.webChatSendMessage(change.event.message, _serverTimestampString, roleForWebChat, originatorId, null, change.sequence);
}
// Update message in DOM
_this15.updateLivePersonMessageInDOM(change.event.message, change.dialogId, change.sequence, originatorId, roleForWebChat, _serverTimestampString).then(function (messageElem) {
var _change$metadata, _change$metadata$;
_this15.lpMessages[change.dialogId + "-" + change.sequence] = messageElem;
// Accept the message to acknowledge as received - note this is not a READ receipt
_this15.acceptMessageIfNotUser(roleForWebChat, change.sequence);
// Handle quick replies if present
if (change.event.quickReplies && Array.isArray(change.event.quickReplies.replies)) {
var quickRepliesData = {
type: 'horizontal',
elements: change.event.quickReplies.replies.map(function (reply) {
return {
type: reply.type,
title: reply.title,
tooltip: reply.tooltip,
click: {
actions: reply.click.actions
}
};
})
};
_this15.renderQuickReplies(quickRepliesData, messageElem, true);
} else if (((_change$metadata = change.metadata) == null ? void 0 : (_change$metadata$ = _change$metadata[0]) == null ? void 0 : _change$metadata$.type) === 'Question' && _this15.isPostSurveyEnabled) {
// If the message is a question and part of the survey that ALSO doesn't have quick replies... re-enable the chat message box
// Regrettably, this is a workaround for the fact that the LivePerson API doesn't provide a way to determine if a message is a question
// with buttons or a freeform text question.
_this15.toggleWebChatUserTextBoxDisabled(false);
}
});
break;
}
case 'ChatStateEvent':
{
if (roleForWebChat !== 'user' && roleForWebChat !== 'lp-system') {
_this15.updateAgentState(change.event.chatState);
}
break;
}
case 'AcceptStatusEvent':
{
change.event.sequenceList.forEach(function (sequence) {
return _this15.updateLivePersonMessageStatus(sequence, change.event.status, change.dialogId);
});
break;
}
}
});
});
// If there is an existing subscriptionId, user is reconnecting to websocket. Set lpSubscribedToMessagingEvents to false
// since we are getting a new subscriptionId from livePersonSubscribeExConversations
if (this.lpSubscriptionId) {
this.lpSubscribedToMessagingEvents = false;
}
// subscribe to open conversations metadata
_context12.next = 11;
return this.livePersonSubscribeExConversations();
case 11:
subscribeExConversationsResponse = _context12.sent;
if ((_subscribeExConversat = subscribeExConversationsResponse.body) != null && _subscribeExConversat.subscriptionId) {
_context12.next = 16;
break;
}
console.error('No subscriptionId found in LivePerson subscribeExConversations response');
this.setNotification(NotificationLevel.ERROR, this.livePersonGenericErrorText);
return _context12.abrupt("return");
case 16:
this.lpSubscriptionId = subscribeExConversationsResponse.body.subscriptionId;
// handle notifications for open conversations
this.lpWebsocket.onNotification(withSubscriptionID(this.lpSubscriptionId), function (notificationBody) {
_this15.handleLivePersonConversationNotification(notificationBody);
});
// If no open conversations, request a new conversation
if (!Object.keys(this.lpOpenConvs)[0]) {
this.livePersonConsumerRequestConversation();
}
// Add event listener for textarea changes
this.webChatTextarea.addEventListener(EventName$A.INPUT, this.handleLpUserInput);
// Listen for user publishing content (sending messages) to LivePerson
this.lpWebsocket.onPublishContent(function (contentObj, timestampString) {
return new Promise(function (resolve, reject) {
try {
if (contentObj.body.event.message.startsWith(_this15.transcriptIntroText) || contentObj.body.event.message.startsWith(_this15.transcriptContinuedText)) {
// Don't render transcript messages the user is sending to LivePerson
resolve();
return;
}
// Render the message in the WebChat UI immediately, that way when success/error/timeout happens,
// we can find the rendered message by id and update it as needed
_this15.webChatSendMessage(contentObj.body.event.message, timestampString, 'user', userId, contentObj.id, null);
// Use setTimeout to wait until the message is rendered in the WebChat UI
setTimeout(function () {
// Dispatch event that LivePerson message is rendered
var event = new CustomEvent(EventName$A.LIVEPERSON_MESSAGE_RENDERED, {
detail: {
messageId: contentObj.id
}
});
window.dispatchEvent(event);
// Resolve the promise when done
resolve();
});
} catch (error) {
// Add messageId to error object data
error.data.messageId = contentObj.id;
// Reject the promise if there's an error
reject(error);
}
});
});
// Add event listener for closing the LivePerson websocket
this.lpWebsocket.ws.addEventListener(EventName$A.CLOSE, function (event) {
return _this15.onCloseLivePersonWebsocket(event);
});
case 22:
case "end":
return _context12.stop();
}
}
}, _callee12, this);
}));
function handleLivePersonOpenedSocket() {
return _handleLivePersonOpenedSocket.apply(this, arguments);
}
return handleLivePersonOpenedSocket;
}()
/**
* Initialize the LivePerson chat
*
* @returns {Promise} A promise that resolves when the LivePerson chat is initialized
*/
;
_proto.initLivePersonChat =
/*#__PURE__*/
function () {
var _initLivePersonChat = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
var _this16 = this;
var isExistingConversation, isAgentAvailable, _this$updateAIChatDra2, _this$lpWebsocket$ws, umsDomain, chatTranscript, mutationConfig;
return _regeneratorRuntime().wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
// Disable the chat box and any action buttons until agent is connected
this.toggleWebChatDisabled(true);
isExistingConversation = Object.keys(this.lpOpenConvs).length > 0;
isAgentAvailable = false;
if (isExistingConversation) {
_context13.next = 7;
break;
}
_context13.next = 6;
return this.checkLivePersonAgentAvailability();
case 6:
isAgentAvailable = _context13.sent;
case 7:
if (!(isExistingConversation || isAgentAvailable)) {
_context13.next = 48;
break;
}
_context13.next = 10;
return this.createLivePersonSession();
case 10:
this.lpSession = _context13.sent;
if (this.lpSession.sessionId) {
_context13.next = 15;
break;
}
console.error('No LivePerson Session found');
this.toggleWebChatDisabled(false);
return _context13.abrupt("return");
case 15:
_context13.next = 17;
return this.getLivePersonJWT();
case 17:
this.lpJWT = _context13.sent;
if (this.lpJWT) {
_context13.next = 22;
break;
}
console.error('No LivePerson JWT found');
this.toggleWebChatDisabled(false);
return _context13.abrupt("return");
case 22:
// Update cookie with the LivePerson JWT
this.updateAIChatDrawerCookie((_this$updateAIChatDra2 = {}, _this$updateAIChatDra2[StorageKeys.lpJWT] = this.lpJWT, _this$updateAIChatDra2));
_context13.next = 25;
return this.getLivePersonUmsDomain();
case 25:
umsDomain = _context13.sent;
if (umsDomain) {
_context13.next = 30;
break;
}
console.error('No LivePerson UMS domain found');
this.toggleWebChatDisabled(false);
return _context13.abrupt("return");
case 30:
if (!(!this.lpWebsocket || ((_this$lpWebsocket$ws = this.lpWebsocket.ws) == null ? void 0 : _this$lpWebsocket$ws.readyState) !== WebSocket.OPEN)) {
_context13.next = 34;
break;
}
_context13.next = 33;
return this.initLivePersonWebsocket(umsDomain);
case 33:
this.lpWebsocket = _context13.sent;
case 34:
if (this.lpWebsocket) {
_context13.next = 38;
break;
}
console.error('No LivePerson websocket found');
this.toggleWebChatDisabled(false);
return _context13.abrupt("return");
case 38:
_context13.next = 40;
return _classPrivateFieldLooseBase(this, _initializeJsonPollock)[_initializeJsonPollock]();
case 40:
this.handleLivePersonOpenedSocket();
// Begin watching the transcript window for new Article elements; specifically the messages
// from an Agent. We will add intersection observers to the new elements to detect when the User
// has read them.
if (!this.lpMutationObserver) {
chatTranscript = this.el.querySelector(Selector$A.WEB_CHAT_TRANSCRIPT_TRANSCRIPT);
this.lpMutationObserver = new MutationObserver(function (mutations) {
for (var _iterator = _createForOfIteratorHelperLoose$6(mutations), _step; !(_step = _iterator()).done;) {
var mutation = _step.value;
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(function (node) {
if (node.nodeName.toLowerCase() === Selector$A.ARTICLE && !node.querySelector(Selector$A.WEB_CHAT_BUBBLE_FROM_USER)) {
// filter out articles that are from user messages
_this16.observeArticleForLivePersonRead(node);
_this16.disablePreviousQuestionSurveyResponseButtons(); // Disable previous survey response buttons
}
});
}
}
});
mutationConfig = {
childList: true,
subtree: false
};
this.lpMutationObserver.observe(chatTranscript, mutationConfig);
}
// Set this to true once connected to a live agent
this.isLivePersonChatActive = true;
// Switch to LivePerson Chat In Queue disclaimer text once connected to a live agent
this.toggleLivePersonDisclaimer(true, this.livePersonInQueueText);
this.updateDrawerTitleText(this.drawerLivePersonTitleText);
this.updateButtonTitleText(this.buttonLivePersonTitleText);
_context13.next = 50;
break;
case 48:
// Post a message to the user that no agent is available.
this.webChatSendMessage(this.livePersonNoAgentsText, new Date().toISOString(), 'bot', null, null, null);
this.toggleWebChatDisabled(false);
case 50:
case "end":
return _context13.stop();
}
}
}, _callee13, this);
}));
function initLivePersonChat() {
return _initLivePersonChat.apply(this, arguments);
}
return initLivePersonChat;
}()
/**
* Handle user closing main LivePerson conversation
*
* @param {number} retryCount The current retry count
*/
;
_proto.handleUserCloseLivePersonConversation =
/*#__PURE__*/
function () {
var _handleUserCloseLivePersonConversation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(retryCount) {
var _this17 = this;
var conversationId, timeoutPromise;
return _regeneratorRuntime().wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
if (retryCount === void 0) {
retryCount = 0;
}
if (this.isPostSurveyEnabled) {
this.lpSurveyForcedClosed = true; // The End live chat button was clicked *during* the survey. Track this so we don't send a survey close message.
}
conversationId = Object.keys(this.lpOpenConvs)[0];
if (conversationId) {
timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.USER_CLOSE_CONVERSATION_TIMEOUT, 'User closing LivePerson conversation timed out'));
}, ms);
});
};
Promise.race([this.lpWebsocket.updateConversationField({
conversationId: conversationId,
conversationField: [{
field: 'DialogChange',
type: 'UPDATE',
dialog: {
dialogId: this.lpOpenConvs[conversationId].activeDialogId,
state: LPUtils.conversationStateTypes.CLOSE,
closedCause: 'Closed by consumer'
}
}]
}), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
return _this17.handleLivePersonResponse(response);
})["catch"](function (error) {
_this17.handleLivePersonError(error, function (newRetryCount) {
return _this17.handleUserCloseLivePersonConversation(newRetryCount);
}, retryCount);
});
} else {
console.warn('User closing LivePerson conversation, but no LivePerson conversation found...');
this.returnUIToAIChatBot();
}
case 4:
case "end":
return _context14.stop();
}
}
}, _callee14, this);
}));
function handleUserCloseLivePersonConversation(_x19) {
return _handleUserCloseLivePersonConversation.apply(this, arguments);
}
return handleUserCloseLivePersonConversation;
}()
/**
* Return the UI to the AI Chat Bot state
*/
;
_proto.returnUIToAIChatBot = function returnUIToAIChatBot() {
var _this$lpMutationObser;
// ensure the forced close state is reset
this.lpSurveyForcedClosed = false;
// Set isLivePersonChatActive to false
this.isLivePersonChatActive = false;
// Switch back to AI Chat disclaimer text
this.toggleLivePersonDisclaimer(false);
// Reset the agent assigned state
this.isLivePersonAgentAssigned = false;
// Enable the chat box
this.toggleWebChatDisabled(false);
// Reset isSendTranscript flag
this.isSendTranscript = false;
// Focus the WebChat textarea
this.webChatTextarea.focus();
// Remove the mutation observer
(_this$lpMutationObser = this.lpMutationObserver) == null ? void 0 : _this$lpMutationObser.disconnect();
// Remove the event listener for textarea changes
this.webChatTextarea.removeEventListener(EventName$A.INPUT, this.handleLpUserInput);
// Return text to the standard AI Chat text
this.updateDrawerTitleText(this.drawerTitleText);
this.updateButtonTitleText(this.buttonTitleText);
// Reset and close the LivePerson websocket to ensure a fresh connection next time
if (this.lpWebsocket) {
if (this.lpWebsocket.ws && this.lpWebsocket.ws.readyState === WebSocket.OPEN) {
// Only try to close if it's open
this.lpWebsocket.ws.close();
}
this.lpWebsocket = null;
}
// Reset the subscription ID so a new one will be created on reconnect
this.lpSubscriptionId = null;
// Clear any stored conversations
this.lpOpenConvs = {};
this.lpMessages = {};
this.curLpChangeSequence = 0;
this.lpSubscribedToMessagingEvents = false;
}
/**
* Observe article elements for LivePerson read status
*
* @param {HTMLElement} article The article element to observe
*/;
_proto.observeArticleForLivePersonRead = function observeArticleForLivePersonRead(article) {
var _this18 = this;
var articleObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.intersectionRatio >= 0.9 && entry.target.dataset.lpMessageSequence && entry.target.dataset.lpMessageSequence !== 'pending') {
var sequence = entry.target.dataset.lpMessageSequence;
_this18.acceptStatusToLivePersonWebsocket(LPUtils.acceptStatusTypes.READ, sequence);
observer.unobserve(entry.target);
observer.disconnect();
}
});
}, {
threshold: 0.9
});
articleObserver.observe(article);
}
/**
* Update AI Chat Drawer title text
*
* @param {string} text The text to update the title with
*/;
_proto.updateDrawerTitleText = function updateDrawerTitleText(text) {
this.el.querySelector(Selector$A.BLOCK_FEATURE_TITLE).textContent = text;
}
/**
* Update AI Chat Button title text
*
* @param {string} text The text to update the title with
*/;
_proto.updateButtonTitleText = function updateButtonTitleText(text) {
this.aiChatButton.querySelector(Selector$A.AI_CHAT_BUTTON_TEXT + " span").textContent = text;
}
/**
* Shows or Hides the Live Person specific 'Disclaimer Text', while hiding any other disclaimer text.
* @param {boolean} true if we should switch to the Live Person disclaimer, false if we should switch it back to the AI-Assistant disclaimer
*/;
_proto.toggleLivePersonDisclaimer = function toggleLivePersonDisclaimer(isShown, disclaimerText) {
var _this19 = this;
if (isShown) {
var lpDisclaimerTextSpan = document.createElement('span');
lpDisclaimerTextSpan.textContent = disclaimerText;
var lpDisclaimerButton = document.createElement('a');
lpDisclaimerButton.href = '#';
lpDisclaimerButton.setAttribute('role', 'button');
lpDisclaimerButton.classList.add(ClassName$q.RETURN_TO_AI_CHAT);
lpDisclaimerButton.innerHTML = "" + this.returnToAiChatText + "";
lpDisclaimerButton.addEventListener(EventName$A.CLICK, function (event) {
event.preventDefault();
_this19.handleUserCloseLivePersonConversation();
});
lpDisclaimerButton.addEventListener(EventName$A.KEYDOWN, function (event) {
if (event.key === ' ' || event.key === 'Enter') {
event.preventDefault();
_this19.handleUserCloseLivePersonConversation();
}
});
this.aiDisclaimerDiv.innerHTML = '';
this.aiDisclaimerDiv.append(lpDisclaimerTextSpan, ' ', lpDisclaimerButton);
} else {
// Set disclaimer back to the AI Disclaimer Text
this.aiDisclaimerDiv.innerHTML = this.aiDisclaimerText;
}
}
/**
* Open the chat drawer.
* @param {string} initialChatText Optional initial chat text to send to bot
*/;
_proto.chatOpen =
/*#__PURE__*/
function () {
var _chatOpen = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(initialChatText) {
var _this$updateAIChatDra3,
_this20 = this;
return _regeneratorRuntime().wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
if (initialChatText === void 0) {
initialChatText = '';
}
this.previouslyFocusedElem = document.activeElement;
this.el.hidden = false;
this.updateAIChatDrawerCookie((_this$updateAIChatDra3 = {}, _this$updateAIChatDra3[StorageKeys.chatDrawerState] = 'OPEN', _this$updateAIChatDra3));
// If source site has changed, send updated source site to bot, and update cookie
if (!(this.sourceSite !== this.getAIChatDrawerCookieObject()[StorageKeys.sourceSite])) {
_context15.next = 7;
break;
}
_context15.next = 7;
return this.updateSourceSite(this.sourceSite);
case 7:
requestAnimationFrame(function () {
_this20.el.classList.add(ClassName$q.SHOW);
if (_this20.mediaQueryListModalDialog.matches) {
_this20.toggleModalDialogMode(true);
} else {
_this20.toggleModalDialogMode(false);
}
});
if (this.aiChatButton) {
this.showChatButton(false);
}
if (initialChatText && this.webChatInstance) {
this.store.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: {
text: initialChatText
}
});
}
this.webChatTextarea.focus();
case 11:
case "end":
return _context15.stop();
}
}
}, _callee15, this);
}));
function chatOpen(_x20) {
return _chatOpen.apply(this, arguments);
}
return chatOpen;
}()
/**
* Close the chat drawer, reenable web chat elements if they were disabled, and focus the search input in banner if it exists,
* otherwise focus the previously focused element.
*/
;
_proto.chatClose = function chatClose() {
var _this$updateAIChatDra4;
this.el.classList.remove(ClassName$q.SHOW);
this.toggleModalDialogMode(false);
this.updateAIChatDrawerCookie((_this$updateAIChatDra4 = {}, _this$updateAIChatDra4[StorageKeys.chatDrawerState] = 'CLOSED', _this$updateAIChatDra4));
if (this.aiChatButton) {
this.showChatButton(true);
}
clearTimeout(this.messageWaitTimeout);
if (this.previouslyFocusedElem) {
this.previouslyFocusedElem.focus();
}
}
/**
* Opens the chat drawer if it is already initialized, otherwise initializes the chat drawer.
*
* @param {string} [initialChatText=''] - The initial text to be sent to the bot when opening or initializing the drawer.
*/;
_proto.chatOpenOrInit = function chatOpenOrInit(initialChatText) {
if (initialChatText === void 0) {
initialChatText = '';
}
if (this.chatInitialized) {
this.chatOpen(initialChatText);
} else {
this.initChat(initialChatText);
}
}
/**
* Returns a Promise that resolves when the first message from the bot has rendered. If a message from the bot is already
* rendered, the Promise resolves immediately.
*
* @returns {Promise}
*/;
_proto.welcomeMessageRendered = function welcomeMessageRendered() {
var _this21 = this;
return new Promise(function (resolve, reject) {
var transcript = _this21.el.querySelector(Selector$A.WEB_CHAT_TRANSCRIPT);
if (!transcript) {
reject(new Error('Transcript element not found. Cannot observe for welcome message.'));
return;
}
// Check if a webchat bubble from the bot already exists
var existingBotBubble = transcript.querySelector(Selector$A.WEB_CHAT_BUBBLE_FROM_BOT);
if (existingBotBubble) {
resolve();
return;
}
var observer = new MutationObserver(function (mutationsList, observer) {
for (var _iterator2 = _createForOfIteratorHelperLoose$6(mutationsList), _step2; !(_step2 = _iterator2()).done;) {
var mutation = _step2.value;
for (var _iterator3 = _createForOfIteratorHelperLoose$6(mutation.addedNodes), _step3; !(_step3 = _iterator3()).done;) {
var addedNode = _step3.value;
if (addedNode.nodeType === Node.ELEMENT_NODE) {
var botBubble = addedNode.querySelector(Selector$A.WEB_CHAT_BUBBLE_FROM_BOT);
if (botBubble) {
observer.disconnect();
resolve();
return;
}
}
}
}
});
observer.observe(transcript, {
childList: true,
subtree: true
});
});
}
/**
* Handle connect fulfilled event on the WebChat instance. Store a reference to the WebChat instance, and store references
* to the send box, form, textarea, and send button elements. Append disclaimer text above send box. Open the chat drawer.
*/;
_proto.onWebChatConnectFulfilled = function onWebChatConnectFulfilled() {
this.webChatInstance = window.WebChat;
this.chatInitialized = true;
this.webChatSendBox = this.el.querySelector(Selector$A.WEB_CHAT_SEND_BOX);
this.webChatForm = this.webChatSendBox.querySelector('form');
this.webChatTextarea = this.webChatForm.querySelector('textarea');
this.webChatTextarea.maxLength = this.webChatMaximumCharacters;
this.webChatSendButton = this.webChatSendBox.querySelector(Selector$A.WEB_CHAT_SEND_BUTTON);
this.firstFocusableElem = this.closeButton;
this.lastFocusableElem = this.webChatSendButton;
// Append disclaimer text above send box
if (this.webChatSendBox && !this.aiDisclaimerDiv) {
this.aiDisclaimerDiv = document.createElement('small');
this.aiDisclaimerDiv.classList.add(ClassName$q.AI_DISCLAIMER);
this.aiDisclaimerDiv.innerHTML = this.aiDisclaimerText;
this.webChatSendBox.insertAdjacentElement('beforebegin', this.aiDisclaimerDiv);
}
this.chatOpen();
}
/**
* Handle start conversation fulfilled event on the WebChat instance. If initial chat text was passed in, send it to the bot
* after the welcome message has rendered.
*
* @param {CustomEvent} event 'startconversationfulfilled' event on the WebChat instance
*/;
_proto.onStartConversationFulfilled =
/*#__PURE__*/
function () {
var _onStartConversationFulfilled = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(event) {
var initialChatText, eventValue;
return _regeneratorRuntime().wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
initialChatText = event.data;
if (!(initialChatText && this.webChatInstance)) {
_context16.next = 8;
break;
}
_context16.next = 4;
return this.welcomeMessageRendered();
case 4:
this.store.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: {
text: initialChatText
}
});
_classPrivateFieldLooseBase(this, _initWebChatTranscriptObserver)[_initWebChatTranscriptObserver]();
_context16.next = 9;
break;
case 8:
_classPrivateFieldLooseBase(this, _initWebChatTranscriptObserver)[_initWebChatTranscriptObserver]();
case 9:
// Disable any previously sent transcript checkboxes and "Continue" buttons that start a new chat with LivePerson,
// as they could be confusing to the user
this.hideLivePersonChatIntroElems();
if (Object.keys(this.lpOpenConvs).length) {
// There is possibly an active conversation with LivePerson
// Don't send transcript again since user is reconnecting and not starting chat from "startLPChat" event
this.isSendTranscript = false;
// Attempt to reconnect to LivePerson
this.initLivePersonChat();
}
// If user opened chat drawer via proactive chat, send proactive chat event to bot
if (this.isInstantiatedByProactiveChat) {
eventValue = {
instantiatedByProactiveChat: this.isInstantiatedByProactiveChat
};
this.webChatSendEvent(EventName$A.INSTANTIATED_BY_PROACTIVE_CHAT, eventValue);
}
case 12:
case "end":
return _context16.stop();
}
}
}, _callee16, this);
}));
function onStartConversationFulfilled(_x21) {
return _onStartConversationFulfilled.apply(this, arguments);
}
return onStartConversationFulfilled;
}()
/**
* Handle transition end event on the chat drawer.
*/
;
_proto.onAIChatDrawerTransitionEnd = function onAIChatDrawerTransitionEnd() {
// When chat drawer has finished sliding off screen, add hidden attribute so elements inside cannot be focused/interacted with
if (!this.el.classList.contains(ClassName$q.SHOW)) {
this.el.hidden = true;
}
}
/**
* Detect when message from bot is appended to the WebChat transcript. If a message from the bot is appended, reenable the
* WebChat elements if they were disabled, and focus the textarea in drawer if it had focus before the message was appended.
*
* @param {MutationRecord[]} mutationsList - List of mutations
*/;
_proto.onWebChatTranscriptMutation = function onWebChatTranscriptMutation(mutationsList) {
for (var _iterator4 = _createForOfIteratorHelperLoose$6(mutationsList), _step4; !(_step4 = _iterator4()).done;) {
var mutation = _step4.value;
for (var _iterator5 = _createForOfIteratorHelperLoose$6(mutation.addedNodes), _step5; !(_step5 = _iterator5()).done;) {
var addedNode = _step5.value;
if (addedNode.nodeType !== Node.ELEMENT_NODE) {
continue;
}
var botBubble = addedNode.querySelector(Selector$A.WEB_CHAT_BUBBLE_FROM_BOT);
// Not a message from bot, or bot is still generating a response
if (!botBubble || botBubble.textContent.startsWith(this.botGeneratingResponseText)) {
continue;
}
// Message from bot rendered, reenable web chat elements.
// Don't handle this for live person messages.
if (!this.isLivePersonChatActive) {
this.toggleWebChatDisabled(false);
}
// Clear timeout
clearTimeout(this.messageWaitTimeout);
if (this.webChatTextAreaHadFocus) {
this.webChatTextarea.focus();
}
return; // Exit once bot bubble is found and handled
}
}
}
/**
* Hide live person messages and transcript form that would trigger a new chat with LivePerson.
*/;
_proto.hideLivePersonChatIntroElems = function hideLivePersonChatIntroElems() {
// get all of the intro messages and forms
var introElems = this.getLPIntroMessageElements();
introElems.forEach(function (elem) {
// Find the parent 'article' element and hide it
var articleElem = elem.closest(Selector$A.ARTICLE);
if (articleElem) {
articleElem.hidden = true;
}
});
}
/**
* Initialize chat.
* @param {string} initialChatText Optional initial chat text to send to bot
*/;
_proto.initChat =
/*#__PURE__*/
function () {
var _initChat = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(initialChatText) {
var _this22 = this;
var token;
return _regeneratorRuntime().wrap(function _callee18$(_context18) {
while (1) {
switch (_context18.prev = _context18.next) {
case 0:
if (initialChatText === void 0) {
initialChatText = '';
}
_context18.next = 3;
return _classPrivateFieldLooseBase(this, _generateDirectLineToken)[_generateDirectLineToken]();
case 3:
token = _context18.sent;
// Create Redux store for WebChat
this.store = window.WebChat.createStore({}, function (_ref4) {
var dispatch = _ref4.dispatch;
return function (next) {
return /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(action) {
var cookieCreation, currentTime, result;
return _regeneratorRuntime().wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
_context17.t0 = action.type;
_context17.next = _context17.t0 === 'DIRECT_LINE/CONNECT' ? 3 : _context17.t0 === 'DIRECT_LINE/CONNECT_FULFILLED' ? 5 : _context17.t0 === 'DIRECT_LINE/POST_ACTIVITY' ? 8 : _context17.t0 === 'DIRECT_LINE/POST_ACTIVITY_FULFILLED' ? 11 : _context17.t0 === 'DIRECT_LINE/INCOMING_ACTIVITY' ? 13 : _context17.t0 === 'WEB_CHAT/SEND_MESSAGE' ? 15 : 23;
break;
case 3:
_this22.handlePreConnect();
return _context17.abrupt("break", 24);
case 5:
_this22.handleConnectFulfilled(dispatch);
_this22.sendLPFeatureFlagToBot(dispatch);
return _context17.abrupt("break", 24);
case 8:
if (!(_this22.isLivePersonChatActive && action.payload.activity.name !== EventName$A.LIVEPERSON_SAVE_IDS)) {
_context17.next = 10;
break;
}
return _context17.abrupt("return");
case 10:
return _context17.abrupt("break", 24);
case 11:
_this22.handlePostActivityFulfilled(action, initialChatText);
return _context17.abrupt("break", 24);
case 13:
_this22.handleIncomingActivity(action, dispatch);
return _context17.abrupt("break", 24);
case 15:
if (!_this22.isLivePersonChatActive) {
_context17.next = 20;
break;
}
// Change the composing state to pause before sending a message
_this22.debouncedChatStateToPause.cancel({
upcomingOnly: true
});
_this22.chatStateToPause();
// Send the message text to LivePerson
_this22.handleLivePersonSendMessage(action.payload.text);
// Return early to prevent dispatching the action to next middleware or store
return _context17.abrupt("return");
case 20:
// Refresh/Regenerate the token
if (token) {
cookieCreation = _this22.getAIChatDrawerCookieObject()[StorageKeys.tokenCreated];
currentTime = Date.now() / 1000;
if (currentTime - cookieCreation < _this22.refreshAfter) {
_classPrivateFieldLooseBase(_this22, _refreshDirectLineToken)[_refreshDirectLineToken]();
}
} else {
_classPrivateFieldLooseBase(_this22, _regenerateAIChatDrawerToken)[_regenerateAIChatDrawerToken]();
}
_this22.handleWebChatSendMessage(action);
return _context17.abrupt("break", 24);
case 23:
return _context17.abrupt("break", 24);
case 24:
// Dispatch the action to next middleware or store
result = next(action);
return _context17.abrupt("return", result);
case 26:
case "end":
return _context17.stop();
}
}
}, _callee17);
}));
return function (_x23) {
return _ref5.apply(this, arguments);
};
}();
};
});
this.directLine = window.WebChat.createDirectLine({
token: token,
webSocket: true
});
// Makes connection to Engine through direct line, with the defined actions and parameters
this.renderWebChat();
case 7:
case "end":
return _context18.stop();
}
}
}, _callee18, this);
}));
function initChat(_x22) {
return _initChat.apply(this, arguments);
}
return initChat;
}()
/**
* Sends an event to the Copilot Chatbot which will update its LivePerson feature flag
* to the current state of the client.
* @param {Function} dispatch - The dispatch function (Redux)
*/
;
_proto.sendLPFeatureFlagToBot = function sendLPFeatureFlagToBot(dispatch) {
dispatch({
type: 'DIRECT_LINE/POST_ACTIVITY',
meta: {
method: 'keyboard'
},
payload: {
activity: {
type: 'event',
name: 'livePersonFeatureFlagEvent',
value: {
livePersonFeatureFlag: this.isLivePersonChatFeatureEnabled
},
channelData: {
postBack: true
}
}
}
});
}
/**
* Split the transcript into chunks that are within the LivePerson message character limit.
*
* @param {string} transcript The transcript to split
* @returns {string[]} An array of transcript chunks
*/;
_proto.splitTranscript = function splitTranscript(transcript) {
var chunks = [];
var startIndex = 0;
var continuedText = this.transcriptContinuedText + "\n\n";
var continuedTextLength = continuedText.length;
while (startIndex < transcript.length) {
var endIndex = startIndex + this.livePersonMessageCharLimit;
if (chunks.length > 0) {
endIndex -= continuedTextLength;
}
if (endIndex > transcript.length) {
endIndex = transcript.length;
} else {
// Ensure we don't split in the middle of a word
var lastSpaceIndex = transcript.lastIndexOf(' ', endIndex);
if (lastSpaceIndex > startIndex) {
endIndex = lastSpaceIndex;
}
}
var chunk = transcript.slice(startIndex, endIndex).trim();
if (chunks.length > 0) {
chunk = continuedText + chunk;
}
chunks.push(chunk);
startIndex = endIndex;
}
return chunks;
}
/**
* Send the chat transcript to LivePerson. If the transcript exceeds the character limit, split it into multiple messages.
*
* @returns {void}
*/;
_proto.sendTranscriptToLivePerson = function sendTranscriptToLivePerson() {
var _this23 = this;
var messageBubbleElems = Array.from(this.webChatTranscriptElem.querySelectorAll(Selector$A.WEB_CHAT_BUBBLE));
if (!messageBubbleElems.length) {
console.error('No messages found in the WebChat transcript');
return;
}
var fullTranscript = this.transcriptIntroText + "\n\n";
messageBubbleElems.forEach(function (messageBubbleElem) {
var fromText = messageBubbleElem.classList.contains(Selector$A.WEB_CHAT_BUBBLE_FROM_USER.replace('.', '')) ? _this23.transcriptFromUserText : _this23.transcriptFromAssistantText;
var messageTextContent = messageBubbleElem.textContent.trim();
fullTranscript += fromText + " " + messageTextContent + "\n\n";
});
var fullTranscriptCharCount = fullTranscript.length;
if (fullTranscriptCharCount > this.livePersonMessageCharLimit) {
// Send multiple messages if the full transcript exceeds the character limit
var messages = this.splitTranscript(fullTranscript, this.livePersonMessageCharLimit);
messages.forEach( /*#__PURE__*/function () {
var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(message) {
return _regeneratorRuntime().wrap(function _callee19$(_context19) {
while (1) {
switch (_context19.prev = _context19.next) {
case 0:
_context19.next = 2;
return _this23.handleLivePersonSendMessage(message);
case 2:
_context19.next = 4;
return new Promise(function (resolve) {
return setTimeout(resolve, 500);
});
case 4:
case "end":
return _context19.stop();
}
}
}, _callee19);
}));
return function (_x24) {
return _ref6.apply(this, arguments);
};
}());
} else {
// Send the full transcript as a single message
this.handleLivePersonSendMessage(fullTranscript);
}
}
/**
* Handle feedback event activity sent from the Copilot.
* Update accessibility properties for the feedback buttons.
* Add event listeners to feedback buttons.
* @param {Object} action - The action object (Redux)
* @param {Function} dispatch - The dispatch function (Redux)
*/;
_proto.handleFeedbackRequestFromBot = function handleFeedbackRequestFromBot(action, dispatch) {
var _this24 = this;
var messageId = action.payload.activity.value;
var positiveActionSet = document.getElementById(messageId + "-positive");
var negativeActionSet = document.getElementById(messageId + "-negative");
if (positiveActionSet) {
var positiveButton = positiveActionSet.querySelector('button');
positiveButton.classList.add(ClassName$q.FEEDBACK_BUTTON);
positiveButton.setAttribute('aria-label', this.botFeedbackPositiveAriaLabel);
positiveButton.querySelector('div').setAttribute('aria-hidden', 'true');
positiveButton.addEventListener(EventName$A.CLICK, function () {
_this24.handleFeedbackButtonClick(dispatch, messageId, 'positive', positiveButton);
});
var positiveButtonImg = positiveButton.querySelector('img');
if (positiveButtonImg) {
positiveButtonImg.setAttribute('alt', '');
}
}
if (negativeActionSet) {
var negativeButton = negativeActionSet.querySelector('button');
negativeButton.classList.add(ClassName$q.FEEDBACK_BUTTON);
negativeButton.setAttribute('aria-label', this.botFeedbackNegativeAriaLabel);
negativeButton.querySelector('div').setAttribute('aria-hidden', 'true');
negativeButton.addEventListener(EventName$A.CLICK, function () {
_this24.handleFeedbackButtonClick(dispatch, messageId, 'negative', negativeButton);
});
var negativeButtonImg = negativeButton.querySelector('img');
if (negativeButtonImg) {
negativeButtonImg.setAttribute('alt', '');
}
}
}
/**
* Handle incoming adaptive card from the bot.
* Add a class to the follow-up bubble content to remove the background.
* Disable the deflection flow buttons after click.
*
* @param {Object} adaptiveCardData - The adaptive card data
*/;
_proto.handleIncomingAdaptiveCard = function handleIncomingAdaptiveCard(adaptiveCardData) {
var _adaptiveCardData$id, _adaptiveCardData$bod;
if ((_adaptiveCardData$id = adaptiveCardData.id) != null && _adaptiveCardData$id.startsWith('follow-up')) {
var adaptiveCardId = adaptiveCardData.id;
// Use setTimeout to ensure the adaptive card is rendered before adding the class
window.setTimeout(function () {
var followUpAdaptiveCardElem = document.getElementById(adaptiveCardId);
if (followUpAdaptiveCardElem) {
// Add class to remove background from follow-up bubble content
var webChatBubbleContent = followUpAdaptiveCardElem.closest(Selector$A.WEB_CHAT_BUBBLE_CONTENT);
webChatBubbleContent.classList.add(ClassName$q.WEBCHAT_BUBBLE_CONTENT_FOLLOW_UP);
}
});
} else if ((_adaptiveCardData$bod = adaptiveCardData.body) != null && _adaptiveCardData$bod.length) {
for (var _iterator6 = _createForOfIteratorHelperLoose$6(adaptiveCardData.body), _step6; !(_step6 = _iterator6()).done;) {
var _bodyItem$id;
var bodyItem = _step6.value;
if ((_bodyItem$id = bodyItem.id) != null && _bodyItem$id.startsWith('deflection-')) {
var _ret = function () {
var deflectionFlowId = bodyItem.id;
// Wait until deflection flow card is rendered using setTimeout
window.setTimeout(function () {
var _document$getElementB;
var deflectionFlowCardElem = (_document$getElementB = document.getElementById(deflectionFlowId)) == null ? void 0 : _document$getElementB.closest(Selector$A.ARTICLE);
if (deflectionFlowCardElem) {
(function () {
var deflectionFlowButtons = deflectionFlowCardElem.querySelectorAll('button');
for (var _iterator7 = _createForOfIteratorHelperLoose$6(deflectionFlowButtons), _step7; !(_step7 = _iterator7()).done;) {
var button = _step7.value;
// Disable all buttons after any one of them is clicked
button.addEventListener(EventName$A.CLICK, function () {
for (var _iterator8 = _createForOfIteratorHelperLoose$6(deflectionFlowButtons), _step8; !(_step8 = _iterator8()).done;) {
var btn = _step8.value;
btn.disabled = true;
}
});
}
})();
}
});
return "break"; // break out of loop after finding deflection flow item
}();
if (_ret === "break") break;
}
}
}
}
/**
* Handle incoming activity from the WebChat store.
*
* @param {Object} action - The action object (Redux)
* @param {Function} dispatch - The dispatch function (Redux)
*/;
_proto.handleIncomingActivity = function handleIncomingActivity(action, dispatch) {
var _activity$from, _activity$attachments, _activity$attachments2, _activity$from2;
var activity = action.payload.activity;
if (activity.type === 'message' && ((_activity$from = activity.from) == null ? void 0 : _activity$from.role) === 'bot' && (_activity$attachments = activity.attachments) != null && _activity$attachments.length && ((_activity$attachments2 = activity.attachments[0].content) == null ? void 0 : _activity$attachments2.type) === 'AdaptiveCard') {
var adaptiveCardData = activity.attachments[0].content;
this.handleIncomingAdaptiveCard(adaptiveCardData);
}
if (activity.type === 'message' && ((_activity$from2 = activity.from) == null ? void 0 : _activity$from2.role) === 'bot' && !this.isLivePersonChatActive) {
// emit an event that a message is received. Developers can listen to this event to perform additional actions, such as fire telemetry events.
var event = new Event(EventName$A.WEBCHAT_MESSAGE_RECEIVED);
window.dispatchEvent(event);
}
if (this.isLivePersonChatActive && activity.type === 'message') {
this.handleLivePersonIncomingActivity(activity);
}
if (activity.type === 'event' && activity.name === EventName$A.FEEDBACK_SENT) {
this.handleFeedbackRequestFromBot(action, dispatch);
}
if (activity.type === 'event' && activity.name === EventName$A.GENERATE_REIMAGINE_UMP) {
this.handleReimagineUMPRequest(action, dispatch);
}
if (activity.type === 'event' && activity.name === EventName$A.LIVEPERSON_CHAT_START && !Object.keys(this.lpOpenConvs).length) {
var _this$updateAIChatDra5;
this.skillId = activity.value.skillId;
this.accountId = activity.value.accountId;
this.isSendTranscript = activity.value.sendTranscript;
// If this "startLPChat" activity has already been seen (from bot chat history), don't start a new LivePerson chat
if (this.startLPChatActivityIds.includes(activity.id)) {
return;
}
this.startLPChatActivityIds.push(activity.id);
this.updateAIChatDrawerCookie((_this$updateAIChatDra5 = {}, _this$updateAIChatDra5[StorageKeys.startLPChatActivityIds] = this.startLPChatActivityIds, _this$updateAIChatDra5));
this.initLivePersonChat();
}
}
/*
* @returns {NodeList} - The list of elements that are part of the LivePerson chat intro messages and send transcript forms
*/;
_proto.getLPIntroMessageElements = function getLPIntroMessageElements() {
return this.el.querySelectorAll("[id^=\"form-\"], [id^=\"greeting-\"], [id^=\"post-\"]");
}
/**
* Handle sending a message to the bot from the WebChat.
*
* @param {Object} action - The action object (Redux)
*/;
_proto.handleWebChatSendMessage =
/*#__PURE__*/
function () {
var _handleWebChatSendMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(action) {
var _this25 = this;
return _regeneratorRuntime().wrap(function _callee20$(_context20) {
while (1) {
switch (_context20.prev = _context20.next) {
case 0:
if (document.activeElement === this.webChatTextarea) {
this.webChatTextAreaHadFocus = true;
}
// Ensure channelData exists and add pageUrl
action.payload = action.payload || {};
action.payload.channelData = Object.assign({}, action.payload.channelData, {
pageUrl: window.location.href
});
this.toggleWebChatDisabled(true);
this.messageWaitTimeout = setTimeout(function () {
_this25.toggleWebChatDisabled(false);
}, this.messageWaitTimeoutDuration);
// If source site has changed, send updated source site to bot, and update cookie
if (!(this.sourceSite !== this.getAIChatDrawerCookieObject()[StorageKeys.sourceSite])) {
_context20.next = 8;
break;
}
_context20.next = 8;
return this.updateSourceSite(this.sourceSite);
case 8:
case "end":
return _context20.stop();
}
}
}, _callee20, this);
}));
function handleWebChatSendMessage(_x25) {
return _handleWebChatSendMessage.apply(this, arguments);
}
return handleWebChatSendMessage;
}()
/**
* Update the chat state of the user in the LivePerson chat.
*
* @param {string} state The chat state
* @returns {Promise} A promise that resolves when the chat state is updated
*/
;
_proto.chatStateTo =
/*#__PURE__*/
function () {
var _chatStateTo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(state) {
var conversationId;
return _regeneratorRuntime().wrap(function _callee21$(_context21) {
while (1) {
switch (_context21.prev = _context21.next) {
case 0:
conversationId = Object.keys(this.lpOpenConvs)[0];
return _context21.abrupt("return", this.lpWebsocket.publishEvent({
dialogId: this.lpOpenConvs[conversationId].activeDialogId,
conversationId: Object.keys(this.lpOpenConvs)[0],
event: {
type: 'ChatStateEvent',
chatState: state
}
}));
case 2:
case "end":
return _context21.stop();
}
}
}, _callee21, this);
}));
function chatStateTo(_x26) {
return _chatStateTo.apply(this, arguments);
}
return chatStateTo;
}()
/**
* Set the user's chat state to COMPOSING for LivePerson
*/
;
_proto.chatStateToComposing = function chatStateToComposing() {
try {
this.chatStateTo(livePersonChatStateTypes.COMPOSING);
} catch (error) {
console.error('Error setting user chat state to COMPOSING:', error);
}
}
/**
* Set the user's chat state to PAUSE for LivePerson
*/;
_proto.chatStateToPause = function chatStateToPause() {
try {
this.chatStateTo(livePersonChatStateTypes.PAUSE);
} catch (error) {
console.error('Error setting user chat state to PAUSE:', error);
}
}
/**
* Returns whether the AI Chat Drawer is visually suppressed or not.
* The AI Chat Drawer is visually suppressed if the isHidden attribute is set to true.
* This is used in scenarios where the AI Chat Drawer should be rendered in HTML, but should not be (or become) visible to the user.
* @returns {boolean} - Whether the AI Chat Drawer is visually suppressed or not
*/;
_proto.getIsHidden = function getIsHidden() {
return this.el.getAttribute(Attributes$5.IS_HIDDEN) !== null;
}
/**
* Debounce input event on WebChat textarea to set the user's chat state to COMPOSING and PAUSE for LivePerson.
*/;
_proto.handleLpUserInput = function handleLpUserInput() {
this.debouncedChatStateToComposing();
this.debouncedChatStateToPause();
}
/**
* Handle sending message to LivePerson.
*
* @param {string} messageText The text to send to LivePerson
* @param {string} messageId The message ID (only used when retrying sending a message)
* @param {number} retryCount The current retry count
*/;
_proto.handleLivePersonSendMessage = function handleLivePersonSendMessage(messageText, messageId, retryCount) {
var _this26 = this;
if (messageId === void 0) {
messageId = null;
}
if (retryCount === void 0) {
retryCount = 0;
}
var isTranscriptMessage = messageText.startsWith(this.transcriptIntroText) || messageText.startsWith(this.transcriptContinuedText);
messageText = new DOMParser().parseFromString(messageText, 'text/html').body.textContent;
// Generate a messageId if one wasn't provided, and immediately render the message in the
// WebChat UI with the generated messageId (if not a transcript message)
if (!messageId && !isTranscriptMessage) {
messageId = Math.floor(Math.random() * 1e9);
// Render the message in the WebChat UI with the generated messageId
var timestampString = new Date().toISOString();
var userId = _classPrivateFieldLooseBase(this, _getLivePersonIdFromJWT)[_getLivePersonIdFromJWT]();
this.webChatSendMessage(messageText, timestampString, 'user', userId, messageId, null);
// Preemptively set the dialog-id and sequence attributes on the message element
// This will prevent duplicate messages when LivePerson sends back a ContentEvent
setTimeout(function () {
var renderedMessageElem = _this26.webChatTranscriptElem.querySelector("[data-lp-message-id=\"" + messageId + "\"]");
if (renderedMessageElem) {
var _this26$lpOpenConvs$O;
var activeDialogId = (_this26$lpOpenConvs$O = _this26.lpOpenConvs[Object.keys(_this26.lpOpenConvs)[0]]) == null ? void 0 : _this26$lpOpenConvs$O.activeDialogId;
if (activeDialogId) {
renderedMessageElem.dataset.lpMessageDialogId = activeDialogId;
// We don't know the sequence yet, but we can use a placeholder that will prevent duplicates
renderedMessageElem.dataset.lpMessageSequence = 'pending';
}
}
// Dispatch event that LivePerson message is rendered
var event = new CustomEvent(EventName$A.LIVEPERSON_MESSAGE_RENDERED, {
detail: {
messageId: messageId
}
});
window.dispatchEvent(event);
}, 0);
}
var timeoutPromise = function timeoutPromise(ms) {
return new Promise(function (_, reject) {
return setTimeout(function () {
return reject(new LPError(LPErrorTypes.SEND_MESSAGE_TIMEOUT, 'Send message to LivePerson timed out', {
messageId: messageId
}));
}, ms);
});
};
// Resolve the promise that completes first
Promise.race([this.publishToLivePersonWebsocket(messageText, messageId), timeoutPromise(livePersonResponseTimeout)]).then(function (response) {
var _response$body;
_this26.handleLivePersonResponse(response);
var messageId = response.reqId;
var renderedMessageElem = _this26.webChatTranscriptElem.querySelector("[data-lp-message-id=\"" + messageId + "\"]");
if (renderedMessageElem && ((_response$body = response.body) == null ? void 0 : _response$body.sequence) >= 0) {
// Add data-lp-message-dialog-id and data-lp-message-sequence attributes to the found message element
renderedMessageElem.dataset.lpMessageDialogId = _this26.lpOpenConvs[Object.keys(_this26.lpOpenConvs)[0]].activeDialogId;
renderedMessageElem.dataset.lpMessageSequence = response.body.sequence;
// Update the message element to show the timestamp
_this26.markMessageAsSent(renderedMessageElem);
}
})["catch"](function (error) {
error.data.messageId = messageId;
_this26.handleLivePersonError(error, function (messageId, newRetryCount) {
return _this26.handleLivePersonSendMessage(messageText, messageId, newRetryCount);
}, retryCount);
});
}
/**
* Handle LivePerson incoming activity.
*
* @param {Object} activity - The activity for a LivePerson incoming message
*/;
_proto.handleLivePersonIncomingActivity = function handleLivePersonIncomingActivity(activity) {
var _this27 = this;
var activityText = activity.text,
activityId = activity.id,
messageSequence = activity.sequence;
if (!activityText) {
console.error('No text found in LivePerson message activity');
return;
}
// Use MutationObserver to wait until message is rendered in the WebChat transcript
var observer = new MutationObserver(function (mutationsList, observer) {
var _activity$from3;
for (var _iterator9 = _createForOfIteratorHelperLoose$6(mutationsList), _step9; !(_step9 = _iterator9()).done;) {
var mutation = _step9.value;
if (mutation.type === 'childList') {
for (var _iterator10 = _createForOfIteratorHelperLoose$6(mutation.addedNodes), _step10; !(_step10 = _iterator10()).done;) {
var node = _step10.value;
if (node.nodeType === Node.ELEMENT_NODE) {
var messageBubbleElem = node.querySelector(Selector$A.WEB_CHAT_BUBBLE);
/* eslint-disable max-depth */
if (messageBubbleElem && Util.normalizeText(messageBubbleElem.textContent) === Util.normalizeText(activityText)) {
switch ((_activity$from3 = activity.from) == null ? void 0 : _activity$from3.role) {
case 'lp-system':
{
// Add class to system message bubble to style it differently
messageBubbleElem.classList.add(ClassName$q.WEBCHAT_BUBBLE_LP_SYSTEM_MESSAGE);
// Add screen-reader-only class to timestamp to hide it visually
var timestampElem = node.querySelector(Selector$A.WEB_CHAT_STATUS);
timestampElem == null ? void 0 : timestampElem.classList.add(ClassName$q.SCREEN_READER_ONLY);
break;
}
case 'user':
{
// Activity is from user, either from user sending a message, or from websocket event
var articleElem = messageBubbleElem.closest(Selector$A.ARTICLE);
if (articleElem) {
// Add data-lp-message-id attribute to the article element
articleElem.dataset.lpMessageId = activityId;
if (messageSequence !== null && messageSequence !== undefined && messageSequence >= 0) {
// Activity is from LivePerson data and has a sequence
// Add data-lp-message-dialog-id and data-lp-message-sequence attributes to the article element
articleElem.dataset.lpMessageDialogId = _this27.lpOpenConvs[Object.keys(_this27.lpOpenConvs)[0]].activeDialogId;
articleElem.dataset.lpMessageSequence = messageSequence;
} else if (!articleElem.dataset.lpMessageSequence || articleElem.dataset.lpMessageSequence === 'pending') {
// Message from user is still pending
_this27.markMessageAsSending(articleElem);
}
}
break;
}
case 'bot':
{
// Message is from LivePerson bot
var _articleElem = messageBubbleElem.closest(Selector$A.ARTICLE);
if (_articleElem) {
// Add data-lp-message-dialog-id attribute to the article element
_articleElem.dataset.lpMessageDialogId = _this27.lpOpenConvs[Object.keys(_this27.lpOpenConvs)[0]].activeDialogId;
// Add data-lp-message-sequence attribute to the article element
_articleElem.dataset.lpMessageSequence = messageSequence;
}
break;
}
// No default
}
// Stop observing once the element is found and modified
observer.disconnect();
return;
}
/* eslint-enable max-depth */
}
}
}
}
});
// Start observing the target node for configured mutations
var targetNode = document.querySelector(Selector$A.WEB_CHAT_TRANSCRIPT);
var config = {
childList: true,
subtree: true
};
observer.observe(targetNode, config);
}
/**
* Handles the timeout for sending a message via LivePerson.
*
* This function is triggered when a message fails to send within a specified timeout period.
* It attempts to find the message element in the web chat transcript using the provided messageId.
* If the message element is found, it marks the message as failed to send.
*
* @param {string} messageId - The unique identifier of the message that failed to send.
*/;
_proto.handleLivePersonSendMessageTimeout = function handleLivePersonSendMessageTimeout(messageId) {
var messageElem = this.webChatTranscriptElem.querySelector("[data-lp-message-id=\"" + messageId + "\"]");
if (!messageElem) {
console.error("Message element with messageId " + messageId + " not found");
return;
}
// Set the message sequence to -1 to indicate that the message failed to send
messageElem.dataset.lpMessageSequence = -1;
// Mark the message as failed to send
this.markMessageAsSendFailed(messageElem);
}
/**
* Creates a quick component and appends it to the associated Adaptive Card container's DOM
* then initializes the UMP with the provided data from the event action.
* @param {} action
*/;
_proto.handleReimagineUMPRequest = function handleReimagineUMPRequest(action) {
// The UMP script and package should be added to pages already.
/* eslint-disable no-undef */
if (!ump) {
console.error('UMP is not defined');
return;
}
var _action$payload$activ = action.payload.activity.value,
dataVideo = _action$payload$activ.dataVideo,
messageId = _action$payload$activ.messageId;
var umpContainer = document.getElementById("" + messageId);
if (!umpContainer) {
console.error("UMP container with messageId " + messageId + " not found");
return;
}
umpContainer.innerHTML = _classPrivateFieldLooseBase(this, _UMP_HTML_TEMPLATE)[_UMP_HTML_TEMPLATE];
var umplayer = umpContainer.querySelector('universal-media-player');
ump(umplayer, dataVideo);
/* eslint-enable no-undef */
}
/*
* Handle feedback button click.
* Updates the icon to the filled svg icon.
* Post a 'feedback' event activity to the bot.
* @param {Function} dispatch - The dispatch function (Redux)
* @param {string} messageId - The message ID
* @param {string} interactionResult - The interaction result (positive/negative)
*/;
_proto.handleFeedbackButtonClick = function handleFeedbackButtonClick(dispatch, messageId, interactionResult, thisButton) {
// Updates icon in the button
var iconSrc = thisButton.querySelector('img').src;
if (iconSrc && interactionResult === 'positive') {
thisButton.querySelector('img').setAttribute('src', FEEDBACK_ICON_SVGS.POSITIVE_FILLED);
} else if (iconSrc && interactionResult === 'negative') {
thisButton.querySelector('img').setAttribute('src', FEEDBACK_ICON_SVGS.NEGATIVE_FILLED);
}
// Send the event activity to the bot
dispatch({
type: 'DIRECT_LINE/POST_ACTIVITY',
meta: {
method: 'keyboard'
},
payload: {
activity: {
channelData: {
postBack: true
},
name: "feedback" + interactionResult + "Request",
type: 'event',
text: messageId,
value: {
sourceSite: this.sourceSite
}
}
}
});
}
/**
* Code to run while connecting to the bot. Dispatch a custom event to indicate that the WebChat
* connection is being initiated.
*/;
_proto.handlePreConnect = function handlePreConnect() {
var event = new Event(EventName$A.WEBCHAT_CONNECT_INITIATED);
window.dispatchEvent(event);
}
/**
* Handle connect fulfilled event on the WebChat instance. Send a 'startConversation' event to the bot.
* @param {Function} dispatch - The dispatch function (Redux)
*/;
_proto.handleConnectFulfilled = function handleConnectFulfilled(dispatch) {
dispatch({
meta: {
method: 'keyboard'
},
payload: {
activity: {
channelData: {
postBack: true,
pageUrl: window.location.href
},
name: 'startConversation',
type: 'event',
value: {
sourceSite: this.sourceSite,
leadId: this.getLeadId()
}
}
},
type: 'DIRECT_LINE/POST_ACTIVITY'
});
var event = new Event(EventName$A.WEBCHAT_CONNECT_FULFILLED);
window.dispatchEvent(event);
}
/**
* Handle post activity fulfilled event on the WebChat instance. If the activity is a 'startConversation' event, dispatch
* a custom event to send initial chat text to the bot.
* @param {Object} action - The action object (Redux)
* @param {string} initialChatText - Optional initial chat text to send to bot
*/;
_proto.handlePostActivityFulfilled = function handlePostActivityFulfilled(action, initialChatText) {
var _action$payload$activ2 = action.payload.activity,
type = _action$payload$activ2.type,
name = _action$payload$activ2.name;
if (type === 'event' && name === 'startConversation') {
var event = new Event(EventName$A.START_CONVERSATION_FULFILLED);
event.data = initialChatText;
window.dispatchEvent(event);
}
if (type === 'event' && name === 'sourceSiteEvent') {
// Resolve the sourceSite update promise
this.resolveSourceSiteUpdate();
}
}
/**
* Set the isHidden attribute on the AI Chat Drawer. If true, the AI Chat Drawer will be visually suppressed and not shown to the user.
* @param {boolean} isHidden - Whether the AI Chat Drawer should be visually suppressed or not
*/;
_proto.setIsHidden = function setIsHidden(isHidden) {
if (isHidden) {
this.el.setAttribute(Attributes$5.IS_HIDDEN, ''); // Set attribute with no value
this.showChatButton(false);
} else {
this.el.removeAttribute(Attributes$5.IS_HIDDEN);
// AI Chat Drawer is unhidden, need to add events for chat action type links
var eventsToAdd = this.addChatActionTypeLinkEvents();
if (eventsToAdd.length) {
Util$1.addEvents(eventsToAdd);
}
}
}
/**
* Marks a message as sending by appending a bulleted span to the status message.
*
* @param {HTMLElement} element - The HTML element representing the message to be marked as sending.
*/;
_proto.markMessageAsSending = function markMessageAsSending(element) {
this.appendBulletedSpanToStatusMessage(element, this.livePersonSendingMessageText);
}
/**
* Marks a message as sent by removing the "* Sending" status message.
*
* @param {HTMLElement} element - The HTML element representing the message to be marked as sent.
*/;
_proto.markMessageAsSent = function markMessageAsSent(element) {
// Remove * Sending from the status message
this.removeBulletedSpanFromStatusMessage(element);
}
/**
* Marks a message as failed to send and provides a retry option.
*
* @param {HTMLElement} element - The message element to mark as failed.
* @returns {void}
*/;
_proto.markMessageAsSendFailed = function markMessageAsSendFailed(element) {
var _this28 = this;
if (!element) {
console.error('No message element found');
return;
}
var statusMessage = element.querySelector(Selector$A.WEB_CHAT_STATUS);
if (!statusMessage) {
console.error('No status message found in message element');
return;
}
// Clear existing HTML from statusMessage
statusMessage.innerHTML = '';
var sendFailedSpan = document.createElement('span');
sendFailedSpan.textContent = this.livePersonSendFailedText;
statusMessage.append(sendFailedSpan);
// Add retry button
var retryButton = document.createElement('a');
retryButton.setAttribute('role', 'button');
retryButton.setAttribute('href', '#');
retryButton.textContent = this.retryButtonText;
retryButton.dataset.biCompnm = 'AI Chat Drawer';
retryButton.dataset.biId = 'ai-chat-drawer';
retryButton.dataset.biCn = this.retryButtonText;
retryButton.dataset.biEcn = 'Retry';
var handleRetryButtonClick = function handleRetryButtonClick(event) {
event.preventDefault();
// Get the text content of the message bubble
var messageText = element.querySelector(Selector$A.WEB_CHAT_BUBBLE_CONTENT).textContent;
if (!messageText) {
console.error('No message text found in message bubble');
return;
}
// Send a new message to LivePerson with the same text
_this28.handleLivePersonSendMessage(messageText);
};
retryButton.addEventListener(EventName$A.CLICK, handleRetryButtonClick);
retryButton.addEventListener(EventName$A.KEYDOWN, function (event) {
if (event.key === 'Enter' || event.key === ' ') {
handleRetryButtonClick(event);
}
});
statusMessage.append(retryButton);
}
/**
* Mark the message as read in the WebChat transcript.
*
* @param {HTMLElement} element - The message element to mark as read
*/;
_proto.markMessageAsRead = function markMessageAsRead(element) {
this.appendBulletedSpanToStatusMessage(element, this.livePersonReadText);
}
/**
* Appends a bulleted span with the specified text to the status message element within the given element.
*
* @param {HTMLElement} element - The parent element containing the status message element.
* @param {string} textToAppend - The text to append as a bulleted span.
*/;
_proto.appendBulletedSpanToStatusMessage = function appendBulletedSpanToStatusMessage(element, textToAppend) {
var _statusMessage$textCo;
if (!element) {
return;
}
var statusMessage = element.querySelector(Selector$A.WEB_CHAT_STATUS);
if (!statusMessage) {
return;
}
var isAlreadyMarked = (_statusMessage$textCo = statusMessage.textContent) == null ? void 0 : _statusMessage$textCo.includes(textToAppend);
if (!isAlreadyMarked) {
var bulletedSpan = document.createElement('span');
bulletedSpan.innerHTML = "• " + textToAppend;
statusMessage.append(bulletedSpan);
}
}
/**
* Removes any span elements that start with a bullet point (•) from the status message within the given element.
*
* @param {HTMLElement} element - The parent element containing the status message.
*/;
_proto.removeBulletedSpanFromStatusMessage = function removeBulletedSpanFromStatusMessage(element) {
if (!element) {
return;
}
var statusMessage = element.querySelector(Selector$A.WEB_CHAT_STATUS);
if (!statusMessage) {
return;
}
var spans = statusMessage.querySelectorAll('span');
for (var _iterator11 = _createForOfIteratorHelperLoose$6(spans), _step11; !(_step11 = _iterator11()).done;) {
var span = _step11.value;
if (span.textContent.startsWith('•')) {
span.remove();
}
}
}
/**
* Code to run when the UHF header intersects with the viewport. Add/remove scroll listener to align chat drawer with bottom
* of UHF header, or top of viewport.
* @param {IntersectionObserverEntry[]} entries - Array of intersection observer entries
*/;
_proto.onUhfHeaderIntersect = function onUhfHeaderIntersect(entries) {
var _this29 = this;
entries.forEach(function (entry) {
if (entry.isIntersecting) {
// UHF header is visible. Add scroll listener to align chat drawer with bottom of UHF header
_this29.uhfHeaderIsVisible = true;
document.addEventListener(EventName$A.SCROLL, _this29.boundOnScrollWithUhfVisible, false);
_this29.boundOnScrollWithUhfVisible();
} else {
// UHF header is not visible. Remove scroll listener, align chat drawer to top of viewport.
_this29.uhfHeaderIsVisible = false;
document.removeEventListener(EventName$A.SCROLL, _this29.boundOnScrollWithUhfVisible, false);
_this29.el.style.top = 0;
_this29.el.style.height = '100%';
}
});
}
/**
* Code to run when the sticky nav is stuck/unstuck. Align chat drawer with bottom of sticky nav when stuck, otherwise align
* to top of viewport.
* @param {MutationRecord[]} mutations - Array of mutation records
*/;
_proto.onStickyNavMutation = function onStickyNavMutation(mutations) {
var _this30 = this;
mutations.forEach(function (mutation) {
var classHasChanged = mutation.target.getAttribute('class') !== mutation.oldValue;
// Ignore mutations that don't involve the sticky nav being stuck/unstuck
if (!classHasChanged || mutation.target.classList.contains(ClassName$q.GET_HEIGHT) || mutation.oldValue.includes(ClassName$q.GET_HEIGHT)) {
return;
}
var isStuck = mutation.target.classList.contains(ClassName$q.STUCK);
if (isStuck) {
// Sticky nav is stuck. Align chat drawer with bottom of sticky nav.
var stickyNavBottom = _this30.stickyNavElem.getBoundingClientRect().bottom;
_this30.el.style.top = stickyNavBottom + "px";
_this30.el.style.height = "calc(100% - " + stickyNavBottom + "px)";
} else if (_this30.uhfHeaderElem && _this30.uhfHeaderElem.getBoundingClientRect().bottom > 0) {
// When the sticky nav transitions from desktop to mobile and is in unstuck, it aligns to the top of the viewport.
// If the UHF header is still in view, align the chat drawer to the bottom of the UHF header.
_this30.onScrollWithUhfVisible();
} else {
// Sticky nav went from stuck to unstuck. Align chat drawer to top of viewport.
_this30.el.style.top = 0;
_this30.el.style.height = '100%';
}
});
}
/**
* Code to run when the page is scrolled and the UHF header is visible. Align chat drawer with bottom of UHF header.
*/;
_proto.onScrollWithUhfVisible = function onScrollWithUhfVisible() {
var _this31 = this;
if (!this.uhfHeaderElem) {
return;
}
var ticking = false;
if (!ticking) {
window.requestAnimationFrame(function () {
var uhfHeaderBottom = _this31.uhfHeaderElem.getBoundingClientRect().bottom + uhfHeaderMarginBottomVal;
// At smaller viewports (<860px), the nav bar turns into a dropdown with position:absolute, and a margin-bottom is added to the header.
// Align the chat drawer below the dropdown to avoid overlapping the nav menu when it takes full width at VP1 (360px).
var marginBottom = parseFloat(window.getComputedStyle(_this31.uhfHeaderElem).marginBottom);
var totalUhfBottom = uhfHeaderBottom + marginBottom;
_this31.el.style.top = totalUhfBottom + "px";
_this31.el.style.height = "calc(100% - " + totalUhfBottom + "px)";
ticking = false;
});
ticking = true;
}
}
/**
* Code to run when the browser is resized, to adjust the chat drawer's position and related UI elements.
* - If the UHF header is visible, aligns the chat drawer with the bottom of the UHF header.
* - Toggles the UHF footer padding based on the chat button/drawer visibility.
*/;
_proto.onBrowserResize = function onBrowserResize() {
if (this.uhfHeaderIsVisible) {
// If the UHF header is visible, align chat drawer with bottom of UHF header
this.onScrollWithUhfVisible();
}
// Toggle the UHF footer bottom padding based on whether the chat is hidden or not
this.toggleUHFBottomPadding(this.mediaQueryListChatHidden.matches);
}
/**
* Code to run when the media query list for chat hidden changes. Toggle the UHF footer padding based on whether the chat is
* hidden or not.
*
* @param {MediaQueryListEvent} event - The media query list event
*/;
_proto.onMediaQueryListChatHiddenChange = function onMediaQueryListChatHiddenChange(event) {
this.toggleUHFBottomPadding(event.matches);
}
/**
* Handles changes to the media query list for modal dialog mode.
* Toggles modal dialog mode based on whether the media query matches.
*
* @param {MediaQueryListEvent} event - The event object representing the change in the media query list.
*/;
_proto.onMediaQueryListModalDialogChange = function onMediaQueryListModalDialogChange(event) {
if (event.matches) {
// If the media query matches, enter modal dialog mode
this.toggleModalDialogMode(true);
} else {
// If the media query does not match, exit modal dialog mode
this.toggleModalDialogMode(false);
}
}
/**
* Toggles the modal dialog mode for the AI Chat Drawer.
*
* If the drawer is open, this method will:
* - Add or remove the 'overflow-hidden' class on the body element based on the modal dialog mode.
* - Set the 'aria-modal' attribute on the drawer element to indicate modal or non-modal state.
* - Set or unset the 'inert' attribute on the drawer's sibling elements for accessibility.
*
* @param {boolean} isModalDialogMode - Whether to enable (true) or disable (false) modal dialog mode.
*/;
_proto.toggleModalDialogMode = function toggleModalDialogMode(isModalDialogMode) {
var isDrawerOpen = this.el.classList.contains(ClassName$q.SHOW);
if (!isDrawerOpen) {
// If the drawer is not open, set back to non-modal dialog mode
isModalDialogMode = false;
}
// Toggle overflow-hidden class on the body element
document.body.classList.toggle(ClassName$q.OVERFLOW_HIDDEN, isModalDialogMode);
// Toggle aria-modal to indicate that the AI Chat Drawer is a modal dialog or non-modal dialog
this.el.setAttribute('aria-modal', isModalDialogMode ? 'true' : 'false');
// Toggle AI Chat Drawer element siblings as inert
Util.toggleSiblingsInert(this.el, isModalDialogMode);
}
/**
* Toggles the visibility of the AI Chat Button component.
* If the Drawer is visibly suppressed, the chat button is not allowed to become visible by this method.
* @param {show} A boolean indicating whether to show or hide the chat button
*/;
_proto.showChatButton = function showChatButton(show) {
if (this.getIsHidden()) {
return; // Do not allow the chat button to be changed to a visible state if the AI Chat Drawer is visually suppressed
}
this.aiChatButton.classList.toggle(ClassName$q.DISPLAY_NONE, !show); // Do allow hiding it though, roflcopter
this.aiChatButton.hidden = !show;
}
/**
* Toggle the UHF footer padding based on whether the chat is hidden or not.
* @param {boolean} isHidden - Whether the chat is hidden or not
*/;
_proto.toggleUHFBottomPadding = function toggleUHFBottomPadding(isHidden) {
if (!this.uhfFooterElem) {
return;
}
this.uhfFooterElem.style.paddingBottom = isHidden ? this.uhfFooterOriginalPadding : this.aiChatButton.offsetHeight + "px";
}
/*
* Toggles the user text input and submit buttons for the WebChat
* @param {boolean} isDisabled - Whether to disable or enable the user text input and submit button
*/;
_proto.toggleWebChatUserTextBoxDisabled = function toggleWebChatUserTextBoxDisabled(isDisabled) {
if (!this.webChatInstance) {
return;
}
this.webChatForm.ariaDisabled = isDisabled;
this.webChatTextarea.ariaDisabled = isDisabled;
this.webChatTextarea.readOnly = isDisabled;
this.webChatSendButton.ariaDisabled = isDisabled;
}
/**
* Disable/Enable web chat elements.
* @param {boolean} isDisabled - Whether to disable or enable web chat elements
*/;
_proto.toggleWebChatDisabled = function toggleWebChatDisabled(isDisabled) {
this.toggleWebChatUserTextBoxDisabled(isDisabled);
// Toggle disabling all buttons in chat history
var actionSetButtons = this.webChatContainer.querySelectorAll(Selector$A.WEB_CHAT_ACTION_SET_BUTTONS);
for (var _iterator12 = _createForOfIteratorHelperLoose$6(actionSetButtons), _step12; !(_step12 = _iterator12()).done;) {
var _button$closest, _button$closest2;
var button = _step12.value;
var isStartLivePersonChatButton = ((_button$closest = button.closest(Selector$A.ARTICLE)) == null ? void 0 : _button$closest.querySelector(Selector$A.SEND_TRANSCRIPT_CHECKBOX_CONTAINER)) !== null;
var isDeflectionFlowButton = ((_button$closest2 = button.closest(Selector$A.ARTICLE)) == null ? void 0 : _button$closest2.querySelector(Selector$A.DEFLECTION_FLOW_ELEMENT)) !== null;
// Skip disabling/enabling "Continue" buttons that start a new chat with LivePerson or deflection flow buttons
if (isStartLivePersonChatButton || isDeflectionFlowButton) {
continue;
}
button.ariaDisabled = isDisabled;
button.classList.toggle(ClassName$q.DISABLED, isDisabled);
button.tabIndex = isDisabled ? -1 : 0;
}
// Update last focusable element in the chat drawer
if (isDisabled) {
var allFocusableDrawerElems = this.el.querySelectorAll(Selector$A.FOCUSABLE_ELEMENTS);
this.lastFocusableElem = allFocusableDrawerElems[allFocusableDrawerElems.length - 1];
} else {
this.lastFocusableElem = this.webChatSendButton;
}
}
/**
* Update the source site value. Dispatch a new activity to the bot with the updated source site value, and update cookies
* with the new source site. Wait for the source site update promise to resolve, then reset the source site update promise.
* @param {string} newSourceSite - The new source site value
*/;
_proto.updateSourceSite =
/*#__PURE__*/
function () {
var _updateSourceSite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(newSourceSite) {
var _this$updateAIChatDra6;
return _regeneratorRuntime().wrap(function _callee22$(_context22) {
while (1) {
switch (_context22.prev = _context22.next) {
case 0:
// Dispatch a new activity to the bot with the updated sourceSite value
this.store.dispatch({
type: 'DIRECT_LINE/POST_ACTIVITY',
meta: {
method: 'keyboard'
},
payload: {
activity: {
type: 'event',
name: 'sourceSiteEvent',
value: {
sourceSite: newSourceSite
},
channelData: {
postBack: true
}
}
}
});
// Update cookie with the new source site
this.updateAIChatDrawerCookie((_this$updateAIChatDra6 = {}, _this$updateAIChatDra6[StorageKeys.sourceSite] = newSourceSite, _this$updateAIChatDra6));
// Wait for the sourceSite update promise to resolve
_context22.next = 4;
return this.sourceSiteUpdatePromise;
case 4:
// Reset the sourceSite update promise
_classPrivateFieldLooseBase(this, _resetSourceSiteUpdatePromise)[_resetSourceSiteUpdatePromise]();
case 5:
case "end":
return _context22.stop();
}
}
}, _callee22, this);
}));
function updateSourceSite(_x27) {
return _updateSourceSite.apply(this, arguments);
}
return updateSourceSite;
}()
/**
* Get the AI Chat Drawer cookie object.
* @returns {Object | null} The AI Chat Drawer cookie object, or null if it cannot be parsed.
*/
;
_proto.getAIChatDrawerCookieObject = function getAIChatDrawerCookieObject() {
var cookieObj = null;
var cookieString = getCookie(StorageKeys.cookieName);
if (!cookieString) {
return null;
}
try {
cookieObj = JSON.parse(cookieString);
} catch (error) {
console.error('Failed to parse AI Chat Drawer cookie', error);
}
return cookieObj;
}
/**
* Update the AI Chat Drawer cookie with the new cookie object.
* @param {Object} newCookieObject The new cookie object to update the AI Chat Drawer cookie with.
*/;
_proto.updateAIChatDrawerCookie = function updateAIChatDrawerCookie(newCookieObject) {
var existingCookieObject = this.getAIChatDrawerCookieObject();
var updatedCookieObject = Object.assign({}, existingCookieObject, newCookieObject);
setCookie(StorageKeys.cookieName, JSON.stringify(updatedCookieObject), CookieConstants.expiryDays, CookieConstants.domain);
}
/**
* Delete the AI Chat Drawer cookie.
*/;
_proto.deleteAIChatDrawerCookie = function deleteAIChatDrawerCookie() {
// Set the Expiration to a negative value, so the browser auto-deletes the cookie.
setCookie(StorageKeys.cookieName, '', -1, CookieConstants.domain);
}
/**
* Remove event handlers.
* @this AIChatDrawer
*/;
_proto.remove = function remove() {
var _this$uhfHeaderInters, _this$stickyNavMutati, _this$webChatTranscri, _this$webChatTextarea, _this$lpMutationObser2;
// remove events, intersection observer, etc.
Util$1.removeEvents(this.events);
document.removeEventListener(EventName$A.SCROLL, this.boundOnScrollWithUhfVisible);
(_this$uhfHeaderInters = this.uhfHeaderIntersectionObserver) == null ? void 0 : _this$uhfHeaderInters.disconnect();
(_this$stickyNavMutati = this.stickyNavMutationObserver) == null ? void 0 : _this$stickyNavMutati.disconnect();
(_this$webChatTranscri = this.webChatTranscriptMutationObserver) == null ? void 0 : _this$webChatTranscri.disconnect();
(_this$webChatTextarea = this.webChatTextarea) == null ? void 0 : _this$webChatTextarea.removeEventListener(EventName$A.INPUT, this.handleLpUserInput);
(_this$lpMutationObser2 = this.lpMutationObserver) == null ? void 0 : _this$lpMutationObser2.disconnect();
// remove this reference from array of instances
var index = aiChatDrawers.indexOf(this);
aiChatDrawers.splice(index, 1);
// Create and dispatch custom event
this[EventName$A.ON_REMOVE] = new CustomEvent(EventName$A.ON_REMOVE, {
bubbles: true
});
this.el.dispatchEvent(this[EventName$A.ON_REMOVE]);
}
/**
* Get instances.
* @returns {Object} A object instance
*/;
AIChatDrawer.getInstances = function getInstances() {
return aiChatDrawers;
};
return AIChatDrawer;
}();
function _setDefaultValuesInMarkup2() {
// Update drawer title text
this.updateDrawerTitleText(this.drawerTitleText);
// Set header controls aria label
if (this.headerControls) {
this.headerControls.setAttribute('aria-label', this.closeButtonAriaLabel);
}
// Update el's aria label
this.el.setAttribute('aria-label', this.chatDrawerAriaLabel);
// Update chat button's default values
_classPrivateFieldLooseBase(this, _setDefaultValuesAiChatButton)[_setDefaultValuesAiChatButton]();
}
function _setDefaultValuesAiChatButton2() {
// Return if there is no click group
if (!this.aiChatButton) {
return;
}
// Update the default theme-day
if (!this.aiChatButton.classList.contains('theme-day') && !this.aiChatButton.classList.contains('theme-night')) {
this.aiChatButton.classList.add('theme-day');
}
// Update the floating button header text
if (this.aiChatButtonHeader && !this.aiChatButtonHeader.textContent) {
this.aiChatButtonHeader.textContent = this.buttonTitleText;
}
// Update the floating badge aria label
if (this.aiChatButtonAnchor && !this.aiChatButtonAnchor.getAttribute('aria-label')) {
this.aiChatButtonAnchor.setAttribute('aria-label', 'Expand AI-powered assistant chat dialog');
}
}
function _addEventHandlers2() {
var _this32 = this;
this.events = [];
var elementsToBind = [this.closeButton, this.uhfNavMenuExpandElem];
// Hide the chat drawer when the close button and UHF nav menu expand button (at mobile viewport) are clicked
elementsToBind.forEach(function (element) {
if (element) {
_this32.events.push({
el: element,
handler: _this32.chatClose.bind(_this32),
type: EventName$A.CLICK
});
}
});
if (this.aiChatButtonDataMount) {
this.events.push({
el: this.aiChatButtonDataMount,
handler: this.onAiChatButtonClick.bind(this),
type: EventName$A.CLICK
});
if (this.aiChatButtonDataMount.tagName !== 'BUTTON') {
this.events.push({
el: this.aiChatButtonDataMount,
handler: this.onAiChatButtonClick.bind(this),
type: EventName$A.KEYDOWN
});
}
}
if (!this.getIsHidden()) {
this.addChatActionTypeLinkEvents();
}
this.events.push({
el: this.el,
handler: this.onAIChatDrawerTransitionEnd.bind(this),
type: EventName$A.TRANSITION_END
}, {
el: this.el,
handler: this.onKeyDown.bind(this),
type: EventName$A.KEYDOWN
}, {
el: document,
handler: this.onDocumentKeyDown.bind(this),
type: EventName$A.KEYDOWN
}, {
el: window,
handler: this.onWebChatConnectFulfilled.bind(this),
type: EventName$A.WEBCHAT_CONNECT_FULFILLED
}, {
el: window,
handler: this.onStartConversationFulfilled.bind(this),
type: EventName$A.START_CONVERSATION_FULFILLED
}, {
el: window,
handler: debounce(this.debouncedResizeDelay, this.onBrowserResize.bind(this)),
type: EventName$A.RESIZE
}, {
el: this.mediaQueryListChatHidden,
handler: this.onMediaQueryListChatHiddenChange.bind(this),
type: EventName$A.CHANGE
}, {
el: this.mediaQueryListModalDialog,
handler: this.onMediaQueryListModalDialogChange.bind(this),
type: EventName$A.CHANGE
});
this.boundOnScrollWithUhfVisible = this.onScrollWithUhfVisible.bind(this);
Util$1.addEvents(this.events);
}
function _initUhfIntersectionObserver2() {
if (!this.uhfHeaderElem) {
return;
}
var options = {
rootMargin: "0px 0px " + uhfHeaderMarginBottomVal + "px 0px"
};
this.uhfHeaderIntersectionObserver = new IntersectionObserver(this.onUhfHeaderIntersect.bind(this), options);
this.uhfHeaderIntersectionObserver.observe(this.uhfHeaderElem);
}
function _initStickyNavMutationObserver2() {
if (!this.stickyNavElem) {
return;
}
var stickyParentElem = this.stickyNavElem.closest(Selector$A.STICKY);
this.stickyNavMutationObserver = new MutationObserver(this.onStickyNavMutation.bind(this));
this.stickyNavMutationObserver.observe(stickyParentElem, {
attributeFilter: ['class'],
attributeOldValue: true
});
}
function _initWebChatTranscriptObserver2() {
this.webChatTranscriptElem = this.el.querySelector(Selector$A.WEB_CHAT_TRANSCRIPT);
if (!this.webChatTranscriptElem) {
console.error('Web Chat transcript element not found.');
return;
}
this.webChatTranscriptMutationObserver = new MutationObserver(this.onWebChatTranscriptMutation.bind(this));
this.webChatTranscriptMutationObserver.observe(this.webChatTranscriptElem, {
subtree: true,
childList: true
});
}
function _positionAiChatButton2() {
if (!this.aiChatButton) {
return;
}
var uhfFooter = document.querySelector(Selector$A.UHF_FOOTER);
if (uhfFooter) {
// insert before the UHF footer
uhfFooter.insertAdjacentElement('beforebegin', this.aiChatButton);
this.showChatButton(true);
} else {
// insert before the closing body tag
document.body.insertAdjacentElement('beforeend', this.aiChatButton);
this.showChatButton(true);
}
}
function _positionAiChatDrawer2() {
var uhfFooter = document.querySelector(Selector$A.UHF_FOOTER);
if (uhfFooter) {
uhfFooter.insertAdjacentElement('beforebegin', this.el);
} else {
document.body.insertAdjacentElement('beforeend', this.el);
}
this.el.hidden = true;
}
function _resetSourceSiteUpdatePromise2() {
var _this33 = this;
this.sourceSiteUpdatePromise = new Promise(function (resolve) {
_this33.resolveSourceSiteUpdate = resolve;
});
}
function _regenerateAIChatDrawerToken2() {
return _regenerateAIChatDrawerToken3.apply(this, arguments);
}
function _regenerateAIChatDrawerToken3() {
_regenerateAIChatDrawerToken3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
return _regeneratorRuntime().wrap(function _callee23$(_context23) {
while (1) {
switch (_context23.prev = _context23.next) {
case 0:
this.deleteAIChatDrawerCookie();
_classPrivateFieldLooseBase(this, _generateDirectLineToken)[_generateDirectLineToken]();
case 2:
case "end":
return _context23.stop();
}
}
}, _callee23, this);
}));
return _regenerateAIChatDrawerToken3.apply(this, arguments);
}
function _generateDirectLineToken2() {
return _generateDirectLineToken3.apply(this, arguments);
}
function _generateDirectLineToken3() {
_generateDirectLineToken3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24() {
var token, cookieObj, _cookieObject, requestOptions, res, _yield$res$json, directLineToken, expiration, cookieObject;
return _regeneratorRuntime().wrap(function _callee24$(_context24) {
while (1) {
switch (_context24.prev = _context24.next) {
case 0:
token = null;
cookieObj = this.getAIChatDrawerCookieObject();
if (typeof cookieObj === 'object' && cookieObj !== null) {
token = cookieObj[StorageKeys.token];
}
_context24.prev = 3;
if (this.hasValidToken()) {
_context24.next = 18;
break;
}
requestOptions = {
method: 'GET',
redirect: 'follow',
headers: {
'ms-cv': window.mscv
}
};
_context24.next = 8;
return fetch(this.tokenEndpoint, requestOptions);
case 8:
res = _context24.sent;
_context24.next = 11;
return res.json();
case 11:
_yield$res$json = _context24.sent;
directLineToken = _yield$res$json.token;
expiration = _yield$res$json.expires_in;
token = directLineToken;
cookieObject = (_cookieObject = {}, _cookieObject[StorageKeys.token] = token, _cookieObject[StorageKeys.tokenCreated] = Date.now() / 1000, _cookieObject[StorageKeys.tuid] = this.tuid, _cookieObject[StorageKeys.lpOpenConvs] = {}, _cookieObject[StorageKeys.startLPChatActivityIds] = [], _cookieObject);
this.updateAIChatDrawerCookie(cookieObject);
_classPrivateFieldLooseBase(this, _setRefreshTimer)[_setRefreshTimer](expiration);
case 18:
return _context24.abrupt("return", token);
case 21:
_context24.prev = 21;
_context24.t0 = _context24["catch"](3);
console.error('Error generating Direct Line token:', _context24.t0);
clearTimeout(this.messageWaitTimeout);
this.toggleWebChatDisabled(false);
// Display generic error notification if possible
this.setNotification(NotificationLevel.ERROR, this.livePersonGenericErrorText);
// TODO if drawer is not open, any way to notify user that the AI Chat Drawer won't work, refresh?
case 27:
case "end":
return _context24.stop();
}
}
}, _callee24, this, [[3, 21]]);
}));
return _generateDirectLineToken3.apply(this, arguments);
}
function _refreshDirectLineToken2() {
return _refreshDirectLineToken3.apply(this, arguments);
}
function _refreshDirectLineToken3() {
_refreshDirectLineToken3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
var _cookieObject2, requestOptions, res, _yield$res$json2, directLineToken, expiration, cookieObject;
return _regeneratorRuntime().wrap(function _callee25$(_context25) {
while (1) {
switch (_context25.prev = _context25.next) {
case 0:
_context25.prev = 0;
requestOptions = {
method: 'POST',
redirect: 'follow',
headers: {
authorization: "Bearer " + this.getAIChatDrawerCookieObject()[StorageKeys.token]
}
};
_context25.next = 4;
return fetch(this.refreshTokenUrl, requestOptions);
case 4:
res = _context25.sent;
_context25.next = 7;
return res.json();
case 7:
_yield$res$json2 = _context25.sent;
directLineToken = _yield$res$json2.token;
expiration = _yield$res$json2.expires_in;
cookieObject = (_cookieObject2 = {}, _cookieObject2[StorageKeys.token] = directLineToken, _cookieObject2[StorageKeys.tokenCreated] = Date.now() / 1000, _cookieObject2[StorageKeys.tuid] = this.tuid, _cookieObject2);
this.updateAIChatDrawerCookie(cookieObject);
_classPrivateFieldLooseBase(this, _setRefreshTimer)[_setRefreshTimer](expiration);
_context25.next = 20;
break;
case 15:
_context25.prev = 15;
_context25.t0 = _context25["catch"](0);
console.error('Error refreshing Direct Line token:', _context25.t0);
clearTimeout(this.messageWaitTimeout);
this.toggleWebChatDisabled(false);
case 20:
case "end":
return _context25.stop();
}
}
}, _callee25, this, [[0, 15]]);
}));
return _refreshDirectLineToken3.apply(this, arguments);
}
function _setRefreshTimer2(expiration) {
var _this34 = this;
var computedExpiration = 0;
if (expiration > this.refreshBefore) {
computedExpiration = (expiration - this.refreshBefore) * 1000;
} else {
throw new Error('Error refreshing Direct Line Token.');
}
// Set a timeout to refresh the token x mins before it expires
setTimeout(function () {
return _classPrivateFieldLooseBase(_this34, _refreshDirectLineToken)[_refreshDirectLineToken]();
}, computedExpiration);
}
function _getLocale2() {
// if document.documentElement.lang is in format 'll-CC', return it
// if (document.documentElement.lang?.includes('-')) {
// return document.documentElement.lang;
// }
// return navigator.languages && navigator.languages.length
// ? navigator.languages[0]
// : navigator.language;
return 'en-US';
}
function _initializeJsonPollock2() {
return _initializeJsonPollock3.apply(this, arguments);
}
function _initializeJsonPollock3() {
_initializeJsonPollock3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26() {
return _regeneratorRuntime().wrap(function _callee26$(_context26) {
while (1) {
switch (_context26.prev = _context26.next) {
case 0:
_context26.prev = 0;
_context26.next = 3;
return Util.loadScript(jsonPollockScriptSrc, 'body');
case 3:
if (window.JsonPollock) {
_context26.next = 6;
break;
}
console.error('JsonPollock not found.');
return _context26.abrupt("return");
case 6:
window.JsonPollock.init({
maxAllowedElements: 200,
onAfterElementRendered: this.onAfterElementRenderedHandler
});
_context26.next = 12;
break;
case 9:
_context26.prev = 9;
_context26.t0 = _context26["catch"](0);
console.error('Error loading JsonPollock:', _context26.t0);
case 12:
case "end":
return _context26.stop();
}
}
}, _callee26, this, [[0, 9]]);
}));
return _initializeJsonPollock3.apply(this, arguments);
}
function _handlePageOpenState2() {
try {
var cookieObject = this.getAIChatDrawerCookieObject();
var lastState = cookieObject ? cookieObject[StorageKeys.chatDrawerState] : null;
var isMobileViewport = window.matchMedia("(max-width: " + (ViewPort.MD - 0.2) + "px)").matches;
// If at mobile viewport and the chat drawer is open, set lastState to 'CLOSED' to close the chat drawer on navigated page.
if (isMobileViewport && lastState === 'OPEN') {
var _this$updateAIChatDra7;
this.updateAIChatDrawerCookie((_this$updateAIChatDra7 = {}, _this$updateAIChatDra7[StorageKeys.chatDrawerState] = 'CLOSED', _this$updateAIChatDra7));
lastState = 'CLOSED';
}
var token = cookieObject ? cookieObject[StorageKeys.token] : null;
// If the cookie exists and is still valid for the Direct Line, refresh it
if (token) {
var cookieCreation = this.getAIChatDrawerCookieObject()[StorageKeys.tokenCreated];
var currentTime = Date.now() / 1000;
if (currentTime - cookieCreation < this.refreshAfter) {
_classPrivateFieldLooseBase(this, _refreshDirectLineToken)[_refreshDirectLineToken]();
}
}
if (this.isChatPersistEnabled && lastState === 'OPEN' && this.hasValidToken()) {
this.chatOpenOrInit();
}
} catch (error) {
console.error('Failed to get chat drawer state from cookies', error);
}
}
function _getSourceSite2() {
try {
var url = new URL(window.location.href);
var domain = url.hostname;
var path = url.pathname.split('/');
var langLoc = document.documentElement.lang.toLowerCase();
// find index of langLoc in path
var langLocIndex = -1;
// Map of language locales to possible source sites.
// Special cases for Serbian language locales.
var langLocs = {
'sr-rs': ['sr-rs', 'sr-latn-rs', 'sr-cyrl-rs'],
"default": [langLoc]
};
var possibleLangLocs = langLocs[langLoc] || langLocs["default"];
langLocIndex = possibleLangLocs.map(function (loc) {
return path.indexOf(loc);
}).find(function (index) {
return index > -1;
});
if (domain === 'azure.microsoft.com' || url.pathname.startsWith('/content/azure/acom')) {
return 'azure';
}
// Example: www.microsoft.com/fr-fr/isv/offer-benefits => isv
if (langLocIndex > -1 && path.length > langLocIndex + 1) {
var siteNameWithoutHtmlExtension = path[langLocIndex + 1].replace('.html', '');
return siteNameWithoutHtmlExtension;
}
} catch (error) {
console.error('Failed to get source site:', error);
}
return 'azure'; // fallback
}
function _getLPEndpoint2(baseEndpoint, path) {
// passing in path such as 'lp/check'
var endpointURL = new URL(baseEndpoint);
endpointURL.pathname = path;
return endpointURL.href;
}
function _getLivePersonIdFromJWT2() {
try {
var payload = JSON.parse(atob(this.lpJWT.split('.')[1]));
return payload.sub;
} catch (error) {
console.error('Error decoding JWT:', error);
return null;
}
}
// `SameValue` abstract operation
// https://tc39.es/ecma262/#sec-samevalue
// eslint-disable-next-line es/no-object-is -- safe
var sameValue$1 = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare -- NaN check
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
var call$4 = functionCall;
var fixRegExpWellKnownSymbolLogic = fixRegexpWellKnownSymbolLogic;
var anObject$3 = anObject$l;
var isNullOrUndefined$4 = isNullOrUndefined$b;
var requireObjectCoercible$1 = requireObjectCoercible$d;
var sameValue = sameValue$1;
var toString$5 = toString$j;
var getMethod$1 = getMethod$7;
var regExpExec = regexpExecAbstract;
// @@search logic
fixRegExpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCallNative) {
return [
// `String.prototype.search` method
// https://tc39.es/ecma262/#sec-string.prototype.search
function search(regexp) {
var O = requireObjectCoercible$1(this);
var searcher = isNullOrUndefined$4(regexp) ? undefined : getMethod$1(regexp, SEARCH);
return searcher ? call$4(searcher, regexp, O) : new RegExp(regexp)[SEARCH](toString$5(O));
},
// `RegExp.prototype[@@search]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@search
function (string) {
var rx = anObject$3(this);
var S = toString$5(string);
var res = maybeCallNative(nativeSearch, rx, S);
if (res.done) return res.value;
var previousLastIndex = rx.lastIndex;
if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
var result = regExpExec(rx, S);
if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
return result === null ? -1 : result.index;
}
];
});
var isObject$9 = isObject$o;
var floor$1 = Math.floor;
// `IsIntegralNumber` abstract operation
// https://tc39.es/ecma262/#sec-isintegralnumber
// eslint-disable-next-line es/no-number-isinteger -- safe
var isIntegralNumber$1 = Number.isInteger || function isInteger(it) {
return !isObject$9(it) && isFinite(it) && floor$1(it) === it;
};
var $$n = _export;
var isIntegralNumber = isIntegralNumber$1;
var abs = Math.abs;
// `Number.isSafeInteger` method
// https://tc39.es/ecma262/#sec-number.issafeinteger
$$n({ target: 'Number', stat: true }, {
isSafeInteger: function isSafeInteger(number) {
return isIntegralNumber(number) && abs(number) <= 0x1FFFFFFFFFFFFF;
}
});
var isCallable$4 = isCallable$u;
var isObject$8 = isObject$o;
var setPrototypeOf$1 = objectSetPrototypeOf;
// makes subclassing work correct for wrapped built-ins
var inheritIfRequired$3 = function ($this, dummy, Wrapper) {
var NewTarget, NewTargetPrototype;
if (
// it can work only with native `setPrototypeOf`
setPrototypeOf$1 &&
// we haven't completely correct pre-ES6 way for getting `new.target`, so use this
isCallable$4(NewTarget = dummy.constructor) &&
NewTarget !== Wrapper &&
isObject$8(NewTargetPrototype = NewTarget.prototype) &&
NewTargetPrototype !== Wrapper.prototype
) setPrototypeOf$1($this, NewTargetPrototype);
return $this;
};
var uncurryThis$d = functionUncurryThis;
// `thisNumberValue` abstract operation
// https://tc39.es/ecma262/#sec-thisnumbervalue
var thisNumberValue$2 = uncurryThis$d(1.0.valueOf);
var DESCRIPTORS$9 = descriptors;
var global$7 = global$B;
var uncurryThis$c = functionUncurryThis;
var isForced$2 = isForced_1;
var defineBuiltIn$4 = defineBuiltIn$i;
var hasOwn$8 = hasOwnProperty_1;
var inheritIfRequired$2 = inheritIfRequired$3;
var isPrototypeOf$3 = objectIsPrototypeOf;
var isSymbol$2 = isSymbol$5;
var toPrimitive = toPrimitive$2;
var fails$d = fails$J;
var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var defineProperty$5 = objectDefineProperty.f;
var thisNumberValue$1 = thisNumberValue$2;
var trim = stringTrim.trim;
var NUMBER = 'Number';
var NativeNumber = global$7[NUMBER];
var NumberPrototype = NativeNumber.prototype;
var TypeError$2 = global$7.TypeError;
var arraySlice$2 = uncurryThis$c(''.slice);
var charCodeAt$1 = uncurryThis$c(''.charCodeAt);
// `ToNumeric` abstract operation
// https://tc39.es/ecma262/#sec-tonumeric
var toNumeric = function (value) {
var primValue = toPrimitive(value, 'number');
return typeof primValue == 'bigint' ? primValue : toNumber(primValue);
};
// `ToNumber` abstract operation
// https://tc39.es/ecma262/#sec-tonumber
var toNumber = function (argument) {
var it = toPrimitive(argument, 'number');
var first, third, radix, maxCode, digits, length, index, code;
if (isSymbol$2(it)) throw TypeError$2('Cannot convert a Symbol value to a number');
if (typeof it == 'string' && it.length > 2) {
it = trim(it);
first = charCodeAt$1(it, 0);
if (first === 43 || first === 45) {
third = charCodeAt$1(it, 2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (charCodeAt$1(it, 1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
default: return +it;
}
digits = arraySlice$2(it, 2);
length = digits.length;
for (index = 0; index < length; index++) {
code = charCodeAt$1(digits, index);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
// `Number` constructor
// https://tc39.es/ecma262/#sec-number-constructor
if (isForced$2(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
var NumberWrapper = function Number(value) {
var n = arguments.length < 1 ? 0 : NativeNumber(toNumeric(value));
var dummy = this;
// check on 1..constructor(foo) case
return isPrototypeOf$3(NumberPrototype, dummy) && fails$d(function () { thisNumberValue$1(dummy); })
? inheritIfRequired$2(Object(n), dummy, NumberWrapper) : n;
};
for (var keys$1 = DESCRIPTORS$9 ? getOwnPropertyNames$1(NativeNumber) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES2015 (in case, if modules with ES2015 Number statics required before):
'EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,' +
// ESNext
'fromString,range'
).split(','), j = 0, key; keys$1.length > j; j++) {
if (hasOwn$8(NativeNumber, key = keys$1[j]) && !hasOwn$8(NumberWrapper, key)) {
defineProperty$5(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));
}
}
NumberWrapper.prototype = NumberPrototype;
NumberPrototype.constructor = NumberWrapper;
defineBuiltIn$4(global$7, NUMBER, NumberWrapper, { constructor: true });
}
var _EventName$ON_INIT$1, _EventName$ON_REFRESH, _EventName$ON_REMOVE$2, _EventName$ON_SELECT$1, _EventName$ON_UPDATE$2;
var cookieExpiryDays = 30;
var cookieKey = 'PMGSKUMarketCk';
/** @type {MarketSelector[]} */
var instances$r = [];
var queryParamKey = 'market';
/**
* CSS selector.
* @enum {string}
*/
var Selector$z = {
AFFECTED: '[data-oc-market-selector]',
DATA_MOUNT: '[data-mount="market-selector"]',
FW_LINKS: '[data-regenerate-fwlink="true"]',
SELECT_MENU: '.custom-select-input',
FW_LINKS_W365: '.oc-w365-fwlink'
};
/**
* JS event name.
* @enum {string}
*/
var EventName$z = {
ON_INIT: 'onInit',
ON_REFRESHED: 'onRefreshed',
ON_REMOVE: 'onRemove',
ON_SELECT: 'onSelect',
ON_UPDATE: 'onUpdate'
};
/**
* Handles change events on select menus.
* @this {MarketSelector} Parent component.
* @param {HTMLSelectElement} selectMenu Select element.
*/
function _change(selectMenu) {
if (selectMenu.selectedOptions.length) {
this.el.dispatchEvent(this[EventName$z.ON_SELECT]);
// update regenerating FWLinks, and add the information to On_Refreshed Event
this.fwlinkParams = selectMenu.selectedOptions[0].dataset.fwlinkParams;
this[EventName$z.ON_REFRESHED].detail.fwlinkParams = this.fwlinkParams;
_setFWLinksQueryParams(this.fwlinkParams);
_removeW365FwdLinkLcid();
_setMarket.call(this, selectMenu.selectedOptions[0].value);
}
}
/**
* Gets a set cookie value for the key provided, if available.
* @param {string} key Cookie key.
* @returns {string | null} Cookie value, or null.
*/
function _getCookie(key) {
var cookies = _getAllCookies();
if (cookies) {
var value = cookies[key];
if (value !== undefined) {
return value;
}
}
return null;
}
/**
* Gets all set cookie values, if available.
* @returns {Record | null} All cookie values.
*/
function _getAllCookies() {
/** @type {Record} */
var cookies = {};
document.cookie.split('; ').forEach(function (pair) {
var separatorIndex = pair.indexOf('=');
if (separatorIndex !== -1) {
var key = pair.slice(0, separatorIndex);
var value = decodeURIComponent(pair.slice(separatorIndex + 1));
cookies[key] = value;
}
});
if (Object.keys(cookies).length > 0) {
return cookies;
}
return null;
}
/**
* Gets the geodetected country code which was previously set by an edge-side include.
* @returns {string | null} Geodetected country code, or null.
*/
function _getGeoCountry() {
if (window.oc && window.oc.geo && window.oc.geo.country && typeof window.oc.geo.country === 'string') {
return window.oc.geo.country;
}
return null;
}
/**
* Updates all regenerating FWLinks href's to the option's designated query params.
* @param {string} queryParams
*/
function _setFWLinksQueryParams(queryParams) {
var fwLinks = document.querySelectorAll(Selector$z.FW_LINKS);
fwLinks.forEach(function (link) {
try {
var url = new URL(link.getAttribute('href'));
var searchParams = new URLSearchParams(queryParams);
var urlSearchParams = new URLSearchParams(url.search);
searchParams.forEach(function (key, value) {
urlSearchParams.set(value, key);
});
// 'clcid' is not a guaranteed part of the new Query Search Params. Delete this from the original fwlink's destination
// url if the