Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Created May 23, 2024 18:26
Show Gist options
  • Select an option

  • Save matthutchinson/7f64c0e9b50ff5514b48b516182068a6 to your computer and use it in GitHub Desktop.

Select an option

Save matthutchinson/7f64c0e9b50ff5514b48b516182068a6 to your computer and use it in GitHub Desktop.
1.2.3/twilio-conversations.js
This file has been truncated, but you can view the full file.
/*
@license
The following license applies to all parts of this software except as
documented below.
Copyright (c) 2019, Twilio, inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of Twilio nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software includes javascript-state-machine under the following license.
Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
This software includes loglevel under the following license.
Copyright (c) 2013 Tim Perry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
This software includes q under the following license.
Copyright 2009รขโ‚ฌโ€œ2014 Kristopher Michael Kowal. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
This software includes platform.js under the following license.
Copyright 2014 Benjamin Tan <https://d10.github.io/>
Copyright 2011-2015 John-David Dalton <http://allyoucanleet.com/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
this.Twilio = this.Twilio || {};
this.Twilio.Conversations = (function (exports) {
'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global$x =
// 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$x = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
var fails$w = fails$x;
// Detect IE8's incomplete defineProperty implementation
var descriptors = !fails$w(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
var objectPropertyIsEnumerable = {};
var $propertyIsEnumerable$1 = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$3 = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor$3 && !$propertyIsEnumerable$1.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$3(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable$1;
var createPropertyDescriptor$6 = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString$2 = {}.toString;
var classofRaw$1 = function (it) {
return toString$2.call(it).slice(8, -1);
};
var fails$v = fails$x;
var classof$9 = classofRaw$1;
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails$v(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof$9(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible$5 = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var IndexedObject$4 = indexedObject;
var requireObjectCoercible$4 = requireObjectCoercible$5;
var toIndexedObject$c = function (it) {
return IndexedObject$4(requireObjectCoercible$4(it));
};
var isObject$k = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
var isObject$j = isObject$k;
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive$6 = function (input, PREFERRED_STRING) {
if (!isObject$j(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject$j(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject$j(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject$j(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var requireObjectCoercible$3 = requireObjectCoercible$5;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
var toObject$g = function (argument) {
return Object(requireObjectCoercible$3(argument));
};
var toObject$f = toObject$g;
var hasOwnProperty = {}.hasOwnProperty;
var has$g = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty.call(toObject$f(it), key);
};
var global$w = global$x;
var isObject$i = isObject$k;
var document$3 = global$w.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject$i(document$3) && isObject$i(document$3.createElement);
var documentCreateElement$1 = function (it) {
return EXISTS ? document$3.createElement(it) : {};
};
var DESCRIPTORS$h = descriptors;
var fails$u = fails$x;
var createElement$1 = documentCreateElement$1;
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !DESCRIPTORS$h && !fails$u(function () {
// eslint-disable-next-line es/no-object-defineproperty -- requied for testing
return Object.defineProperty(createElement$1('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var DESCRIPTORS$g = descriptors;
var propertyIsEnumerableModule$2 = objectPropertyIsEnumerable;
var createPropertyDescriptor$5 = createPropertyDescriptor$6;
var toIndexedObject$b = toIndexedObject$c;
var toPrimitive$5 = toPrimitive$6;
var has$f = has$g;
var IE8_DOM_DEFINE$1 = ie8DomDefine;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
objectGetOwnPropertyDescriptor.f = DESCRIPTORS$g ? $getOwnPropertyDescriptor$1 : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject$b(O);
P = toPrimitive$5(P, true);
if (IE8_DOM_DEFINE$1) try {
return $getOwnPropertyDescriptor$1(O, P);
} catch (error) { /* empty */ }
if (has$f(O, P)) return createPropertyDescriptor$5(!propertyIsEnumerableModule$2.f.call(O, P), O[P]);
};
var objectDefineProperty = {};
var isObject$h = isObject$k;
var anObject$f = function (it) {
if (!isObject$h(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
var DESCRIPTORS$f = descriptors;
var IE8_DOM_DEFINE = ie8DomDefine;
var anObject$e = anObject$f;
var toPrimitive$4 = toPrimitive$6;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty$1 = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
objectDefineProperty.f = DESCRIPTORS$f ? $defineProperty$1 : function defineProperty(O, P, Attributes) {
anObject$e(O);
P = toPrimitive$4(P, true);
anObject$e(Attributes);
if (IE8_DOM_DEFINE) try {
return $defineProperty$1(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var DESCRIPTORS$e = descriptors;
var definePropertyModule$7 = objectDefineProperty;
var createPropertyDescriptor$4 = createPropertyDescriptor$6;
var createNonEnumerableProperty$d = DESCRIPTORS$e ? function (object, key, value) {
return definePropertyModule$7.f(object, key, createPropertyDescriptor$4(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var redefine$b = {exports: {}};
var global$v = global$x;
var createNonEnumerableProperty$c = createNonEnumerableProperty$d;
var setGlobal$3 = function (key, value) {
try {
createNonEnumerableProperty$c(global$v, key, value);
} catch (error) {
global$v[key] = value;
} return value;
};
var global$u = global$x;
var setGlobal$2 = setGlobal$3;
var SHARED = '__core-js_shared__';
var store$3 = global$u[SHARED] || setGlobal$2(SHARED, {});
var sharedStore = store$3;
var store$2 = sharedStore;
var functionToString = Function.toString;
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (typeof store$2.inspectSource != 'function') {
store$2.inspectSource = function (it) {
return functionToString.call(it);
};
}
var inspectSource$3 = store$2.inspectSource;
var global$t = global$x;
var inspectSource$2 = inspectSource$3;
var WeakMap$1 = global$t.WeakMap;
var nativeWeakMap = typeof WeakMap$1 === 'function' && /native code/.test(inspectSource$2(WeakMap$1));
var shared$5 = {exports: {}};
var store$1 = sharedStore;
(shared$5.exports = function (key, value) {
return store$1[key] || (store$1[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.15.2',
mode: 'global',
copyright: 'ร‚ยฉ 2021 Denis Pushkarev (zloirock.ru)'
});
var id$1 = 0;
var postfix = Math.random();
var uid$5 = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id$1 + postfix).toString(36);
};
var shared$4 = shared$5.exports;
var uid$4 = uid$5;
var keys$3 = shared$4('keys');
var sharedKey$4 = function (key) {
return keys$3[key] || (keys$3[key] = uid$4(key));
};
var hiddenKeys$6 = {};
var NATIVE_WEAK_MAP = nativeWeakMap;
var global$s = global$x;
var isObject$g = isObject$k;
var createNonEnumerableProperty$b = createNonEnumerableProperty$d;
var objectHas = has$g;
var shared$3 = sharedStore;
var sharedKey$3 = sharedKey$4;
var hiddenKeys$5 = hiddenKeys$6;
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var WeakMap = global$s.WeakMap;
var set$2, get$1, has$e;
var enforce = function (it) {
return has$e(it) ? get$1(it) : set$2(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject$g(it) || (state = get$1(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP || shared$3.state) {
var store = shared$3.state || (shared$3.state = new WeakMap());
var wmget = store.get;
var wmhas = store.has;
var wmset = store.set;
set$2 = function (it, metadata) {
if (wmhas.call(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
wmset.call(store, it, metadata);
return metadata;
};
get$1 = function (it) {
return wmget.call(store, it) || {};
};
has$e = function (it) {
return wmhas.call(store, it);
};
} else {
var STATE = sharedKey$3('state');
hiddenKeys$5[STATE] = true;
set$2 = function (it, metadata) {
if (objectHas(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty$b(it, STATE, metadata);
return metadata;
};
get$1 = function (it) {
return objectHas(it, STATE) ? it[STATE] : {};
};
has$e = function (it) {
return objectHas(it, STATE);
};
}
var internalState = {
set: set$2,
get: get$1,
has: has$e,
enforce: enforce,
getterFor: getterFor
};
var global$r = global$x;
var createNonEnumerableProperty$a = createNonEnumerableProperty$d;
var has$d = has$g;
var setGlobal$1 = setGlobal$3;
var inspectSource$1 = inspectSource$3;
var InternalStateModule$7 = internalState;
var getInternalState$7 = InternalStateModule$7.get;
var enforceInternalState = InternalStateModule$7.enforce;
var TEMPLATE = String(String).split('String');
(redefine$b.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
var state;
if (typeof value == 'function') {
if (typeof key == 'string' && !has$d(value, 'name')) {
createNonEnumerableProperty$a(value, 'name', key);
}
state = enforceInternalState(value);
if (!state.source) {
state.source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
}
if (O === global$r) {
if (simple) O[key] = value;
else setGlobal$1(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty$a(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState$7(this).source || inspectSource$1(this);
});
var global$q = global$x;
var path$2 = global$q;
var path$1 = path$2;
var global$p = global$x;
var aFunction$a = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
var getBuiltIn$7 = function (namespace, method) {
return arguments.length < 2 ? aFunction$a(path$1[namespace]) || aFunction$a(global$p[namespace])
: path$1[namespace] && path$1[namespace][method] || global$p[namespace] && global$p[namespace][method];
};
var objectGetOwnPropertyNames = {};
var ceil = Math.ceil;
var floor$5 = Math.floor;
// `ToInteger` abstract operation
// https://tc39.es/ecma262/#sec-tointeger
var toInteger$9 = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor$5 : ceil)(argument);
};
var toInteger$8 = toInteger$9;
var min$5 = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
var toLength$k = function (argument) {
return argument > 0 ? min$5(toInteger$8(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var toInteger$7 = toInteger$9;
var max$3 = Math.max;
var min$4 = 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$6 = function (index, length) {
var integer = toInteger$7(index);
return integer < 0 ? max$3(integer + length, 0) : min$4(integer, length);
};
var toIndexedObject$a = toIndexedObject$c;
var toLength$j = toLength$k;
var toAbsoluteIndex$5 = toAbsoluteIndex$6;
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod$5 = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject$a($this);
var length = toLength$j(O.length);
var index = toAbsoluteIndex$5(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$5(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod$5(false)
};
var has$c = has$g;
var toIndexedObject$9 = toIndexedObject$c;
var indexOf = arrayIncludes.indexOf;
var hiddenKeys$4 = hiddenKeys$6;
var objectKeysInternal = function (object, names) {
var O = toIndexedObject$9(object);
var i = 0;
var result = [];
var key;
for (key in O) !has$c(hiddenKeys$4, key) && has$c(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has$c(O, key = names[i++])) {
~indexOf(result, key) || result.push(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$6 = getBuiltIn$7;
var getOwnPropertyNamesModule$1 = objectGetOwnPropertyNames;
var getOwnPropertySymbolsModule$2 = objectGetOwnPropertySymbols;
var anObject$d = anObject$f;
// all object keys, includes non-enumerable and symbols
var ownKeys$3 = getBuiltIn$6('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule$1.f(anObject$d(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule$2.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
var has$b = has$g;
var ownKeys$2 = ownKeys$3;
var getOwnPropertyDescriptorModule$3 = objectGetOwnPropertyDescriptor;
var definePropertyModule$6 = objectDefineProperty;
var copyConstructorProperties$2 = function (target, source) {
var keys = ownKeys$2(source);
var defineProperty = definePropertyModule$6.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$3.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has$b(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var fails$t = fails$x;
var replacement = /#|\.prototype\./;
var isForced$4 = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails$t(detection)
: !!detection;
};
var normalize = isForced$4.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced$4.data = {};
var NATIVE = isForced$4.NATIVE = 'N';
var POLYFILL = isForced$4.POLYFILL = 'P';
var isForced_1 = isForced$4;
var global$o = global$x;
var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
var createNonEnumerableProperty$9 = createNonEnumerableProperty$d;
var redefine$a = redefine$b.exports;
var setGlobal = setGlobal$3;
var copyConstructorProperties$1 = copyConstructorProperties$2;
var isForced$3 = 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.noTargetGet - prevent calling a getter on target
*/
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$o;
} else if (STATIC) {
target = global$o[TARGET] || setGlobal(TARGET, {});
} else {
target = (global$o[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor$2(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced$3(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$9(sourceProperty, 'sham', true);
}
// extend global
redefine$a(target, key, sourceProperty, options);
}
};
var aFunction$9 = function (it) {
if (typeof it != 'function') {
throw TypeError(String(it) + ' is not a function');
} return it;
};
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$d = descriptors;
var definePropertyModule$5 = objectDefineProperty;
var anObject$c = anObject$f;
var objectKeys$3 = objectKeys$4;
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
var objectDefineProperties = DESCRIPTORS$d ? Object.defineProperties : function defineProperties(O, Properties) {
anObject$c(O);
var keys = objectKeys$3(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule$5.f(O, key = keys[index++], Properties[key]);
return O;
};
var getBuiltIn$5 = getBuiltIn$7;
var html$2 = getBuiltIn$5('document', 'documentElement');
var anObject$b = anObject$f;
var defineProperties = objectDefineProperties;
var enumBugKeys = enumBugKeys$3;
var hiddenKeys$2 = hiddenKeys$6;
var html$1 = html$2;
var documentCreateElement = documentCreateElement$1;
var sharedKey$2 = sharedKey$4;
var GT = '>';
var LT = '<';
var PROTOTYPE$2 = '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 {
/* global ActiveXObject -- old IE */
activeXDocument = document.domain && new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE$2][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys$2[IE_PROTO$1] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE$2] = anObject$b(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE$2] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO$1] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : defineProperties(result, Properties);
};
var aFunction$8 = aFunction$9;
var isObject$f = isObject$k;
var slice = [].slice;
var factories = {};
var construct = function (C, argsLength, args) {
if (!(argsLength in factories)) {
for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func -- we have no proper alternatives, IE8- only
factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
} return factories[argsLength](C, args);
};
// `Function.prototype.bind` method implementation
// https://tc39.es/ecma262/#sec-function.prototype.bind
var functionBind = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction$8(this);
var partArgs = slice.call(arguments, 1);
var boundFunction = function bound(/* args... */) {
var args = partArgs.concat(slice.call(arguments));
return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
};
if (isObject$f(fn.prototype)) boundFunction.prototype = fn.prototype;
return boundFunction;
};
var $$o = _export;
var getBuiltIn$4 = getBuiltIn$7;
var aFunction$7 = aFunction$9;
var anObject$a = anObject$f;
var isObject$e = isObject$k;
var create$6 = objectCreate;
var bind$7 = functionBind;
var fails$s = fails$x;
var nativeConstruct = getBuiltIn$4('Reflect', 'construct');
// `Reflect.construct` method
// https://tc39.es/ecma262/#sec-reflect.construct
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails$s(function () {
function F() { /* empty */ }
return !(nativeConstruct(function () { /* empty */ }, [], F) instanceof F);
});
var ARGS_BUG = !fails$s(function () {
nativeConstruct(function () { /* empty */ });
});
var FORCED$8 = NEW_TARGET_BUG || ARGS_BUG;
$$o({ target: 'Reflect', stat: true, forced: FORCED$8, sham: FORCED$8 }, {
construct: function construct(Target, args /* , newTarget */) {
aFunction$7(Target);
anObject$a(args);
var newTarget = arguments.length < 3 ? Target : aFunction$7(arguments[2]);
if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget);
if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
switch (args.length) {
case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind$7.apply(Target, $args))();
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype;
var instance = create$6(isObject$e(proto) ? proto : Object.prototype);
var result = Function.apply.call(Target, instance, args);
return isObject$e(result) ? result : instance;
}
});
var $$n = _export;
var toObject$e = toObject$g;
var nativeKeys = objectKeys$4;
var fails$r = fails$x;
var FAILS_ON_PRIMITIVES$1 = fails$r(function () { nativeKeys(1); });
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
$$n({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$1 }, {
keys: function keys(it) {
return nativeKeys(toObject$e(it));
}
});
var getBuiltIn$3 = getBuiltIn$7;
var engineUserAgent = getBuiltIn$3('navigator', 'userAgent') || '';
var global$n = global$x;
var userAgent$4 = engineUserAgent;
var process$3 = global$n.process;
var versions = process$3 && process$3.versions;
var v8 = versions && versions.v8;
var match, version$3;
if (v8) {
match = v8.split('.');
version$3 = match[0] < 4 ? 1 : match[0] + match[1];
} else if (userAgent$4) {
match = userAgent$4.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent$4.match(/Chrome\/(\d+)/);
if (match) version$3 = match[1];
}
}
var engineV8Version = version$3 && +version$3;
/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION$3 = engineV8Version;
var fails$q = fails$x;
// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails$q(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$2 = nativeSymbol;
var useSymbolAsUid = NATIVE_SYMBOL$2
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
var classof$8 = classofRaw$1;
// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
var isArray$4 = Array.isArray || function isArray(arg) {
return classof$8(arg) == 'Array';
};
var objectGetOwnPropertyNamesExternal = {};
/* eslint-disable es/no-object-getownpropertynames -- safe */
var toIndexedObject$8 = toIndexedObject$c;
var $getOwnPropertyNames$1 = objectGetOwnPropertyNames.f;
var toString$1 = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return $getOwnPropertyNames$1(it);
} catch (error) {
return windowNames.slice();
}
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
objectGetOwnPropertyNamesExternal.f = function getOwnPropertyNames(it) {
return windowNames && toString$1.call(it) == '[object Window]'
? getWindowNames(it)
: $getOwnPropertyNames$1(toIndexedObject$8(it));
};
var global$m = global$x;
var shared$2 = shared$5.exports;
var has$a = has$g;
var uid$3 = uid$5;
var NATIVE_SYMBOL$1 = nativeSymbol;
var USE_SYMBOL_AS_UID$1 = useSymbolAsUid;
var WellKnownSymbolsStore$1 = shared$2('wks');
var Symbol$1 = global$m.Symbol;
var createWellKnownSymbol = USE_SYMBOL_AS_UID$1 ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid$3;
var wellKnownSymbol$n = function (name) {
if (!has$a(WellKnownSymbolsStore$1, name) || !(NATIVE_SYMBOL$1 || typeof WellKnownSymbolsStore$1[name] == 'string')) {
if (NATIVE_SYMBOL$1 && has$a(Symbol$1, name)) {
WellKnownSymbolsStore$1[name] = Symbol$1[name];
} else {
WellKnownSymbolsStore$1[name] = createWellKnownSymbol('Symbol.' + name);
}
} return WellKnownSymbolsStore$1[name];
};
var wellKnownSymbolWrapped = {};
var wellKnownSymbol$m = wellKnownSymbol$n;
wellKnownSymbolWrapped.f = wellKnownSymbol$m;
var path = path$2;
var has$9 = has$g;
var wrappedWellKnownSymbolModule$1 = wellKnownSymbolWrapped;
var defineProperty$a = objectDefineProperty.f;
var defineWellKnownSymbol$2 = function (NAME) {
var Symbol = path.Symbol || (path.Symbol = {});
if (!has$9(Symbol, NAME)) defineProperty$a(Symbol, NAME, {
value: wrappedWellKnownSymbolModule$1.f(NAME)
});
};
var defineProperty$9 = objectDefineProperty.f;
var has$8 = has$g;
var wellKnownSymbol$l = wellKnownSymbol$n;
var TO_STRING_TAG$4 = wellKnownSymbol$l('toStringTag');
var setToStringTag$6 = function (it, TAG, STATIC) {
if (it && !has$8(it = STATIC ? it : it.prototype, TO_STRING_TAG$4)) {
defineProperty$9(it, TO_STRING_TAG$4, { configurable: true, value: TAG });
}
};
var aFunction$6 = aFunction$9;
// optional / simple context binding
var functionBindContext = function (fn, that, length) {
aFunction$6(fn);
if (that === undefined) return fn;
switch (length) {
case 0: return function () {
return fn.call(that);
};
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
var isObject$d = isObject$k;
var isArray$3 = isArray$4;
var wellKnownSymbol$k = wellKnownSymbol$n;
var SPECIES$6 = wellKnownSymbol$k('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate$3 = function (originalArray, length) {
var C;
if (isArray$3(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray$3(C.prototype))) C = undefined;
else if (isObject$d(C)) {
C = C[SPECIES$6];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var bind$6 = functionBindContext;
var IndexedObject$3 = indexedObject;
var toObject$d = toObject$g;
var toLength$i = toLength$k;
var arraySpeciesCreate$2 = arraySpeciesCreate$3;
var push = [].push;
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterOut }` methods implementation
var createMethod$4 = 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_OUT = TYPE == 7;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject$d($this);
var self = IndexedObject$3(O);
var boundFunction = bind$6(callbackfn, that, 3);
var length = toLength$i(self.length);
var index = 0;
var create = specificCreate || arraySpeciesCreate$2;
var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_OUT ? 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.call(target, value); // filter
} else switch (TYPE) {
case 4: return false; // every
case 7: push.call(target, value); // filterOut
}
}
}
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$4(0),
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map: createMethod$4(1),
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter: createMethod$4(2),
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some: createMethod$4(3),
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every: createMethod$4(4),
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find: createMethod$4(5),
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod$4(6),
// `Array.prototype.filterOut` method
// https://github.com/tc39/proposal-array-filtering
filterOut: createMethod$4(7)
};
var $$m = _export;
var global$l = global$x;
var getBuiltIn$2 = getBuiltIn$7;
var DESCRIPTORS$c = descriptors;
var NATIVE_SYMBOL = nativeSymbol;
var USE_SYMBOL_AS_UID = useSymbolAsUid;
var fails$p = fails$x;
var has$7 = has$g;
var isArray$2 = isArray$4;
var isObject$c = isObject$k;
var anObject$9 = anObject$f;
var toObject$c = toObject$g;
var toIndexedObject$7 = toIndexedObject$c;
var toPrimitive$3 = toPrimitive$6;
var createPropertyDescriptor$3 = createPropertyDescriptor$6;
var nativeObjectCreate = objectCreate;
var objectKeys$2 = objectKeys$4;
var getOwnPropertyNamesModule = objectGetOwnPropertyNames;
var getOwnPropertyNamesExternal = objectGetOwnPropertyNamesExternal;
var getOwnPropertySymbolsModule$1 = objectGetOwnPropertySymbols;
var getOwnPropertyDescriptorModule$2 = objectGetOwnPropertyDescriptor;
var definePropertyModule$4 = objectDefineProperty;
var propertyIsEnumerableModule$1 = objectPropertyIsEnumerable;
var createNonEnumerableProperty$8 = createNonEnumerableProperty$d;
var redefine$9 = redefine$b.exports;
var shared$1 = shared$5.exports;
var sharedKey$1 = sharedKey$4;
var hiddenKeys$1 = hiddenKeys$6;
var uid$2 = uid$5;
var wellKnownSymbol$j = wellKnownSymbol$n;
var wrappedWellKnownSymbolModule = wellKnownSymbolWrapped;
var defineWellKnownSymbol$1 = defineWellKnownSymbol$2;
var setToStringTag$5 = setToStringTag$6;
var InternalStateModule$6 = internalState;
var $forEach$2 = arrayIteration.forEach;
var HIDDEN = sharedKey$1('hidden');
var SYMBOL = 'Symbol';
var PROTOTYPE$1 = 'prototype';
var TO_PRIMITIVE = wellKnownSymbol$j('toPrimitive');
var setInternalState$6 = InternalStateModule$6.set;
var getInternalState$6 = InternalStateModule$6.getterFor(SYMBOL);
var ObjectPrototype$3 = Object[PROTOTYPE$1];
var $Symbol$1 = global$l.Symbol;
var $stringify = getBuiltIn$2('JSON', 'stringify');
var nativeGetOwnPropertyDescriptor$2 = getOwnPropertyDescriptorModule$2.f;
var nativeDefineProperty$1 = definePropertyModule$4.f;
var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;
var nativePropertyIsEnumerable = propertyIsEnumerableModule$1.f;
var AllSymbols = shared$1('symbols');
var ObjectPrototypeSymbols = shared$1('op-symbols');
var StringToSymbolRegistry = shared$1('string-to-symbol-registry');
var SymbolToStringRegistry = shared$1('symbol-to-string-registry');
var WellKnownSymbolsStore = shared$1('wks');
var QObject = global$l.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDescriptor = DESCRIPTORS$c && fails$p(function () {
return nativeObjectCreate(nativeDefineProperty$1({}, 'a', {
get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (O, P, Attributes) {
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$2(ObjectPrototype$3, P);
if (ObjectPrototypeDescriptor) delete ObjectPrototype$3[P];
nativeDefineProperty$1(O, P, Attributes);
if (ObjectPrototypeDescriptor && O !== ObjectPrototype$3) {
nativeDefineProperty$1(ObjectPrototype$3, P, ObjectPrototypeDescriptor);
}
} : nativeDefineProperty$1;
var wrap$1 = function (tag, description) {
var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol$1[PROTOTYPE$1]);
setInternalState$6(symbol, {
type: SYMBOL,
tag: tag,
description: description
});
if (!DESCRIPTORS$c) symbol.description = description;
return symbol;
};
var isSymbol = USE_SYMBOL_AS_UID ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return Object(it) instanceof $Symbol$1;
};
var $defineProperty = function defineProperty(O, P, Attributes) {
if (O === ObjectPrototype$3) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
anObject$9(O);
var key = toPrimitive$3(P, true);
anObject$9(Attributes);
if (has$7(AllSymbols, key)) {
if (!Attributes.enumerable) {
if (!has$7(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor$3(1, {}));
O[HIDDEN][key] = true;
} else {
if (has$7(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor$3(0, false) });
} return setSymbolDescriptor(O, key, Attributes);
} return nativeDefineProperty$1(O, key, Attributes);
};
var $defineProperties = function defineProperties(O, Properties) {
anObject$9(O);
var properties = toIndexedObject$7(Properties);
var keys = objectKeys$2(properties).concat($getOwnPropertySymbols(properties));
$forEach$2(keys, function (key) {
if (!DESCRIPTORS$c || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
});
return O;
};
var $create = function create(O, Properties) {
return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);
};
var $propertyIsEnumerable = function propertyIsEnumerable(V) {
var P = toPrimitive$3(V, true);
var enumerable = nativePropertyIsEnumerable.call(this, P);
if (this === ObjectPrototype$3 && has$7(AllSymbols, P) && !has$7(ObjectPrototypeSymbols, P)) return false;
return enumerable || !has$7(this, P) || !has$7(AllSymbols, P) || has$7(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
var it = toIndexedObject$7(O);
var key = toPrimitive$3(P, true);
if (it === ObjectPrototype$3 && has$7(AllSymbols, key) && !has$7(ObjectPrototypeSymbols, key)) return;
var descriptor = nativeGetOwnPropertyDescriptor$2(it, key);
if (descriptor && has$7(AllSymbols, key) && !(has$7(it, HIDDEN) && it[HIDDEN][key])) {
descriptor.enumerable = true;
}
return descriptor;
};
var $getOwnPropertyNames = function getOwnPropertyNames(O) {
var names = nativeGetOwnPropertyNames(toIndexedObject$7(O));
var result = [];
$forEach$2(names, function (key) {
if (!has$7(AllSymbols, key) && !has$7(hiddenKeys$1, key)) result.push(key);
});
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype$3;
var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject$7(O));
var result = [];
$forEach$2(names, function (key) {
if (has$7(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has$7(ObjectPrototype$3, key))) {
result.push(AllSymbols[key]);
}
});
return result;
};
// `Symbol` constructor
// https://tc39.es/ecma262/#sec-symbol-constructor
if (!NATIVE_SYMBOL) {
$Symbol$1 = function Symbol() {
if (this instanceof $Symbol$1) throw TypeError('Symbol is not a constructor');
var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
var tag = uid$2(description);
var setter = function (value) {
if (this === ObjectPrototype$3) setter.call(ObjectPrototypeSymbols, value);
if (has$7(this, HIDDEN) && has$7(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDescriptor(this, tag, createPropertyDescriptor$3(1, value));
};
if (DESCRIPTORS$c && USE_SETTER) setSymbolDescriptor(ObjectPrototype$3, tag, { configurable: true, set: setter });
return wrap$1(tag, description);
};
redefine$9($Symbol$1[PROTOTYPE$1], 'toString', function toString() {
return getInternalState$6(this).tag;
});
redefine$9($Symbol$1, 'withoutSetter', function (description) {
return wrap$1(uid$2(description), description);
});
propertyIsEnumerableModule$1.f = $propertyIsEnumerable;
definePropertyModule$4.f = $defineProperty;
getOwnPropertyDescriptorModule$2.f = $getOwnPropertyDescriptor;
getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;
getOwnPropertySymbolsModule$1.f = $getOwnPropertySymbols;
wrappedWellKnownSymbolModule.f = function (name) {
return wrap$1(wellKnownSymbol$j(name), name);
};
if (DESCRIPTORS$c) {
// https://github.com/tc39/proposal-Symbol-description
nativeDefineProperty$1($Symbol$1[PROTOTYPE$1], 'description', {
configurable: true,
get: function description() {
return getInternalState$6(this).description;
}
});
{
redefine$9(ObjectPrototype$3, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
}
}
}
$$m({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {
Symbol: $Symbol$1
});
$forEach$2(objectKeys$2(WellKnownSymbolsStore), function (name) {
defineWellKnownSymbol$1(name);
});
$$m({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {
// `Symbol.for` method
// https://tc39.es/ecma262/#sec-symbol.for
'for': function (key) {
var string = String(key);
if (has$7(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
var symbol = $Symbol$1(string);
StringToSymbolRegistry[string] = symbol;
SymbolToStringRegistry[symbol] = string;
return symbol;
},
// `Symbol.keyFor` method
// https://tc39.es/ecma262/#sec-symbol.keyfor
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
if (has$7(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
},
useSetter: function () { USE_SETTER = true; },
useSimple: function () { USE_SETTER = false; }
});
$$m({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS$c }, {
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
create: $create,
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
defineProperty: $defineProperty,
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
defineProperties: $defineProperties,
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor: $getOwnPropertyDescriptor
});
$$m({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames: $getOwnPropertyNames,
// `Object.getOwnPropertySymbols` method
// https://tc39.es/ecma262/#sec-object.getownpropertysymbols
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
$$m({ target: 'Object', stat: true, forced: fails$p(function () { getOwnPropertySymbolsModule$1.f(1); }) }, {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return getOwnPropertySymbolsModule$1.f(toObject$c(it));
}
});
// `JSON.stringify` method behavior with symbols
// https://tc39.es/ecma262/#sec-json.stringify
if ($stringify) {
var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails$p(function () {
var symbol = $Symbol$1();
// MS Edge converts symbol values to JSON as {}
return $stringify([symbol]) != '[null]'
// WebKit converts symbol values to JSON as null
|| $stringify({ a: symbol }) != '{}'
// V8 throws on boxed symbols
|| $stringify(Object(symbol)) != '{}';
});
$$m({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
stringify: function stringify(it, replacer, space) {
var args = [it];
var index = 1;
var $replacer;
while (arguments.length > index) args.push(arguments[index++]);
$replacer = replacer;
if (!isObject$c(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray$2(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return $stringify.apply(null, args);
}
});
}
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
if (!$Symbol$1[PROTOTYPE$1][TO_PRIMITIVE]) {
createNonEnumerableProperty$8($Symbol$1[PROTOTYPE$1], TO_PRIMITIVE, $Symbol$1[PROTOTYPE$1].valueOf);
}
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag$5($Symbol$1, SYMBOL);
hiddenKeys$1[HIDDEN] = true;
var fails$o = fails$x;
var wellKnownSymbol$i = wellKnownSymbol$n;
var V8_VERSION$2 = engineV8Version;
var SPECIES$5 = wellKnownSymbol$i('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$o(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$5] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var $$l = _export;
var $filter$1 = arrayIteration.filter;
var arrayMethodHasSpeciesSupport$4 = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport$4('filter');
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
$$l({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var $$k = _export;
var fails$n = fails$x;
var toIndexedObject$6 = toIndexedObject$c;
var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var DESCRIPTORS$b = descriptors;
var FAILS_ON_PRIMITIVES = fails$n(function () { nativeGetOwnPropertyDescriptor$1(1); });
var FORCED$7 = !DESCRIPTORS$b || FAILS_ON_PRIMITIVES;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
$$k({ target: 'Object', stat: true, forced: FORCED$7, sham: !DESCRIPTORS$b }, {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
return nativeGetOwnPropertyDescriptor$1(toIndexedObject$6(it), key);
}
});
var toPrimitive$2 = toPrimitive$6;
var definePropertyModule$3 = objectDefineProperty;
var createPropertyDescriptor$2 = createPropertyDescriptor$6;
var createProperty$5 = function (object, key, value) {
var propertyKey = toPrimitive$2(key);
if (propertyKey in object) definePropertyModule$3.f(object, propertyKey, createPropertyDescriptor$2(0, value));
else object[propertyKey] = value;
};
var $$j = _export;
var DESCRIPTORS$a = descriptors;
var ownKeys$1 = ownKeys$3;
var toIndexedObject$5 = toIndexedObject$c;
var getOwnPropertyDescriptorModule$1 = objectGetOwnPropertyDescriptor;
var createProperty$4 = createProperty$5;
// `Object.getOwnPropertyDescriptors` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
$$j({ target: 'Object', stat: true, sham: !DESCRIPTORS$a }, {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIndexedObject$5(object);
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$1.f;
var keys = ownKeys$1(O);
var result = {};
var index = 0;
var key, descriptor;
while (keys.length > index) {
descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
if (descriptor !== undefined) createProperty$4(result, key, descriptor);
}
return result;
}
});
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(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(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits$1(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof$2(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof$2 = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof$2 = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof$2(obj);
}
function _possibleConstructorReturn$1(self, call) {
if (call && (_typeof$2(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf$1(o) {
_getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf$1(o);
}
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined$1; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
} // Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype$3 = {};
IteratorPrototype$3[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype$3 = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype$3);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
prototype[method] = function (arg) {
return this._invoke(method, arg);
};
});
}
function isGeneratorFunction(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction" : false;
}
function mark(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
}
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
function awrap(arg) {
return {
__await: arg
};
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value && _typeof$2(value) === "object" && hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function (unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function (error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = // If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
} // Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
}; // Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
function async(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
} // Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done ? GenStateCompleted : GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted; // Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
} // Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
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 (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (!info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
} // The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
} // Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function () {
return this;
};
Gp.toString = function () {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (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) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{
tryLoc: "root"
}];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
function keys$2(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse(); // Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
} // To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined$1;
next.done = true;
return next;
};
return next.next = next;
}
} // Return an iterator with no values.
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined$1,
done: true
};
}
Context.prototype = {
constructor: Context,
reset: function reset(skipTempReset) {
this.prev = 0;
this.next = 0; // Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function stop() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function dispatchException(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined$1;
}
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function abrupt(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;
}
}
if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function complete(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" || record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function finish(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function _catch(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 (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
} // The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined$1;
}
return ContinueSentinel;
}
}; // Export a default namespace that plays well with Rollup
var _regeneratorRuntime = {
wrap: wrap,
isGeneratorFunction: isGeneratorFunction,
AsyncIterator: AsyncIterator,
mark: mark,
awrap: awrap,
async: async,
keys: keys$2,
values: values
};
// 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
};
var fails$m = fails$x;
var arrayMethodIsStrict$4 = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails$m(function () {
// eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing
method.call(null, argument || function () { throw 1; }, 1);
});
};
var $forEach$1 = arrayIteration.forEach;
var arrayMethodIsStrict$3 = arrayMethodIsStrict$4;
var STRICT_METHOD$3 = arrayMethodIsStrict$3('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.foreach
var arrayForEach = !STRICT_METHOD$3 ? 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 global$k = global$x;
var DOMIterables$1 = domIterables;
var forEach$1 = arrayForEach;
var createNonEnumerableProperty$7 = createNonEnumerableProperty$d;
for (var COLLECTION_NAME$1 in DOMIterables$1) {
var Collection$1 = global$k[COLLECTION_NAME$1];
var CollectionPrototype$1 = Collection$1 && Collection$1.prototype;
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype$1 && CollectionPrototype$1.forEach !== forEach$1) try {
createNonEnumerableProperty$7(CollectionPrototype$1, 'forEach', forEach$1);
} catch (error) {
CollectionPrototype$1.forEach = forEach$1;
}
}
var wellKnownSymbol$h = wellKnownSymbol$n;
var create$5 = objectCreate;
var definePropertyModule$2 = objectDefineProperty;
var UNSCOPABLES = wellKnownSymbol$h('unscopables');
var ArrayPrototype$1 = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype$1[UNSCOPABLES] == undefined) {
definePropertyModule$2.f(ArrayPrototype$1, UNSCOPABLES, {
configurable: true,
value: create$5(null)
});
}
// add a key to Array.prototype[@@unscopables]
var addToUnscopables$3 = function (key) {
ArrayPrototype$1[UNSCOPABLES][key] = true;
};
var iterators = {};
var fails$l = fails$x;
var correctPrototypeGetter = !fails$l(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 has$6 = has$g;
var toObject$b = toObject$g;
var sharedKey = sharedKey$4;
var CORRECT_PROTOTYPE_GETTER = correctPrototypeGetter;
var IE_PROTO = sharedKey('IE_PROTO');
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 ? Object.getPrototypeOf : function (O) {
O = toObject$b(O);
if (has$6(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectPrototype$2 : null;
};
var fails$k = fails$x;
var getPrototypeOf$4 = objectGetPrototypeOf;
var createNonEnumerableProperty$6 = createNonEnumerableProperty$d;
var has$5 = has$g;
var wellKnownSymbol$g = wellKnownSymbol$n;
var ITERATOR$6 = wellKnownSymbol$g('iterator');
var BUGGY_SAFARI_ITERATORS$1 = false;
var returnThis$2 = function () { return this; };
// `%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$4(getPrototypeOf$4(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = IteratorPrototype$2 == undefined || fails$k(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 (!has$5(IteratorPrototype$2, ITERATOR$6)) {
createNonEnumerableProperty$6(IteratorPrototype$2, ITERATOR$6, returnThis$2);
}
var iteratorsCore = {
IteratorPrototype: IteratorPrototype$2,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var create$4 = objectCreate;
var createPropertyDescriptor$1 = createPropertyDescriptor$6;
var setToStringTag$4 = setToStringTag$6;
var Iterators$4 = iterators;
var returnThis$1 = function () { return this; };
var createIteratorConstructor$1 = function (IteratorConstructor, NAME, next) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create$4(IteratorPrototype$1, { next: createPropertyDescriptor$1(1, next) });
setToStringTag$4(IteratorConstructor, TO_STRING_TAG, false);
Iterators$4[TO_STRING_TAG] = returnThis$1;
return IteratorConstructor;
};
var isObject$b = isObject$k;
var aPossiblePrototype$1 = function (it) {
if (!isObject$b(it) && it !== null) {
throw TypeError("Can't set " + String(it) + ' as a prototype');
} return it;
};
/* eslint-disable no-proto -- safe */
var anObject$8 = anObject$f;
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 = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
setter.call(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject$8(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter.call(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var $$i = _export;
var createIteratorConstructor = createIteratorConstructor$1;
var getPrototypeOf$3 = objectGetPrototypeOf;
var setPrototypeOf$6 = objectSetPrototypeOf;
var setToStringTag$3 = setToStringTag$6;
var createNonEnumerableProperty$5 = createNonEnumerableProperty$d;
var redefine$8 = redefine$b.exports;
var wellKnownSymbol$f = wellKnownSymbol$n;
var Iterators$3 = iterators;
var IteratorsCore = iteratorsCore;
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 defineIterator$3 = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(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$3(anyNativeIterator.call(new Iterable()));
if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (getPrototypeOf$3(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf$6) {
setPrototypeOf$6(CurrentIteratorPrototype, IteratorPrototype);
} else if (typeof CurrentIteratorPrototype[ITERATOR$5] != 'function') {
createNonEnumerableProperty$5(CurrentIteratorPrototype, ITERATOR$5, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag$3(CurrentIteratorPrototype, TO_STRING_TAG, true);
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return nativeIterator.call(this); };
}
// define iterator
if (IterablePrototype[ITERATOR$5] !== defaultIterator) {
createNonEnumerableProperty$5(IterablePrototype, ITERATOR$5, defaultIterator);
}
Iterators$3[NAME] = defaultIterator;
// 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)) {
redefine$8(IterablePrototype, KEY, methods[KEY]);
}
} else $$i({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
return methods;
};
var toIndexedObject$4 = toIndexedObject$c;
var addToUnscopables$2 = addToUnscopables$3;
var Iterators$2 = iterators;
var InternalStateModule$5 = internalState;
var defineIterator$2 = defineIterator$3;
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState$5 = InternalStateModule$5.set;
var getInternalState$5 = InternalStateModule$5.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$2(Array, 'Array', function (iterated, kind) {
setInternalState$5(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject$4(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState$5(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
Iterators$2.Arguments = Iterators$2.Array;
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables$2('keys');
addToUnscopables$2('values');
addToUnscopables$2('entries');
var wellKnownSymbol$e = wellKnownSymbol$n;
var TO_STRING_TAG$3 = wellKnownSymbol$e('toStringTag');
var test$2 = {};
test$2[TO_STRING_TAG$3] = 'z';
var toStringTagSupport = String(test$2) === '[object z]';
var TO_STRING_TAG_SUPPORT$2 = toStringTagSupport;
var classofRaw = classofRaw$1;
var wellKnownSymbol$d = wellKnownSymbol$n;
var TO_STRING_TAG$2 = wellKnownSymbol$d('toStringTag');
// 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$7 = 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(it), TO_STRING_TAG$2)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
};
var TO_STRING_TAG_SUPPORT$1 = toStringTagSupport;
var classof$6 = classof$7;
// `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$6(this) + ']';
};
var TO_STRING_TAG_SUPPORT = toStringTagSupport;
var redefine$7 = redefine$b.exports;
var toString = objectToString;
// `Object.prototype.toString` method
// https://tc39.es/ecma262/#sec-object.prototype.tostring
if (!TO_STRING_TAG_SUPPORT) {
redefine$7(Object.prototype, 'toString', toString, { unsafe: true });
}
var global$j = global$x;
var nativePromiseConstructor = global$j.Promise;
var redefine$6 = redefine$b.exports;
var redefineAll$3 = function (target, src, options) {
for (var key in src) redefine$6(target, key, src[key], options);
return target;
};
var getBuiltIn$1 = getBuiltIn$7;
var definePropertyModule$1 = objectDefineProperty;
var wellKnownSymbol$c = wellKnownSymbol$n;
var DESCRIPTORS$9 = descriptors;
var SPECIES$4 = wellKnownSymbol$c('species');
var setSpecies$4 = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn$1(CONSTRUCTOR_NAME);
var defineProperty = definePropertyModule$1.f;
if (DESCRIPTORS$9 && Constructor && !Constructor[SPECIES$4]) {
defineProperty(Constructor, SPECIES$4, {
configurable: true,
get: function () { return this; }
});
}
};
var anInstance$5 = function (it, Constructor, name) {
if (!(it instanceof Constructor)) {
throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
} return it;
};
var wellKnownSymbol$b = wellKnownSymbol$n;
var Iterators$1 = iterators;
var ITERATOR$4 = wellKnownSymbol$b('iterator');
var ArrayPrototype = Array.prototype;
// check on default Array iterator
var isArrayIteratorMethod$3 = function (it) {
return it !== undefined && (Iterators$1.Array === it || ArrayPrototype[ITERATOR$4] === it);
};
var classof$5 = classof$7;
var Iterators = iterators;
var wellKnownSymbol$a = wellKnownSymbol$n;
var ITERATOR$3 = wellKnownSymbol$a('iterator');
var getIteratorMethod$3 = function (it) {
if (it != undefined) return it[ITERATOR$3]
|| it['@@iterator']
|| Iterators[classof$5(it)];
};
var anObject$7 = anObject$f;
var iteratorClose$2 = function (iterator) {
var returnMethod = iterator['return'];
if (returnMethod !== undefined) {
return anObject$7(returnMethod.call(iterator)).value;
}
};
var anObject$6 = anObject$f;
var isArrayIteratorMethod$2 = isArrayIteratorMethod$3;
var toLength$h = toLength$k;
var bind$5 = functionBindContext;
var getIteratorMethod$2 = getIteratorMethod$3;
var iteratorClose$1 = iteratorClose$2;
var Result = function (stopped, result) {
this.stopped = stopped;
this.result = result;
};
var iterate$3 = function (iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = bind$5(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED);
var iterator, iterFn, index, length, result, next, step;
var stop = function (condition) {
if (iterator) iteratorClose$1(iterator);
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_ITERATOR) {
iterator = iterable;
} else {
iterFn = getIteratorMethod$2(iterable);
if (typeof iterFn != 'function') throw TypeError('Target is not iterable');
// optimisation for array iterators
if (isArrayIteratorMethod$2(iterFn)) {
for (index = 0, length = toLength$h(iterable.length); length > index; index++) {
result = callFn(iterable[index]);
if (result && result instanceof Result) return result;
} return new Result(false);
}
iterator = iterFn.call(iterable);
}
next = iterator.next;
while (!(step = next.call(iterator)).done) {
try {
result = callFn(step.value);
} catch (error) {
iteratorClose$1(iterator);
throw error;
}
if (typeof result == 'object' && result && result instanceof Result) return result;
} return new Result(false);
};
var wellKnownSymbol$9 = wellKnownSymbol$n;
var ITERATOR$2 = wellKnownSymbol$9('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR$2] = 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$4 = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR$2] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
var anObject$5 = anObject$f;
var aFunction$5 = aFunction$9;
var wellKnownSymbol$8 = wellKnownSymbol$n;
var SPECIES$3 = wellKnownSymbol$8('species');
// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
var speciesConstructor$5 = function (O, defaultConstructor) {
var C = anObject$5(O).constructor;
var S;
return C === undefined || (S = anObject$5(C)[SPECIES$3]) == undefined ? defaultConstructor : aFunction$5(S);
};
var userAgent$3 = engineUserAgent;
var engineIsIos = /(?:iphone|ipod|ipad).*applewebkit/i.test(userAgent$3);
var classof$4 = classofRaw$1;
var global$i = global$x;
var engineIsNode = classof$4(global$i.process) == 'process';
var global$h = global$x;
var fails$j = fails$x;
var bind$4 = functionBindContext;
var html = html$2;
var createElement = documentCreateElement$1;
var IS_IOS$1 = engineIsIos;
var IS_NODE$2 = engineIsNode;
var location = global$h.location;
var set$1 = global$h.setImmediate;
var clear = global$h.clearImmediate;
var process$2 = global$h.process;
var MessageChannel = global$h.MessageChannel;
var Dispatch = global$h.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function (id) {
// eslint-disable-next-line no-prototype-builtins -- safe
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[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$h.postMessage(id + '', location.protocol + '//' + location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set$1 || !clear) {
set$1 = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func -- spec requirement
(typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (IS_NODE$2) {
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$4(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global$h.addEventListener &&
typeof postMessage == 'function' &&
!global$h.importScripts &&
location && location.protocol !== 'file:' &&
!fails$j(post)
) {
defer = post;
global$h.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$1,
clear: clear
};
var userAgent$2 = engineUserAgent;
var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(userAgent$2);
var global$g = global$x;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var macrotask = task$1.set;
var IS_IOS = engineIsIos;
var IS_WEBOS_WEBKIT = engineIsWebosWebkit;
var IS_NODE$1 = engineIsNode;
var MutationObserver = global$g.MutationObserver || global$g.WebKitMutationObserver;
var document$2 = global$g.document;
var process$1 = global$g.process;
var Promise$1 = global$g.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor$1(global$g, '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$1 && (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$1 && !IS_WEBOS_WEBKIT && MutationObserver && document$2) {
toggle = true;
node = document$2.createTextNode('');
new MutationObserver(flush).observe(node, { characterData: true });
notify$1 = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (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 = promise.then;
notify$1 = function () {
then.call(promise, flush);
};
// Node.js without promises
} else if (IS_NODE$1) {
notify$1 = function () {
process$1.nextTick(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify$1 = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global$g, 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 newPromiseCapability$2 = {};
var aFunction$4 = aFunction$9;
var PromiseCapability = function (C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction$4(resolve);
this.reject = aFunction$4(reject);
};
// `NewPromiseCapability` abstract operation
// https://tc39.es/ecma262/#sec-newpromisecapability
newPromiseCapability$2.f = function (C) {
return new PromiseCapability(C);
};
var anObject$4 = anObject$f;
var isObject$a = isObject$k;
var newPromiseCapability$1 = newPromiseCapability$2;
var promiseResolve$1 = function (C, x) {
anObject$4(C);
if (isObject$a(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability$1.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
var global$f = global$x;
var hostReportErrors$1 = function (a, b) {
var console = global$f.console;
if (console && console.error) {
arguments.length === 1 ? console.error(a) : console.error(a, b);
}
};
var perform$1 = function (exec) {
try {
return { error: false, value: exec() };
} catch (error) {
return { error: true, value: error };
}
};
var engineIsBrowser = typeof window == 'object';
var $$h = _export;
var global$e = global$x;
var getBuiltIn = getBuiltIn$7;
var NativePromise = nativePromiseConstructor;
var redefine$5 = redefine$b.exports;
var redefineAll$2 = redefineAll$3;
var setPrototypeOf$5 = objectSetPrototypeOf;
var setToStringTag$2 = setToStringTag$6;
var setSpecies$3 = setSpecies$4;
var isObject$9 = isObject$k;
var aFunction$3 = aFunction$9;
var anInstance$4 = anInstance$5;
var inspectSource = inspectSource$3;
var iterate$2 = iterate$3;
var checkCorrectnessOfIteration$3 = checkCorrectnessOfIteration$4;
var speciesConstructor$4 = speciesConstructor$5;
var task = task$1.set;
var microtask = microtask$1;
var promiseResolve = promiseResolve$1;
var hostReportErrors = hostReportErrors$1;
var newPromiseCapabilityModule = newPromiseCapability$2;
var perform = perform$1;
var InternalStateModule$4 = internalState;
var isForced$2 = isForced_1;
var wellKnownSymbol$7 = wellKnownSymbol$n;
var IS_BROWSER = engineIsBrowser;
var IS_NODE = engineIsNode;
var V8_VERSION$1 = engineV8Version;
var SPECIES$2 = wellKnownSymbol$7('species');
var PROMISE = 'Promise';
var getInternalState$4 = InternalStateModule$4.get;
var setInternalState$4 = InternalStateModule$4.set;
var getInternalPromiseState = InternalStateModule$4.getterFor(PROMISE);
var NativePromisePrototype = NativePromise && NativePromise.prototype;
var PromiseConstructor = NativePromise;
var PromiseConstructorPrototype = NativePromisePrototype;
var TypeError$1 = global$e.TypeError;
var document$1 = global$e.document;
var process = global$e.process;
var newPromiseCapability = newPromiseCapabilityModule.f;
var newGenericPromiseCapability = newPromiseCapability;
var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && global$e.dispatchEvent);
var NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function';
var UNHANDLED_REJECTION = 'unhandledrejection';
var REJECTION_HANDLED = 'rejectionhandled';
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var SUBCLASSING = false;
var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
var FORCED$6 = isForced$2(PROMISE, function () {
var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(PromiseConstructor);
var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(PromiseConstructor);
// 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$1 === 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$1 >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false;
// Detect correctness of subclassing with @@species support
var promise = new PromiseConstructor(function (resolve) { resolve(1); });
var FakePromise = function (exec) {
exec(function () { /* empty */ }, function () { /* empty */ });
};
var constructor = promise.constructor = {};
constructor[SPECIES$2] = 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 && !NATIVE_REJECTION_EVENT;
});
var INCORRECT_ITERATION$1 = FORCED$6 || !checkCorrectnessOfIteration$3(function (iterable) {
PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
});
// helpers
var isThenable = function (it) {
var then;
return isObject$9(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (state, isReject) {
if (state.notified) return;
state.notified = true;
var chain = state.reactions;
microtask(function () {
var value = state.value;
var ok = state.state == FULFILLED;
var index = 0;
// variable length - can't use forEach
while (chain.length > index) {
var reaction = chain[index++];
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$1('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
}
state.reactions = [];
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$e.dispatchEvent(event);
} else event = { promise: promise, reason: reason };
if (!NATIVE_REJECTION_EVENT && (handler = global$e['on' + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
};
var onUnhandled = function (state) {
task.call(global$e, function () {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform(function () {
if (IS_NODE) {
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 || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function (state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function (state) {
task.call(global$e, function () {
var promise = state.facade;
if (IS_NODE) {
process.emit('rejectionHandled', promise);
} else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind$3 = 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$1("Promise can't be resolved itself");
var then = isThenable(value);
if (then) {
microtask(function () {
var wrapper = { done: false };
try {
then.call(value,
bind$3(internalResolve, wrapper, state),
bind$3(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$6) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise(executor) {
anInstance$4(this, PromiseConstructor, PROMISE);
aFunction$3(executor);
Internal.call(this);
var state = getInternalState$4(this);
try {
executor(bind$3(internalResolve, state), bind$3(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
PromiseConstructorPrototype = PromiseConstructor.prototype;
// eslint-disable-next-line no-unused-vars -- required for `.length`
Internal = function Promise(executor) {
setInternalState$4(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: [],
rejection: false,
state: PENDING,
value: undefined
});
};
Internal.prototype = redefineAll$2(PromiseConstructorPrototype, {
// `Promise.prototype.then` method
// https://tc39.es/ecma262/#sec-promise.prototype.then
then: function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability(speciesConstructor$4(this, PromiseConstructor));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = IS_NODE ? process.domain : undefined;
state.parent = true;
state.reactions.push(reaction);
if (state.state != PENDING) notify(state, false);
return reaction.promise;
},
// `Promise.prototype.catch` method
// https://tc39.es/ecma262/#sec-promise.prototype.catch
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
var state = getInternalState$4(promise);
this.promise = promise;
this.resolve = bind$3(internalResolve, state);
this.reject = bind$3(internalReject, state);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === PromiseConstructor || C === PromiseWrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
if (typeof NativePromise == 'function' && NativePromisePrototype !== Object.prototype) {
nativeThen = NativePromisePrototype.then;
if (!SUBCLASSING) {
// make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
redefine$5(NativePromisePrototype, 'then', function then(onFulfilled, onRejected) {
var that = this;
return new PromiseConstructor(function (resolve, reject) {
nativeThen.call(that, resolve, reject);
}).then(onFulfilled, onRejected);
// https://github.com/zloirock/core-js/issues/640
}, { unsafe: true });
// makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
redefine$5(NativePromisePrototype, 'catch', PromiseConstructorPrototype['catch'], { unsafe: true });
}
// make `.constructor === Promise` work for native promise-based APIs
try {
delete NativePromisePrototype.constructor;
} catch (error) { /* empty */ }
// make `instanceof Promise` work for native promise-based APIs
if (setPrototypeOf$5) {
setPrototypeOf$5(NativePromisePrototype, PromiseConstructorPrototype);
}
}
}
$$h({ global: true, wrap: true, forced: FORCED$6 }, {
Promise: PromiseConstructor
});
setToStringTag$2(PromiseConstructor, PROMISE, false);
setSpecies$3(PROMISE);
PromiseWrapper = getBuiltIn(PROMISE);
// statics
$$h({ target: PROMISE, stat: true, forced: FORCED$6 }, {
// `Promise.reject` method
// https://tc39.es/ecma262/#sec-promise.reject
reject: function reject(r) {
var capability = newPromiseCapability(this);
capability.reject.call(undefined, r);
return capability.promise;
}
});
$$h({ target: PROMISE, stat: true, forced: FORCED$6 }, {
// `Promise.resolve` method
// https://tc39.es/ecma262/#sec-promise.resolve
resolve: function resolve(x) {
return promiseResolve(this, x);
}
});
$$h({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, {
// `Promise.all` method
// https://tc39.es/ecma262/#sec-promise.all
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aFunction$3(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate$2(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
$promiseResolve.call(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;
},
// `Promise.race` method
// https://tc39.es/ecma262/#sec-promise.race
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aFunction$3(C.resolve);
iterate$2(iterable, function (promise) {
$promiseResolve.call(C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var toInteger$6 = toInteger$9;
var requireObjectCoercible$2 = requireObjectCoercible$5;
// `String.prototype.{ codePointAt, at }` methods implementation
var createMethod$3 = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = String(requireObjectCoercible$2($this));
var position = toInteger$6(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = S.charCodeAt(position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING ? S.charAt(position) : first
: CONVERT_TO_STRING ? S.slice(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$3(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod$3(true)
};
var charAt$1 = stringMultibyte.charAt;
var InternalStateModule$3 = internalState;
var defineIterator$1 = defineIterator$3;
var STRING_ITERATOR = 'String Iterator';
var setInternalState$3 = InternalStateModule$3.set;
var getInternalState$3 = InternalStateModule$3.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator$1(String, 'String', function (iterated) {
setInternalState$3(this, {
type: STRING_ITERATOR,
string: String(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState$3(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt$1(string, index);
state.index += point.length;
return { value: point, done: false };
});
var global$d = global$x;
var DOMIterables = domIterables;
var ArrayIteratorMethods = es_array_iterator;
var createNonEnumerableProperty$4 = createNonEnumerableProperty$d;
var wellKnownSymbol$6 = wellKnownSymbol$n;
var ITERATOR$1 = wellKnownSymbol$6('iterator');
var TO_STRING_TAG$1 = wellKnownSymbol$6('toStringTag');
var ArrayValues = ArrayIteratorMethods.values;
for (var COLLECTION_NAME in DOMIterables) {
var Collection = global$d[COLLECTION_NAME];
var CollectionPrototype = Collection && Collection.prototype;
if (CollectionPrototype) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[ITERATOR$1] !== ArrayValues) try {
createNonEnumerableProperty$4(CollectionPrototype, ITERATOR$1, ArrayValues);
} catch (error) {
CollectionPrototype[ITERATOR$1] = ArrayValues;
}
if (!CollectionPrototype[TO_STRING_TAG$1]) {
createNonEnumerableProperty$4(CollectionPrototype, TO_STRING_TAG$1, 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$4(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
} catch (error) {
CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
}
}
}
}
var DESCRIPTORS$8 = descriptors;
var fails$i = fails$x;
var objectKeys$1 = objectKeys$4;
var getOwnPropertySymbolsModule = objectGetOwnPropertySymbols;
var propertyIsEnumerableModule = objectPropertyIsEnumerable;
var toObject$a = toObject$g;
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$8 = Object.defineProperty;
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
var objectAssign = !$assign || fails$i(function () {
// should have correct order of operations (Edge bug)
if (DESCRIPTORS$8 && $assign({ b: 1 }, $assign(defineProperty$8({}, 'a', {
enumerable: true,
get: function () {
defineProperty$8(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$1($assign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
var T = toObject$a(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
var propertyIsEnumerable = propertyIsEnumerableModule.f;
while (argumentsLength > index) {
var S = IndexedObject$2(arguments[index++]);
var keys = getOwnPropertySymbols ? objectKeys$1(S).concat(getOwnPropertySymbols(S)) : objectKeys$1(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS$8 || propertyIsEnumerable.call(S, key)) T[key] = S[key];
}
} return T;
} : $assign;
var $$g = _export;
var assign = objectAssign;
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es/no-object-assign -- required for testing
$$g({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
assign: assign
});
var isObject$8 = isObject$k;
var setPrototypeOf$4 = 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$4 &&
// we haven't completely correct pre-ES6 way for getting `new.target`, so use this
typeof (NewTarget = dummy.constructor) == 'function' &&
NewTarget !== Wrapper &&
isObject$8(NewTargetPrototype = NewTarget.prototype) &&
NewTargetPrototype !== Wrapper.prototype
) setPrototypeOf$4($this, NewTargetPrototype);
return $this;
};
// a string of all valid unicode whitespaces
var whitespaces$1 = '\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 requireObjectCoercible$1 = requireObjectCoercible$5;
var whitespaces = whitespaces$1;
var whitespace = '[' + whitespaces + ']';
var ltrim = RegExp('^' + whitespace + whitespace + '*');
var rtrim = RegExp(whitespace + whitespace + '*$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod$2 = function (TYPE) {
return function ($this) {
var string = String(requireObjectCoercible$1($this));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
};
var stringTrim = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimstart
start: createMethod$2(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimend
end: createMethod$2(2),
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
trim: createMethod$2(3)
};
var DESCRIPTORS$7 = descriptors;
var global$c = global$x;
var isForced$1 = isForced_1;
var redefine$4 = redefine$b.exports;
var has$4 = has$g;
var classof$3 = classofRaw$1;
var inheritIfRequired$2 = inheritIfRequired$3;
var toPrimitive$1 = toPrimitive$6;
var fails$h = fails$x;
var create$3 = objectCreate;
var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var defineProperty$7 = objectDefineProperty.f;
var trim = stringTrim.trim;
var NUMBER = 'Number';
var NativeNumber = global$c[NUMBER];
var NumberPrototype = NativeNumber.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_CLASSOF = classof$3(create$3(NumberPrototype)) == NUMBER;
// `ToNumber` abstract operation
// https://tc39.es/ecma262/#sec-tonumber
var toNumber = function (argument) {
var it = toPrimitive$1(argument, false);
var first, third, radix, maxCode, digits, length, index, code;
if (typeof it == 'string' && it.length > 2) {
it = trim(it);
first = it.charCodeAt(0);
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(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 = it.slice(2);
length = digits.length;
for (index = 0; index < length; index++) {
code = digits.charCodeAt(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$1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
var NumberWrapper = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var dummy = this;
return dummy instanceof NumberWrapper
// check on 1..constructor(foo) case
&& (BROKEN_CLASSOF ? fails$h(function () { NumberPrototype.valueOf.call(dummy); }) : classof$3(dummy) != NUMBER)
? inheritIfRequired$2(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
};
for (var keys$1 = DESCRIPTORS$7 ? getOwnPropertyNames$2(NativeNumber) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES2015 (in case, if modules with ES2015 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' +
// ESNext
'fromString,range'
).split(','), j$1 = 0, key$1; keys$1.length > j$1; j$1++) {
if (has$4(NativeNumber, key$1 = keys$1[j$1]) && !has$4(NumberWrapper, key$1)) {
defineProperty$7(NumberWrapper, key$1, getOwnPropertyDescriptor(NativeNumber, key$1));
}
}
NumberWrapper.prototype = NumberPrototype;
NumberPrototype.constructor = NumberWrapper;
redefine$4(global$c, NUMBER, NumberWrapper);
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if ((typeof Reflect === "undefined" ? "undefined" : _typeof$2(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
}
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __metadata(metadataKey, metadataValue) {
if ((typeof Reflect === "undefined" ? "undefined" : _typeof$2(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
var domain$1;
// This constructor is used to store event handlers. Instantiating this is
// faster than explicitly calling `Object.create(null)` to get a "clean" empty
// object (tested with v8 v4.9).
function EventHandlers$1() {}
EventHandlers$1.prototype = Object.create(null);
function EventEmitter$1() {
EventEmitter$1.init.call(this);
}
// nodejs oddity
// require('events') === require('events').EventEmitter
EventEmitter$1.EventEmitter = EventEmitter$1;
EventEmitter$1.usingDomains = false;
EventEmitter$1.prototype.domain = undefined;
EventEmitter$1.prototype._events = undefined;
EventEmitter$1.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter$1.defaultMaxListeners = 10;
EventEmitter$1.init = function() {
this.domain = null;
if (EventEmitter$1.usingDomains) {
// if there is an active domain, then attach to it.
if (domain$1.active ) ;
}
if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
this._events = new EventHandlers$1();
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter$1.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || isNaN(n))
throw new TypeError('"n" argument must be a positive number');
this._maxListeners = n;
return this;
};
function $getMaxListeners$1(that) {
if (that._maxListeners === undefined)
return EventEmitter$1.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter$1.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners$1(this);
};
// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone$1(handler, isFn, self) {
if (isFn)
handler.call(self);
else {
var len = handler.length;
var listeners = arrayClone$1(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self);
}
}
function emitOne$1(handler, isFn, self, arg1) {
if (isFn)
handler.call(self, arg1);
else {
var len = handler.length;
var listeners = arrayClone$1(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1);
}
}
function emitTwo$1(handler, isFn, self, arg1, arg2) {
if (isFn)
handler.call(self, arg1, arg2);
else {
var len = handler.length;
var listeners = arrayClone$1(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1, arg2);
}
}
function emitThree$1(handler, isFn, self, arg1, arg2, arg3) {
if (isFn)
handler.call(self, arg1, arg2, arg3);
else {
var len = handler.length;
var listeners = arrayClone$1(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1, arg2, arg3);
}
}
function emitMany$1(handler, isFn, self, args) {
if (isFn)
handler.apply(self, args);
else {
var len = handler.length;
var listeners = arrayClone$1(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].apply(self, args);
}
}
EventEmitter$1.prototype.emit = function emit(type) {
var er, handler, len, args, i, events, domain;
var doError = (type === 'error');
events = this._events;
if (events)
doError = (doError && events.error == null);
else if (!doError)
return false;
domain = this.domain;
// If there is no 'error' event listener then throw.
if (doError) {
er = arguments[1];
if (domain) {
if (!er)
er = new Error('Uncaught, unspecified "error" event');
er.domainEmitter = this;
er.domain = domain;
er.domainThrown = false;
domain.emit('error', er);
} else if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
return false;
}
handler = events[type];
if (!handler)
return false;
var isFn = typeof handler === 'function';
len = arguments.length;
switch (len) {
// fast cases
case 1:
emitNone$1(handler, isFn, this);
break;
case 2:
emitOne$1(handler, isFn, this, arguments[1]);
break;
case 3:
emitTwo$1(handler, isFn, this, arguments[1], arguments[2]);
break;
case 4:
emitThree$1(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
break;
// slower
default:
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
emitMany$1(handler, isFn, this, args);
}
return true;
};
function _addListener$1(target, type, listener, prepend) {
var m;
var events;
var existing;
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
events = target._events;
if (!events) {
events = target._events = new EventHandlers$1();
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (!existing) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = prepend ? [listener, existing] :
[existing, listener];
} else {
// If we've already got an array, just append.
if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
}
// Check for listener leak
if (!existing.warned) {
m = $getMaxListeners$1(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + type + ' listeners added. ' +
'Use emitter.setMaxListeners() to increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
emitWarning$1(w);
}
}
}
return target;
}
function emitWarning$1(e) {
typeof console.warn === 'function' ? console.warn(e) : console.log(e);
}
EventEmitter$1.prototype.addListener = function addListener(type, listener) {
return _addListener$1(this, type, listener, false);
};
EventEmitter$1.prototype.on = EventEmitter$1.prototype.addListener;
EventEmitter$1.prototype.prependListener =
function prependListener(type, listener) {
return _addListener$1(this, type, listener, true);
};
function _onceWrap$1(target, type, listener) {
var fired = false;
function g() {
target.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(target, arguments);
}
}
g.listener = listener;
return g;
}
EventEmitter$1.prototype.once = function once(type, listener) {
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
this.on(type, _onceWrap$1(this, type, listener));
return this;
};
EventEmitter$1.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
this.prependListener(type, _onceWrap$1(this, type, listener));
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter$1.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
events = this._events;
if (!events)
return this;
list = events[type];
if (!list)
return this;
if (list === listener || (list.listener && list.listener === listener)) {
if (--this._eventsCount === 0)
this._events = new EventHandlers$1();
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list[0] = undefined;
if (--this._eventsCount === 0) {
this._events = new EventHandlers$1();
return this;
} else {
delete events[type];
}
} else {
spliceOne$1(list, position);
}
if (events.removeListener)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
// Alias for removeListener added in NodeJS 10.0
// https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
EventEmitter$1.prototype.off = function(type, listener){
return this.removeListener(type, listener);
};
EventEmitter$1.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events;
events = this._events;
if (!events)
return this;
// not listening for removeListener, no need to emit
if (!events.removeListener) {
if (arguments.length === 0) {
this._events = new EventHandlers$1();
this._eventsCount = 0;
} else if (events[type]) {
if (--this._eventsCount === 0)
this._events = new EventHandlers$1();
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
for (var i = 0, key; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = new EventHandlers$1();
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
do {
this.removeListener(type, listeners[listeners.length - 1]);
} while (listeners[0]);
}
return this;
};
EventEmitter$1.prototype.listeners = function listeners(type) {
var evlistener;
var ret;
var events = this._events;
if (!events)
ret = [];
else {
evlistener = events[type];
if (!evlistener)
ret = [];
else if (typeof evlistener === 'function')
ret = [evlistener.listener || evlistener];
else
ret = unwrapListeners$1(evlistener);
}
return ret;
};
EventEmitter$1.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount$1.call(emitter, type);
}
};
EventEmitter$1.prototype.listenerCount = listenerCount$1;
function listenerCount$1(type) {
var events = this._events;
if (events) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener) {
return evlistener.length;
}
}
return 0;
}
EventEmitter$1.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
};
// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne$1(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
list[i] = list[k];
list.pop();
}
function arrayClone$1(arr, i) {
var copy = new Array(i);
while (i--)
copy[i] = arr[i];
return copy;
}
function unwrapListeners$1(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
var _polyfillNode_events = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': EventEmitter$1,
EventEmitter: EventEmitter$1
});
var $$f = _export;
var fails$g = fails$x;
var isArray$1 = isArray$4;
var isObject$7 = isObject$k;
var toObject$9 = toObject$g;
var toLength$g = toLength$k;
var createProperty$3 = createProperty$5;
var arraySpeciesCreate$1 = arraySpeciesCreate$3;
var arrayMethodHasSpeciesSupport$3 = arrayMethodHasSpeciesSupport$5;
var wellKnownSymbol$5 = wellKnownSymbol$n;
var V8_VERSION = engineV8Version;
var IS_CONCAT_SPREADABLE = wellKnownSymbol$5('isConcatSpreadable');
var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
// 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 >= 51 || !fails$g(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport$3('concat');
var isConcatSpreadable = function (O) {
if (!isObject$7(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray$1(O);
};
var FORCED$5 = !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
$$f({ target: 'Array', proto: true, forced: FORCED$5 }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
concat: function concat(arg) {
var O = toObject$9(this);
var A = arraySpeciesCreate$1(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 = toLength$g(E.length);
if (n + len > MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty$3(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty$3(A, n++, E);
}
}
A.length = n;
return A;
}
});
var anObject$3 = anObject$f;
var iteratorClose = 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$3(value)[0], value[1]) : fn(value);
} catch (error) {
iteratorClose(iterator);
throw error;
}
};
var bind$2 = functionBindContext;
var toObject$8 = toObject$g;
var callWithSafeIterationClosing = callWithSafeIterationClosing$1;
var isArrayIteratorMethod$1 = isArrayIteratorMethod$3;
var toLength$f = toLength$k;
var createProperty$2 = createProperty$5;
var getIteratorMethod$1 = getIteratorMethod$3;
// `Array.from` method implementation
// https://tc39.es/ecma262/#sec-array.from
var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject$8(arrayLike);
var C = typeof this == 'function' ? this : Array;
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iteratorMethod = getIteratorMethod$1(O);
var index = 0;
var length, result, step, iterator, next, value;
if (mapping) mapfn = bind$2(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod$1(iteratorMethod))) {
iterator = iteratorMethod.call(O);
next = iterator.next;
result = new C();
for (;!(step = next.call(iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty$2(result, index, value);
}
} else {
length = toLength$f(O.length);
result = new C(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty$2(result, index, value);
}
}
result.length = index;
return result;
};
var $$e = _export;
var from = arrayFrom;
var checkCorrectnessOfIteration$2 = checkCorrectnessOfIteration$4;
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
$$e({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: from
});
var loglevel = {exports: {}};
(function (module) {
(function (root, definition) {
if (module.exports) {
module.exports = definition();
} else {
root.log = definition();
}
})(commonjsGlobal, function () {
var noop = function noop() {};
var undefinedType = "undefined";
var isIE = (typeof window === "undefined" ? "undefined" : _typeof$2(window)) !== undefinedType && _typeof$2(window.navigator) !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
var logMethods = ["trace", "debug", "info", "warn", "error"]; // Cross-browser bind equivalent that works at least back to IE6
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function () {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
} // Trace() doesn't print the message in IE, so for that case we need to wrap it
function traceForIE() {
if (console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
// In old IE, native console methods themselves don't have apply().
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
if (console.trace) console.trace();
} // Build the best logging method possible for this env
// Wherever possible we want to bind, not wrap, to preserve stack traces
function realMethod(methodName) {
if (methodName === 'debug') {
methodName = 'log';
}
if ((typeof console === "undefined" ? "undefined" : _typeof$2(console)) === undefinedType) {
return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
} else if (methodName === 'trace' && isIE) {
return traceForIE;
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
} // These private functions always need `this` to be set properly
function replaceLoggingMethods(level, loggerName) {
/*jshint validthis:true */
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = i < level ? noop : this.methodFactory(methodName, level, loggerName);
} // Define log.log as an alias for log.debug
this.log = this.debug;
} // In old IE versions, the console isn't present until you first open it.
// We build realMethod() replacements here that regenerate logging methods
function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
return function () {
if ((typeof console === "undefined" ? "undefined" : _typeof$2(console)) !== undefinedType) {
replaceLoggingMethods.call(this, level, loggerName);
this[methodName].apply(this, arguments);
}
};
} // By default, we use closely bound real methods wherever possible, and
// otherwise we wait for a console to appear, and then try again.
function defaultMethodFactory(methodName, level, loggerName) {
/*jshint validthis:true */
return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
}
function Logger(name, defaultLevel, factory) {
var self = this;
var currentLevel;
var storageKey = "loglevel";
if (typeof name === "string") {
storageKey += ":" + name;
} else if (_typeof$2(name) === "symbol") {
storageKey = undefined;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
if ((typeof window === "undefined" ? "undefined" : _typeof$2(window)) === undefinedType || !storageKey) return; // Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {} // Use session cookie as fallback
try {
window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
if ((typeof window === "undefined" ? "undefined" : _typeof$2(window)) === undefinedType || !storageKey) return;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {} // Fallback to cookies if local storage gives us nothing
if (_typeof$2(storedLevel) === undefinedType) {
try {
var cookie = window.document.cookie;
var location = cookie.indexOf(encodeURIComponent(storageKey) + "=");
if (location !== -1) {
storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
}
} catch (ignore) {}
} // If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
/*
*
* Public logger API - see https://github.com/pimterry/loglevel for details
*
*/
self.name = name;
self.levels = {
"TRACE": 0,
"DEBUG": 1,
"INFO": 2,
"WARN": 3,
"ERROR": 4,
"SILENT": 5
};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
return currentLevel;
};
self.setLevel = function (level, persist) {
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
currentLevel = level;
if (persist !== false) {
// defaults to true
persistLevelIfPossible(level);
}
replaceLoggingMethods.call(self, level, name);
if ((typeof console === "undefined" ? "undefined" : _typeof$2(console)) === undefinedType && level < self.levels.SILENT) {
return "No console available for logging";
}
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.setDefaultLevel = function (level) {
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.enableAll = function (persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function (persist) {
self.setLevel(self.levels.SILENT, persist);
}; // Initialize with the right level
var initialLevel = getPersistedLevel();
if (initialLevel == null) {
initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
}
self.setLevel(initialLevel, false);
}
/*
*
* Top-level API
*
*/
var defaultLogger = new Logger();
var _loggersByName = {};
defaultLogger.getLogger = function getLogger(name) {
if (_typeof$2(name) !== "symbol" && typeof name !== "string" || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(name, defaultLogger.getLevel(), defaultLogger.methodFactory);
}
return logger;
}; // Grab the current global log variable in case of overwrite
var _log = (typeof window === "undefined" ? "undefined" : _typeof$2(window)) !== undefinedType ? window.log : undefined;
defaultLogger.noConflict = function () {
if ((typeof window === "undefined" ? "undefined" : _typeof$2(window)) !== undefinedType && window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
defaultLogger.getLoggers = function getLoggers() {
return _loggersByName;
}; // ES6 default export, for compatibility
defaultLogger['default'] = defaultLogger;
return defaultLogger;
});
})(loglevel);
function prepareLine$4(prefix, args) {
return ["".concat(new Date().toISOString(), " Conversations ").concat(prefix, ":")].concat(Array.from(args));
}
var log$g = loglevel.exports.getLogger('twilio-conversations'); // twilio-conversations is used by Flex SDK. Please DO NOT change
var Logger$3 = /*#__PURE__*/function () {
function Logger(prefix) {
_classCallCheck$1(this, Logger);
_defineProperty$1(this, "prefix", '');
this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0 ? prefix + ' ' : '';
}
_createClass(Logger, [{
key: "setLevel",
value: function setLevel(level) {
log$g.setLevel(level);
}
}, {
key: "trace",
value: function trace() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
log$g.trace.apply(null, prepareLine$4(this.prefix + 'T', args));
}
}, {
key: "debug",
value: function debug() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
log$g.debug.apply(null, prepareLine$4(this.prefix + 'D', args));
}
}, {
key: "info",
value: function info() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
log$g.info.apply(null, prepareLine$4(this.prefix + 'I', args));
}
}, {
key: "warn",
value: function warn() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
log$g.warn.apply(null, prepareLine$4(this.prefix + 'W', args));
}
}, {
key: "error",
value: function error() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
log$g.error.apply(null, prepareLine$4(this.prefix + 'E', args));
}
}], [{
key: "scope",
value: function scope(prefix) {
return new Logger(prefix);
}
}, {
key: "setLevel",
value: function setLevel(level) {
log$g.setLevel(level);
}
}, {
key: "trace",
value: function trace() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
log$g.trace.apply(null, prepareLine$4('T', args));
}
}, {
key: "debug",
value: function debug() {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
log$g.debug.apply(null, prepareLine$4('D', args));
}
}, {
key: "info",
value: function info() {
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8];
}
log$g.info.apply(null, prepareLine$4('I', args));
}
}, {
key: "warn",
value: function warn() {
for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
args[_key9] = arguments[_key9];
}
log$g.warn.apply(null, prepareLine$4('W', args));
}
}, {
key: "error",
value: function error() {
for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
args[_key10] = arguments[_key10];
}
log$g.error.apply(null, prepareLine$4('E', args));
}
}]);
return Logger;
}();
var TYPING_PATH = '/v1/typing';
var TYPING_TIMEOUT = 5;
var HTTP_CACHE_LIFETIME = 'PT5S';
var CONSUMPTION_HORIZON_SENDING_INTERVAL = 'PT5S';
var USER_INFOS_TO_SUBSCRIBE = 100;
var MINIMUM_RETRY_DELAY$2 = 1000;
var MAXIMUM_RETRY_DELAY$2 = 4000;
var MAXIMUM_ATTEMPTS_COUNT$1 = 3;
var RETRY_WHEN_THROTTLED$1 = true;
var Configuration$4 = /*#__PURE__*/function () {
function Configuration(options) {
_classCallCheck$1(this, Configuration);
options = options || {};
var constructorOptions = options.Chat || options.IPMessaging || options || {};
this.region = constructorOptions.region || options.region;
this.baseUrl = constructorOptions.apiUri || constructorOptions.typingUri || (!this.region || this.region === 'us1' ? 'https://aim.twilio.com' : "https://aim.".concat(this.region, ".twilio.com"));
this.typingIndicatorUri = this.baseUrl + TYPING_PATH;
this.typingIndicatorTimeoutOverride = constructorOptions.typingIndicatorTimeoutOverride;
this.httpCacheIntervalOverride = constructorOptions.httpCacheIntervalOverride;
this.consumptionReportIntervalOverride = constructorOptions.consumptionReportIntervalOverride;
this.userInfosToSubscribeOverride = constructorOptions.userInfosToSubscribeOverride;
this.retryWhenThrottledOverride = constructorOptions.retryWhenThrottledOverride;
this.backoffConfigOverride = constructorOptions.backoffConfigOverride;
this.productId = options.productId;
}
_createClass(Configuration, [{
key: "typingIndicatorTimeoutDefault",
get: function get() {
return TYPING_TIMEOUT * 1000;
}
}, {
key: "httpCacheIntervalDefault",
get: function get() {
return HTTP_CACHE_LIFETIME;
}
}, {
key: "consumptionReportIntervalDefault",
get: function get() {
return CONSUMPTION_HORIZON_SENDING_INTERVAL;
}
}, {
key: "userInfosToSubscribeDefault",
get: function get() {
return USER_INFOS_TO_SUBSCRIBE;
}
}, {
key: "retryWhenThrottledDefault",
get: function get() {
return RETRY_WHEN_THROTTLED$1;
}
}, {
key: "backoffConfigDefault",
get: function get() {
return {
min: MINIMUM_RETRY_DELAY$2,
max: MAXIMUM_RETRY_DELAY$2,
maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT$1
};
}
}]);
return Configuration;
}();
var $$d = _export;
var $map$1 = arrayIteration.map;
var arrayMethodHasSpeciesSupport$2 = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport$2('map');
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
// with adding support of @@species
$$d({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, {
map: function map(callbackfn /* , thisArg */) {
return $map$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var anObject$2 = anObject$f;
// `RegExp.prototype.flags` getter implementation
// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
var regexpFlags$1 = function () {
var that = anObject$2(this);
var result = '';
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.sticky) result += 'y';
return result;
};
var regexpStickyHelpers = {};
var fails$f = fails$x;
// babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError,
var RE = function (s, f) {
return RegExp(s, f);
};
regexpStickyHelpers.UNSUPPORTED_Y = fails$f(function () {
var re = RE('a', 'y');
re.lastIndex = 2;
return re.exec('abcd') != null;
});
regexpStickyHelpers.BROKEN_CARET = fails$f(function () {
// https://bugzilla.mozilla.org/show_bug.cgi?id=773687
var re = RE('^r', 'gy');
re.lastIndex = 2;
return re.exec('str') != null;
});
var fails$e = fails$x;
var regexpUnsupportedDotAll = fails$e(function () {
// babel-minify transpiles RegExp('.', 's') -> /./s and it causes SyntaxError
var re = RegExp('.', (typeof '').charAt(0));
return !(re.dotAll && re.exec('\n') && re.flags === 's');
});
var fails$d = fails$x;
var regexpUnsupportedNcg = fails$d(function () {
// babel-minify transpiles RegExp('.', 'g') -> /./g and it causes SyntaxError
var re = RegExp('(?<a>b)', (typeof '').charAt(5));
return re.exec('b').groups.a !== 'b' ||
'b'.replace(re, '$<a>c') !== 'bc';
});
/* eslint-disable regexp/no-assertion-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */
/* eslint-disable regexp/no-useless-quantifier -- testing */
var regexpFlags = regexpFlags$1;
var stickyHelpers = regexpStickyHelpers;
var shared = shared$5.exports;
var create$2 = objectCreate;
var getInternalState$2 = internalState.get;
var UNSUPPORTED_DOT_ALL = regexpUnsupportedDotAll;
var UNSUPPORTED_NCG = regexpUnsupportedNcg;
var nativeExec = RegExp.prototype.exec;
var nativeReplace = shared('native-string-replace', String.prototype.replace);
var patchedExec = nativeExec;
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/;
var re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1.lastIndex !== 0 || re2.lastIndex !== 0;
})();
var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.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 || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG;
if (PATCH) {
// eslint-disable-next-line max-statements -- TODO
patchedExec = function exec(str) {
var re = this;
var state = getInternalState$2(re);
var raw = state.raw;
var result, reCopy, lastIndex, match, i, object, group;
if (raw) {
raw.lastIndex = re.lastIndex;
result = patchedExec.call(raw, str);
re.lastIndex = raw.lastIndex;
return result;
}
var groups = state.groups;
var sticky = UNSUPPORTED_Y && re.sticky;
var flags = regexpFlags.call(re);
var source = re.source;
var charsAdded = 0;
var strCopy = str;
if (sticky) {
flags = flags.replace('y', '');
if (flags.indexOf('g') === -1) {
flags += 'g';
}
strCopy = String(str).slice(re.lastIndex);
// Support anchored sticky behavior.
if (re.lastIndex > 0 && (!re.multiline || re.multiline && 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 = nativeExec.call(sticky ? reCopy : re, strCopy);
if (sticky) {
if (match) {
match.input = match.input.slice(charsAdded);
match[0] = match[0].slice(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' work for /(.?)?/
nativeReplace.call(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$2(null);
for (i = 0; i < groups.length; i++) {
group = groups[i];
object[group[0]] = match[group[1]];
}
}
return match;
};
}
var regexpExec$2 = patchedExec;
var $$c = _export;
var exec = regexpExec$2;
// `RegExp.prototype.exec` method
// https://tc39.es/ecma262/#sec-regexp.prototype.exec
$$c({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, {
exec: exec
});
// TODO: Remove from `core-js@4` since it's moved to entry points
var redefine$3 = redefine$b.exports;
var regexpExec$1 = regexpExec$2;
var fails$c = fails$x;
var wellKnownSymbol$4 = wellKnownSymbol$n;
var createNonEnumerableProperty$3 = createNonEnumerableProperty$d;
var SPECIES$1 = wellKnownSymbol$4('species');
var RegExpPrototype$1 = RegExp.prototype;
var fixRegexpWellKnownSymbolLogic = function (KEY, exec, FORCED, SHAM) {
var SYMBOL = wellKnownSymbol$4(KEY);
var DELEGATES_TO_SYMBOL = !fails$c(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$c(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$1] = 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 nativeRegExpMethod = /./[SYMBOL];
var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
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: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
});
redefine$3(String.prototype, KEY, methods[0]);
redefine$3(RegExpPrototype$1, SYMBOL, methods[1]);
}
if (SHAM) createNonEnumerableProperty$3(RegExpPrototype$1[SYMBOL], 'sham', true);
};
var charAt = stringMultibyte.charAt;
// `AdvanceStringIndex` abstract operation
// https://tc39.es/ecma262/#sec-advancestringindex
var advanceStringIndex$1 = function (S, index, unicode) {
return index + (unicode ? charAt(S, index).length : 1);
};
var toObject$7 = toObject$g;
var floor$4 = Math.floor;
var replace$1 = ''.replace;
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$1 = 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$7(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return replace$1.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor$4(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
};
var classof$2 = classofRaw$1;
var regexpExec = regexpExec$2;
// `RegExpExec` abstract operation
// https://tc39.es/ecma262/#sec-regexpexec
var regexpExecAbstract = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classof$2(R) !== 'RegExp') {
throw TypeError('RegExp#exec called on incompatible receiver');
}
return regexpExec.call(R, S);
};
var fixRegExpWellKnownSymbolLogic = fixRegexpWellKnownSymbolLogic;
var fails$b = fails$x;
var anObject$1 = anObject$f;
var toLength$e = toLength$k;
var toInteger$5 = toInteger$9;
var requireObjectCoercible = requireObjectCoercible$5;
var advanceStringIndex = advanceStringIndex$1;
var getSubstitution = getSubstitution$1;
var regExpExec = regexpExecAbstract;
var wellKnownSymbol$3 = wellKnownSymbol$n;
var REPLACE = wellKnownSymbol$3('replace');
var max$2 = Math.max;
var min$3 = Math.min;
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]) {
return /./[REPLACE]('a', '$0') === '';
}
return false;
})();
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails$b(function () {
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
// @@replace logic
fixRegExpWellKnownSymbolLogic('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(this);
var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
return replacer !== undefined
? replacer.call(searchValue, O, replaceValue)
: nativeReplace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
function (string, replaceValue) {
if (
typeof replaceValue === 'string' &&
replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1 &&
replaceValue.indexOf('$<') === -1
) {
var res = maybeCallNative(nativeReplace, this, string, replaceValue);
if (res.done) return res.value;
}
var rx = anObject$1(this);
var S = String(string);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regExpExec(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength$e(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max$2(min$3(toInteger$5(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++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
}, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);
var $$b = _export;
var IndexedObject$1 = indexedObject;
var toIndexedObject$3 = toIndexedObject$c;
var arrayMethodIsStrict$2 = arrayMethodIsStrict$4;
var nativeJoin = [].join;
var ES3_STRINGS = IndexedObject$1 != Object;
var STRICT_METHOD$2 = arrayMethodIsStrict$2('join', ',');
// `Array.prototype.join` method
// https://tc39.es/ecma262/#sec-array.prototype.join
$$b({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$2 }, {
join: function join(separator) {
return nativeJoin.call(toIndexedObject$3(this), separator === undefined ? ',' : separator);
}
});
var rfc6902 = {};
var pointer = {};
Object.defineProperty(pointer, "__esModule", {
value: true
});
pointer.Pointer = void 0;
/**
Unescape token part of a JSON Pointer string
`token` should *not* contain any '/' characters.
> Evaluation of each reference token begins by decoding any escaped
> character sequence. This is performed by first transforming any
> occurrence of the sequence '~1' to '/', and then transforming any
> occurrence of the sequence '~0' to '~'. By performing the
> substitutions in this order, an implementation avoids the error of
> turning '~01' first into '~1' and then into '/', which would be
> incorrect (the string '~01' correctly becomes '~1' after
> transformation).
Here's my take:
~1 is unescaped with higher priority than ~0 because it is a lower-order escape character.
I say "lower order" because '/' needs escaping due to the JSON Pointer serialization technique.
Whereas, '~' is escaped because escaping '/' uses the '~' character.
*/
function unescape(token) {
return token.replace(/~1/g, '/').replace(/~0/g, '~');
}
/** Escape token part of a JSON Pointer string
> '~' needs to be encoded as '~0' and '/'
> needs to be encoded as '~1' when these characters appear in a
> reference token.
This is the exact inverse of `unescape()`, so the reverse replacements must take place in reverse order.
*/
function escape(token) {
return token.replace(/~/g, '~0').replace(/\//g, '~1');
}
/**
JSON Pointer representation
*/
var Pointer =
/** @class */
function () {
function Pointer(tokens) {
if (tokens === void 0) {
tokens = [''];
}
this.tokens = tokens;
}
/**
`path` *must* be a properly escaped string.
*/
Pointer.fromJSON = function (path) {
var tokens = path.split('/').map(unescape);
if (tokens[0] !== '') throw new Error("Invalid JSON Pointer: " + path);
return new Pointer(tokens);
};
Pointer.prototype.toString = function () {
return this.tokens.map(escape).join('/');
};
/**
Returns an object with 'parent', 'key', and 'value' properties.
In the special case that this Pointer's path == "",
this object will be {parent: null, key: '', value: object}.
Otherwise, parent and key will have the property such that parent[key] == value.
*/
Pointer.prototype.evaluate = function (object) {
var parent = null;
var key = '';
var value = object;
for (var i = 1, l = this.tokens.length; i < l; i++) {
parent = value;
key = this.tokens[i]; // not sure if this the best way to handle non-existant paths...
value = (parent || {})[key];
}
return {
parent: parent,
key: key,
value: value
};
};
Pointer.prototype.get = function (object) {
return this.evaluate(object).value;
};
Pointer.prototype.set = function (object, value) {
var cursor = object;
for (var i = 1, l = this.tokens.length - 1, token = this.tokens[i]; i < l; i++) {
// not sure if this the best way to handle non-existant paths...
cursor = (cursor || {})[token];
}
if (cursor) {
cursor[this.tokens[this.tokens.length - 1]] = value;
}
};
Pointer.prototype.push = function (token) {
// mutable
this.tokens.push(token);
};
/**
`token` should be a String. It'll be coerced to one anyway.
immutable (shallowly)
*/
Pointer.prototype.add = function (token) {
var tokens = this.tokens.concat(String(token));
return new Pointer(tokens);
};
return Pointer;
}();
pointer.Pointer = Pointer;
var patch = {};
var util = {};
(function (exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clone = exports.objectType = exports.hasOwnProperty = void 0;
exports.hasOwnProperty = Object.prototype.hasOwnProperty;
function objectType(object) {
if (object === undefined) {
return 'undefined';
}
if (object === null) {
return 'null';
}
if (Array.isArray(object)) {
return 'array';
}
return _typeof$2(object);
}
exports.objectType = objectType;
/**
Recursively copy a value.
@param source - should be a JavaScript primitive, Array, or (plain old) Object.
@returns copy of source where every Array and Object have been recursively
reconstructed from their constituent elements
*/
function clone(source) {
// loose-equality checking for null is faster than strict checking for each of null/undefined/true/false
// checking null first, then calling typeof, is faster than vice-versa
if (source == null || _typeof$2(source) != 'object') {
// short-circuiting is faster than a single return
return source;
} // x.constructor == Array is the fastest way to check if x is an Array
if (source.constructor == Array) {
// construction via imperative for-loop is faster than source.map(arrayVsObject)
var length_1 = source.length; // setting the Array length during construction is faster than just `[]` or `new Array()`
var arrayTarget = new Array(length_1);
for (var i = 0; i < length_1; i++) {
arrayTarget[i] = clone(source[i]);
}
return arrayTarget;
} // Object
var objectTarget = {}; // declaring the variable (with const) inside the loop is faster
for (var key in source) {
// hasOwnProperty costs a bit of performance, but it's semantically necessary
// using a global helper is MUCH faster than calling source.hasOwnProperty(key)
if (exports.hasOwnProperty.call(source, key)) {
objectTarget[key] = clone(source[key]);
}
}
return objectTarget;
}
exports.clone = clone;
})(util);
var equal = {};
Object.defineProperty(equal, "__esModule", {
value: true
});
equal.compare = void 0;
var util_1$2 = util;
/**
Evaluate `left === right`, treating `left` and `right` as ordered lists.
@returns true iff `left` and `right` have identical lengths, and every element
of `left` is equal to the corresponding element of `right`. Equality is
determined recursivly, via `compare`.
*/
function compareArrays(left, right) {
var length = left.length;
if (length !== right.length) {
return false;
}
for (var i = 0; i < length; i++) {
if (!compare(left[i], right[i])) {
return false;
}
}
return true;
}
/**
Evaluate `left === right`, treating `left` and `right` as property maps.
@returns true iff every property in `left` has a value equal to the value of the
corresponding property in `right`, and vice-versa, stopping as soon as
possible. Equality is determined recursivly, via `compare`.
*/
function compareObjects(left, right) {
var left_keys = Object.keys(left);
var right_keys = Object.keys(right);
var length = left_keys.length; // quick exit if the number of keys don't match up
if (length !== right_keys.length) {
return false;
} // we don't know for sure that Set(left_keys) is equal to Set(right_keys),
// much less that their values in left and right are equal, but if right
// contains each key in left, we know it can't have any additional keys
for (var i = 0; i < length; i++) {
var key = left_keys[i];
if (!util_1$2.hasOwnProperty.call(right, key) || !compare(left[key], right[key])) {
return false;
}
}
return true;
}
/**
`compare()` returns true if `left` and `right` are materially equal
(i.e., would produce equivalent JSON), false otherwise.
> Here, "equal" means that the value at the target location and the
> value conveyed by "value" are of the same JSON type, and that they
> are considered equal by the following rules for that type:
> o strings: are considered equal if they contain the same number of
> Unicode characters and their code points are byte-by-byte equal.
> o numbers: are considered equal if their values are numerically
> equal.
> o arrays: are considered equal if they contain the same number of
> values, and if each value can be considered equal to the value at
> the corresponding position in the other array, using this list of
> type-specific rules.
> o objects: are considered equal if they contain the same number of
> members, and if each member can be considered equal to a member in
> the other object, by comparing their keys (as strings) and their
> values (using this list of type-specific rules).
> o literals (false, true, and null): are considered equal if they are
> the same.
*/
function compare(left, right) {
// strict equality handles literals, numbers, and strings (a sufficient but not necessary cause)
if (left === right) {
return true;
}
var left_type = util_1$2.objectType(left);
var right_type = util_1$2.objectType(right); // check arrays
if (left_type == 'array' && right_type == 'array') {
return compareArrays(left, right);
} // check objects
if (left_type == 'object' && right_type == 'object') {
return compareObjects(left, right);
} // mismatched arrays & objects, etc., are always inequal
return false;
}
equal.compare = compare;
var __extends = commonjsGlobal && commonjsGlobal.__extends || function () {
var _extendStatics = function extendStatics(d, b) {
_extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) {
if (b.hasOwnProperty(p)) d[p] = b[p];
}
};
return _extendStatics(d, b);
};
return function (d, b) {
_extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
Object.defineProperty(patch, "__esModule", {
value: true
});
patch.apply = patch.InvalidOperationError = patch.test = patch.copy = patch.move = patch.replace = patch.remove = patch.add = patch.TestError = patch.MissingError = void 0;
var pointer_1$1 = pointer;
var util_1$1 = util;
var equal_1$1 = equal;
var MissingError =
/** @class */
function (_super) {
__extends(MissingError, _super);
function MissingError(path) {
var _this = _super.call(this, "Value required at path: " + path) || this;
_this.path = path;
_this.name = 'MissingError';
return _this;
}
return MissingError;
}(Error);
patch.MissingError = MissingError;
var TestError =
/** @class */
function (_super) {
__extends(TestError, _super);
function TestError(actual, expected) {
var _this = _super.call(this, "Test failed: " + actual + " != " + expected) || this;
_this.actual = actual;
_this.expected = expected;
_this.name = 'TestError';
return _this;
}
return TestError;
}(Error);
patch.TestError = TestError;
function _add(object, key, value) {
if (Array.isArray(object)) {
// `key` must be an index
if (key == '-') {
object.push(value);
} else {
var index = parseInt(key, 10);
object.splice(index, 0, value);
}
} else {
object[key] = value;
}
}
function _remove(object, key) {
if (Array.isArray(object)) {
// '-' syntax doesn't make sense when removing
var index = parseInt(key, 10);
object.splice(index, 1);
} else {
// not sure what the proper behavior is when path = ''
delete object[key];
}
}
/**
> o If the target location specifies an array index, a new value is
> inserted into the array at the specified index.
> o If the target location specifies an object member that does not
> already exist, a new member is added to the object.
> o If the target location specifies an object member that does exist,
> that member's value is replaced.
*/
function add(object, operation) {
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object); // it's not exactly a "MissingError" in the same way that `remove` is -- more like a MissingParent, or something
if (endpoint.parent === undefined) {
return new MissingError(operation.path);
}
_add(endpoint.parent, endpoint.key, util_1$1.clone(operation.value));
return null;
}
patch.add = add;
/**
> The "remove" operation removes the value at the target location.
> The target location MUST exist for the operation to be successful.
*/
function remove(object, operation) {
// endpoint has parent, key, and value properties
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object);
if (endpoint.value === undefined) {
return new MissingError(operation.path);
} // not sure what the proper behavior is when path = ''
_remove(endpoint.parent, endpoint.key);
return null;
}
patch.remove = remove;
/**
> The "replace" operation replaces the value at the target location
> with a new value. The operation object MUST contain a "value" member
> whose content specifies the replacement value.
> The target location MUST exist for the operation to be successful.
> This operation is functionally identical to a "remove" operation for
> a value, followed immediately by an "add" operation at the same
> location with the replacement value.
Even more simply, it's like the add operation with an existence check.
*/
function replace(object, operation) {
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object);
if (endpoint.parent === null) {
return new MissingError(operation.path);
} // this existence check treats arrays as a special case
if (Array.isArray(endpoint.parent)) {
if (parseInt(endpoint.key, 10) >= endpoint.parent.length) {
return new MissingError(operation.path);
}
} else if (endpoint.value === undefined) {
return new MissingError(operation.path);
}
endpoint.parent[endpoint.key] = operation.value;
return null;
}
patch.replace = replace;
/**
> The "move" operation removes the value at a specified location and
> adds it to the target location.
> The operation object MUST contain a "from" member, which is a string
> containing a JSON Pointer value that references the location in the
> target document to move the value from.
> This operation is functionally identical to a "remove" operation on
> the "from" location, followed immediately by an "add" operation at
> the target location with the value that was just removed.
> The "from" location MUST NOT be a proper prefix of the "path"
> location; i.e., a location cannot be moved into one of its children.
TODO: throw if the check described in the previous paragraph fails.
*/
function move(object, operation) {
var from_endpoint = pointer_1$1.Pointer.fromJSON(operation.from).evaluate(object);
if (from_endpoint.value === undefined) {
return new MissingError(operation.from);
}
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object);
if (endpoint.parent === undefined) {
return new MissingError(operation.path);
}
_remove(from_endpoint.parent, from_endpoint.key);
_add(endpoint.parent, endpoint.key, from_endpoint.value);
return null;
}
patch.move = move;
/**
> The "copy" operation copies the value at a specified location to the
> target location.
> The operation object MUST contain a "from" member, which is a string
> containing a JSON Pointer value that references the location in the
> target document to copy the value from.
> The "from" location MUST exist for the operation to be successful.
> This operation is functionally identical to an "add" operation at the
> target location using the value specified in the "from" member.
Alternatively, it's like 'move' without the 'remove'.
*/
function copy(object, operation) {
var from_endpoint = pointer_1$1.Pointer.fromJSON(operation.from).evaluate(object);
if (from_endpoint.value === undefined) {
return new MissingError(operation.from);
}
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object);
if (endpoint.parent === undefined) {
return new MissingError(operation.path);
}
_add(endpoint.parent, endpoint.key, util_1$1.clone(from_endpoint.value));
return null;
}
patch.copy = copy;
/**
> The "test" operation tests that a value at the target location is
> equal to a specified value.
> The operation object MUST contain a "value" member that conveys the
> value to be compared to the target location's value.
> The target location MUST be equal to the "value" value for the
> operation to be considered successful.
*/
function test$1(object, operation) {
var endpoint = pointer_1$1.Pointer.fromJSON(operation.path).evaluate(object);
var result = equal_1$1.compare(endpoint.value, operation.value);
if (!result) {
return new TestError(endpoint.value, operation.value);
}
return null;
}
patch.test = test$1;
var InvalidOperationError =
/** @class */
function (_super) {
__extends(InvalidOperationError, _super);
function InvalidOperationError(operation) {
var _this = _super.call(this, "Invalid operation: " + operation.op) || this;
_this.operation = operation;
_this.name = 'InvalidOperationError';
return _this;
}
return InvalidOperationError;
}(Error);
patch.InvalidOperationError = InvalidOperationError;
/**
Switch on `operation.op`, applying the corresponding patch function for each
case to `object`.
*/
function apply(object, operation) {
// not sure why TypeScript can't infer typesafety of:
// {add, remove, replace, move, copy, test}[operation.op](object, operation)
// (seems like a bug)
switch (operation.op) {
case 'add':
return add(object, operation);
case 'remove':
return remove(object, operation);
case 'replace':
return replace(object, operation);
case 'move':
return move(object, operation);
case 'copy':
return copy(object, operation);
case 'test':
return test$1(object, operation);
}
return new InvalidOperationError(operation);
}
patch.apply = apply;
var diff = {};
Object.defineProperty(diff, "__esModule", {
value: true
});
diff.diffAny = diff.diffObjects = diff.diffArrays = diff.intersection = diff.subtract = diff.isDestructive = void 0;
var equal_1 = equal;
var util_1 = util;
function isDestructive(_a) {
var op = _a.op;
return op === 'remove' || op === 'replace' || op === 'copy' || op === 'move';
}
diff.isDestructive = isDestructive;
/**
List the keys in `minuend` that are not in `subtrahend`.
A key is only considered if it is both 1) an own-property (o.hasOwnProperty(k))
of the object, and 2) has a value that is not undefined. This is to match JSON
semantics, where JSON object serialization drops keys with undefined values.
@param minuend Object of interest
@param subtrahend Object of comparison
@returns Array of keys that are in `minuend` but not in `subtrahend`.
*/
function subtract(minuend, subtrahend) {
// initialize empty object; we only care about the keys, the values can be anything
var obj = {}; // build up obj with all the properties of minuend
for (var add_key in minuend) {
if (util_1.hasOwnProperty.call(minuend, add_key) && minuend[add_key] !== undefined) {
obj[add_key] = 1;
}
} // now delete all the properties of subtrahend from obj
// (deleting a missing key has no effect)
for (var del_key in subtrahend) {
if (util_1.hasOwnProperty.call(subtrahend, del_key) && subtrahend[del_key] !== undefined) {
delete obj[del_key];
}
} // finally, extract whatever keys remain in obj
return Object.keys(obj);
}
diff.subtract = subtract;
/**
List the keys that shared by all `objects`.
The semantics of what constitutes a "key" is described in {@link subtract}.
@param objects Array of objects to compare
@returns Array of keys that are in ("own-properties" of) every object in `objects`.
*/
function intersection(objects) {
var length = objects.length; // prepare empty counter to keep track of how many objects each key occurred in
var counter = {}; // go through each object and increment the counter for each key in that object
for (var i = 0; i < length; i++) {
var object = objects[i];
for (var key in object) {
if (util_1.hasOwnProperty.call(object, key) && object[key] !== undefined) {
counter[key] = (counter[key] || 0) + 1;
}
}
} // now delete all keys from the counter that were not seen in every object
for (var key in counter) {
if (counter[key] < length) {
delete counter[key];
}
} // finally, extract whatever keys remain in the counter
return Object.keys(counter);
}
diff.intersection = intersection;
function isArrayAdd(array_operation) {
return array_operation.op === 'add';
}
function isArrayRemove(array_operation) {
return array_operation.op === 'remove';
}
function appendArrayOperation(base, operation) {
return {
// the new operation must be pushed on the end
operations: base.operations.concat(operation),
cost: base.cost + 1
};
}
/**
Calculate the shortest sequence of operations to get from `input` to `output`,
using a dynamic programming implementation of the Levenshtein distance algorithm.
To get from the input ABC to the output AZ we could just delete all the input
and say "insert A, insert Z" and be done with it. That's what we do if the
input is empty. But we can be smarter.
output
A Z
- -
[0] 1 2
input A | 1 [0] 1
B | 2 [1] 1
C | 3 2 [2]
1) start at 0,0 (+0)
2) keep A (+0)
3) remove B (+1)
4) replace C with Z (+1)
If the `input` (source) is empty, they'll all be in the top row, resulting in an
array of 'add' operations.
If the `output` (target) is empty, everything will be in the left column,
resulting in an array of 'remove' operations.
@returns A list of add/remove/replace operations.
*/
function diffArrays(input, output, ptr, diff) {
if (diff === void 0) {
diff = diffAny;
} // set up cost matrix (very simple initialization: just a map)
var memo = {
'0,0': {
operations: [],
cost: 0
}
};
/**
Calculate the cheapest sequence of operations required to get from
input.slice(0, i) to output.slice(0, j).
There may be other valid sequences with the same cost, but none cheaper.
@param i The row in the layout above
@param j The column in the layout above
@returns An object containing a list of operations, along with the total cost
of applying them (+1 for each add/remove/replace operation)
*/
function dist(i, j) {
// memoized
var memo_key = i + "," + j;
var memoized = memo[memo_key];
if (memoized === undefined) {
if (i > 0 && j > 0 && equal_1.compare(input[i - 1], output[j - 1])) {
// equal (no operations => no cost)
memoized = dist(i - 1, j - 1);
} else {
var alternatives = [];
if (i > 0) {
// NOT topmost row
var remove_base = dist(i - 1, j);
var remove_operation = {
op: 'remove',
index: i - 1
};
alternatives.push(appendArrayOperation(remove_base, remove_operation));
}
if (j > 0) {
// NOT leftmost column
var add_base = dist(i, j - 1);
var add_operation = {
op: 'add',
index: i - 1,
value: output[j - 1]
};
alternatives.push(appendArrayOperation(add_base, add_operation));
}
if (i > 0 && j > 0) {
// TABLE MIDDLE
// supposing we replaced it, compute the rest of the costs:
var replace_base = dist(i - 1, j - 1); // okay, the general plan is to replace it, but we can be smarter,
// recursing into the structure and replacing only part of it if
// possible, but to do so we'll need the original value
var replace_operation = {
op: 'replace',
index: i - 1,
original: input[i - 1],
value: output[j - 1]
};
alternatives.push(appendArrayOperation(replace_base, replace_operation));
} // the only other case, i === 0 && j === 0, has already been memoized
// the meat of the algorithm:
// sort by cost to find the lowest one (might be several ties for lowest)
// [4, 6, 7, 1, 2].sort((a, b) => a - b) -> [ 1, 2, 4, 6, 7 ]
var best = alternatives.sort(function (a, b) {
return a.cost - b.cost;
})[0];
memoized = best;
}
memo[memo_key] = memoized;
}
return memoized;
} // handle weird objects masquerading as Arrays that don't have proper length
// properties by using 0 for everything but positive numbers
var input_length = isNaN(input.length) || input.length <= 0 ? 0 : input.length;
var output_length = isNaN(output.length) || output.length <= 0 ? 0 : output.length;
var array_operations = dist(input_length, output_length).operations;
var padded_operations = array_operations.reduce(function (_a, array_operation) {
var operations = _a[0],
padding = _a[1];
if (isArrayAdd(array_operation)) {
var padded_index = array_operation.index + 1 + padding;
var index_token = padded_index < input_length + padding ? String(padded_index) : '-';
var operation = {
op: array_operation.op,
path: ptr.add(index_token).toString(),
value: array_operation.value
}; // padding++ // maybe only if array_operation.index > -1 ?
return [operations.concat(operation), padding + 1];
} else if (isArrayRemove(array_operation)) {
var operation = {
op: array_operation.op,
path: ptr.add(String(array_operation.index + padding)).toString()
}; // padding--
return [operations.concat(operation), padding - 1];
} else {
// replace
var replace_ptr = ptr.add(String(array_operation.index + padding));
var replace_operations = diff(array_operation.original, array_operation.value, replace_ptr);
return [operations.concat.apply(operations, replace_operations), padding];
}
}, [[], 0])[0];
return padded_operations;
}
diff.diffArrays = diffArrays;
function diffObjects(input, output, ptr, diff) {
if (diff === void 0) {
diff = diffAny;
} // if a key is in input but not output -> remove it
var operations = [];
subtract(input, output).forEach(function (key) {
operations.push({
op: 'remove',
path: ptr.add(key).toString()
});
}); // if a key is in output but not input -> add it
subtract(output, input).forEach(function (key) {
operations.push({
op: 'add',
path: ptr.add(key).toString(),
value: output[key]
});
}); // if a key is in both, diff it recursively
intersection([input, output]).forEach(function (key) {
operations.push.apply(operations, diff(input[key], output[key], ptr.add(key)));
});
return operations;
}
diff.diffObjects = diffObjects;
/**
`diffAny()` returns an empty array if `input` and `output` are materially equal
(i.e., would produce equivalent JSON); otherwise it produces an array of patches
that would transform `input` into `output`.
*/
function diffAny(input, output, ptr, diff) {
if (diff === void 0) {
diff = diffAny;
} // strict equality handles literals, numbers, and strings (a sufficient but not necessary cause)
if (input === output) {
return [];
}
var input_type = util_1.objectType(input);
var output_type = util_1.objectType(output);
if (input_type == 'array' && output_type == 'array') {
return diffArrays(input, output, ptr, diff);
}
if (input_type == 'object' && output_type == 'object') {
return diffObjects(input, output, ptr, diff);
} // at this point we know that input and output are materially different;
// could be array -> object, object -> array, boolean -> undefined,
// number -> string, or some other combination, but nothing that can be split
// up into multiple patches: so `output` must replace `input` wholesale.
return [{
op: 'replace',
path: ptr.toString(),
value: output
}];
}
diff.diffAny = diffAny;
Object.defineProperty(rfc6902, "__esModule", {
value: true
});
rfc6902.createTests = createPatch_1 = rfc6902.createPatch = rfc6902.applyPatch = void 0;
var pointer_1 = pointer;
var patch_1 = patch;
var diff_1 = diff;
/**
Apply a 'application/json-patch+json'-type patch to an object.
`patch` *must* be an array of operations.
> Operation objects MUST have exactly one "op" member, whose value
> indicates the operation to perform. Its value MUST be one of "add",
> "remove", "replace", "move", "copy", or "test"; other values are
> errors.
This method mutates the target object in-place.
@returns list of results, one for each operation: `null` indicated success,
otherwise, the result will be an instance of one of the Error classes:
MissingError, InvalidOperationError, or TestError.
*/
function applyPatch(object, patch) {
return patch.map(function (operation) {
return patch_1.apply(object, operation);
});
}
rfc6902.applyPatch = applyPatch;
function wrapVoidableDiff(diff) {
function wrappedDiff(input, output, ptr) {
var custom_patch = diff(input, output, ptr); // ensure an array is always returned
return Array.isArray(custom_patch) ? custom_patch : diff_1.diffAny(input, output, ptr, wrappedDiff);
}
return wrappedDiff;
}
/**
Produce a 'application/json-patch+json'-type patch to get from one object to
another.
This does not alter `input` or `output` unless they have a property getter with
side-effects (which is not a good idea anyway).
`diff` is called on each pair of comparable non-primitive nodes in the
`input`/`output` object trees, producing nested patches. Return `undefined`
to fall back to default behaviour.
Returns list of operations to perform on `input` to produce `output`.
*/
function createPatch(input, output, diff) {
var ptr = new pointer_1.Pointer(); // a new Pointer gets a default path of [''] if not specified
return (diff ? wrapVoidableDiff(diff) : diff_1.diffAny)(input, output, ptr);
}
var createPatch_1 = rfc6902.createPatch = createPatch;
/**
Create a test operation based on `input`'s current evaluation of the JSON
Pointer `path`; if such a pointer cannot be resolved, returns undefined.
*/
function createTest(input, path) {
var endpoint = pointer_1.Pointer.fromJSON(path).evaluate(input);
if (endpoint !== undefined) {
return {
op: 'test',
path: path,
value: endpoint.value
};
}
}
/**
Produce an 'application/json-patch+json'-type list of tests, to verify that
existing values in an object are identical to the those captured at some
checkpoint (whenever this function is called).
This does not alter `input` or `output` unless they have a property getter with
side-effects (which is not a good idea anyway).
Returns list of test operations.
*/
function createTests(input, patch) {
var tests = new Array();
patch.filter(diff_1.isDestructive).forEach(function (operation) {
var pathTest = createTest(input, operation.path);
if (pathTest) tests.push(pathTest);
if ('from' in operation) {
var fromTest = createTest(input, operation.from);
if (fromTest) tests.push(fromTest);
}
});
return tests;
}
rfc6902.createTests = createTests;
/**
* Checks if objects are equal
*/
function isDeepEqual(o1, o2) {
return createPatch_1(o1, o2).length === 0;
}
/**
* Deep-clone an object. Note that this does not work on object containing
* functions.
* @param {object} obj - the object to deep-clone
* @returns {object}
*/
function deepClone$1(obj) {
return JSON.parse(JSON.stringify(obj));
}
function parseToNumber(value) {
if (typeof value !== 'undefined' && !isNaN(Number(value))) {
return Number(value);
}
return null;
} // timeString cannot be typed `string` because in member.ts
// call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp.
function parseTime$1(timeString) {
try {
return new Date(timeString);
} catch (e) {
return null;
}
}
function parseAttributes(rawAttributes, warningMessage, log) {
var attributes = {};
if (rawAttributes) {
try {
attributes = JSON.parse(rawAttributes);
} catch (e) {
log.warn(warningMessage, e);
}
}
return attributes;
}
/**
* Construct URI with query parameters
*/
var UriBuilder$1 = /*#__PURE__*/function () {
function UriBuilder(base) {
_classCallCheck$1(this, UriBuilder);
this.base = base.replace(/\/$/, '');
this.args = [];
this.paths = [];
}
_createClass(UriBuilder, [{
key: "arg",
value: function arg(name, value) {
if (typeof value !== 'undefined') {
this.args.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
return this;
}
}, {
key: "path",
value: function path(name) {
this.paths.push(encodeURIComponent(name));
return this;
}
}, {
key: "build",
value: function build() {
var result = this.base;
if (this.paths.length) {
result += '/' + this.paths.join('/');
}
if (this.args.length) {
result += '?' + this.args.join('&');
}
return result;
}
}]);
return UriBuilder;
}();
var browser$2 = {};
var $$a = _export;
var isObject$6 = isObject$k;
var isArray = isArray$4;
var toAbsoluteIndex$4 = toAbsoluteIndex$6;
var toLength$d = toLength$k;
var toIndexedObject$2 = toIndexedObject$c;
var createProperty$1 = createProperty$5;
var wellKnownSymbol$2 = wellKnownSymbol$n;
var arrayMethodHasSpeciesSupport$1 = arrayMethodHasSpeciesSupport$5;
var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport$1('slice');
var SPECIES = wellKnownSymbol$2('species');
var nativeSlice = [].slice;
var max$1 = Math.max;
// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
$$a({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, {
slice: function slice(start, end) {
var O = toIndexedObject$2(this);
var length = toLength$d(O.length);
var k = toAbsoluteIndex$4(start, length);
var fin = toAbsoluteIndex$4(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject$6(Constructor)) {
Constructor = Constructor[SPECIES];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === Array || Constructor === undefined) {
return nativeSlice.call(O, k, fin);
}
}
result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty$1(result, n, O[k]);
result.length = n;
return result;
}
});
var $$9 = _export;
var DESCRIPTORS$6 = descriptors;
var global$b = global$x;
var has$3 = has$g;
var isObject$5 = isObject$k;
var defineProperty$6 = objectDefineProperty.f;
var copyConstructorProperties = copyConstructorProperties$2;
var NativeSymbol = global$b.Symbol;
if (DESCRIPTORS$6 && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||
// Safari 12 bug
NativeSymbol().description !== undefined
)) {
var EmptyStringDescriptionStore = {};
// wrap Symbol constructor for correct work with undefined description
var SymbolWrapper = function Symbol() {
var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
var result = this instanceof SymbolWrapper
? new NativeSymbol(description)
// in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
: description === undefined ? NativeSymbol() : NativeSymbol(description);
if (description === '') EmptyStringDescriptionStore[result] = true;
return result;
};
copyConstructorProperties(SymbolWrapper, NativeSymbol);
var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
symbolPrototype.constructor = SymbolWrapper;
var symbolToString = symbolPrototype.toString;
var native = String(NativeSymbol('test')) == 'Symbol(test)';
var regexp = /^Symbol\((.*)\)[^)]+$/;
defineProperty$6(symbolPrototype, 'description', {
configurable: true,
get: function description() {
var symbol = isObject$5(this) ? this.valueOf() : this;
var string = symbolToString.call(symbol);
if (has$3(EmptyStringDescriptionStore, symbol)) return '';
var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
return desc === '' ? undefined : desc;
}
});
$$9({ global: true, forced: true }, {
Symbol: SymbolWrapper
});
}
var defineWellKnownSymbol = defineWellKnownSymbol$2;
// `Symbol.iterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');
var _typeof$1 = {exports: {}};
(function (module) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
}
return _typeof(obj);
}
module.exports = _typeof;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(_typeof$1));
var DESCRIPTORS$5 = descriptors;
var defineProperty$5 = objectDefineProperty.f;
var FunctionPrototype = Function.prototype;
var FunctionPrototypeToString = FunctionPrototype.toString;
var nameRE = /^\s*function ([^ (]*)/;
var NAME$1 = 'name';
// Function instances `.name` property
// https://tc39.es/ecma262/#sec-function-instances-name
if (DESCRIPTORS$5 && !(NAME$1 in FunctionPrototype)) {
defineProperty$5(FunctionPrototype, NAME$1, {
configurable: true,
get: function () {
try {
return FunctionPrototypeToString.call(this).match(nameRE)[1];
} catch (error) {
return '';
}
}
});
}
var isObject$4 = isObject$k;
var floor$3 = Math.floor;
// `Number.isInteger` method implementation
// https://tc39.es/ecma262/#sec-number.isinteger
var isInteger$2 = function isInteger(it) {
return !isObject$4(it) && isFinite(it) && floor$3(it) === it;
};
var $$8 = _export;
var isInteger$1 = isInteger$2;
// `Number.isInteger` method
// https://tc39.es/ecma262/#sec-number.isinteger
$$8({ target: 'Number', stat: true }, {
isInteger: isInteger$1
});
var slicedToArray = {exports: {}};
var arrayWithHoles = {exports: {}};
(function (module) {
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(arrayWithHoles));
var iterableToArrayLimit = {exports: {}};
(function (module) {
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
module.exports = _iterableToArrayLimit;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(iterableToArrayLimit));
var unsupportedIterableToArray = {exports: {}};
var arrayLikeToArray = {exports: {}};
(function (module) {
function _arrayLikeToArray(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;
}
module.exports = _arrayLikeToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(arrayLikeToArray));
(function (module) {
var arrayLikeToArray$1 = arrayLikeToArray.exports;
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return arrayLikeToArray$1(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$1(o, minLen);
}
module.exports = _unsupportedIterableToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(unsupportedIterableToArray));
var nonIterableRest = {exports: {}};
(function (module) {
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableRest;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(nonIterableRest));
(function (module) {
var arrayWithHoles$1 = arrayWithHoles.exports;
var iterableToArrayLimit$1 = iterableToArrayLimit.exports;
var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports;
var nonIterableRest$1 = nonIterableRest.exports;
function _slicedToArray(arr, i) {
return arrayWithHoles$1(arr) || iterableToArrayLimit$1(arr, i) || unsupportedIterableToArray$1(arr, i) || nonIterableRest$1();
}
module.exports = _slicedToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(slicedToArray));
var DESCRIPTORS$4 = descriptors;
var objectKeys = objectKeys$4;
var toIndexedObject$1 = toIndexedObject$c;
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
// `Object.{ entries, values }` methods implementation
var createMethod$1 = function (TO_ENTRIES) {
return function (it) {
var O = toIndexedObject$1(it);
var keys = objectKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS$4 || propertyIsEnumerable.call(O, key)) {
result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
}
}
return result;
};
};
var objectToArray = {
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
entries: createMethod$1(true),
// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
values: createMethod$1(false)
};
var $$7 = _export;
var $entries = objectToArray.entries;
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
$$7({ target: 'Object', stat: true }, {
entries: function entries(O) {
return $entries(O);
}
});
var toConsumableArray = {exports: {}};
var arrayWithoutHoles = {exports: {}};
(function (module) {
var arrayLikeToArray$1 = arrayLikeToArray.exports;
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray$1(arr);
}
module.exports = _arrayWithoutHoles;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(arrayWithoutHoles));
var iterableToArray = {exports: {}};
(function (module) {
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(iterableToArray));
var nonIterableSpread = {exports: {}};
(function (module) {
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableSpread;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(nonIterableSpread));
(function (module) {
var arrayWithoutHoles$1 = arrayWithoutHoles.exports;
var iterableToArray$1 = iterableToArray.exports;
var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports;
var nonIterableSpread$1 = nonIterableSpread.exports;
function _toConsumableArray(arr) {
return arrayWithoutHoles$1(arr) || iterableToArray$1(arr) || unsupportedIterableToArray$1(arr) || nonIterableSpread$1();
}
module.exports = _toConsumableArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(toConsumableArray));
var classCallCheck = {exports: {}};
(function (module) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(classCallCheck));
var inherits = {exports: {}};
var setPrototypeOf$3 = {exports: {}};
(function (module) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(setPrototypeOf$3));
(function (module) {
var setPrototypeOf = setPrototypeOf$3.exports;
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(inherits));
var possibleConstructorReturn = {exports: {}};
var assertThisInitialized = {exports: {}};
(function (module) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(assertThisInitialized));
(function (module) {
var _typeof = _typeof$1.exports["default"];
var assertThisInitialized$1 = assertThisInitialized.exports;
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized$1(self);
}
module.exports = _possibleConstructorReturn;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(possibleConstructorReturn));
var getPrototypeOf$2 = {exports: {}};
(function (module) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(getPrototypeOf$2));
var $$6 = _export;
var $includes$1 = arrayIncludes.includes;
var addToUnscopables$1 = addToUnscopables$3;
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
$$6({ target: 'Array', proto: true }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes$1(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables$1('includes');
Object.defineProperty(browser$2, '__esModule', {
value: true
});
var _typeof = _typeof$1.exports;
var _slicedToArray$1 = slicedToArray.exports;
var _toConsumableArray$1 = toConsumableArray.exports;
var _classCallCheck = classCallCheck.exports;
var _inherits = inherits.exports;
var _possibleConstructorReturn = possibleConstructorReturn.exports;
var _getPrototypeOf = getPrototypeOf$2.exports;
function _interopDefaultLegacy$2(e) {
return e && _typeof$2(e) === 'object' && 'default' in e ? e : {
'default': e
};
}
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy$2(_typeof);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy$2(_slicedToArray$1);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy$2(_toConsumableArray$1);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy$2(_classCallCheck);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy$2(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy$2(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy$2(_getPrototypeOf);
var custom = function custom() {
for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) {
checks[_key] = arguments[_key];
}
return {
checks: checks
};
};
function _createForOfIteratorHelper$3$1(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray$3$1(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
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 normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray$3$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$3$1(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$3$1(o, minLen);
}
function _arrayLikeToArray$3$1(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;
}
var type = function type() {
for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) {
checks[_key] = arguments[_key];
}
return custom(function (value) {
var isValid = false;
var expectedTypes = [];
var _iterator = _createForOfIteratorHelper$3$1(checks),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _type = _step.value;
if (typeof _type === "string") {
isValid = isValid || _typeof__default['default'](value) === _type;
expectedTypes.push("of type ".concat(_type));
continue;
}
isValid = isValid || value instanceof _type;
expectedTypes.push("an instance of ".concat(_type.name));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return [isValid, expectedTypes];
});
};
function _createForOfIteratorHelper$2$1(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray$2$1(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
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 normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray$2$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$2$1(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$2$1(o, minLen);
}
function _arrayLikeToArray$2$1(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;
}
var literal = function literal() {
for (var _len = arguments.length, checks = new Array(_len), _key = 0; _key < _len; _key++) {
checks[_key] = arguments[_key];
}
return custom(function (value) {
var isValid = false;
var expectedTypes = [];
var _iterator = _createForOfIteratorHelper$2$1(checks),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var type = _step.value;
isValid = isValid || value === type;
expectedTypes.push(typeof type === "string" ? "\"".concat(type, "\"") : "".concat(type));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return [isValid, expectedTypes];
});
};
var nonEmptyString = custom(function (value) {
return [typeof value === "string" && value.length > 0, "a non-empty string"];
});
var nonNegativeInteger = custom(function (value) {
return [typeof value === "number" && Number.isInteger(value) && value >= 0, "a non-negative integer"];
});
var pureObject = custom(function (value) {
return [_typeof__default['default'](value) === "object" && value !== null && !Array.isArray(value), "a pure object (non-null and non-array)"];
});
function _createSuper$N(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct$O();
return function _createSuperInternal() {
var Super = _getPrototypeOf__default['default'](Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf__default['default'](this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn__default['default'](this, result);
};
}
function _isNativeReflectConstruct$O() {
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 _createForOfIteratorHelper$1$1(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray$1$1(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
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 normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray$1$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$1$1(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$1$1(o, minLen);
}
function _arrayLikeToArray$1$1(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;
}
var runtimeTypeValidation = function runtimeTypeValidation(rules, values) {
if (values.length > rules.length) {
throw new Error("Expected at most ".concat(rules.length, " argument(s), but got ").concat(values.length));
}
while (values.length < rules.length) {
values.push(undefined);
}
var _iterator = _createForOfIteratorHelper$1$1(values.entries()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray__default['default'](_step.value, 2),
index = _step$value[0],
value = _step$value[1];
var _validateValue = validateValue(rules[index], value),
_validateValue2 = _slicedToArray__default['default'](_validateValue, 4),
isValid = _validateValue2[0],
received = _validateValue2[1],
expected = _validateValue2[2],
delimeter = _validateValue2[3];
if (isValid) {
continue;
}
var argumentIndex = index + 1;
throw new Error("Argument ".concat(argumentIndex, " is expected to be ").concat(expected).concat(delimeter, " but got ").concat(received));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
};
var stringifyReceivedType = function stringifyReceivedType(value) {
var _value$constructor;
var receivedType;
var types = ["undefined", "boolean", "number", "bigint", "string"];
if (types.includes(_typeof__default['default'](value))) {
receivedType = typeof value === "string" ? "\"".concat(value, "\"") : "".concat(value);
}
if (_typeof__default['default'](value) === "object" && (value === null || value === void 0 ? void 0 : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) !== "Object") {
var _value$constructor2;
receivedType = value === null ? "null" : "instance of ".concat(value === null || value === void 0 ? void 0 : (_value$constructor2 = value.constructor) === null || _value$constructor2 === void 0 ? void 0 : _value$constructor2.name);
}
if (!receivedType) {
receivedType = _typeof__default['default'](value);
}
return receivedType;
};
/* eslint-disable @typescript-eslint/no-explicit-any */
var validateConstructorTypes = function validateConstructorTypes() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var finalRuleSet = convertRuleArguments(args);
return function (ctor) {
return /*#__PURE__*/function (_ctor) {
_inherits__default['default'](_class, _ctor);
var _super = _createSuper$N(_class);
function _class() {
_classCallCheck__default['default'](this, _class);
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
runtimeTypeValidation(finalRuleSet, args);
return _super.call.apply(_super, [this].concat(args));
}
return _class;
}(ctor);
};
};
/* eslint-enable @typescript-eslint/no-explicit-any */
var validateTypes = function validateTypes() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var finalRuleSet = convertRuleArguments(args);
return function (target, propertyKey, descriptor) {
if (typeof descriptor.value !== "function") {
throw new Error("The validateTypes decorator can only be applied to methods");
}
var originalMethod = descriptor.value;
descriptor.value = function () {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
runtimeTypeValidation(finalRuleSet, args);
return originalMethod.apply(this, args);
};
};
};
var validateTypesAsync = function validateTypesAsync() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
var finalRuleSet = convertRuleArguments(args);
return function (target, propertyKey, descriptor) {
if (typeof descriptor.value !== "function") {
throw new Error("The validateTypesAsync decorator can only be applied to methods");
}
var originalMethod = descriptor.value;
descriptor.value = function () {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
try {
runtimeTypeValidation(finalRuleSet, args);
} catch (e) {
return Promise.reject(e);
}
return originalMethod.apply(this, args);
};
};
};
var convertRuleArguments = function convertRuleArguments(args) {
var finalRuleDefinitionSet = [];
var _iterator2 = _createForOfIteratorHelper$1$1(args),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var arg = _step2.value;
finalRuleDefinitionSet.push(convertRuleArgument(arg));
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return finalRuleDefinitionSet;
};
var convertRuleArgument = function convertRuleArgument(arg) {
var finalArgumentRuleDefinitions = [];
var declaredRules = Array.isArray(arg) ? arg : [arg];
var _iterator3 = _createForOfIteratorHelper$1$1(declaredRules),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var rule = _step3.value;
if (typeof rule === "string" || typeof rule === "function") {
finalArgumentRuleDefinitions.push(type(rule));
continue;
}
finalArgumentRuleDefinitions.push(rule);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return finalArgumentRuleDefinitions;
};
var validateValue = function validateValue(ruleDefinitions, value) {
var expectedTypes = [];
var customReceivedType;
var isValid = false;
var _iterator4 = _createForOfIteratorHelper$1$1(ruleDefinitions),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var definition = _step4.value;
var _iterator5 = _createForOfIteratorHelper$1$1(definition.checks),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var check = _step5.value;
var _check = check(value),
_check2 = _slicedToArray__default['default'](_check, 3),
checkPassed = _check2[0],
typeDescription = _check2[1],
_receivedType = _check2[2];
isValid = isValid || checkPassed;
if (!customReceivedType && _receivedType) {
customReceivedType = _receivedType;
}
if (typeDescription) {
expectedTypes = typeof typeDescription === "string" ? [].concat(_toConsumableArray__default['default'](expectedTypes), [typeDescription]) : [].concat(_toConsumableArray__default['default'](expectedTypes), _toConsumableArray__default['default'](typeDescription));
}
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
if (isValid) {
return [true];
}
var receivedType = customReceivedType || stringifyReceivedType(value);
var lastIndex = expectedTypes.length - 1;
var expectedTypesString = lastIndex > 0 ? "".concat(expectedTypes.slice(0, lastIndex).join(", "), " or ").concat(expectedTypes[lastIndex]) : expectedTypes.join(", ");
return [false, receivedType, expectedTypesString, lastIndex > 1 ? ";" : ","];
};
var objectSchema = function objectSchema(name, schema) {
return custom(function (object) {
if (_typeof__default['default'](object) !== "object" || object === null || Array.isArray(object)) {
return [false, "valid ".concat(name, " (should be a pure object)")];
}
for (var _i = 0, _Object$entries = Object.entries(schema); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray__default['default'](_Object$entries[_i], 2),
key = _Object$entries$_i[0],
rules = _Object$entries$_i[1];
var _validateValue = validateValue(convertRuleArgument(rules), object[key]),
_validateValue2 = _slicedToArray__default['default'](_validateValue, 3),
isValid = _validateValue2[0],
received = _validateValue2[1],
expected = _validateValue2[2];
if (!isValid) {
return [false, "valid ".concat(name, " (key \"").concat(key, "\" should be ").concat(expected, ")"), "malformed ".concat(name, " (key \"").concat(key, "\" is ").concat(received, ")")];
}
}
return [true];
});
};
function _createForOfIteratorHelper$6(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray$7(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
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 normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
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;
}
var array = function array(name, rules) {
return custom(function (value) {
if (!Array.isArray(value)) {
return [false, "an array of ".concat(name)];
}
var _iterator = _createForOfIteratorHelper$6(value.entries()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray__default['default'](_step.value, 2),
key = _step$value[0],
valueOfKey = _step$value[1];
var _validateValue = validateValue(convertRuleArgument(rules), valueOfKey),
_validateValue2 = _slicedToArray__default['default'](_validateValue, 3),
isValid = _validateValue2[0],
received = _validateValue2[1],
expected = _validateValue2[2];
if (!isValid) {
return [false, "a valid array of ".concat(name, " (index ").concat(key, " should be ").concat(expected, ")"), "malformed array of ".concat(name, " (index ").concat(key, " is ").concat(received, ")")];
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return [true];
});
};
browser$2.array = array;
var custom_1 = browser$2.custom = custom;
var literal_1 = browser$2.literal = literal;
var nonEmptyString_1 = browser$2.nonEmptyString = nonEmptyString;
var nonNegativeInteger_1 = browser$2.nonNegativeInteger = nonNegativeInteger;
var objectSchema_1 = browser$2.objectSchema = objectSchema;
var pureObject_1 = browser$2.pureObject = pureObject;
browser$2.runtimeTypeValidation = runtimeTypeValidation;
browser$2.stringifyReceivedType = stringifyReceivedType;
browser$2.type = type;
browser$2.validateConstructorTypes = validateConstructorTypes;
var validateTypes_1 = browser$2.validateTypes = validateTypes;
var validateTypesAsync_1 = browser$2.validateTypesAsync = validateTypesAsync;
function _createSuper$M(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$N(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$N() { 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; } }
var log$f = Logger$3.scope('User');
/**
* @classdesc Extended user information.
* Note that <code>isOnline</code> and <code>isNotifiable</code> properties are eligible
* to use only if reachability function is enabled.
* You may check if it is enabled by reading value of {@link Client}'s <code>reachabilityEnabled</code> property.
*
* @property {String} identity - User identity
* @property {String} friendlyName - User friendly name, null if not set
* @property {any} attributes - Object with custom attributes for user
* @property {Boolean} isOnline - User real-time conversation connection status
* @property {Boolean} isNotifiable - User push notification registration status
* @property {Boolean} isSubscribed - Check if this user receives real-time status updates
*
* @fires User#updated
* @fires User#userSubscribed
* @fires User#userUnsubscribed
*
* @constructor
* @param {String} identity - Identity of user
* @param {String} entityId - id of user's object
* @param {Object} datasync - datasync service
* @param {Object} session - session service
*/
var User = /*#__PURE__*/function (_EventEmitter) {
_inherits$1(User, _EventEmitter);
var _super = _createSuper$M(User);
/**
* The update reason for <code>updated</code> event emitted on User
* @typedef {('friendlyName' | 'attributes' | 'reachabilityOnline' | 'reachabilityNotifiable')} User#UpdateReason
*/
function User(identity, entityName, services) {
var _this;
_classCallCheck$1(this, User);
_this = _super.call(this);
_this.subscribed = 'initializing';
_this.setMaxListeners(0);
_this.services = services;
_this.state = {
identity: identity,
entityName: entityName,
friendlyName: null,
attributes: {},
online: null,
notifiable: null
};
return _this;
}
_createClass(User, [{
key: "identity",
get: function get() {
return this.state.identity;
},
set: function set(identity) {
this.state.identity = identity;
}
}, {
key: "entityName",
set: function set(name) {
this.state.entityName = name;
}
}, {
key: "attributes",
get: function get() {
return this.state.attributes;
}
}, {
key: "friendlyName",
get: function get() {
return this.state.friendlyName;
}
}, {
key: "isOnline",
get: function get() {
return this.state.online;
}
}, {
key: "isNotifiable",
get: function get() {
return this.state.notifiable;
}
}, {
key: "isSubscribed",
get: function get() {
return this.subscribed == 'subscribed';
} // Handles service updates
}, {
key: "_update",
value: function _update(key, value) {
var updateReasons = [];
log$f.debug('User for', this.state.identity, 'updated:', key, value);
switch (key) {
case 'friendlyName':
if (this.state.friendlyName !== value.value) {
updateReasons.push('friendlyName');
this.state.friendlyName = value.value;
}
break;
case 'attributes':
var updateAttributes = parseAttributes(value.value, "Retrieved malformed attributes from the server for user: ".concat(this.state.identity), log$f);
if (!isDeepEqual(this.state.attributes, updateAttributes)) {
this.state.attributes = updateAttributes;
updateReasons.push('attributes');
}
break;
case 'reachability':
if (this.state.online !== value.online) {
this.state.online = value.online;
updateReasons.push('reachabilityOnline');
}
if (this.state.notifiable !== value.notifiable) {
this.state.notifiable = value.notifiable;
updateReasons.push('reachabilityNotifiable');
}
break;
default:
return;
}
if (updateReasons.length > 0) {
this.emit('updated', {
user: this,
updateReasons: updateReasons
});
}
} // Fetch reachability info
}, {
key: "_updateReachabilityInfo",
value: function _updateReachabilityInfo(map, update) {
var _this2 = this;
if (!this.services.session.reachabilityEnabled) {
return Promise.resolve();
}
return map.get('reachability').then(update).catch(function (err) {
log$f.warn('Failed to get reachability info for ', _this2.state.identity, err);
});
} // Fetch user
}, {
key: "_fetch",
value: function () {
var _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var _this3 = this;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.state.entityName) {
_context.next = 2;
break;
}
return _context.abrupt("return", this);
case 2:
this.promiseToFetch = this.services.syncClient.map({
id: this.state.entityName,
mode: 'open_existing',
includeItems: true
}).then(function (map) {
_this3.entity = map;
map.on('itemUpdated', function (args) {
log$f.debug(_this3.state.entityName + ' (' + _this3.state.identity + ') itemUpdated: ' + args.item.key);
return _this3._update(args.item.key, args.item.data);
});
return Promise.all([map.get('friendlyName').then(function (item) {
return _this3._update(item.key, item.data);
}), map.get('attributes').then(function (item) {
return _this3._update(item.key, item.data);
}), _this3._updateReachabilityInfo(map, function (item) {
return _this3._update(item.key, item.data);
})]);
}).then(function () {
log$f.debug('Fetched for', _this3.identity);
_this3.subscribed = 'subscribed';
_this3.emit('userSubscribed', _this3);
return _this3;
}).catch(function (err) {
_this3.promiseToFetch = null;
throw err;
});
return _context.abrupt("return", this.promiseToFetch);
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function _fetch() {
return _fetch2.apply(this, arguments);
}
return _fetch;
}()
}, {
key: "_ensureFetched",
value: function _ensureFetched() {
return this.promiseToFetch || this._fetch();
}
/**
* Updates user attributes.
* @param {any} attributes new attributes for User.
* @returns {Promise<User>}
*/
}, {
key: "updateAttributes",
value: function () {
var _updateAttributes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(attributes) {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(this.subscribed == 'unsubscribed')) {
_context2.next = 2;
break;
}
throw new Error('Can\'t modify unsubscribed object');
case 2:
_context2.next = 4;
return this.services.session.addCommand('editUserAttributes', {
username: this.state.identity,
attributes: JSON.stringify(attributes)
});
case 4:
return _context2.abrupt("return", this);
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function updateAttributes(_x) {
return _updateAttributes.apply(this, arguments);
}
return updateAttributes;
}()
/**
* Update Users friendlyName.
* @param {String|null} friendlyName - Updated friendlyName
* @returns {Promise<User>}
*/
}, {
key: "updateFriendlyName",
value: function () {
var _updateFriendlyName = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(friendlyName) {
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(this.subscribed == 'unsubscribed')) {
_context3.next = 2;
break;
}
throw new Error('Can\'t modify unsubscribed object');
case 2:
_context3.next = 4;
return this.services.session.addCommand('editUserFriendlyName', {
username: this.state.identity,
friendlyName: friendlyName
});
case 4:
return _context3.abrupt("return", this);
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function updateFriendlyName(_x2) {
return _updateFriendlyName.apply(this, arguments);
}
return updateFriendlyName;
}()
/**
* Removes User from subscription list.
* @returns {Promise<void>} Promise of completion
*/
}, {
key: "unsubscribe",
value: function () {
var _unsubscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!this.promiseToFetch) {
_context4.next = 7;
break;
}
_context4.next = 3;
return this.promiseToFetch;
case 3:
this.entity.close();
this.promiseToFetch = null;
this.subscribed = 'unsubscribed';
this.emit('userUnsubscribed', this);
case 7:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function unsubscribe() {
return _unsubscribe.apply(this, arguments);
}
return unsubscribe;
}()
}]);
return User;
}(EventEmitter$1);
__decorate([validateTypesAsync_1(['string', 'number', 'boolean', 'object', literal_1(null)]), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], User.prototype, "updateAttributes", null);
__decorate([validateTypesAsync_1(['string', literal_1(null)]), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], User.prototype, "updateFriendlyName", null);
/**
* Fired when User's properties or reachability status have been updated.
* @event User#updated
* @type {Object}
* @property {User} user - Updated User
* @property {User#UpdateReason[]} updateReasons - Array of User's updated event reasons
*/
/**
* Fired when Client is subscribed to User.
* @event User#userSubscribed
* @type {User}
*/
/**
* Fired when Client is unsubscribed from this User.
* @event User#userUnsubscribed
* @type {User}
*/
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayLikeToArray$6(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 _unsupportedIterableToArray$6(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$6(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$6(o, minLen);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$6(arr, i) || _nonIterableRest();
}
var internalMetadata = {exports: {}};
var fails$a = fails$x;
var freezing = !fails$a(function () {
// eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing
return Object.isExtensible(Object.preventExtensions({}));
});
var hiddenKeys = hiddenKeys$6;
var isObject$3 = isObject$k;
var has$2 = has$g;
var defineProperty$4 = objectDefineProperty.f;
var uid$1 = uid$5;
var FREEZING = freezing;
var METADATA = uid$1('meta');
var id = 0;
// eslint-disable-next-line es/no-object-isextensible -- safe
var isExtensible = Object.isExtensible || function () {
return true;
};
var setMetadata = function (it) {
defineProperty$4(it, METADATA, { value: {
objectID: 'O' + id++, // object ID
weakData: {} // weak collections IDs
} });
};
var fastKey$1 = function (it, create) {
// return a primitive with prefix
if (!isObject$3(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has$2(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMetadata(it);
// return object ID
} return it[METADATA].objectID;
};
var getWeakData = function (it, create) {
if (!has$2(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMetadata(it);
// return the store of weak collections IDs
} return it[METADATA].weakData;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZING && meta.REQUIRED && isExtensible(it) && !has$2(it, METADATA)) setMetadata(it);
return it;
};
var meta = internalMetadata.exports = {
REQUIRED: false,
fastKey: fastKey$1,
getWeakData: getWeakData,
onFreeze: onFreeze
};
hiddenKeys[METADATA] = true;
var $$5 = _export;
var global$a = global$x;
var isForced = isForced_1;
var redefine$2 = redefine$b.exports;
var InternalMetadataModule = internalMetadata.exports;
var iterate$1 = iterate$3;
var anInstance$3 = anInstance$5;
var isObject$2 = isObject$k;
var fails$9 = fails$x;
var checkCorrectnessOfIteration$1 = checkCorrectnessOfIteration$4;
var setToStringTag$1 = setToStringTag$6;
var inheritIfRequired$1 = inheritIfRequired$3;
var collection$2 = function (CONSTRUCTOR_NAME, wrapper, common) {
var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
var ADDER = IS_MAP ? 'set' : 'add';
var NativeConstructor = global$a[CONSTRUCTOR_NAME];
var NativePrototype = NativeConstructor && NativeConstructor.prototype;
var Constructor = NativeConstructor;
var exported = {};
var fixMethod = function (KEY) {
var nativeMethod = NativePrototype[KEY];
redefine$2(NativePrototype, KEY,
KEY == 'add' ? function add(value) {
nativeMethod.call(this, value === 0 ? 0 : value);
return this;
} : KEY == 'delete' ? function (key) {
return IS_WEAK && !isObject$2(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
} : KEY == 'get' ? function get(key) {
return IS_WEAK && !isObject$2(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);
} : KEY == 'has' ? function has(key) {
return IS_WEAK && !isObject$2(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
} : function set(key, value) {
nativeMethod.call(this, key === 0 ? 0 : key, value);
return this;
}
);
};
var REPLACE = isForced(
CONSTRUCTOR_NAME,
typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails$9(function () {
new NativeConstructor().entries().next();
}))
);
if (REPLACE) {
// create collection constructor
Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
InternalMetadataModule.REQUIRED = true;
} else if (isForced(CONSTRUCTOR_NAME, true)) {
var instance = new Constructor();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails$9(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
// eslint-disable-next-line no-new -- required for testing
var ACCEPT_ITERABLES = checkCorrectnessOfIteration$1(function (iterable) { new NativeConstructor(iterable); });
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails$9(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new NativeConstructor();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
Constructor = wrapper(function (dummy, iterable) {
anInstance$3(dummy, Constructor, CONSTRUCTOR_NAME);
var that = inheritIfRequired$1(new NativeConstructor(), dummy, Constructor);
if (iterable != undefined) iterate$1(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
return that;
});
Constructor.prototype = NativePrototype;
NativePrototype.constructor = Constructor;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;
}
exported[CONSTRUCTOR_NAME] = Constructor;
$$5({ global: true, forced: Constructor != NativeConstructor }, exported);
setToStringTag$1(Constructor, CONSTRUCTOR_NAME);
if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
return Constructor;
};
var defineProperty$3 = objectDefineProperty.f;
var create$1 = objectCreate;
var redefineAll$1 = redefineAll$3;
var bind$1 = functionBindContext;
var anInstance$2 = anInstance$5;
var iterate = iterate$3;
var defineIterator = defineIterator$3;
var setSpecies$2 = setSpecies$4;
var DESCRIPTORS$3 = descriptors;
var fastKey = internalMetadata.exports.fastKey;
var InternalStateModule$2 = internalState;
var setInternalState$2 = InternalStateModule$2.set;
var internalStateGetterFor = InternalStateModule$2.getterFor;
var collectionStrong$2 = {
getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance$2(that, C, CONSTRUCTOR_NAME);
setInternalState$2(that, {
type: CONSTRUCTOR_NAME,
index: create$1(null),
first: undefined,
last: undefined,
size: 0
});
if (!DESCRIPTORS$3) that.size = 0;
if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
});
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
var define = function (that, key, value) {
var state = getInternalState(that);
var entry = getEntry(that, key);
var previous, index;
// change existing entry
if (entry) {
entry.value = value;
// create new entry
} else {
state.last = entry = {
index: index = fastKey(key, true),
key: key,
value: value,
previous: previous = state.last,
next: undefined,
removed: false
};
if (!state.first) state.first = entry;
if (previous) previous.next = entry;
if (DESCRIPTORS$3) state.size++;
else that.size++;
// add to index
if (index !== 'F') state.index[index] = entry;
} return that;
};
var getEntry = function (that, key) {
var state = getInternalState(that);
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return state.index[index];
// frozen object case
for (entry = state.first; entry; entry = entry.next) {
if (entry.key == key) return entry;
}
};
redefineAll$1(C.prototype, {
// `{ Map, Set }.prototype.clear()` methods
// https://tc39.es/ecma262/#sec-map.prototype.clear
// https://tc39.es/ecma262/#sec-set.prototype.clear
clear: function clear() {
var that = this;
var state = getInternalState(that);
var data = state.index;
var entry = state.first;
while (entry) {
entry.removed = true;
if (entry.previous) entry.previous = entry.previous.next = undefined;
delete data[entry.index];
entry = entry.next;
}
state.first = state.last = undefined;
if (DESCRIPTORS$3) state.size = 0;
else that.size = 0;
},
// `{ Map, Set }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.delete
// https://tc39.es/ecma262/#sec-set.prototype.delete
'delete': function (key) {
var that = this;
var state = getInternalState(that);
var entry = getEntry(that, key);
if (entry) {
var next = entry.next;
var prev = entry.previous;
delete state.index[entry.index];
entry.removed = true;
if (prev) prev.next = next;
if (next) next.previous = prev;
if (state.first == entry) state.first = next;
if (state.last == entry) state.last = prev;
if (DESCRIPTORS$3) state.size--;
else that.size--;
} return !!entry;
},
// `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods
// https://tc39.es/ecma262/#sec-map.prototype.foreach
// https://tc39.es/ecma262/#sec-set.prototype.foreach
forEach: function forEach(callbackfn /* , that = undefined */) {
var state = getInternalState(this);
var boundFunction = bind$1(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var entry;
while (entry = entry ? entry.next : state.first) {
boundFunction(entry.value, entry.key, this);
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
}
},
// `{ Map, Set}.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.has
// https://tc39.es/ecma262/#sec-set.prototype.has
has: function has(key) {
return !!getEntry(this, key);
}
});
redefineAll$1(C.prototype, IS_MAP ? {
// `Map.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-map.prototype.get
get: function get(key) {
var entry = getEntry(this, key);
return entry && entry.value;
},
// `Map.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-map.prototype.set
set: function set(key, value) {
return define(this, key === 0 ? 0 : key, value);
}
} : {
// `Set.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-set.prototype.add
add: function add(value) {
return define(this, value = value === 0 ? 0 : value, value);
}
});
if (DESCRIPTORS$3) defineProperty$3(C.prototype, 'size', {
get: function () {
return getInternalState(this).size;
}
});
return C;
},
setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) {
var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';
var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);
var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME);
// `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods
// https://tc39.es/ecma262/#sec-map.prototype.entries
// https://tc39.es/ecma262/#sec-map.prototype.keys
// https://tc39.es/ecma262/#sec-map.prototype.values
// https://tc39.es/ecma262/#sec-map.prototype-@@iterator
// https://tc39.es/ecma262/#sec-set.prototype.entries
// https://tc39.es/ecma262/#sec-set.prototype.keys
// https://tc39.es/ecma262/#sec-set.prototype.values
// https://tc39.es/ecma262/#sec-set.prototype-@@iterator
defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) {
setInternalState$2(this, {
type: ITERATOR_NAME,
target: iterated,
state: getInternalCollectionState(iterated),
kind: kind,
last: undefined
});
}, function () {
var state = getInternalIteratorState(this);
var kind = state.kind;
var entry = state.last;
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
// get next entry
if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {
// or finish the iteration
state.target = undefined;
return { value: undefined, done: true };
}
// return step by kind
if (kind == 'keys') return { value: entry.key, done: false };
if (kind == 'values') return { value: entry.value, done: false };
return { value: [entry.key, entry.value], done: false };
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// `{ Map, Set }.prototype[@@species]` accessors
// https://tc39.es/ecma262/#sec-get-map-@@species
// https://tc39.es/ecma262/#sec-get-set-@@species
setSpecies$2(CONSTRUCTOR_NAME);
}
};
var collection$1 = collection$2;
var collectionStrong$1 = collectionStrong$2;
// `Map` constructor
// https://tc39.es/ecma262/#sec-map-objects
collection$1('Map', function (init) {
return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong$1);
var browser$1 = {};
var defineProperty$2 = {exports: {}};
(function (module) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
module.exports["default"] = module.exports, module.exports.__esModule = true;
}(defineProperty$2));
function _createSuper$L(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$M(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$M() { 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; } }
Object.defineProperty(browser$1, '__esModule', {
value: true
});
var _defineProperty = defineProperty$2.exports;
function _interopDefaultLegacy$1(e) {
return e && _typeof$2(e) === 'object' && 'default' in e ? e : {
'default': e
};
}
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy$1(_defineProperty);
var domain; // This constructor is used to store event handlers. Instantiating this is
// faster than explicitly calling `Object.create(null)` to get a "clean" empty
// object (tested with v8 v4.9).
function EventHandlers() {}
EventHandlers.prototype = Object.create(null);
function EventEmitter() {
EventEmitter.init.call(this);
} // nodejs oddity
// require('events') === require('events').EventEmitter
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.usingDomains = false;
EventEmitter.prototype.domain = undefined;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
EventEmitter.init = function () {
this.domain = null;
if (EventEmitter.usingDomains) {
// if there is an active domain, then attach to it.
if (domain.active) ;
}
if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
this._events = new EventHandlers();
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
}; // Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number');
this._maxListeners = n;
return this;
};
function $getMaxListeners(that) {
if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this);
}; // These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone(handler, isFn, self) {
if (isFn) handler.call(self);else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
listeners[i].call(self);
}
}
}
function emitOne(handler, isFn, self, arg1) {
if (isFn) handler.call(self, arg1);else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
listeners[i].call(self, arg1);
}
}
}
function emitTwo(handler, isFn, self, arg1, arg2) {
if (isFn) handler.call(self, arg1, arg2);else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
listeners[i].call(self, arg1, arg2);
}
}
}
function emitThree(handler, isFn, self, arg1, arg2, arg3) {
if (isFn) handler.call(self, arg1, arg2, arg3);else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
listeners[i].call(self, arg1, arg2, arg3);
}
}
}
function emitMany(handler, isFn, self, args) {
if (isFn) handler.apply(self, args);else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i) {
listeners[i].apply(self, args);
}
}
}
EventEmitter.prototype.emit = function emit(type) {
var er, handler, len, args, i, events, domain;
var doError = type === 'error';
events = this._events;
if (events) doError = doError && events.error == null;else if (!doError) return false;
domain = this.domain; // If there is no 'error' event listener then throw.
if (doError) {
er = arguments[1];
if (domain) {
if (!er) er = new Error('Uncaught, unspecified "error" event');
er.domainEmitter = this;
er.domain = domain;
er.domainThrown = false;
domain.emit('error', er);
} else if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
return false;
}
handler = events[type];
if (!handler) return false;
var isFn = typeof handler === 'function';
len = arguments.length;
switch (len) {
// fast cases
case 1:
emitNone(handler, isFn, this);
break;
case 2:
emitOne(handler, isFn, this, arguments[1]);
break;
case 3:
emitTwo(handler, isFn, this, arguments[1], arguments[2]);
break;
case 4:
emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
break;
// slower
default:
args = new Array(len - 1);
for (i = 1; i < len; i++) {
args[i - 1] = arguments[i];
}
emitMany(handler, isFn, this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
events = target._events;
if (!events) {
events = target._events = new EventHandlers();
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener) {
target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (!existing) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = prepend ? [listener, existing] : [existing, listener];
} else {
// If we've already got an array, just append.
if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
} // Check for listener leak
if (!existing.warned) {
m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
emitWarning(w);
}
}
}
return target;
}
function emitWarning(e) {
typeof console.warn === 'function' ? console.warn(e) : console.log(e);
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener = function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function _onceWrap(target, type, listener) {
var fired = false;
function g() {
target.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(target, arguments);
}
}
g.listener = listener;
return g;
}
EventEmitter.prototype.once = function once(type, listener) {
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
this.prependListener(type, _onceWrap(this, type, listener));
return this;
}; // emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function removeListener(type, listener) {
var list, events, position, i, originalListener;
if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
events = this._events;
if (!events) return this;
list = events[type];
if (!list) return this;
if (list === listener || list.listener && list.listener === listener) {
if (--this._eventsCount === 0) this._events = new EventHandlers();else {
delete events[type];
if (events.removeListener) this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length; i-- > 0;) {
if (list[i] === listener || list[i].listener && list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0) return this;
if (list.length === 1) {
list[0] = undefined;
if (--this._eventsCount === 0) {
this._events = new EventHandlers();
return this;
} else {
delete events[type];
}
} else {
spliceOne(list, position);
}
if (events.removeListener) this.emit('removeListener', type, originalListener || listener);
}
return this;
}; // Alias for removeListener added in NodeJS 10.0
// https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
EventEmitter.prototype.off = function (type, listener) {
return this.removeListener(type, listener);
};
EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
var listeners, events;
events = this._events;
if (!events) return this; // not listening for removeListener, no need to emit
if (!events.removeListener) {
if (arguments.length === 0) {
this._events = new EventHandlers();
this._eventsCount = 0;
} else if (events[type]) {
if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type];
}
return this;
} // emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
for (var i = 0, key; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = new EventHandlers();
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
do {
this.removeListener(type, listeners[listeners.length - 1]);
} while (listeners[0]);
}
return this;
};
EventEmitter.prototype.listeners = function listeners(type) {
var evlistener;
var ret;
var events = this._events;
if (!events) ret = [];else {
evlistener = events[type];
if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener);
}
return ret;
};
EventEmitter.listenerCount = function (emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
}; // About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {
list[i] = list[k];
}
list.pop();
}
function arrayClone(arr, i) {
var copy = new Array(i);
while (i--) {
copy[i] = arr[i];
}
return copy;
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
/**
* Provides retrier service
*/
var Retrier$4 = /*#__PURE__*/function (_EventEmitter) {
_inherits$1(Retrier, _EventEmitter);
var _super = _createSuper$L(Retrier);
// fibonacci strategy
/**
* Creates a new Retrier instance
*/
function Retrier(options) {
var _this;
_classCallCheck$1(this, Retrier);
_this = _super.call(this);
_defineProperty__default['default'](_assertThisInitialized(_this), "timeout", null);
_defineProperty__default['default'](_assertThisInitialized(_this), "startTimestamp", -1);
_this.minDelay = options.min;
_this.maxDelay = options.max;
_this.initialDelay = options.initial || 0;
_this.maxAttemptsCount = options.maxAttemptsCount || 0;
_this.maxAttemptsTime = options.maxAttemptsTime || 0;
_this.randomness = options.randomness || 0;
_this.inProgress = false;
_this.attemptNum = 0;
_this.prevDelay = 0;
_this.currDelay = 0;
return _this;
}
_createClass(Retrier, [{
key: "attempt",
value: function attempt() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.attemptNum++;
this.emit("attempt", this);
}
}, {
key: "nextDelay",
value: function nextDelay(delayOverride) {
if (typeof delayOverride === "number") {
this.prevDelay = 0;
this.currDelay = delayOverride;
return delayOverride;
}
if (this.attemptNum == 0) {
return this.initialDelay;
}
if (this.attemptNum == 1) {
this.currDelay = this.minDelay;
return this.currDelay;
}
this.prevDelay = this.currDelay;
var delay = this.currDelay + this.prevDelay;
if (this.maxDelay && delay > this.maxDelay) {
this.currDelay = this.maxDelay;
delay = this.maxDelay;
}
this.currDelay = delay;
return delay;
}
}, {
key: "randomize",
value: function randomize(delay) {
var area = delay * this.randomness;
var corr = Math.round(Math.random() * area * 2 - area);
return Math.max(0, delay + corr);
}
}, {
key: "scheduleAttempt",
value: function scheduleAttempt(delayOverride) {
var _this2 = this;
if (this.maxAttemptsCount && this.attemptNum >= this.maxAttemptsCount) {
this.cleanup();
this.emit("failed", new Error("Maximum attempt count limit reached"));
return;
}
var delay = this.nextDelay(delayOverride);
delay = this.randomize(delay);
if (this.maxAttemptsTime && this.startTimestamp + this.maxAttemptsTime < Date.now() + delay) {
this.cleanup();
this.emit("failed", new Error("Maximum attempt time limit reached"));
return;
}
this.timeout = setTimeout(function () {
return _this2.attempt();
}, delay);
}
}, {
key: "cleanup",
value: function cleanup() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.inProgress = false;
this.attemptNum = 0;
this.prevDelay = 0;
this.currDelay = 0;
}
}, {
key: "start",
value: function start() {
if (this.inProgress) {
throw new Error("Retrier is already in progress");
}
this.inProgress = true;
this.startTimestamp = Date.now();
this.scheduleAttempt(this.initialDelay);
}
}, {
key: "cancel",
value: function cancel() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
this.inProgress = false;
this.emit("cancelled");
}
} // @todo Must be a T here, so the entire Retrier must be typed on this value type.
// eslint-disable-next-line
}, {
key: "succeeded",
value: function succeeded(arg) {
this.emit("succeeded", arg);
}
}, {
key: "failed",
value: function failed(err, nextAttemptDelayOverride) {
if (this.timeout) {
throw new Error("Retrier attempt is already in progress");
}
this.scheduleAttempt(nextAttemptDelayOverride);
}
}]);
return Retrier;
}(EventEmitter);
/**
* Run retrier as an async function with possibility to await for it.
* Example:
* ```
* const result = AsyncRetrier.run(async () => somePromise);
* ```
*/
var AsyncRetrier = /*#__PURE__*/function (_EventEmitter2) {
_inherits$1(AsyncRetrier, _EventEmitter2);
var _super2 = _createSuper$L(AsyncRetrier);
// This any must be T typed directly on the AsyncRetrier
// eslint-disable-next-line
function AsyncRetrier(options) {
var _this3;
_classCallCheck$1(this, AsyncRetrier);
_this3 = _super2.call(this);
_defineProperty__default['default'](_assertThisInitialized(_this3), "resolve", function () {
return void 0;
});
_defineProperty__default['default'](_assertThisInitialized(_this3), "reject", function () {
return void 0;
});
_this3.retrier = new Retrier$4(options);
return _this3;
}
_createClass(AsyncRetrier, [{
key: "run",
value: function run(handler) {
var _this4 = this;
this.retrier.on("attempt", function () {
handler().then(function (v) {
return _this4.retrier.succeeded(v);
}).catch(function (e) {
return _this4.retrier.failed(e);
});
});
this.retrier.on("succeeded", function (arg) {
return _this4.resolve(arg);
});
this.retrier.on("cancelled", function () {
return _this4.reject(new Error("Cancelled"));
});
this.retrier.on("failed", function (err) {
return _this4.reject(err);
});
return new Promise(function (resolve, reject) {
_this4.resolve = resolve;
_this4.reject = reject;
_this4.retrier.start();
});
}
}, {
key: "cancel",
value: function cancel() {
this.retrier.cancel();
}
}]);
return AsyncRetrier;
}(EventEmitter);
function isDef$4(value) {
return value !== undefined && value !== null;
}
var Backoff$4 = /*#__PURE__*/function (_EventEmitter3) {
_inherits$1(Backoff, _EventEmitter3);
var _super3 = _createSuper$L(Backoff);
function Backoff(options) {
var _this5;
_classCallCheck$1(this, Backoff);
_this5 = _super3.call(this);
_defineProperty__default['default'](_assertThisInitialized(_this5), "backoffDelay", 0);
_defineProperty__default['default'](_assertThisInitialized(_this5), "nextBackoffDelay", 0);
_defineProperty__default['default'](_assertThisInitialized(_this5), "backoffNumber", 0);
_defineProperty__default['default'](_assertThisInitialized(_this5), "timeoutID", null);
_defineProperty__default['default'](_assertThisInitialized(_this5), "maxNumberOfRetry", -1);
options = options || {};
var _options = options,
initialDelay = _options.initialDelay,
maxDelay = _options.maxDelay,
randomisationFactor = _options.randomisationFactor,
factor = _options.factor;
if (isDef$4(initialDelay) && initialDelay < 1) {
throw new Error("The initial timeout must be equal to or greater than 1.");
}
if (isDef$4(maxDelay) && maxDelay <= 1) {
throw new Error("The maximal timeout must be greater than 1.");
}
if (isDef$4(randomisationFactor) && (randomisationFactor < 0 || randomisationFactor > 1)) {
throw new Error("The randomisation factor must be between 0 and 1.");
}
if (isDef$4(factor) && factor <= 1) {
throw new Error("Exponential factor should be greater than 1.");
}
_this5.initialDelay = initialDelay || 100;
_this5.maxDelay = maxDelay || 10000;
if (_this5.maxDelay <= _this5.initialDelay) {
throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");
}
_this5.randomisationFactor = randomisationFactor || 0;
_this5.factor = factor || 2;
_this5.reset();
return _this5;
}
_createClass(Backoff, [{
key: "backoff",
value: function backoff(err) {
if (this.timeoutID == null) {
if (this.backoffNumber === this.maxNumberOfRetry) {
this.emit("fail", err);
this.reset();
} else {
this.backoffDelay = this.next();
this.timeoutID = setTimeout(this.onBackoff.bind(this), this.backoffDelay);
this.emit("backoff", this.backoffNumber, this.backoffDelay, err);
}
}
}
}, {
key: "reset",
value: function reset() {
this.backoffDelay = 0;
this.nextBackoffDelay = this.initialDelay;
this.backoffNumber = 0;
if (this.timeoutID) {
clearTimeout(this.timeoutID);
}
this.timeoutID = null;
}
}, {
key: "failAfter",
value: function failAfter(maxNumberOfRetry) {
if (maxNumberOfRetry <= 0) {
throw new Error("Expected a maximum number of retry greater than 0 but got ".concat(maxNumberOfRetry));
}
this.maxNumberOfRetry = maxNumberOfRetry;
}
}, {
key: "next",
value: function next() {
this.backoffDelay = Math.min(this.nextBackoffDelay, this.maxDelay);
this.nextBackoffDelay = this.backoffDelay * this.factor;
var randomisationMultiple = 1 + Math.random() * this.randomisationFactor;
return Math.min(this.maxDelay, Math.round(this.backoffDelay * randomisationMultiple));
}
}, {
key: "onBackoff",
value: function onBackoff() {
this.timeoutID = null;
this.emit("ready", this.backoffNumber, this.backoffDelay);
this.backoffNumber++;
}
}], [{
key: "exponential",
value: function exponential(options) {
return new Backoff(options);
}
}]);
return Backoff;
}(EventEmitter);
browser$1.AsyncRetrier = AsyncRetrier;
browser$1.Backoff = Backoff$4;
var Retrier_1 = browser$1.Retrier = Retrier$4;
function _createForOfIteratorHelper$5(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$5(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(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$5(o, minLen); }
function _arrayLikeToArray$5(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; }
var Network$1 = /*#__PURE__*/function () {
function Network(config, services) {
var _this = this;
_classCallCheck$1(this, Network);
this.config = config;
this.services = services;
this.cache = new Map();
this.cacheLifetime = 0;
this.services.session.getHttpCacheInterval().then(function (seconds) {
_this.cacheLifetime = seconds * 1000;
_this.cleanupCache();
});
}
_createClass(Network, [{
key: "backoffConfig",
value: function backoffConfig() {
return Object.assign(this.config.backoffConfigDefault, this.config.backoffConfigOverride);
}
}, {
key: "retryWhenThrottled",
value: function retryWhenThrottled() {
if (typeof this.config.retryWhenThrottledOverride !== 'undefined') {
return this.config.retryWhenThrottledOverride;
}
if (typeof this.config.retryWhenThrottledDefault !== 'undefined') {
return this.config.retryWhenThrottledDefault;
}
return false;
}
}, {
key: "isExpired",
value: function isExpired(timestamp) {
return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime;
}
}, {
key: "cleanupCache",
value: function cleanupCache() {
var _iterator = _createForOfIteratorHelper$5(this.cache),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
k = _step$value[0],
v = _step$value[1];
if (this.isExpired(v.timestamp)) {
this.cache.delete(k);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (this.cache.size === 0) {
clearInterval(this.timer);
}
}
}, {
key: "pokeTimer",
value: function pokeTimer() {
var _this2 = this;
this.timer = this.timer || setInterval(function () {
return _this2.cleanupCache();
}, this.cacheLifetime * 2);
}
}, {
key: "executeWithRetry",
value: function executeWithRetry(request) {
var _this3 = this;
var retryWhenThrottled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return new Promise(function (resolve, reject) {
var codesToRetryOn = [502, 503, 504];
if (retryWhenThrottled) {
codesToRetryOn.push(429);
}
var retrier = new Retrier_1(_this3.backoffConfig());
retrier.on('attempt', function () {
request().then(function (result) {
return retrier.succeeded(result);
}).catch(function (err) {
if (codesToRetryOn.indexOf(err.status) > -1) {
retrier.failed(err);
} else if (err.message === 'Twilsock disconnected') {
// Ugly hack. We must make a proper exceptions for twilsock
retrier.failed(err);
} else {
// Fatal error
retrier.removeAllListeners();
retrier.cancel();
reject(err);
}
});
});
retrier.on('succeeded', function (result) {
resolve(result);
});
retrier.on('cancelled', function (err) {
return reject(err);
});
retrier.on('failed', function (err) {
return reject(err);
});
retrier.start();
});
}
}, {
key: "get",
value: function () {
var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) {
var _this4 = this;
var cacheEntry, headers, response;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
cacheEntry = this.cache.get(url);
if (!(cacheEntry && !this.isExpired(cacheEntry.timestamp))) {
_context.next = 3;
break;
}
return _context.abrupt("return", cacheEntry.response);
case 3:
headers = {};
_context.next = 6;
return this.executeWithRetry(function () {
return _this4.services.transport.get(url, headers, _this4.config.productId);
}, this.retryWhenThrottled());
case 6:
response = _context.sent;
this.cache.set(url, {
response: response,
timestamp: Date.now()
});
this.pokeTimer();
return _context.abrupt("return", response);
case 10:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function get(_x) {
return _get.apply(this, arguments);
}
return get;
}()
}]);
return Network;
}();
var NotificationTypes = function NotificationTypes() {
_classCallCheck$1(this, NotificationTypes);
};
_defineProperty$1(NotificationTypes, "TYPING_INDICATOR", 'twilio.ipmsg.typing_indicator');
_defineProperty$1(NotificationTypes, "NEW_MESSAGE", 'twilio.conversations.new_message');
_defineProperty$1(NotificationTypes, "ADDED_TO_CONVERSATION", 'twilio.conversations.added_to_conversation');
_defineProperty$1(NotificationTypes, "REMOVED_FROM_CONVERSATION", 'twilio.conversations.removed_from_conversation');
_defineProperty$1(NotificationTypes, "CONSUMPTION_UPDATE", 'twilio.channel.consumption_update');
var RestPaginator = /*#__PURE__*/function () {
/*
* @constructor
* @param {Array} items Array of element for current page
* @param {Object} params
* @private
*/
function RestPaginator(items, source, prevToken, nextToken) {
_classCallCheck$1(this, RestPaginator);
this.state = {
prevToken: prevToken,
nextToken: nextToken,
source: source,
items: items
};
}
_createClass(RestPaginator, [{
key: "hasNextPage",
get: function get() {
return !!this.state.nextToken;
}
}, {
key: "hasPrevPage",
get: function get() {
return !!this.state.prevToken;
}
}, {
key: "items",
get: function get() {
return this.state.items;
}
}, {
key: "nextPage",
value: function nextPage() {
return this.hasNextPage ? this.state.source(this.state.nextToken) : Promise.reject(new Error('No next page'));
}
}, {
key: "prevPage",
value: function prevPage() {
return this.hasPrevPage ? this.state.source(this.state.prevToken) : Promise.reject(new Error('No previous page'));
}
}]);
return RestPaginator;
}();
var SyncListDescriptor =
/**
* @param {Object} descriptor - sync list descriptor data object
* @private
*/
function SyncListDescriptor(descriptor) {
_classCallCheck$1(this, SyncListDescriptor);
this.channel_sid = descriptor.channel_sid;
this.status = descriptor.status;
this.channel = descriptor.channel;
this.messages = descriptor.messages;
this.roster = descriptor.roster;
this.lastConsumedMessageIndex = descriptor.last_consumed_message_index;
this.notificationLevel = descriptor.notification_level;
this.descriptor = descriptor;
};
/**
* Provides async pagination interface for sync list
*
* @property {Network} network Network transport
* @property {string} syncListUrl Url to the sync list endpoint
*/
var SyncList$1 = /*#__PURE__*/function () {
/**
* @param {SyncListServices} services - services needed for SyncList service
* @private
*/
function SyncList(services) {
_classCallCheck$1(this, SyncList);
this.services = services;
}
_createClass(SyncList, [{
key: "getPage",
value: function () {
var _getPage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(args) {
var _this = this;
var links, url, response;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
args = args || {};
_context.next = 3;
return this.services.session.getSessionLinks();
case 3:
links = _context.sent;
url = new UriBuilder$1(links.syncListUrl).arg('PageToken', args.pageToken).build();
_context.next = 7;
return this.services.network.get(url);
case 7:
response = _context.sent;
return _context.abrupt("return", new RestPaginator(response.body.channels.map(function (x) {
return new SyncListDescriptor(x);
}), function (pageToken) {
return _this.getPage({
pageToken: pageToken
});
}, response.body.meta.previous_token, response.body.meta.next_token));
case 9:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function getPage(_x) {
return _getPage.apply(this, arguments);
}
return getPage;
}()
}]);
return SyncList;
}();
var lib$8 = {};
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf$1(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
var client$3 = {};
var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events);
var logger$4 = {};
Object.defineProperty(logger$4, "__esModule", {
value: true
});
var loglevelLog$1 = loglevel.exports;
var log$e = loglevelLog$1.getLogger('twilsock'); // twilsock is used by Flex SDK. Please DO NOT change
function prepareLine$3(prefix, args) {
return ["".concat(new Date().toISOString(), " Twilsock ").concat(prefix, ":")].concat(Array.from(args));
}
var Logger$2 = /*#__PURE__*/function () {
function Logger(prefix) {
_classCallCheck$1(this, Logger);
this.prefix = '';
this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0 ? ' ' + prefix + ':' : '';
}
_createClass(Logger, [{
key: "setLevel",
value: function setLevel(level) {
log$e.setLevel(level);
}
}, {
key: "trace",
value: function trace() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
log$e.debug.apply(null, prepareLine$3('T', args));
}
}, {
key: "debug",
value: function debug() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
log$e.debug.apply(null, prepareLine$3('D', args));
}
}, {
key: "info",
value: function info() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
log$e.info.apply(null, prepareLine$3('I', args));
}
}, {
key: "warn",
value: function warn() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
log$e.warn.apply(null, prepareLine$3('W', args));
}
}, {
key: "error",
value: function error() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
log$e.error.apply(null, prepareLine$3('E', args));
}
}], [{
key: "setLevel",
value: function setLevel(level) {
log$e.setLevel(level);
}
}, {
key: "trace",
value: function trace() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
log$e.trace.apply(null, prepareLine$3('T', args));
}
}, {
key: "debug",
value: function debug() {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
log$e.debug.apply(null, prepareLine$3('D', args));
}
}, {
key: "info",
value: function info() {
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8];
}
log$e.info.apply(null, prepareLine$3('I', args));
}
}, {
key: "warn",
value: function warn() {
for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
args[_key9] = arguments[_key9];
}
log$e.warn.apply(null, prepareLine$3('W', args));
}
}, {
key: "error",
value: function error() {
for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
args[_key10] = arguments[_key10];
}
log$e.error.apply(null, prepareLine$3('E', args));
}
}]);
return Logger;
}();
logger$4.Logger = Logger$2;
var logInstance$1 = new Logger$2('');
logger$4.log = logInstance$1;
var configuration$3 = {};
Object.defineProperty(configuration$3, "__esModule", {
value: true
});
var packageVersion = '0.6.2';
/**
* Settings container for the Twilsock client library
*/
var Configuration$3 = /*#__PURE__*/function () {
/**
* @param {String} token - authentication token
* @param {Object} options - options to override defaults
*/
function Configuration(token, activeGrant) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck$1(this, Configuration);
this.confirmedCapabilities = new Set();
this.activeGrant = activeGrant;
this._token = token;
var region = options.region || 'us1';
var defaultTwilsockUrl = "wss://tsock.".concat(region, ".twilio.com/v3/wsconnect");
var twilsockOptions = options.twilsock || options.Twilsock || {};
this.url = twilsockOptions.uri || defaultTwilsockUrl;
this._continuationToken = options.continuationToken ? options.continuationToken : null;
this.logLevel = options.logLevel ? options.logLevel : 'error';
this.retryPolicy = options.retryPolicy ? options.retryPolicy : {
min: 1 * 1000,
max: 2 * 60 * 1000,
randomness: 0.2
};
this.clientMetadata = options.clientMetadata ? options.clientMetadata : {};
this.clientMetadata.ver = packageVersion;
this.initRegistrations = options.initRegistrations ? options.initRegistrations : null;
this.tweaks = options.tweaks ? options.tweaks : null;
}
_createClass(Configuration, [{
key: "token",
get: function get() {
return this._token;
}
}, {
key: "continuationToken",
get: function get() {
return this._continuationToken;
}
}, {
key: "updateToken",
value: function updateToken(token) {
this._token = token;
}
}, {
key: "updateContinuationToken",
value: function updateContinuationToken(continuationToken) {
this._continuationToken = continuationToken;
}
}]);
return Configuration;
}();
configuration$3.Configuration = Configuration$3;
var twilsock = {};
var stateMachine = {exports: {}};
(function (module, exports) {
(function webpackUniversalModuleDefinition(root, factory) {
module.exports = factory();
})(commonjsGlobal, function () {
return (
/******/
function (modules) {
// webpackBootstrap
/******/
// The module cache
/******/
var installedModules = {};
/******/
/******/
// The require function
/******/
function __webpack_require__(moduleId) {
/******/
/******/
// Check if module is in cache
/******/
if (installedModules[moduleId]) {
/******/
return installedModules[moduleId].exports;
/******/
}
/******/
// Create a new module (and put it into the cache)
/******/
var module = installedModules[moduleId] = {
/******/
i: moduleId,
/******/
l: false,
/******/
exports: {}
/******/
};
/******/
/******/
// Execute the module function
/******/
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/
// Flag the module as loaded
/******/
module.l = true;
/******/
/******/
// Return the exports of the module
/******/
return module.exports;
/******/
}
/******/
/******/
/******/
// expose the modules object (__webpack_modules__)
/******/
__webpack_require__.m = modules;
/******/
/******/
// expose the module cache
/******/
__webpack_require__.c = installedModules;
/******/
/******/
// identity function for calling harmony imports with the correct context
/******/
__webpack_require__.i = function (value) {
return value;
};
/******/
/******/
// define getter function for harmony exports
/******/
__webpack_require__.d = function (exports, name, getter) {
/******/
if (!__webpack_require__.o(exports, name)) {
/******/
Object.defineProperty(exports, name, {
/******/
configurable: false,
/******/
enumerable: true,
/******/
get: getter
/******/
});
/******/
}
/******/
};
/******/
/******/
// getDefaultExport function for compatibility with non-harmony modules
/******/
__webpack_require__.n = function (module) {
/******/
var getter = module && module.__esModule ?
/******/
function getDefault() {
return module['default'];
} :
/******/
function getModuleExports() {
return module;
};
/******/
__webpack_require__.d(getter, 'a', getter);
/******/
return getter;
/******/
};
/******/
/******/
// Object.prototype.hasOwnProperty.call
/******/
__webpack_require__.o = function (object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
};
/******/
/******/
// __webpack_public_path__
/******/
__webpack_require__.p = "";
/******/
/******/
// Load entry module and return exports
/******/
return __webpack_require__(__webpack_require__.s = 5);
/******/
}(
/************************************************************************/
/******/
[
/* 0 */
/***/
function (module, exports, __webpack_require__) {
module.exports = function (target, sources) {
var n, source, key;
for (n = 1; n < arguments.length; n++) {
source = arguments[n];
for (key in source) {
if (source.hasOwnProperty(key)) target[key] = source[key];
}
}
return target;
};
/***/
},
/* 1 */
/***/
function (module, exports, __webpack_require__) {
var mixin = __webpack_require__(0); //-------------------------------------------------------------------------------------------------
module.exports = {
build: function build(target, config) {
var n,
max,
plugin,
plugins = config.plugins;
for (n = 0, max = plugins.length; n < max; n++) {
plugin = plugins[n];
if (plugin.methods) mixin(target, plugin.methods);
if (plugin.properties) Object.defineProperties(target, plugin.properties);
}
},
hook: function hook(fsm, name, additional) {
var n,
max,
method,
plugin,
plugins = fsm.config.plugins,
args = [fsm.context];
if (additional) args = args.concat(additional);
for (n = 0, max = plugins.length; n < max; n++) {
plugin = plugins[n];
method = plugins[n][name];
if (method) method.apply(plugin, args);
}
}
}; //-------------------------------------------------------------------------------------------------
/***/
},
/* 2 */
/***/
function (module, exports, __webpack_require__) {
function camelize(label) {
if (label.length === 0) return label;
var n,
result,
words = label.split(/[_-]/); // single word with first character already lowercase, return untouched
if (words.length === 1 && words[0][0].toLowerCase() === words[0][0]) return label;
result = words[0].toLowerCase();
for (n = 1; n < words.length; n++) {
result = result + words[n].charAt(0).toUpperCase() + words[n].substring(1).toLowerCase();
}
return result;
} //-------------------------------------------------------------------------------------------------
camelize.prepended = function (prepend, label) {
label = camelize(label);
return prepend + label[0].toUpperCase() + label.substring(1);
}; //-------------------------------------------------------------------------------------------------
module.exports = camelize;
/***/
},
/* 3 */
/***/
function (module, exports, __webpack_require__) {
var mixin = __webpack_require__(0),
camelize = __webpack_require__(2); //-------------------------------------------------------------------------------------------------
function Config(options, StateMachine) {
options = options || {};
this.options = options; // preserving original options can be useful (e.g visualize plugin)
this.defaults = StateMachine.defaults;
this.states = [];
this.transitions = [];
this.map = {};
this.lifecycle = this.configureLifecycle();
this.init = this.configureInitTransition(options.init);
this.data = this.configureData(options.data);
this.methods = this.configureMethods(options.methods);
this.map[this.defaults.wildcard] = {};
this.configureTransitions(options.transitions || []);
this.plugins = this.configurePlugins(options.plugins, StateMachine.plugin);
} //-------------------------------------------------------------------------------------------------
mixin(Config.prototype, {
addState: function addState(name) {
if (!this.map[name]) {
this.states.push(name);
this.addStateLifecycleNames(name);
this.map[name] = {};
}
},
addStateLifecycleNames: function addStateLifecycleNames(name) {
this.lifecycle.onEnter[name] = camelize.prepended('onEnter', name);
this.lifecycle.onLeave[name] = camelize.prepended('onLeave', name);
this.lifecycle.on[name] = camelize.prepended('on', name);
},
addTransition: function addTransition(name) {
if (this.transitions.indexOf(name) < 0) {
this.transitions.push(name);
this.addTransitionLifecycleNames(name);
}
},
addTransitionLifecycleNames: function addTransitionLifecycleNames(name) {
this.lifecycle.onBefore[name] = camelize.prepended('onBefore', name);
this.lifecycle.onAfter[name] = camelize.prepended('onAfter', name);
this.lifecycle.on[name] = camelize.prepended('on', name);
},
mapTransition: function mapTransition(transition) {
var name = transition.name,
from = transition.from,
to = transition.to;
this.addState(from);
if (typeof to !== 'function') this.addState(to);
this.addTransition(name);
this.map[from][name] = transition;
return transition;
},
configureLifecycle: function configureLifecycle() {
return {
onBefore: {
transition: 'onBeforeTransition'
},
onAfter: {
transition: 'onAfterTransition'
},
onEnter: {
state: 'onEnterState'
},
onLeave: {
state: 'onLeaveState'
},
on: {
transition: 'onTransition'
}
};
},
configureInitTransition: function configureInitTransition(init) {
if (typeof init === 'string') {
return this.mapTransition(mixin({}, this.defaults.init, {
to: init,
active: true
}));
} else if (_typeof$2(init) === 'object') {
return this.mapTransition(mixin({}, this.defaults.init, init, {
active: true
}));
} else {
this.addState(this.defaults.init.from);
return this.defaults.init;
}
},
configureData: function configureData(data) {
if (typeof data === 'function') return data;else if (_typeof$2(data) === 'object') return function () {
return data;
};else return function () {
return {};
};
},
configureMethods: function configureMethods(methods) {
return methods || {};
},
configurePlugins: function configurePlugins(plugins, builtin) {
plugins = plugins || [];
var n, max, plugin;
for (n = 0, max = plugins.length; n < max; n++) {
plugin = plugins[n];
if (typeof plugin === 'function') plugins[n] = plugin = plugin();
if (plugin.configure) plugin.configure(this);
}
return plugins;
},
configureTransitions: function configureTransitions(transitions) {
var i,
n,
transition,
from,
to,
wildcard = this.defaults.wildcard;
for (n = 0; n < transitions.length; n++) {
transition = transitions[n];
from = Array.isArray(transition.from) ? transition.from : [transition.from || wildcard];
to = transition.to || wildcard;
for (i = 0; i < from.length; i++) {
this.mapTransition({
name: transition.name,
from: from[i],
to: to
});
}
}
},
transitionFor: function transitionFor(state, transition) {
var wildcard = this.defaults.wildcard;
return this.map[state][transition] || this.map[wildcard][transition];
},
transitionsFor: function transitionsFor(state) {
var wildcard = this.defaults.wildcard;
return Object.keys(this.map[state]).concat(Object.keys(this.map[wildcard]));
},
allStates: function allStates() {
return this.states;
},
allTransitions: function allTransitions() {
return this.transitions;
}
}); //-------------------------------------------------------------------------------------------------
module.exports = Config; //-------------------------------------------------------------------------------------------------
/***/
},
/* 4 */
/***/
function (module, exports, __webpack_require__) {
var mixin = __webpack_require__(0),
Exception = __webpack_require__(6),
plugin = __webpack_require__(1),
UNOBSERVED = [null, []]; //-------------------------------------------------------------------------------------------------
function JSM(context, config) {
this.context = context;
this.config = config;
this.state = config.init.from;
this.observers = [context];
} //-------------------------------------------------------------------------------------------------
mixin(JSM.prototype, {
init: function init(args) {
mixin(this.context, this.config.data.apply(this.context, args));
plugin.hook(this, 'init');
if (this.config.init.active) return this.fire(this.config.init.name, []);
},
is: function is(state) {
return Array.isArray(state) ? state.indexOf(this.state) >= 0 : this.state === state;
},
isPending: function isPending() {
return this.pending;
},
can: function can(transition) {
return !this.isPending() && !!this.seek(transition);
},
cannot: function cannot(transition) {
return !this.can(transition);
},
allStates: function allStates() {
return this.config.allStates();
},
allTransitions: function allTransitions() {
return this.config.allTransitions();
},
transitions: function transitions() {
return this.config.transitionsFor(this.state);
},
seek: function seek(transition, args) {
var wildcard = this.config.defaults.wildcard,
entry = this.config.transitionFor(this.state, transition),
to = entry && entry.to;
if (typeof to === 'function') return to.apply(this.context, args);else if (to === wildcard) return this.state;else return to;
},
fire: function fire(transition, args) {
return this.transit(transition, this.state, this.seek(transition, args), args);
},
transit: function transit(transition, from, to, args) {
var lifecycle = this.config.lifecycle,
changed = this.config.options.observeUnchangedState || from !== to;
if (!to) return this.context.onInvalidTransition(transition, from, to);
if (this.isPending()) return this.context.onPendingTransition(transition, from, to);
this.config.addState(to); // might need to add this state if it's unknown (e.g. conditional transition or goto)
this.beginTransit();
args.unshift({
// this context will be passed to each lifecycle event observer
transition: transition,
from: from,
to: to,
fsm: this.context
});
return this.observeEvents([this.observersForEvent(lifecycle.onBefore.transition), this.observersForEvent(lifecycle.onBefore[transition]), changed ? this.observersForEvent(lifecycle.onLeave.state) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onLeave[from]) : UNOBSERVED, this.observersForEvent(lifecycle.on.transition), changed ? ['doTransit', [this]] : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter.state) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter[to]) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.on[to]) : UNOBSERVED, this.observersForEvent(lifecycle.onAfter.transition), this.observersForEvent(lifecycle.onAfter[transition]), this.observersForEvent(lifecycle.on[transition])], args);
},
beginTransit: function beginTransit() {
this.pending = true;
},
endTransit: function endTransit(result) {
this.pending = false;
return result;
},
failTransit: function failTransit(result) {
this.pending = false;
throw result;
},
doTransit: function doTransit(lifecycle) {
this.state = lifecycle.to;
},
observe: function observe(args) {
if (args.length === 2) {
var observer = {};
observer[args[0]] = args[1];
this.observers.push(observer);
} else {
this.observers.push(args[0]);
}
},
observersForEvent: function observersForEvent(event) {
// TODO: this could be cached
var n = 0,
max = this.observers.length,
observer,
result = [];
for (; n < max; n++) {
observer = this.observers[n];
if (observer[event]) result.push(observer);
}
return [event, result, true];
},
observeEvents: function observeEvents(events, args, previousEvent, previousResult) {
if (events.length === 0) {
return this.endTransit(previousResult === undefined ? true : previousResult);
}
var event = events[0][0],
observers = events[0][1],
pluggable = events[0][2];
args[0].event = event;
if (event && pluggable && event !== previousEvent) plugin.hook(this, 'lifecycle', args);
if (observers.length === 0) {
events.shift();
return this.observeEvents(events, args, event, previousResult);
} else {
var observer = observers.shift(),
result = observer[event].apply(observer, args);
if (result && typeof result.then === 'function') {
return result.then(this.observeEvents.bind(this, events, args, event)).catch(this.failTransit.bind(this));
} else if (result === false) {
return this.endTransit(false);
} else {
return this.observeEvents(events, args, event, result);
}
}
},
onInvalidTransition: function onInvalidTransition(transition, from, to) {
throw new Exception("transition is invalid in current state", transition, from, to, this.state);
},
onPendingTransition: function onPendingTransition(transition, from, to) {
throw new Exception("transition is invalid while previous transition is still in progress", transition, from, to, this.state);
}
}); //-------------------------------------------------------------------------------------------------
module.exports = JSM; //-------------------------------------------------------------------------------------------------
/***/
},
/* 5 */
/***/
function (module, exports, __webpack_require__) {
var mixin = __webpack_require__(0),
camelize = __webpack_require__(2),
plugin = __webpack_require__(1),
Config = __webpack_require__(3),
JSM = __webpack_require__(4); //-----------------------------------------------------------------------------------------------
var PublicMethods = {
is: function is(state) {
return this._fsm.is(state);
},
can: function can(transition) {
return this._fsm.can(transition);
},
cannot: function cannot(transition) {
return this._fsm.cannot(transition);
},
observe: function observe() {
return this._fsm.observe(arguments);
},
transitions: function transitions() {
return this._fsm.transitions();
},
allTransitions: function allTransitions() {
return this._fsm.allTransitions();
},
allStates: function allStates() {
return this._fsm.allStates();
},
onInvalidTransition: function onInvalidTransition(t, from, to) {
return this._fsm.onInvalidTransition(t, from, to);
},
onPendingTransition: function onPendingTransition(t, from, to) {
return this._fsm.onPendingTransition(t, from, to);
}
};
var PublicProperties = {
state: {
configurable: false,
enumerable: true,
get: function get() {
return this._fsm.state;
},
set: function set(state) {
throw Error('use transitions to change state');
}
}
}; //-----------------------------------------------------------------------------------------------
function StateMachine(options) {
return apply(this || {}, options);
}
function factory() {
var cstor, options;
if (typeof arguments[0] === 'function') {
cstor = arguments[0];
options = arguments[1] || {};
} else {
cstor = function cstor() {
this._fsm.apply(this, arguments);
};
options = arguments[0] || {};
}
var config = new Config(options, StateMachine);
build(cstor.prototype, config);
cstor.prototype._fsm.config = config; // convenience access to shared config without needing an instance
return cstor;
} //-------------------------------------------------------------------------------------------------
function apply(instance, options) {
var config = new Config(options, StateMachine);
build(instance, config);
instance._fsm();
return instance;
}
function build(target, config) {
if (_typeof$2(target) !== 'object' || Array.isArray(target)) throw Error('StateMachine can only be applied to objects');
plugin.build(target, config);
Object.defineProperties(target, PublicProperties);
mixin(target, PublicMethods);
mixin(target, config.methods);
config.allTransitions().forEach(function (transition) {
target[camelize(transition)] = function () {
return this._fsm.fire(transition, [].slice.call(arguments));
};
});
target._fsm = function () {
this._fsm = new JSM(this, config);
this._fsm.init(arguments);
};
} //-----------------------------------------------------------------------------------------------
StateMachine.version = '3.0.1';
StateMachine.factory = factory;
StateMachine.apply = apply;
StateMachine.defaults = {
wildcard: '*',
init: {
name: 'init',
from: 'none'
}
}; //===============================================================================================
module.exports = StateMachine;
/***/
},
/* 6 */
/***/
function (module, exports, __webpack_require__) {
module.exports = function (message, transition, from, to, current) {
this.message = message;
this.transition = transition;
this.from = from;
this.to = to;
this.current = current;
};
/***/
}
/******/
])
);
});
})(stateMachine);
var messages = {};
var init = {};
var abstractmessage = {};
var rngBrowser = {exports: {}};
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API. We do the best we can via
// feature-detection
// getRandomValues needs to be invoked in a context where "this" is a Crypto
// implementation. Also, find the complete implementation of crypto on IE11.
var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto);
if (getRandomValues) {
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
rngBrowser.exports = function whatwgRNG() {
getRandomValues(rnds8);
return rnds8;
};
} else {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var rnds = new Array(16);
rngBrowser.exports = function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return rnds;
};
}
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid$2(buf, offset) {
var i = offset || 0;
var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join('');
}
var bytesToUuid_1 = bytesToUuid$2;
var rng$1 = rngBrowser.exports;
var bytesToUuid$1 = bytesToUuid_1; // **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
var _nodeId;
var _clockseq; // Previous uuid creation time
var _lastMSecs = 0;
var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
function v1$1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var node = options.node || _nodeId;
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
var seedBytes = rng$1();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
} // UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
} // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
} // Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000; // `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff; // `time_mid`
var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff; // `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
b[i++] = clockseq & 0xff; // `node`
for (var n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf ? buf : bytesToUuid$1(b);
}
var v1_1 = v1$1;
var rng = rngBrowser.exports;
var bytesToUuid = bytesToUuid_1;
function v4$1(options, buf, offset) {
var i = buf && offset || 0;
if (typeof options == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
var v4_1 = v4$1;
var v1 = v1_1;
var v4 = v4_1;
var uuid$2 = v4;
uuid$2.v1 = v1;
uuid$2.v4 = v4;
var uuid_1$3 = uuid$2;
Object.defineProperty(abstractmessage, "__esModule", {
value: true
});
var uuid_1$2 = uuid_1$3;
var AbstractMessage = function AbstractMessage(id) {
_classCallCheck$1(this, AbstractMessage);
this.id = id || "TM".concat(uuid_1$2.v4());
};
abstractmessage.AbstractMessage = AbstractMessage;
function _createSuper$K(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$L(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$L() { 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; } }
Object.defineProperty(init, "__esModule", {
value: true
});
var abstractmessage_1$6 = abstractmessage;
var Init = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Init, _abstractmessage_1$Ab);
var _super = _createSuper$K(Init);
function Init(token, continuationToken, metadata) {
var _this;
var registrations = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var tweaks = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
_classCallCheck$1(this, Init);
_this = _super.call(this);
_this.method = 'init';
_this.token = token;
_this.continuation_token = continuationToken;
_this.metadata = metadata;
_this.registrations = registrations;
_this.tweaks = tweaks;
_this.capabilities = ['client_update', 'offline_storage', 'telemetry.v1'];
return _this;
}
return Init;
}(abstractmessage_1$6.AbstractMessage);
init.Init = Init;
var initReply = {};
function _createSuper$J(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$K(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$K() { 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; } }
Object.defineProperty(initReply, "__esModule", {
value: true
});
var abstractmessage_1$5 = abstractmessage;
var ContinuationTokenStatus = function ContinuationTokenStatus() {
_classCallCheck$1(this, ContinuationTokenStatus);
};
initReply.ContinuationTokenStatus = ContinuationTokenStatus;
var InitReply = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(InitReply, _abstractmessage_1$Ab);
var _super = _createSuper$J(InitReply);
function InitReply(id, continuationToken, continuationTokenStatus, offlineStorage, initRegistrations, debugInfo, confirmedCapabilities) {
var _this;
_classCallCheck$1(this, InitReply);
_this = _super.call(this, id);
_this.continuationToken = continuationToken;
_this.continuationTokenStatus = continuationTokenStatus;
_this.offlineStorage = offlineStorage;
_this.initRegistrations = initRegistrations;
_this.debugInfo = debugInfo;
_this.confirmedCapabilities = confirmedCapabilities;
return _this;
}
return InitReply;
}(abstractmessage_1$5.AbstractMessage);
initReply.InitReply = InitReply;
var update = {};
function _createSuper$I(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$J(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$J() { 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; } }
Object.defineProperty(update, "__esModule", {
value: true
});
var abstractmessage_1$4 = abstractmessage;
var Update = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Update, _abstractmessage_1$Ab);
var _super = _createSuper$I(Update);
function Update(token) {
var _this;
_classCallCheck$1(this, Update);
_this = _super.call(this);
_this.method = 'update';
_this.token = token;
return _this;
}
return Update;
}(abstractmessage_1$4.AbstractMessage);
update.Update = Update;
var message = {};
function _createSuper$H(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$I(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$I() { 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; } }
Object.defineProperty(message, "__esModule", {
value: true
});
var abstractmessage_1$3 = abstractmessage;
var Message$1 = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Message, _abstractmessage_1$Ab);
var _super = _createSuper$H(Message);
function Message(grant, contentType, request) {
var _this;
_classCallCheck$1(this, Message);
_this = _super.call(this);
_this.method = 'message';
_this.active_grant = grant;
_this.payload_type = contentType;
_this.http_request = request;
return _this;
}
return Message;
}(abstractmessage_1$3.AbstractMessage);
message.Message = Message$1;
var reply = {};
function _createSuper$G(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$H(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$H() { 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; } }
Object.defineProperty(reply, "__esModule", {
value: true
});
var abstractmessage_1$2 = abstractmessage;
var Reply = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Reply, _abstractmessage_1$Ab);
var _super = _createSuper$G(Reply);
function Reply(id) {
var _this;
_classCallCheck$1(this, Reply);
_this = _super.call(this, id);
_this.method = 'reply';
_this.payload_type = 'application/json';
_this.status = {
code: 200,
status: 'OK'
};
return _this;
}
return Reply;
}(abstractmessage_1$2.AbstractMessage);
reply.Reply = Reply;
var close = {};
function _createSuper$F(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$G(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$G() { 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; } }
Object.defineProperty(close, "__esModule", {
value: true
});
var abstractmessage_1$1 = abstractmessage;
var Close = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Close, _abstractmessage_1$Ab);
var _super = _createSuper$F(Close);
function Close() {
var _this;
_classCallCheck$1(this, Close);
_this = _super.call(this);
_this.method = 'close';
return _this;
}
return Close;
}(abstractmessage_1$1.AbstractMessage);
close.Close = Close;
var telemetry = {};
function _createSuper$E(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$F(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$F() { 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; } }
Object.defineProperty(telemetry, "__esModule", {
value: true
});
var abstractmessage_1 = abstractmessage;
var TelemetryEvent = function TelemetryEvent(start, // relative to event send time
end, // relative to event send time
title, details, id, // optional, default will be random assigned by backend
type) {
_classCallCheck$1(this, TelemetryEvent);
this.start = start;
this.end = end;
this.title = title;
this.details = details;
this.id = id;
this.type = type;
} // optional, default will be "SDK" assigned by backend
;
telemetry.TelemetryEvent = TelemetryEvent;
var Telemetry = /*#__PURE__*/function (_abstractmessage_1$Ab) {
_inherits$1(Telemetry, _abstractmessage_1$Ab);
var _super = _createSuper$E(Telemetry);
function Telemetry(events) {
var _this;
_classCallCheck$1(this, Telemetry);
_this = _super.call(this);
_this.method = 'telemetry.v1';
_this.events = events;
return _this;
}
return Telemetry;
}(abstractmessage_1.AbstractMessage);
telemetry.Telemetry = Telemetry;
Object.defineProperty(messages, "__esModule", {
value: true
});
var init_1 = init;
messages.Init = init_1.Init;
var initReply_1 = initReply;
messages.InitReply = initReply_1.InitReply;
var update_1 = update;
messages.Update = update_1.Update;
var message_1 = message;
messages.Message = message_1.Message;
var reply_1 = reply;
messages.Reply = reply_1.Reply;
var close_1 = close;
messages.Close = close_1.Close;
var telemetry_1$1 = telemetry;
messages.Telemetry = telemetry_1$1.Telemetry;
var parser = {};
Object.defineProperty(parser, "__esModule", {
value: true
});
var logger_1$j = logger$4;
function byteLength(s) {
var escstr = encodeURIComponent(s);
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
});
return binstr.length;
}
function stringToUint8Array(s) {
var escstr = encodeURIComponent(s);
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
});
var ua = new Uint8Array(binstr.length);
Array.prototype.forEach.call(binstr, function (ch, i) {
ua[i] = ch.charCodeAt(0);
});
return ua;
}
function uint8ArrayToString(ua) {
var binstr = Array.prototype.map.call(ua, function (ch) {
return String.fromCharCode(ch);
}).join('');
var escstr = binstr.replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = '0' + code;
}
return '%' + code;
});
return decodeURIComponent(escstr);
}
function getJsonObject(array) {
return JSON.parse(uint8ArrayToString(array));
}
function getMagic(buffer) {
var strMagic = '';
var idx = 0;
for (; idx < buffer.length; ++idx) {
var chr = String.fromCharCode(buffer[idx]);
strMagic += chr;
if (chr === '\r') {
idx += 2;
break;
}
}
var magics = strMagic.split(' ');
return {
size: idx,
protocol: magics[0],
version: magics[1],
headerSize: Number(magics[2])
};
}
var Parser = /*#__PURE__*/function () {
function Parser() {
_classCallCheck$1(this, Parser);
}
_createClass(Parser, null, [{
key: "parse",
value: function parse(message) {
var fieldMargin = 2;
var dataView = new Uint8Array(message);
var magic = getMagic(dataView);
if (magic.protocol !== 'TWILSOCK' || magic.version !== 'V3.0') {
logger_1$j.log.error("unsupported protocol: ".concat(magic.protocol, " ver ").concat(magic.version)); //throw new Error('Unsupported protocol');
//this.fsm.unsupportedProtocol();
return;
}
var header = null;
try {
header = getJsonObject(dataView.subarray(magic.size, magic.size + magic.headerSize));
} catch (e) {
logger_1$j.log.error('failed to parse message header', e, message); //throw new Error('Failed to parse message');
//this.fsm.protocolError();
return;
}
logger_1$j.log.debug('message received: ', header.method);
logger_1$j.log.trace('message received: ', header);
var payload = null;
if (header.payload_size > 0) {
var payloadOffset = fieldMargin + magic.size + magic.headerSize;
var payloadSize = header.payload_size;
if (!header.hasOwnProperty('payload_type') || header.payload_type.indexOf('application/json') === 0) {
try {
payload = getJsonObject(dataView.subarray(payloadOffset, payloadOffset + payloadSize));
} catch (e) {
logger_1$j.log.error('failed to parse message body', e, message); //this.fsm.protocolError();
return;
}
} else if (header.payload_type.indexOf('text/plain') === 0) {
payload = uint8ArrayToString(dataView.subarray(payloadOffset, payloadOffset + payloadSize));
}
}
return {
method: header.method,
header: header,
payload: payload
};
}
}, {
key: "createPacket",
value: function createPacket(header) {
var payloadString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
header.payload_size = byteLength(payloadString); // eslint-disable-line camelcase
var headerString = JSON.stringify(header) + '\r\n';
var magicString = 'TWILSOCK V3.0 ' + (byteLength(headerString) - 2) + '\r\n';
logger_1$j.log.debug('send request:', magicString + headerString + payloadString);
var message = stringToUint8Array(magicString + headerString + payloadString);
return message.buffer;
}
}]);
return Parser;
}();
parser.Parser = Parser;
var twilsockreplyerror = {};
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _isNativeReflectConstruct$E() {
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(Parent, args, Class) {
if (_isNativeReflectConstruct$E()) {
_construct = Reflect.construct;
} else {
_construct = 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(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(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(Class, arguments, _getPrototypeOf$1(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
var twilsockerror = {};
function _createSuper$D(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$D(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$D() { 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; } }
Object.defineProperty(twilsockerror, "__esModule", {
value: true
});
var TwilsockError = /*#__PURE__*/function (_Error) {
_inherits$1(TwilsockError, _Error);
var _super = _createSuper$D(TwilsockError);
function TwilsockError(description) {
_classCallCheck$1(this, TwilsockError);
return _super.call(this, description);
}
return TwilsockError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
twilsockerror.TwilsockError = TwilsockError;
function _createSuper$C(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$C(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$C() { 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; } }
Object.defineProperty(twilsockreplyerror, "__esModule", {
value: true
});
var twilsockerror_1$8 = twilsockerror;
var TwilsockReplyError = /*#__PURE__*/function (_twilsockerror_1$Twil) {
_inherits$1(TwilsockReplyError, _twilsockerror_1$Twil);
var _super = _createSuper$C(TwilsockReplyError);
function TwilsockReplyError(description, reply) {
var _this;
_classCallCheck$1(this, TwilsockReplyError);
_this = _super.call(this, description);
_this.reply = reply;
return _this;
}
return TwilsockReplyError;
}(twilsockerror_1$8.TwilsockError);
twilsockreplyerror.TwilsockReplyError = TwilsockReplyError;
var backoffretrier = {};
var lib$7 = {};
var retrier$3 = {};
function _createSuper$B(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$B(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$B() { 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; } }
Object.defineProperty(retrier$3, "__esModule", {
value: true
});
var events_1$i = require$$0;
/**
* Provides retrier service
*/
var Retrier$3 = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Retrier, _events_1$EventEmitte);
var _super = _createSuper$B(Retrier);
/**
* Creates a new Retrier instance
*/
function Retrier(options) {
var _this;
_classCallCheck$1(this, Retrier);
_this = _super.call(this);
_this.minDelay = options.min;
_this.maxDelay = options.max;
_this.initialDelay = options.initial || 0;
_this.maxAttemptsCount = options.maxAttemptsCount || 0;
_this.maxAttemptsTime = options.maxAttemptsTime || 0;
_this.randomness = options.randomness || 0;
_this.inProgress = false;
_this.attemptNum = 0;
_this.prevDelay = 0;
_this.currDelay = 0;
return _this;
}
_createClass(Retrier, [{
key: "attempt",
value: function attempt() {
clearTimeout(this.timeout);
this.attemptNum++;
this.timeout = null;
this.emit('attempt', this);
}
}, {
key: "nextDelay",
value: function nextDelay(delayOverride) {
if (typeof delayOverride === 'number') {
this.prevDelay = 0;
this.currDelay = delayOverride;
return delayOverride;
}
if (this.attemptNum == 0) {
return this.initialDelay;
}
if (this.attemptNum == 1) {
this.currDelay = this.minDelay;
return this.currDelay;
}
this.prevDelay = this.currDelay;
var delay = this.currDelay + this.prevDelay;
if (this.maxDelay && delay > this.maxDelay) {
this.currDelay = this.maxDelay;
delay = this.maxDelay;
}
this.currDelay = delay;
return delay;
}
}, {
key: "randomize",
value: function randomize(delay) {
var area = delay * this.randomness;
var corr = Math.round(Math.random() * area * 2 - area);
return Math.max(0, delay + corr);
}
}, {
key: "scheduleAttempt",
value: function scheduleAttempt(delayOverride) {
var _this2 = this;
if (this.maxAttemptsCount && this.attemptNum >= this.maxAttemptsCount) {
this.cleanup();
this.emit('failed', new Error('Maximum attempt count limit reached'));
this.reject(new Error('Maximum attempt count reached'));
return;
}
var delay = this.nextDelay(delayOverride);
delay = this.randomize(delay);
if (this.maxAttemptsTime && this.startTimestamp + this.maxAttemptsTime < Date.now() + delay) {
this.cleanup();
this.emit('failed', new Error('Maximum attempt time limit reached'));
this.reject(new Error('Maximum attempt time limit reached'));
return;
}
this.timeout = setTimeout(function () {
return _this2.attempt();
}, delay);
}
}, {
key: "cleanup",
value: function cleanup() {
clearTimeout(this.timeout);
this.timeout = null;
this.inProgress = false;
this.attemptNum = 0;
this.prevDelay = 0;
this.currDelay = 0;
}
}, {
key: "start",
value: function start() {
var _this3 = this;
if (this.inProgress) {
throw new Error('Retrier is already in progress');
}
this.inProgress = true;
return new Promise(function (resolve, reject) {
_this3.resolve = resolve;
_this3.reject = reject;
_this3.startTimestamp = Date.now();
_this3.scheduleAttempt(_this3.initialDelay);
});
}
}, {
key: "cancel",
value: function cancel() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
this.inProgress = false;
this.emit('cancelled');
this.reject(new Error('Cancelled'));
}
}
}, {
key: "succeeded",
value: function succeeded(arg) {
this.emit('succeeded', arg);
this.resolve(arg);
}
}, {
key: "failed",
value: function failed(err, nextAttemptDelayOverride) {
if (this.timeout) {
throw new Error('Retrier attempt is already in progress');
}
this.scheduleAttempt(nextAttemptDelayOverride);
}
}, {
key: "run",
value: function run(handler) {
var _this4 = this;
this.on('attempt', function () {
handler().then(function (v) {
return _this4.succeeded(v);
}).catch(function (e) {
return _this4.failed(e);
});
});
return this.start();
}
}]);
return Retrier;
}(events_1$i.EventEmitter);
retrier$3.Retrier = Retrier$3;
retrier$3.default = Retrier$3;
var backoff$3 = {};
function _createSuper$A(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$A(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$A() { 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; } }
Object.defineProperty(backoff$3, "__esModule", {
value: true
});
var events_1$h = require$$0;
function isDef$3(value) {
return value !== undefined && value !== null;
}
var Backoff$3 = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Backoff, _events_1$EventEmitte);
var _super = _createSuper$A(Backoff);
function Backoff(options) {
var _this;
_classCallCheck$1(this, Backoff);
_this = _super.call(this);
options = options || {};
if (isDef$3(options.initialDelay) && options.initialDelay < 1) {
throw new Error('The initial timeout must be equal to or greater than 1.');
} else if (isDef$3(options.maxDelay) && options.maxDelay <= 1) {
throw new Error('The maximal timeout must be greater than 1.');
} else if (isDef$3(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) {
throw new Error('The randomisation factor must be between 0 and 1.');
} else if (isDef$3(options.factor) && options.factor <= 1) {
throw new Error("Exponential factor should be greater than 1.");
}
_this.initialDelay = options.initialDelay || 100;
_this.maxDelay = options.maxDelay || 10000;
if (_this.maxDelay <= _this.initialDelay) {
throw new Error('The maximal backoff delay must be greater than the initial backoff delay.');
}
_this.randomisationFactor = options.randomisationFactor || 0;
_this.factor = options.factor || 2;
_this.maxNumberOfRetry = -1;
_this.reset();
return _this;
}
_createClass(Backoff, [{
key: "backoff",
value: function backoff(err) {
if (this.timeoutID == null) {
if (this.backoffNumber === this.maxNumberOfRetry) {
this.emit('fail', err);
this.reset();
} else {
this.backoffDelay = this.next();
this.timeoutID = setTimeout(this.onBackoff.bind(this), this.backoffDelay);
this.emit('backoff', this.backoffNumber, this.backoffDelay, err);
}
}
}
}, {
key: "reset",
value: function reset() {
this.backoffDelay = 0;
this.nextBackoffDelay = this.initialDelay;
this.backoffNumber = 0;
clearTimeout(this.timeoutID);
this.timeoutID = null;
}
}, {
key: "failAfter",
value: function failAfter(maxNumberOfRetry) {
if (maxNumberOfRetry <= 0) {
throw new Error("Expected a maximum number of retry greater than 0 but got ".concat(maxNumberOfRetry));
}
this.maxNumberOfRetry = maxNumberOfRetry;
}
}, {
key: "next",
value: function next() {
this.backoffDelay = Math.min(this.nextBackoffDelay, this.maxDelay);
this.nextBackoffDelay = this.backoffDelay * this.factor;
var randomisationMultiple = 1 + Math.random() * this.randomisationFactor;
return Math.min(this.maxDelay, Math.round(this.backoffDelay * randomisationMultiple));
}
}, {
key: "onBackoff",
value: function onBackoff() {
this.timeoutID = null;
this.emit('ready', this.backoffNumber, this.backoffDelay);
this.backoffNumber++;
}
}], [{
key: "exponential",
value: function exponential(options) {
return new Backoff(options);
}
}]);
return Backoff;
}(events_1$h.EventEmitter);
backoff$3.Backoff = Backoff$3;
backoff$3.default = Backoff$3;
Object.defineProperty(lib$7, "__esModule", {
value: true
});
var retrier_1$3 = retrier$3;
lib$7.Retrier = retrier_1$3.Retrier;
var backoff_1$3 = backoff$3;
lib$7.Backoff = backoff_1$3.Backoff;
lib$7.default = retrier_1$3.Retrier;
function _createSuper$z(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$z(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$z() { 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; } }
Object.defineProperty(backoffretrier, "__esModule", {
value: true
});
var events_1$g = require$$0;
var operation_retrier_1$3 = lib$7;
/**
* Retrier with backoff override capability
*/
var BackoffRetrier = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(BackoffRetrier, _events_1$EventEmitte);
var _super = _createSuper$z(BackoffRetrier);
function BackoffRetrier(options) {
var _this;
_classCallCheck$1(this, BackoffRetrier);
_this = _super.call(this);
_this.options = options ? Object.assign({}, options) : {};
return _this;
}
_createClass(BackoffRetrier, [{
key: "inProgress",
get: function get() {
return !!this.retrier;
}
/**
* Should be called once per attempt series to start retrier.
*/
}, {
key: "start",
value: function start() {
if (this.inProgress) {
throw new Error('Already waiting for next attempt, call finishAttempt(success : boolean) to finish it');
}
this.createRetrier();
}
/**
* Should be called to stop retrier entirely.
*/
}, {
key: "stop",
value: function stop() {
this.cleanRetrier();
this.newBackoff = null;
this.usedBackoff = null;
}
/**
* Modifies backoff for next attempt.
* Expected behavior:
* - If there was no backoff passed previously reschedulling next attempt to given backoff
* - If previous backoff was longer then ignoring this one.
* - If previous backoff was shorter then reschedulling with this one.
* With or without backoff retrier will keep growing normally.
* @param delay delay of next attempts in ms.
*/
}, {
key: "modifyBackoff",
value: function modifyBackoff(delay) {
this.newBackoff = delay;
}
/**
* Mark last emmited attempt as failed, initiating either next of fail if limits were hit.
*/
}, {
key: "attemptFailed",
value: function attemptFailed() {
if (!this.inProgress) {
throw new Error('No attempt is in progress');
}
if (this.newBackoff) {
var shouldUseNewBackoff = !this.usedBackoff || this.usedBackoff < this.newBackoff;
if (shouldUseNewBackoff) {
this.createRetrier();
} else {
this.retrier.failed(new Error());
}
} else {
this.retrier.failed(new Error());
}
}
}, {
key: "cancel",
value: function cancel() {
if (this.retrier) {
this.retrier.cancel();
}
}
}, {
key: "cleanRetrier",
value: function cleanRetrier() {
if (this.retrier) {
this.retrier.removeAllListeners();
this.retrier.cancel();
this.retrier = null;
}
}
}, {
key: "getRetryPolicy",
value: function getRetryPolicy() {
var clone = Object.assign({}, this.options);
if (this.newBackoff) {
clone.min = this.newBackoff;
clone.max = this.options.max && this.options.max > this.newBackoff ? this.options.max : this.newBackoff;
} // As we're always skipping first attempt we should add one extra if limit is present
clone.maxAttemptsCount = this.options.maxAttemptsCount ? this.options.maxAttemptsCount + 1 : undefined;
return clone;
}
}, {
key: "createRetrier",
value: function createRetrier() {
var _this2 = this;
this.cleanRetrier();
var retryPolicy = this.getRetryPolicy();
this.retrier = new operation_retrier_1$3.Retrier(retryPolicy);
this.retrier.once('attempt', function () {
_this2.retrier.on('attempt', function () {
return _this2.emit('attempt');
});
_this2.retrier.failed(new Error('Skipping first attempt'));
});
this.retrier.on('failed', function (err) {
return _this2.emit('failed', err);
});
this.usedBackoff = this.newBackoff;
this.newBackoff = null;
this.retrier.start().catch(function (err) {});
}
}]);
return BackoffRetrier;
}(events_1$g.EventEmitter);
backoffretrier.BackoffRetrier = BackoffRetrier;
function _createSuper$y(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$y(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$y() { 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; } }
Object.defineProperty(twilsock, "__esModule", {
value: true
});
var events_1$f = require$$0;
var StateMachine = stateMachine.exports;
var logger_1$i = logger$4;
var Messages$3 = messages;
var parser_1$1 = parser;
var twilsockreplyerror_1$1 = twilsockreplyerror;
var backoffretrier_1 = backoffretrier;
var DISCONNECTING_TIMEOUT = 3000; // Wraps asynchronous rescheduling
// Just makes it simpler to find these hacks over the code
function trampoline(f) {
setTimeout(f, 0);
}
var Response = function Response() {
_classCallCheck$1(this, Response);
};
twilsock.Response = Response;
/**
* Twilsock channel level protocol implementation
*/
var TwilsockChannel = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(TwilsockChannel, _events_1$EventEmitte);
var _super = _createSuper$y(TwilsockChannel);
function TwilsockChannel(websocket, transport, config) {
var _this;
_classCallCheck$1(this, TwilsockChannel);
_this = _super.call(this);
_this.terminalStates = ['disconnected', 'rejected'];
_this.lastEmittedState = undefined;
_this.tokenExpiredSasCode = 20104;
_this.terminationReason = 'Connection is not initialized';
_this.websocket = websocket;
_this.websocket.on('connected', function () {
return _this.fsm.socketConnected();
});
_this.websocket.on('disconnected', function (e) {
return _this.fsm.socketClosed();
});
_this.websocket.on('message', function (message) {
return _this.onIncomingMessage(message);
});
_this.websocket.on('socketError', function (e) {
return _this.emit('connectionError', {
terminal: false,
message: "Socket error: ".concat(e.message),
httpStatusCode: null,
errorCode: null
});
});
_this.transport = transport;
_this.config = config;
_this.retrier = new backoffretrier_1.BackoffRetrier(config.retryPolicy);
_this.retrier.on('attempt', function () {
return _this.retry();
});
_this.retrier.on('failed', function (err) {
logger_1$i.log.warn("Retrying failed: ".concat(err.message));
_this.disconnect();
});
if (typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') {
window.addEventListener('online', function () {
logger_1$i.log.debug('Browser reported connectivity state: online');
_this.resetBackoff();
_this.fsm.systemOnline();
});
window.addEventListener('offline', function () {
logger_1$i.log.debug('Browser reported connectivity state: offline');
_this.websocket.close();
_this.fsm.socketClosed();
});
}
_this.fsm = new StateMachine({
init: 'disconnected',
transitions: [{
name: 'userConnect',
from: ['disconnected', 'rejected'],
to: 'connecting'
}, {
name: 'userConnect',
from: ['connecting', 'connected']
}, {
name: 'userDisconnect',
from: ['connecting', 'initialising', 'connected', 'updating', 'retrying', 'rejected', 'waitSocketClosed', 'waitOffloadSocketClosed'],
to: 'disconnecting'
}, {
name: 'userRetry',
from: ['retrying'],
to: 'connecting'
}, {
name: 'socketConnected',
from: ['connecting'],
to: 'initialising'
}, {
name: 'socketClosed',
from: ['connecting', 'initialising', 'connected', 'updating', 'error', 'waitOffloadSocketClosed'],
to: 'retrying'
}, {
name: 'socketClosed',
from: ['disconnecting'],
to: 'disconnected'
}, {
name: 'socketClosed',
from: ['waitSocketClosed'],
to: 'disconnected'
}, {
name: 'socketClosed',
from: ['rejected'],
to: 'rejected'
}, {
name: 'initSuccess',
from: ['initialising'],
to: 'connected'
}, {
name: 'initError',
from: ['initialising'],
to: 'error'
}, {
name: 'tokenRejected',
from: ['initialising', 'updating'],
to: 'rejected'
}, {
name: 'protocolError',
from: ['initialising', 'connected', 'updating'],
to: 'error'
}, {
name: 'receiveClose',
from: ['initialising', 'connected', 'updating'],
to: 'waitSocketClosed'
}, {
name: 'receiveOffload',
from: ['initialising', 'connected', 'updating'],
to: 'waitOffloadSocketClosed'
}, {
name: 'unsupportedProtocol',
from: ['initialising', 'connected', 'updating'],
to: 'unsupported'
}, {
name: 'receiveFatalClose',
from: ['initialising', 'connected', 'updating'],
to: 'unsupported'
}, {
name: 'userUpdateToken',
from: ['disconnected', 'rejected', 'connecting', 'retrying'],
to: 'connecting'
}, {
name: 'userUpdateToken',
from: ['connected'],
to: 'updating'
}, {
name: 'updateSuccess',
from: ['updating'],
to: 'connected'
}, {
name: 'updateError',
from: ['updating'],
to: 'error'
}, {
name: 'userSend',
from: ['connected'],
to: 'connected'
}, {
name: 'systemOnline',
from: ['retrying'],
to: 'connecting'
}],
methods: {
onConnecting: function onConnecting() {
_this.setupSocket();
_this.emit('connecting');
},
onEnterInitialising: function onEnterInitialising() {
_this.sendInit();
},
onLeaveInitialising: function onLeaveInitialising() {
_this.cancelInit();
},
onEnterUpdating: function onEnterUpdating() {
_this.sendUpdate();
},
onLeaveUpdating: function onLeaveUpdating() {
_this.cancelUpdate();
},
onEnterRetrying: function onEnterRetrying() {
_this.initRetry();
_this.emit('connecting');
},
onEnterConnected: function onEnterConnected() {
_this.resetBackoff();
_this.onConnected();
},
onUserUpdateToken: function onUserUpdateToken() {
_this.resetBackoff();
},
onTokenRejected: function onTokenRejected() {
_this.resetBackoff();
_this.closeSocket(true);
_this.finalizeSocket();
},
onUserDisconnect: function onUserDisconnect() {
_this.closeSocket(true);
},
onEnterDisconnecting: function onEnterDisconnecting() {
_this.startDisconnectTimer();
},
onLeaveDisconnecting: function onLeaveDisconnecting() {
_this.cancelDisconnectTimer();
},
onEnterWaitSocketClosed: function onEnterWaitSocketClosed() {
_this.startDisconnectTimer();
},
onLeaveWaitSocketClosed: function onLeaveWaitSocketClosed() {
_this.cancelDisconnectTimer();
},
onEnterWaitOffloadSocketClosed: function onEnterWaitOffloadSocketClosed() {
_this.startDisconnectTimer();
},
onLeaveWaitOffloadSocketClosed: function onLeaveWaitOffloadSocketClosed() {
_this.cancelDisconnectTimer();
},
onDisconnected: function onDisconnected() {
_this.resetBackoff();
_this.finalizeSocket();
},
onReceiveClose: function onReceiveClose(event, args) {
_this.onCloseReceived(args);
},
onReceiveOffload: function onReceiveOffload(event, args) {
logger_1$i.log.debug('onreceiveoffload: ', args);
_this.modifyBackoff(args.body);
_this.onCloseReceived(args.status);
},
onUnsupported: function onUnsupported() {
_this.closeSocket(true);
_this.finalizeSocket();
},
onError: function onError(lifecycle, graceful) {
_this.closeSocket(graceful);
_this.finalizeSocket();
},
onEnterState: function onEnterState(event) {
if (event.from !== 'none') {
_this.changeState(event);
}
},
onInvalidTransition: function onInvalidTransition(transition, from, to) {
logger_1$i.log.warn('FSM: unexpected transition', from, to);
}
}
});
return _this;
}
_createClass(TwilsockChannel, [{
key: "changeState",
value: function changeState(event) {
logger_1$i.log.debug("FSM: ".concat(event.transition, ": ").concat(event.from, " --> ").concat(event.to));
if (this.lastEmittedState !== this.state) {
this.lastEmittedState = this.state;
this.emit('stateChanged', this.state);
}
}
}, {
key: "resetBackoff",
value: function resetBackoff() {
logger_1$i.log.trace('resetBackoff');
this.retrier.stop();
}
}, {
key: "modifyBackoff",
value: function modifyBackoff(body) {
logger_1$i.log.trace('modifyBackoff', body);
var backoffPolicy = body ? body.backoff_policy : null;
if (backoffPolicy && typeof backoffPolicy.reconnect_min_ms === 'number') {
this.retrier.modifyBackoff(backoffPolicy.reconnect_min_ms);
}
}
}, {
key: "startDisconnectTimer",
value: function startDisconnectTimer() {
var _this2 = this;
logger_1$i.log.trace('startDisconnectTimer');
if (this.disconnectingTimer) {
clearTimeout(this.disconnectingTimer);
this.disconnectingTimer = null;
}
this.disconnectingTimer = setTimeout(function () {
logger_1$i.log.debug('disconnecting is timed out');
_this2.closeSocket(true);
}, DISCONNECTING_TIMEOUT);
}
}, {
key: "cancelDisconnectTimer",
value: function cancelDisconnectTimer() {
logger_1$i.log.trace('cancelDisconnectTimer');
if (this.disconnectingTimer) {
clearTimeout(this.disconnectingTimer);
this.disconnectingTimer = null;
}
}
}, {
key: "isConnected",
get: function get() {
return this.state === 'connected' && this.websocket.isConnected;
}
}, {
key: "state",
get: function get() {
switch (this.fsm.state) {
case 'connecting':
case 'initialising':
case 'retrying':
case 'error':
return 'connecting';
case 'updating':
case 'connected':
return 'connected';
case 'rejected':
return 'rejected';
case 'disconnecting':
case 'waitSocketClosed':
case 'waitOffloadSocketClosed':
return 'disconnecting';
case 'disconnected':
default:
return 'disconnected';
}
}
}, {
key: "initRetry",
value: function initRetry() {
logger_1$i.log.debug('initRetry');
if (this.retrier.inProgress) {
this.retrier.attemptFailed();
} else {
this.retrier.start();
}
}
}, {
key: "retry",
value: function retry() {
if (this.fsm.state != 'connecting') {
logger_1$i.log.trace('retry');
this.websocket.close();
this.fsm.userRetry();
} else {
logger_1$i.log.trace('can\t retry as already connecting');
}
}
}, {
key: "onConnected",
value: function onConnected() {
this.emit('connected');
}
}, {
key: "finalizeSocket",
value: function finalizeSocket() {
logger_1$i.log.trace('finalizeSocket');
this.websocket.close();
this.emit('disconnected');
if (this.disconnectedPromiseResolve) {
this.disconnectedPromiseResolve();
this.disconnectedPromiseResolve = null;
}
}
}, {
key: "setupSocket",
value: function setupSocket() {
logger_1$i.log.trace('setupSocket:', this.config.token);
this.emit('beforeConnect'); // This is used by client to record startup telemetry event
this.websocket.connect();
}
}, {
key: "onIncomingMessage",
value: function onIncomingMessage(message) {
var _parser_1$Parser$pars = parser_1$1.Parser.parse(message),
method = _parser_1$Parser$pars.method,
header = _parser_1$Parser$pars.header,
payload = _parser_1$Parser$pars.payload;
if (method !== 'reply') {
this.confirmReceiving(header);
}
if (method === 'notification') {
this.emit('message', header.message_type, payload);
} else if (header.method === 'reply') {
this.transport.processReply({
id: header.id,
status: header.status,
header: header,
body: payload
});
} else if (header.method === 'client_update') {
if (header.client_update_type === 'token_about_to_expire') {
this.emit('tokenAboutToExpire');
}
} else if (header.method === 'close') {
if (header.status.code === 308) {
logger_1$i.log.debug('Connection has been offloaded');
this.fsm.receiveOffload({
status: header.status.status,
body: payload
});
} else if (header.status.code === 406) {
// Not acceptable message
var _message = "Server closed connection because can't parse protocol: ".concat(JSON.stringify(header.status));
this.emitReplyConnectionError(_message, header, true);
logger_1$i.log.error(_message);
this.fsm.receiveFatalClose();
} else if (header.status.code === 417) {
// Protocol error
logger_1$i.log.error("Server closed connection because can't parse client reply: ".concat(JSON.stringify(header.status)));
this.fsm.receiveFatalClose(header.status.status);
} else if (header.status.code === 410) {
// Expired token
logger_1$i.log.warn("Server closed connection: ".concat(JSON.stringify(header.status)));
this.fsm.receiveClose(header.status.status);
this.emit('tokenExpired');
} else if (header.status.code === 401) {
// Authentication fail
logger_1$i.log.error("Server closed connection: ".concat(JSON.stringify(header.status)));
this.fsm.receiveClose(header.status.status);
} else {
logger_1$i.log.warn('unexpected message: ', header.status); // Try to reconnect
this.fsm.receiveOffload({
status: header.status.status,
body: null
});
}
}
}
}, {
key: "sendInit",
value: function () {
var _sendInit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var reply, isTerminalError;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
logger_1$i.log.trace('sendInit');
_context.prev = 1;
this.emit('beforeSendInit'); // This is used by client to record startup telemetry event
_context.next = 5;
return this.transport.sendInit();
case 5:
reply = _context.sent;
this.config.updateContinuationToken(reply.continuationToken);
this.config.confirmedCapabilities = reply.confirmedCapabilities;
this.fsm.initSuccess(reply);
this.emit('initialized', reply);
this.emit('tokenUpdated');
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](1);
if (_context.t0 instanceof twilsockreplyerror_1$1.TwilsockReplyError) {
isTerminalError = false;
logger_1$i.log.warn("Init rejected by server: ".concat(JSON.stringify(_context.t0.reply.status)));
this.emit('sendInitFailed'); // This is used by client to record startup telemetry event
// @todo emit telemetry from inside "if" below for more granularity...
if (_context.t0.reply.status.code === 401 || _context.t0.reply.status.code === 403) {
isTerminalError = true;
this.fsm.tokenRejected(_context.t0.reply.status);
if (_context.t0.reply.status.errorCode === this.tokenExpiredSasCode) {
this.emit('tokenExpired');
}
} else if (_context.t0.reply.status.code === 429) {
this.modifyBackoff(_context.t0.reply.body);
this.fsm.initError(true);
} else if (_context.t0.reply.status.code === 500) {
this.fsm.initError(false);
} else {
this.fsm.initError(true);
}
this.emitReplyConnectionError(_context.t0.message, _context.t0.reply, isTerminalError);
} else {
this.terminationReason = _context.t0.message;
this.emit('connectionError', {
terminal: true,
message: "Unknown error during connection initialisation: ".concat(_context.t0.message, "\n").concat(JSON.stringify(_context.t0, null, 2)),
httpStatusCode: null,
errorCode: null
});
this.fsm.initError(true);
}
this.emit('tokenUpdated', _context.t0);
case 17:
case "end":
return _context.stop();
}
}
}, _callee, this, [[1, 13]]);
}));
function sendInit() {
return _sendInit.apply(this, arguments);
}
return sendInit;
}()
}, {
key: "sendUpdate",
value: function () {
var _sendUpdate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
var message, reply, isTerminalError;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
logger_1$i.log.trace('sendUpdate');
message = new Messages$3.Update(this.config.token);
_context2.prev = 2;
_context2.next = 5;
return this.transport.sendWithReply(message);
case 5:
reply = _context2.sent;
this.fsm.updateSuccess(reply.body);
this.emit('tokenUpdated');
_context2.next = 14;
break;
case 10:
_context2.prev = 10;
_context2.t0 = _context2["catch"](2);
if (_context2.t0 instanceof twilsockreplyerror_1$1.TwilsockReplyError) {
isTerminalError = false;
logger_1$i.log.warn("Token update rejected by server: ".concat(JSON.stringify(_context2.t0.reply.status)));
if (_context2.t0.reply.status.code === 401 || _context2.t0.reply.status.code === 403) {
isTerminalError = true;
this.fsm.tokenRejected(_context2.t0.reply.status);
if (_context2.t0.reply.status.errorCode === this.tokenExpiredSasCode) {
this.emit('tokenExpired');
}
} else if (_context2.t0.reply.status.code === 429) {
this.modifyBackoff(_context2.t0.reply.body);
this.fsm.updateError(_context2.t0.reply.status);
} else {
this.fsm.updateError(_context2.t0.reply.status);
}
this.emitReplyConnectionError(_context2.t0.message, _context2.t0.reply, isTerminalError);
} else {
this.emit('error', false, _context2.t0.message, null, null);
this.fsm.updateError(_context2.t0);
}
this.emit('tokenUpdated', _context2.t0);
case 14:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[2, 10]]);
}));
function sendUpdate() {
return _sendUpdate.apply(this, arguments);
}
return sendUpdate;
}()
}, {
key: "emitReplyConnectionError",
value: function emitReplyConnectionError(message, header, terminal) {
var description = header.status && header.status.description ? header.status.description : message;
var httpStatusCode = header.status.code;
var errorCode = header.status && header.status.errorCode ? header.status.errorCode : null;
if (terminal) {
this.terminationReason = description;
}
this.emit('connectionError', {
terminal: terminal,
message: "Connection error: ".concat(description),
httpStatusCode: httpStatusCode,
errorCode: errorCode
});
}
}, {
key: "cancelInit",
value: function cancelInit() {
logger_1$i.log.trace('cancelInit'); // TODO: implement
}
}, {
key: "cancelUpdate",
value: function cancelUpdate() {
logger_1$i.log.trace('cancelUpdate'); // TODO: implement
}
/**
* Should be called for each message to confirm it received
*/
}, {
key: "confirmReceiving",
value: function confirmReceiving(messageHeader) {
logger_1$i.log.trace('confirmReceiving');
try {
//@todo send telemetry events AnyEvents
this.transport.send(new Messages$3.Reply(messageHeader.id));
} catch (e) {
logger_1$i.log.debug('failed to confirm packet receiving', e);
}
}
/**
* Shutdown connection
*/
}, {
key: "closeSocket",
value: function closeSocket(graceful) {
var _this3 = this;
logger_1$i.log.trace("closeSocket (graceful: ".concat(graceful, ")"));
if (graceful && this.transport.isConnected) {
this.transport.sendClose();
}
this.websocket.close();
trampoline(function () {
return _this3.fsm.socketClosed();
});
}
/**
* Initiate the twilsock connection
* If already connected, it does nothing
*/
}, {
key: "connect",
value: function connect() {
logger_1$i.log.trace('connect');
this.fsm.userConnect();
}
/**
* Close twilsock connection
* If already disconnected, it does nothing
*/
}, {
key: "disconnect",
value: function disconnect() {
var _this4 = this;
logger_1$i.log.trace('disconnect');
if (this.fsm.is('disconnected')) {
return Promise.resolve();
}
return new Promise(function (resolve) {
_this4.disconnectedPromiseResolve = resolve;
_this4.fsm.userDisconnect();
});
}
/**
* Update fpa token for twilsock connection
*/
}, {
key: "updateToken",
value: function updateToken(token) {
var _this5 = this;
logger_1$i.log.trace('updateToken:', token);
return new Promise(function (resolve, reject) {
_this5.once('tokenUpdated', function (e) {
if (e) {
reject(e);
} else {
resolve();
}
});
_this5.fsm.userUpdateToken();
});
}
}, {
key: "isTerminalState",
get: function get() {
return this.terminalStates.indexOf(this.fsm.state) !== -1;
}
}, {
key: "getTerminationReason",
get: function get() {
return this.terminationReason;
}
}, {
key: "onCloseReceived",
value: function onCloseReceived(reason) {
this.websocket.close();
}
}]);
return TwilsockChannel;
}(events_1$f.EventEmitter);
twilsock.TwilsockChannel = TwilsockChannel;
twilsock.TwilsockImpl = TwilsockChannel;
var packetinterface = {};
var metadata = {};
var platform$4 = {exports: {}};
(function (module, exports) {
(function () {
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Used as a reference to the global object. */
var root = objectTypes[typeof window === "undefined" ? "undefined" : _typeof$2(window)] && window || this;
/** Detect free variable `exports`. */
var freeExports = exports;
/** Detect free variable `module`. */
var freeModule = module && !module.nodeType && module;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */
var freeGlobal = freeExports && freeModule && _typeof$2(commonjsGlobal) == 'object' && commonjsGlobal;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
root = freeGlobal;
}
/**
* Used as the maximum length of an array-like object.
* See the [ES6 spec](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
* for more details.
*/
var maxSafeInteger = Math.pow(2, 53) - 1;
/** Regular expression to detect Opera. */
var reOpera = /\bOpera/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check for own properties of an object. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to resolve the internal `[[Class]]` of values. */
var toString = objectProto.toString;
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
*
* @private
* @param {string} string The string to capitalize.
* @returns {string} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* A utility function to clean up the OS name.
*
* @private
* @param {string} os The OS name to clean up.
* @param {string} [pattern] A `RegExp` pattern matching the OS name.
* @param {string} [label] A label for the OS.
*/
function cleanupOS(os, pattern, label) {
// Platform tokens are defined at:
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
var data = {
'10.0': '10',
'6.4': '10 Technical Preview',
'6.3': '8.1',
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
}; // Detect Windows version from platform tokens.
if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) && (data = data[/[\d.]+$/.exec(os)])) {
os = 'Windows ' + data;
} // Correct character case and cleanup string.
os = String(os);
if (pattern && label) {
os = os.replace(RegExp(pattern, 'i'), label);
}
os = format(os.replace(/ ce$/i, ' CE').replace(/\bhpw/i, 'web').replace(/\bMacintosh\b/, 'Mac OS').replace(/_PowerPC\b/i, ' OS').replace(/\b(OS X) [^ \d]+/i, '$1').replace(/\bMac (OS X)\b/, '$1').replace(/\/(\d)/, ' $1').replace(/_/g, '.').replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '').replace(/\bx86\.64\b/gi, 'x86_64').replace(/\b(Windows Phone) OS\b/, '$1').replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1').split(' on ')[0]);
return os;
}
/**
* An iteration utility for arrays and objects.
*
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object ? object.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Trim and conditionally capitalize string values.
*
* @private
* @param {string} string The string to format.
* @returns {string} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string);
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
if (hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
}
/**
* Gets the internal `[[Class]]` of a value.
*
* @private
* @param {*} value The value.
* @returns {string} The `[[Class]]`.
*/
function getClassOf(value) {
return value == null ? capitalize(value) : toString.call(value).slice(8, -1);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of "object", "function", or "unknown".
*
* @private
* @param {*} object The owner of the property.
* @param {string} property The property to check.
* @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? _typeof$2(object[property]) : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) && (type == 'object' ? !!object[property] : true);
}
/**
* Prepares a string for use in a `RegExp` by making hyphens and spaces optional.
*
* @private
* @param {string} string The string to qualify.
* @returns {string} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* A bare-bones `Array#reduce` like utility function.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @returns {*} The accumulated result.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function (value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Removes leading and trailing whitespace from a string.
*
* @private
* @param {string} string The string to trim.
* @returns {string} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
*
* @memberOf platform
* @param {Object|string} [ua=navigator.userAgent] The user agent string or
* context object.
* @returns {Object} A platform object.
*/
function parse(ua) {
/** The environment context object. */
var context = root;
/** Used to flag when a custom context is provided. */
var isCustomContext = ua && _typeof$2(ua) == 'object' && getClassOf(ua) != 'String'; // Juggle arguments.
if (isCustomContext) {
context = ua;
ua = null;
}
/** Browser navigator object. */
var nav = context.navigator || {};
/** Browser user agent string. */
var userAgent = nav.userAgent || '';
ua || (ua = userAgent);
/** Used to detect if browser is like Chrome. */
var likeChrome = isCustomContext ? !!nav.likeChrome : /\bChrome\b/.test(ua) && !/internal|\n/i.test(toString.toString());
/** Internal `[[Class]]` value shortcuts. */
var objectClass = 'Object',
airRuntimeClass = isCustomContext ? objectClass : 'ScriptBridgingProxyObject',
enviroClass = isCustomContext ? objectClass : 'Environment',
javaClass = isCustomContext && context.java ? 'JavaPackage' : getClassOf(context.java),
phantomClass = isCustomContext ? objectClass : 'RuntimeObject';
/** Detect Java environments. */
var java = /\bJava/.test(javaClass) && context.java;
/** Detect Rhino. */
var rhino = java && getClassOf(context.environment) == enviroClass;
/** A character to represent alpha. */
var alpha = java ? 'a' : "\u03B1";
/** A character to represent beta. */
var beta = java ? 'b' : "\u03B2";
/** Browser document object. */
var doc = context.document || {};
/**
* Detect Opera browser (Presto-based).
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
var opera = context.operamini || context.opera;
/** Opera `[[Class]]`. */
var operaClass = reOpera.test(operaClass = isCustomContext && opera ? opera['[[Class]]'] : getClassOf(opera)) ? operaClass : opera = null;
/*------------------------------------------------------------------------*/
/** Temporary variable used over the script's lifetime. */
var data;
/** The CPU architecture. */
var arch = ua;
/** Platform description array. */
var description = [];
/** Platform alpha/beta indicator. */
var prerelease = null;
/** A flag to indicate that environment features should be used to resolve the platform. */
var useFeatures = ua == userAgent;
/** The browser/environment version. */
var version = useFeatures && opera && typeof opera.version == 'function' && opera.version();
/** A flag to indicate if the OS ends with "/ Version" */
var isSpecialCasedOS;
/* Detectable layout engines (order is important). */
var layout = getLayout([{
'label': 'EdgeHTML',
'pattern': 'Edge'
}, 'Trident', {
'label': 'WebKit',
'pattern': 'AppleWebKit'
}, 'iCab', 'Presto', 'NetFront', 'Tasman', 'KHTML', 'Gecko']);
/* Detectable browser names (order is important). */
var name = getName(['Adobe AIR', 'Arora', 'Avant Browser', 'Breach', 'Camino', 'Electron', 'Epiphany', 'Fennec', 'Flock', 'Galeon', 'GreenBrowser', 'iCab', 'Iceweasel', 'K-Meleon', 'Konqueror', 'Lunascape', 'Maxthon', {
'label': 'Microsoft Edge',
'pattern': '(?:Edge|Edg|EdgA|EdgiOS)'
}, 'Midori', 'Nook Browser', 'PaleMoon', 'PhantomJS', 'Raven', 'Rekonq', 'RockMelt', {
'label': 'Samsung Internet',
'pattern': 'SamsungBrowser'
}, 'SeaMonkey', {
'label': 'Silk',
'pattern': '(?:Cloud9|Silk-Accelerated)'
}, 'Sleipnir', 'SlimBrowser', {
'label': 'SRWare Iron',
'pattern': 'Iron'
}, 'Sunrise', 'Swiftfox', 'Vivaldi', 'Waterfox', 'WebPositive', {
'label': 'Yandex Browser',
'pattern': 'YaBrowser'
}, {
'label': 'UC Browser',
'pattern': 'UCBrowser'
}, 'Opera Mini', {
'label': 'Opera Mini',
'pattern': 'OPiOS'
}, 'Opera', {
'label': 'Opera',
'pattern': 'OPR'
}, 'Chromium', 'Chrome', {
'label': 'Chrome',
'pattern': '(?:HeadlessChrome)'
}, {
'label': 'Chrome Mobile',
'pattern': '(?:CriOS|CrMo)'
}, {
'label': 'Firefox',
'pattern': '(?:Firefox|Minefield)'
}, {
'label': 'Firefox for iOS',
'pattern': 'FxiOS'
}, {
'label': 'IE',
'pattern': 'IEMobile'
}, {
'label': 'IE',
'pattern': 'MSIE'
}, 'Safari']);
/* Detectable products (order is important). */
var product = getProduct([{
'label': 'BlackBerry',
'pattern': 'BB10'
}, 'BlackBerry', {
'label': 'Galaxy S',
'pattern': 'GT-I9000'
}, {
'label': 'Galaxy S2',
'pattern': 'GT-I9100'
}, {
'label': 'Galaxy S3',
'pattern': 'GT-I9300'
}, {
'label': 'Galaxy S4',
'pattern': 'GT-I9500'
}, {
'label': 'Galaxy S5',
'pattern': 'SM-G900'
}, {
'label': 'Galaxy S6',
'pattern': 'SM-G920'
}, {
'label': 'Galaxy S6 Edge',
'pattern': 'SM-G925'
}, {
'label': 'Galaxy S7',
'pattern': 'SM-G930'
}, {
'label': 'Galaxy S7 Edge',
'pattern': 'SM-G935'
}, 'Google TV', 'Lumia', 'iPad', 'iPod', 'iPhone', 'Kindle', {
'label': 'Kindle Fire',
'pattern': '(?:Cloud9|Silk-Accelerated)'
}, 'Nexus', 'Nook', 'PlayBook', 'PlayStation Vita', 'PlayStation', 'TouchPad', 'Transformer', {
'label': 'Wii U',
'pattern': 'WiiU'
}, 'Wii', 'Xbox One', {
'label': 'Xbox 360',
'pattern': 'Xbox'
}, 'Xoom']);
/* Detectable manufacturers. */
var manufacturer = getManufacturer({
'Apple': {
'iPad': 1,
'iPhone': 1,
'iPod': 1
},
'Alcatel': {},
'Archos': {},
'Amazon': {
'Kindle': 1,
'Kindle Fire': 1
},
'Asus': {
'Transformer': 1
},
'Barnes & Noble': {
'Nook': 1
},
'BlackBerry': {
'PlayBook': 1
},
'Google': {
'Google TV': 1,
'Nexus': 1
},
'HP': {
'TouchPad': 1
},
'HTC': {},
'Huawei': {},
'Lenovo': {},
'LG': {},
'Microsoft': {
'Xbox': 1,
'Xbox One': 1
},
'Motorola': {
'Xoom': 1
},
'Nintendo': {
'Wii U': 1,
'Wii': 1
},
'Nokia': {
'Lumia': 1
},
'Oppo': {},
'Samsung': {
'Galaxy S': 1,
'Galaxy S2': 1,
'Galaxy S3': 1,
'Galaxy S4': 1
},
'Sony': {
'PlayStation': 1,
'PlayStation Vita': 1
},
'Xiaomi': {
'Mi': 1,
'Redmi': 1
}
});
/* Detectable operating systems (order is important). */
var os = getOS(['Windows Phone', 'KaiOS', 'Android', 'CentOS', {
'label': 'Chrome OS',
'pattern': 'CrOS'
}, 'Debian', {
'label': 'DragonFly BSD',
'pattern': 'DragonFly'
}, 'Fedora', 'FreeBSD', 'Gentoo', 'Haiku', 'Kubuntu', 'Linux Mint', 'OpenBSD', 'Red Hat', 'SuSE', 'Ubuntu', 'Xubuntu', 'Cygwin', 'Symbian OS', 'hpwOS', 'webOS ', 'webOS', 'Tablet OS', 'Tizen', 'Linux', 'Mac OS X', 'Macintosh', 'Mac', 'Windows 98;', 'Windows ']);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function (result, guess) {
return result || RegExp('\\b' + (guess.pattern || qualify(guess)) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
*
* @private
* @param {Array} guesses An object of guesses.
* @returns {null|string} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function (result, value, key) {
// Lookup the manufacturer by product or scan the UA for the manufacturer.
return result || (value[product] || value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)) && key;
});
}
/**
* Picks the browser name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function (result, guess) {
return result || RegExp('\\b' + (guess.pattern || qualify(guess)) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function (result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) {
result = cleanupOS(result, pattern, guess.label || guess);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function (result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) || RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua))) {
// Split by forward slash and append product version if needed.
if ((result = String(guess.label && !RegExp(pattern, 'i').test(guess.label) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
} // Correct character case and cleanup string.
guess = guess.label || guess;
result = format(result[0].replace(RegExp(pattern, 'i'), guess).replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ').replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
*
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {null|string} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function (result, pattern) {
return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/**
* Returns `platform.description` when the platform object is coerced to a string.
*
* @name toString
* @memberOf platform
* @returns {string} Returns `platform.description` if available, else an empty string.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// Convert layout to an array so we can add extra details.
layout && (layout = [layout]); // Detect Android products.
// Browsers on Android devices typically provide their product IDS after "Android;"
// up to "Build" or ") AppleWebKit".
// Example:
// "Mozilla/5.0 (Linux; Android 8.1.0; Moto G (5) Plus) AppleWebKit/537.36
// (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36"
if (/\bAndroid\b/.test(os) && !product && (data = /\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(ua))) {
product = trim(data[1]) // Replace any language codes (eg. "en-US").
.replace(/^[a-z]{2}-[a-z]{2};\s*/i, '') || null;
} // Detect product names that contain their manufacturer's name.
if (manufacturer && !product) {
product = getProduct([manufacturer]);
} else if (manufacturer && product) {
product = product.replace(RegExp('^(' + qualify(manufacturer) + ')[-_.\\s]', 'i'), manufacturer + ' ').replace(RegExp('^(' + qualify(manufacturer) + ')[-_.]?(\\w)', 'i'), manufacturer + ' $2');
} // Clean up Google TV.
if (data = /\bGoogle TV\b/.exec(product)) {
product = data[0];
} // Detect simulators.
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
} // Detect Opera Mini 8+ running in Turbo/Uncompressed mode on iOS.
if (name == 'Opera Mini' && /\bOPiOS\b/.test(ua)) {
description.push('running in Turbo/Uncompressed mode');
} // Detect IE Mobile 11.
if (name == 'IE' && /\blike iPhone OS\b/.test(ua)) {
data = parse(ua.replace(/like iPhone OS/, ''));
manufacturer = data.manufacturer;
product = data.product;
} // Detect iOS.
else if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) ? ' ' + data[1].replace(/_/g, '.') : '');
} // Detect Kubuntu.
else if (name == 'Konqueror' && /^Linux\b/i.test(os)) {
os = 'Kubuntu';
} // Detect Android browsers.
else if (manufacturer && manufacturer != 'Google' && (/Chrome/.test(name) && !/\bMobile Safari\b/i.test(ua) || /\bVita\b/.test(product)) || /\bAndroid\b/.test(os) && /^Chrome/.test(name) && /\bVersion\//i.test(ua)) {
name = 'Android Browser';
os = /\bAndroid\b/.test(os) ? os : 'Android';
} // Detect Silk desktop/accelerated modes.
else if (name == 'Silk') {
if (!/\bMobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
} // Detect UC Browser speed mode.
else if (name == 'UC Browser' && /\bUCWEB\b/.test(ua)) {
description.push('speed mode');
} // Detect PaleMoon identifying as Firefox.
else if (name == 'PaleMoon' && (data = /\bFirefox\/([\d.]+)\b/.exec(ua))) {
description.push('identifying as Firefox ' + data[1]);
} // Detect Firefox OS and products running Firefox.
else if (name == 'Firefox' && (data = /\b(Mobile|Tablet|TV)\b/i.exec(ua))) {
os || (os = 'Firefox OS');
product || (product = data[1]);
} // Detect false positives for Firefox/Safari.
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /\b(?:Firefox|Safari)\b/.exec(name))) {
// Escape the `/` for Firefox 1.
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// Clear name of false positives.
name = null;
} // Reassign a generic name.
if ((data = product || manufacturer || os) && (product || manufacturer || /\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os) ? os : data) + ' Browser';
}
} // Add Chrome version to description for Electron.
else if (name == 'Electron' && (data = (/\bChrome\/([\d.]+)\b/.exec(ua) || 0)[1])) {
description.push('Chromium ' + data);
} // Detect non-Opera (Presto-based) versions (order is important).
if (!version) {
version = getVersion(['(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)', 'Version', qualify(name), '(?:Firefox|Minefield|NetFront)']);
} // Detect stubborn layout engines.
if (data = layout == 'iCab' && parseFloat(version) > 3 && 'WebKit' || /\bOpera\b/.test(name) && (/\bOPR\b/.test(ua) ? 'Blink' : 'Presto') || /\b(?:Midori|Nook|Safari)\b/i.test(ua) && !/^(?:Trident|EdgeHTML)$/.test(layout) && 'WebKit' || !layout && /\bMSIE\b/i.test(ua) && (os == 'Mac OS' ? 'Tasman' : 'Trident') || layout == 'WebKit' && /\bPlayStation\b(?! Vita\b)/i.test(name) && 'NetFront') {
layout = [data];
} // Detect Windows Phone 7 desktop mode.
if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone ' + (/\+$/.test(data) ? data : data + '.x');
description.unshift('desktop mode');
} // Detect Windows Phone 8.x desktop mode.
else if (/\bWPDesktop\b/i.test(ua)) {
name = 'IE Mobile';
os = 'Windows Phone 8.x';
description.unshift('desktop mode');
version || (version = (/\brv:([\d.]+)/.exec(ua) || 0)[1]);
} // Detect IE 11 identifying as other browsers.
else if (name != 'IE' && layout == 'Trident' && (data = /\brv:([\d.]+)/.exec(ua))) {
if (name) {
description.push('identifying as ' + name + (version ? ' ' + version : ''));
}
name = 'IE';
version = data[1];
} // Leverage environment features.
if (useFeatures) {
// Detect server-side environments.
// Rhino has a global function while others have a global object.
if (isHostType(context, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (rhino) {
try {
version = context.require('ringo/engine').version.join('.');
name = 'RingoJS';
} catch (e) {
if ((data = context.system) && data.global.system == context.system) {
name = 'Narwhal';
os || (os = data[0].os || null);
}
}
if (!name) {
name = 'Rhino';
}
} else if (_typeof$2(context.process) == 'object' && !context.process.browser && (data = context.process)) {
if (_typeof$2(data.versions) == 'object') {
if (typeof data.versions.electron == 'string') {
description.push('Node ' + data.versions.node);
name = 'Electron';
version = data.versions.electron;
} else if (typeof data.versions.nw == 'string') {
description.push('Chromium ' + version, 'Node ' + data.versions.node);
name = 'NW.js';
version = data.versions.nw;
}
}
if (!name) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version);
version = version ? version[0] : null;
}
}
} // Detect Adobe AIR.
else if (getClassOf(data = context.runtime) == airRuntimeClass) {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
} // Detect PhantomJS.
else if (getClassOf(data = context.phantom) == phantomClass) {
name = 'PhantomJS';
version = (data = data.version || null) && data.major + '.' + data.minor + '.' + data.patch;
} // Detect IE compatibility modes.
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// We're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode.
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout && (layout[1] = '');
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
} // Detect IE 11 masking as other browsers.
else if (typeof doc.documentMode == 'number' && /^(?:Chrome|Firefox)\b/.test(name)) {
description.push('masking as ' + name + ' ' + version);
name = 'IE';
version = '11.0';
layout = ['Trident'];
os = 'Windows';
}
os = os && format(os);
} // Detect prerelease phases.
if (version && (data = /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || /\bMinefield\b/i.test(ua) && 'a')) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
} // Detect Firefox Mobile.
if (name == 'Fennec' || name == 'Firefox' && /\b(?:Android|Firefox OS|KaiOS)\b/.test(os)) {
name = 'Firefox Mobile';
} // Obscure Maxthon's unreliable version.
else if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
} // Detect Xbox 360 and Xbox One.
else if (/\bXbox\b/i.test(product)) {
if (product == 'Xbox 360') {
os = null;
}
if (product == 'Xbox 360' && /\bIEMobile\b/.test(ua)) {
description.unshift('mobile mode');
}
} // Add mobile postfix.
else if ((/^(?:Chrome|IE|Opera)$/.test(name) || name && !product && !/Browser|Mobi/.test(name)) && (os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
} // Detect IE platform preview.
else if (name == 'IE' && useFeatures) {
try {
if (context.external === null) {
description.unshift('platform preview');
}
} catch (e) {
description.unshift('embedded');
}
} // Detect BlackBerry OS version.
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if ((/\bBlackBerry\b/.test(product) || /\bBB10\b/.test(ua)) && (data = (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || version)) {
data = [data, /BB10/.test(ua)];
os = (data[1] ? (product = null, manufacturer = 'BlackBerry') : 'Device Software') + ' ' + data[0];
version = null;
} // Detect Opera identifying/masking itself as another browser.
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && product != 'Wii' && (useFeatures && opera || /Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua) || name == 'Firefox' && /\bOS X (?:\d+\.){2,}/.test(os) || name == 'IE' && (os && !/^Win/.test(os) && version > 5.5 || /\bWindows XP\b/.test(os) && version > 8 || version == 8 && !/\bTrident\b/.test(ua))) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) {
// When "identifying", the UA contains both Opera and the other browser's name.
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/\bIE\b/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
} // When "masking", the UA contains only the other browser's name.
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/\bIE\b/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
} // Detect WebKit Nightly and approximate Chrome/Safari versions.
if (data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1]) {
// Correct build number for numeric comparison.
// (e.g. "532.5" becomes "532.05")
data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; // Nightly builds are postfixed with a "+".
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
} // Clear incorrect browser versions.
else if (version == data[1] || version == (data[2] = (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
version = null;
} // Use the full Chrome version when available.
data[1] = (/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua) || 0)[1]; // Detect Blink layout engine.
if (data[0] == 537.36 && data[2] == 537.36 && parseFloat(data[1]) >= 28 && layout == 'WebKit') {
layout = ['Blink'];
} // Detect JavaScriptCore.
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || !likeChrome && !data[1]) {
layout && (layout[1] = 'like Safari');
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : data < 537 ? 6 : data < 538 ? 7 : data < 601 ? 8 : data < 602 ? 9 : data < 604 ? 10 : data < 606 ? 11 : data < 608 ? 12 : '12');
} else {
layout && (layout[1] = 'like Chrome');
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : data < 537.11 ? '21+' : data < 537.13 ? 23 : data < 537.18 ? 24 : data < 537.24 ? 25 : data < 537.36 ? 26 : layout != 'Blink' ? '27' : '28');
} // Add the postfix of ".x" or "+" for approximate versions.
layout && (layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+')); // Obscure version for some Safari 1-2 releases.
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
} else if (name == 'Chrome' && /\bHeadlessChrome/i.test(ua)) {
description.unshift('headless');
}
} // Detect Opera desktop modes.
if (name == 'Opera' && (data = /\bzbov|zvav$/.exec(os))) {
name += ' ';
description.unshift('desktop mode');
if (data == 'zvav') {
name += 'Mini';
version = null;
} else {
name += 'Mobile';
}
os = os.replace(RegExp(' *' + data + '$'), '');
} // Detect Chrome desktop mode.
else if (name == 'Safari' && /\bChrome\b/.exec(layout && layout[1])) {
description.unshift('desktop mode');
name = 'Chrome Mobile';
version = null;
if (/\bOS X\b/.test(os)) {
manufacturer = 'Apple';
os = 'iOS 4.3+';
} else {
os = null;
}
} // Newer versions of SRWare Iron uses the Chrome tag to indicate its version number.
else if (/\bSRWare Iron\b/.test(name) && !version) {
version = getVersion('Chrome');
} // Strip incorrect OS versions.
if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
} // Ensure OS does not include the browser name.
if (os && os.indexOf(name) != -1 && !RegExp(name + ' OS').test(os)) {
os = os.replace(RegExp(' *' + qualify(name) + ' *'), '');
} // Add layout engine.
if (layout && !/\b(?:Avant|Nook)\b/.test(name) && (/Browser|Lunascape|Maxthon/.test(name) || name != 'Safari' && /^iOS/.test(os) && /\bSafari\b/.test(layout[1]) || /^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name) && layout[1])) {
// Don't add layout details to description if they are falsey.
(data = layout[layout.length - 1]) && description.push(data);
} // Combine contextual information.
if (description.length) {
description = ['(' + description.join('; ') + ')'];
} // Append manufacturer to description.
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
} // Append product to description.
if (product) {
description.push((/^on /.test(description[description.length - 1]) ? '' : 'on ') + product);
} // Parse the OS into an object.
if (os) {
data = / ([\d.+]+)$/.exec(os);
isSpecialCasedOS = data && os.charAt(os.length - data[0].length - 1) == '/';
os = {
'architecture': 32,
'family': data && !isSpecialCasedOS ? os.replace(data[0], '') : os,
'version': data ? data[1] : null,
'toString': function toString() {
var version = this.version;
return this.family + (version && !isSpecialCasedOS ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : '');
}
};
} // Add browser/OS architecture.
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) {
if (os) {
os.architecture = 64;
os.family = os.family.replace(RegExp(' *' + data), '');
}
if (name && (/\bWOW64\b/i.test(ua) || useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform) && !/\bWin64; x64\b/i.test(ua))) {
description.unshift('32-bit');
}
} // Chrome 39 and above on OS X is always 64-bit.
else if (os && /^OS X/.test(os.family) && name == 'Chrome' && parseFloat(version) >= 39) {
os.architecture = 64;
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
*
* @name platform
* @type Object
*/
var platform = {};
/**
* The platform description.
*
* @memberOf platform
* @type string|null
*/
platform.description = ua;
/**
* The name of the browser's layout engine.
*
* The list of common layout engines include:
* "Blink", "EdgeHTML", "Gecko", "Trident" and "WebKit"
*
* @memberOf platform
* @type string|null
*/
platform.layout = layout && layout[0];
/**
* The name of the product's manufacturer.
*
* The list of manufacturers include:
* "Apple", "Archos", "Amazon", "Asus", "Barnes & Noble", "BlackBerry",
* "Google", "HP", "HTC", "LG", "Microsoft", "Motorola", "Nintendo",
* "Nokia", "Samsung" and "Sony"
*
* @memberOf platform
* @type string|null
*/
platform.manufacturer = manufacturer;
/**
* The name of the browser/environment.
*
* The list of common browser names include:
* "Chrome", "Electron", "Firefox", "Firefox for iOS", "IE",
* "Microsoft Edge", "PhantomJS", "Safari", "SeaMonkey", "Silk",
* "Opera Mini" and "Opera"
*
* Mobile versions of some browsers have "Mobile" appended to their name:
* eg. "Chrome Mobile", "Firefox Mobile", "IE Mobile" and "Opera Mobile"
*
* @memberOf platform
* @type string|null
*/
platform.name = name;
/**
* The alpha/beta release indicator.
*
* @memberOf platform
* @type string|null
*/
platform.prerelease = prerelease;
/**
* The name of the product hosting the browser.
*
* The list of common products include:
*
* "BlackBerry", "Galaxy S4", "Lumia", "iPad", "iPod", "iPhone", "Kindle",
* "Kindle Fire", "Nexus", "Nook", "PlayBook", "TouchPad" and "Transformer"
*
* @memberOf platform
* @type string|null
*/
platform.product = product;
/**
* The browser's user agent string.
*
* @memberOf platform
* @type string|null
*/
platform.ua = ua;
/**
* The browser/environment version.
*
* @memberOf platform
* @type string|null
*/
platform.version = name && version;
/**
* The name of the operating system.
*
* @memberOf platform
* @type Object
*/
platform.os = os || {
/**
* The CPU architecture the OS is built for.
*
* @memberOf platform.os
* @type number|null
*/
'architecture': null,
/**
* The family of the OS.
*
* Common values include:
* "Windows", "Windows Server 2008 R2 / 7", "Windows Server 2008 / Vista",
* "Windows XP", "OS X", "Linux", "Ubuntu", "Debian", "Fedora", "Red Hat",
* "SuSE", "Android", "iOS" and "Windows Phone"
*
* @memberOf platform.os
* @type string|null
*/
'family': null,
/**
* The version of the OS.
*
* @memberOf platform.os
* @type string|null
*/
'version': null,
/**
* Returns the OS string.
*
* @memberOf platform.os
* @returns {string} The OS string.
*/
'toString': function toString() {
return 'null';
}
};
platform.parse = parse;
platform.toString = toStringPlatform;
if (platform.version) {
description.unshift(version);
}
if (platform.name) {
description.unshift(name);
}
if (os && name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product))) {
description.push(product ? '(' + os + ')' : 'on ' + os);
}
if (description.length) {
platform.description = description.join(' ');
}
return platform;
}
/*--------------------------------------------------------------------------*/
// Export platform.
var platform = parse(); // Some AMD build optimizers, like r.js, check for condition patterns like the following:
if (freeExports && freeModule) {
// Export for CommonJS support.
forOwn(platform, function (value, key) {
freeExports[key] = value;
});
} else {
// Export to the global object.
root.platform = platform;
}
}).call(commonjsGlobal);
})(platform$4, platform$4.exports);
var platform$2 = platform$4.exports;
var platform$3 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), platform$4.exports, {
'default': platform$2
}));
Object.defineProperty(metadata, "__esModule", {
value: true
});
var platform$1 = platform$4.exports;
var Metadata = /*#__PURE__*/function () {
function Metadata() {
_classCallCheck$1(this, Metadata);
}
_createClass(Metadata, null, [{
key: "getMetadata",
value: function getMetadata(options) {
typeof navigator !== 'undefined' ? platform$1.parse(navigator.userAgent) : platform$1;
var overrides = options && options.clientMetadata ? options.clientMetadata : {};
var fieldNames = ['ver', 'env', 'envv', 'os', 'osv', 'osa', 'type', 'sdk', 'sdkv', 'dev', 'devv', 'devt', 'app', 'appv'];
var defaults = {
'env': platform$1.name,
'envv': platform$1.version,
'os': platform$1.os.family,
'osv': platform$1.os.version,
'osa': platform$1.os.architecture,
'sdk': 'js-default'
};
var finalClientMetadata = {};
fieldNames.filter(function (key) {
return key in overrides || key in defaults;
}).forEach(function (key) {
return finalClientMetadata[key] = key in overrides ? overrides[key] : defaults[key];
});
return finalClientMetadata;
}
}]);
return Metadata;
}();
metadata.Metadata = Metadata;
Object.defineProperty(packetinterface, "__esModule", {
value: true
});
var logger_1$h = logger$4;
var uuid_1$1 = uuid_1$3;
var twilsockerror_1$7 = twilsockerror;
var twilsockreplyerror_1 = twilsockreplyerror;
var parser_1 = parser;
var Messages$2 = messages;
var metadata_1 = metadata;
var REQUEST_TIMEOUT$1 = 30000;
function isHttpSuccess$1(code) {
return code >= 200 && code < 300;
}
/**
* Makes sure that body is properly stringified
*/
function preparePayload(payload) {
switch (_typeof$2(payload)) {
case 'undefined':
return '';
case 'object':
return JSON.stringify(payload);
default:
return payload;
}
}
var PacketResponse = function PacketResponse() {
_classCallCheck$1(this, PacketResponse);
};
packetinterface.PacketResponse = PacketResponse;
var PacketInterface = /*#__PURE__*/function () {
function PacketInterface(channel, config) {
var _this = this;
_classCallCheck$1(this, PacketInterface);
this.config = config;
this.activeRequests = new Map();
this.channel = channel;
this.channel.on('reply', function (reply) {
return _this.processReply(reply);
});
this.channel.on('disconnected', function () {
_this.activeRequests.forEach(function (descriptor) {
clearTimeout(descriptor.timeout);
descriptor.reject(new twilsockerror_1$7.TwilsockError('disconnected'));
});
_this.activeRequests.clear();
});
}
_createClass(PacketInterface, [{
key: "isConnected",
get: function get() {
return this.channel.isConnected;
}
}, {
key: "processReply",
value: function processReply(reply) {
var request = this.activeRequests.get(reply.id);
if (request) {
clearTimeout(request.timeout);
this.activeRequests.delete(reply.id);
if (!isHttpSuccess$1(reply.status.code)) {
request.reject(new twilsockreplyerror_1.TwilsockReplyError('Transport failure: ' + reply.status.status, reply));
logger_1$h.log.trace('message rejected');
} else {
request.resolve(reply);
}
}
}
}, {
key: "storeRequest",
value: function storeRequest(id, resolve, reject) {
var requestDescriptor = {
resolve: resolve,
reject: reject,
timeout: setTimeout(function () {
logger_1$h.log.trace('request', id, 'is timed out');
reject(new twilsockerror_1$7.TwilsockError('Twilsock: request timeout: ' + id));
}, REQUEST_TIMEOUT$1)
};
this.activeRequests.set(id, requestDescriptor);
}
}, {
key: "shutdown",
value: function shutdown() {
this.activeRequests.forEach(function (descriptor) {
clearTimeout(descriptor.timeout);
descriptor.reject(new twilsockerror_1$7.TwilsockError('Twilsock: request cancelled by user'));
});
this.activeRequests.clear();
}
}, {
key: "sendInit",
value: function () {
var _sendInit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var metadata, message, response;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
logger_1$h.log.trace('sendInit');
metadata = metadata_1.Metadata.getMetadata(this.config);
message = new Messages$2.Init(this.config.token, this.config.continuationToken, metadata, this.config.initRegistrations, this.config.tweaks);
_context.next = 5;
return this.sendWithReply(message);
case 5:
response = _context.sent;
return _context.abrupt("return", new Messages$2.InitReply(response.id, response.header.continuation_token, response.header.continuation_token_status, response.header.offline_storage, response.header.init_registrations, response.header.debug_info, new Set(response.header.capabilities)));
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function sendInit() {
return _sendInit.apply(this, arguments);
}
return sendInit;
}()
}, {
key: "sendClose",
value: function sendClose() {
var message = new Messages$2.Close(); //@todo send telemetry AnyEventsIncludingUnfinished
this.send(message);
}
}, {
key: "sendWithReply",
value: function sendWithReply(header, payload) {
var _this2 = this;
return new Promise(function (resolve, reject) {
var id = _this2.send(header, payload);
_this2.storeRequest(id, resolve, reject);
});
}
}, {
key: "send",
value: function send(header, payload) {
header.id = header.id || "TM".concat(uuid_1$1.v4());
var message = parser_1.Parser.createPacket(header, preparePayload(payload));
try {
this.channel.send(message);
return header.id;
} catch (e) {
logger_1$h.log.debug('failed to send ', header, e);
logger_1$h.log.trace(e.stack);
throw e;
}
}
}]);
return PacketInterface;
}();
packetinterface.PacketInterface = PacketInterface;
var websocketchannel = {};
var _nodeResolve_empty = {};
var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': _nodeResolve_empty
});
var require$$1 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
function _createSuper$x(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$x(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$x() { 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; } }
Object.defineProperty(websocketchannel, "__esModule", {
value: true
});
var events_1$e = require$$0;
var logger_1$g = logger$4;
var WebSocketChannel = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(WebSocketChannel, _events_1$EventEmitte);
var _super = _createSuper$x(WebSocketChannel);
function WebSocketChannel(url) {
var _this;
_classCallCheck$1(this, WebSocketChannel);
_this = _super.call(this);
_this.url = url;
_this.WebSocket = commonjsGlobal['WebSocket'] || commonjsGlobal['MozWebSocket'] || require$$1;
return _this;
}
_createClass(WebSocketChannel, [{
key: "isConnected",
get: function get() {
return this.socket && this.socket.readyState === 1;
}
}, {
key: "connect",
value: function connect() {
var _this2 = this;
logger_1$g.log.trace('connecting to socket');
var socket;
try {
socket = new this.WebSocket(this.url);
} catch (e) {
logger_1$g.log.debug("Socket error: ".concat(this.url));
this.emit('socketError', e);
return;
}
socket.binaryType = 'arraybuffer';
socket.onopen = function () {
logger_1$g.log.debug("socket opened ".concat(_this2.url));
_this2.emit('connected');
};
socket.onclose = function (e) {
logger_1$g.log.debug('socket closed', e);
_this2.emit('disconnected', e);
};
socket.onerror = function (e) {
logger_1$g.log.debug('Socket error:', e);
_this2.emit('socketError', e);
};
socket.onmessage = function (message) {
_this2.emit('message', message.data);
};
this.socket = socket;
}
}, {
key: "send",
value: function send(message) {
this.socket.send(message);
}
}, {
key: "close",
value: function close() {
logger_1$g.log.trace('closing socket');
if (this.socket) {
this.socket.onopen = null;
this.socket.onclose = null;
this.socket.onerror = null;
this.socket.onmessage = null;
try {
this.socket.close();
} finally {}
}
}
}]);
return WebSocketChannel;
}(events_1$e.EventEmitter);
websocketchannel.WebSocketChannel = WebSocketChannel;
var registrations = {};
function _createSuper$w(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$w(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$w() { 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; } }
Object.defineProperty(registrations, "__esModule", {
value: true
});
var logger_1$f = logger$4;
var events_1$d = require$$0;
var uuid_1 = uuid_1$3;
var twilsockerror_1$6 = twilsockerror;
/**
* Registrations module handles all operations with registration contexts through twilsock
* Main role: it automatically refreshes all registrations after reconnect.
*/
var Registrations = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Registrations, _events_1$EventEmitte);
var _super = _createSuper$w(Registrations);
function Registrations(transport) {
var _this;
_classCallCheck$1(this, Registrations);
_this = _super.call(this);
_this.transport = transport;
_this.registrations = new Map();
_this.registrationsInProgress = new Map();
return _this;
}
_createClass(Registrations, [{
key: "putNotificationContext",
value: function () {
var _putNotificationContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(contextId, context) {
var header;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
header = {
method: 'put_notification_ctx',
notification_ctx_id: contextId
};
_context.next = 3;
return this.transport.sendWithReply(header, context);
case 3:
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function putNotificationContext(_x, _x2) {
return _putNotificationContext.apply(this, arguments);
}
return putNotificationContext;
}()
}, {
key: "deleteNotificationContext",
value: function () {
var _deleteNotificationContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(contextId) {
var message;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
message = {
method: 'delete_notification_ctx',
notification_ctx_id: contextId
};
_context2.next = 3;
return this.transport.sendWithReply(message);
case 3:
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function deleteNotificationContext(_x3) {
return _deleteNotificationContext.apply(this, arguments);
}
return deleteNotificationContext;
}()
}, {
key: "updateRegistration",
value: function () {
var _updateRegistration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(contextId, context) {
var registrationAttempts, attemptId;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
logger_1$f.log.debug('update registration for context', contextId);
registrationAttempts = this.registrationsInProgress.get(contextId);
if (!registrationAttempts) {
registrationAttempts = new Set();
this.registrationsInProgress.set(contextId, registrationAttempts);
}
attemptId = uuid_1.v4();
registrationAttempts.add(attemptId);
_context3.prev = 5;
_context3.next = 8;
return this.putNotificationContext(contextId, context);
case 8:
logger_1$f.log.debug('registration attempt succeeded for context', context);
registrationAttempts.delete(attemptId);
if (registrationAttempts.size === 0) {
this.registrationsInProgress.delete(contextId);
this.emit('registered', contextId);
}
_context3.next = 19;
break;
case 13:
_context3.prev = 13;
_context3.t0 = _context3["catch"](5);
logger_1$f.log.warn('registration attempt failed for context', context);
logger_1$f.log.debug(_context3.t0);
registrationAttempts.delete(attemptId);
if (registrationAttempts.size === 0) {
this.registrationsInProgress.delete(contextId);
this.emit('registrationFailed', contextId, _context3.t0);
}
case 19:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[5, 13]]);
}));
function updateRegistration(_x4, _x5) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;
}()
}, {
key: "updateRegistrations",
value: function updateRegistrations() {
var _this2 = this;
logger_1$f.log.trace("refreshing ".concat(this.registrations.size, " registrations"));
this.registrations.forEach(function (context, id) {
_this2.updateRegistration(id, context);
});
}
}, {
key: "setNotificationsContext",
value: function setNotificationsContext(contextId, context) {
if (!contextId || !context) {
throw new twilsockerror_1$6.TwilsockError('Invalid arguments provided');
}
this.registrations.set(contextId, context);
if (this.transport.isConnected) {
this.updateRegistration(contextId, context);
}
}
}, {
key: "removeNotificationsContext",
value: function () {
var _removeNotificationsContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(contextId) {
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (this.registrations.has(contextId)) {
_context4.next = 2;
break;
}
return _context4.abrupt("return");
case 2:
_context4.next = 4;
return this.deleteNotificationContext(contextId);
case 4:
if (this.transport.isConnected) {
this.registrations.delete(contextId);
}
case 5:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function removeNotificationsContext(_x6) {
return _removeNotificationsContext.apply(this, arguments);
}
return removeNotificationsContext;
}()
}]);
return Registrations;
}(events_1$d.EventEmitter);
registrations.Registrations = Registrations;
var upstream = {};
var twilsockupstreamerror = {};
function _createSuper$v(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$v(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$v() { 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; } }
Object.defineProperty(twilsockupstreamerror, "__esModule", {
value: true
});
var twilsockerror_1$5 = twilsockerror;
var TwilsockUpstreamError = /*#__PURE__*/function (_twilsockerror_1$Twil) {
_inherits$1(TwilsockUpstreamError, _twilsockerror_1$Twil);
var _super = _createSuper$v(TwilsockUpstreamError);
function TwilsockUpstreamError(status, description, body) {
var _this;
_classCallCheck$1(this, TwilsockUpstreamError);
_this = _super.call(this, description);
_this.status = status;
_this.description = description;
_this.body = body;
return _this;
}
return TwilsockUpstreamError;
}(twilsockerror_1$5.TwilsockError);
twilsockupstreamerror.TwilsockUpstreamError = TwilsockUpstreamError;
var transportunavailableerror = {};
function _createSuper$u(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$u(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$u() { 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; } }
Object.defineProperty(transportunavailableerror, "__esModule", {
value: true
});
var twilsockerror_1$4 = twilsockerror;
var TransportUnavailableError = /*#__PURE__*/function (_twilsockerror_1$Twil) {
_inherits$1(TransportUnavailableError, _twilsockerror_1$Twil);
var _super = _createSuper$u(TransportUnavailableError);
function TransportUnavailableError(description) {
_classCallCheck$1(this, TransportUnavailableError);
return _super.call(this, description);
}
return TransportUnavailableError;
}(twilsockerror_1$4.TwilsockError);
transportunavailableerror.TransportUnavailableError = TransportUnavailableError;
Object.defineProperty(upstream, "__esModule", {
value: true
});
var logger_1$e = logger$4;
var twilsockerror_1$3 = twilsockerror;
var twilsockupstreamerror_1 = twilsockupstreamerror;
var Messages$1 = messages;
var transportunavailableerror_1$1 = transportunavailableerror;
var REQUEST_TIMEOUT = 20000;
function isHttpSuccess(code) {
return code >= 200 && code < 300;
}
function isHttpReply(packet) {
return packet && packet.header && packet.header.http_status;
}
function parseUri(uri) {
var match = uri.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
if (match) {
var uriStruct = {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7],
params: null
};
if (uriStruct.search.length > 0) {
var paramsString = uriStruct.search.substring(1);
uriStruct.params = paramsString.split('&').map(function (el) {
return el.split('=');
}).reduce(function (prev, curr) {
if (!prev.hasOwnProperty(curr[0])) {
prev[curr[0]] = curr[1];
} else if (Array.isArray(prev[curr[0]])) {
prev[curr[0]].push(curr[1]);
} else {
prev[curr[0]] = [prev[curr[0]], curr[1]];
}
return prev;
}, {});
}
return uriStruct;
}
throw new twilsockerror_1$3.TwilsockError('Incorrect URI: ' + uri);
}
function twilsockAddress(method, uri) {
var parsedUri = parseUri(uri);
var to = {
method: method,
host: parsedUri.host,
path: parsedUri.pathname
};
if (parsedUri.params) {
to.params = parsedUri.params;
}
return to;
}
function twilsockParams(method, uri, headers, body, grant) {
return {
to: twilsockAddress(method, uri),
headers: headers,
body: body,
grant: grant
};
}
var Upstream = /*#__PURE__*/function () {
function Upstream(transport, twilsock, config) {
_classCallCheck$1(this, Upstream);
this.config = config;
this.transport = transport;
this.pendingMessages = [];
this.twilsock = twilsock;
}
_createClass(Upstream, [{
key: "saveMessage",
value: function saveMessage(message) {
var _this = this;
return new Promise(function (resolve, reject) {
var requestDescriptor = {
message: message,
resolve: resolve,
reject: reject,
alreadyRejected: false,
timeout: setTimeout(function () {
logger_1$e.log.debug('request is timed out');
reject(new twilsockerror_1$3.TwilsockError("request '".concat(message.to.method, "' to '").concat(message.to.host, "' timed out")));
requestDescriptor.alreadyRejected = true;
}, REQUEST_TIMEOUT)
};
_this.pendingMessages.push(requestDescriptor);
});
}
}, {
key: "sendPendingMessages",
value: function sendPendingMessages() {
var _this2 = this;
var _loop = function _loop() {
var request = _this2.pendingMessages[0]; // Do not send message if we've rejected its promise already
if (!request.alreadyRejected) {
try {
var message = request.message;
_this2.actualSend(message).then(function (response) {
return request.resolve(response);
}).catch(function (e) {
return request.reject(e);
});
clearTimeout(request.timeout);
} catch (e) {
logger_1$e.log.debug('Failed to send pending message', e);
return "break";
}
}
_this2.pendingMessages.splice(0, 1);
};
while (this.pendingMessages.length) {
var _ret = _loop();
if (_ret === "break") break;
}
}
}, {
key: "rejectPendingMessages",
value: function rejectPendingMessages() {
var _this3 = this;
this.pendingMessages.forEach(function (message) {
message.reject(new transportunavailableerror_1$1.TransportUnavailableError('Unable to connect: ' + _this3.twilsock.getTerminationReason));
clearTimeout(message.timeout);
});
this.pendingMessages.splice(0, this.pendingMessages.length);
}
}, {
key: "actualSend",
value: function () {
var _actualSend = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(message) {
var address, headers, body, grant, httpRequest, upstreamMessage, reply;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
address = message.to;
headers = message.headers;
body = message.body;
grant = message.grant ? message.grant : this.config.activeGrant;
httpRequest = {
host: address.host,
path: address.path,
method: address.method,
params: address.params,
headers: headers
};
upstreamMessage = new Messages$1.Message(grant, headers['Content-Type'] || 'application/json', httpRequest);
_context.next = 8;
return this.transport.sendWithReply(upstreamMessage, body);
case 8:
reply = _context.sent;
if (!(isHttpReply(reply) && !isHttpSuccess(reply.header.http_status.code))) {
_context.next = 11;
break;
}
throw new twilsockupstreamerror_1.TwilsockUpstreamError(reply.header.http_status.code, reply.header.http_status.status, reply.body);
case 11:
return _context.abrupt("return", {
status: reply.header.http_status,
headers: reply.header.http_headers,
body: reply.body
});
case 12:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function actualSend(_x) {
return _actualSend.apply(this, arguments);
}
return actualSend;
}()
/**
* Send an upstream message
* @param {string} method The upstream method
* @param {string} url URL to send the message to
* @param {object} [headers] The message headers
* @param {any} [body] The message body
* @param {string} [grant] The product grant
* @returns {Promise<Result>} Result from remote side
*/
}, {
key: "send",
value: function send(method, url) {
var headers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var body = arguments.length > 3 ? arguments[3] : undefined;
var grant = arguments.length > 4 ? arguments[4] : undefined;
if (this.twilsock.isTerminalState) {
return Promise.reject(new transportunavailableerror_1$1.TransportUnavailableError('Unable to connect: ' + this.twilsock.getTerminationReason));
}
var twilsockMessage = twilsockParams(method, url, headers, body, grant);
if (!this.twilsock.isConnected) {
return this.saveMessage(twilsockMessage);
}
return this.actualSend(twilsockMessage);
}
}]);
return Upstream;
}();
upstream.Upstream = Upstream;
var deferred = {};
Object.defineProperty(deferred, "__esModule", {
value: true
});
var Deferred$1 = /*#__PURE__*/function () {
function Deferred() {
var _this = this;
_classCallCheck$1(this, Deferred);
this._promise = new Promise(function (resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
});
}
_createClass(Deferred, [{
key: "promise",
get: function get() {
return this._promise;
}
}, {
key: "update",
value: function update(value) {
this._resolve(value);
}
}, {
key: "set",
value: function set(value) {
this.current = value;
this._resolve(value);
}
}, {
key: "fail",
value: function fail(e) {
this._reject(e);
}
}]);
return Deferred;
}();
deferred.Deferred = Deferred$1;
var offlinestorage = {};
Object.defineProperty(offlinestorage, "__esModule", {
value: true
});
var twilsockerror_1$2 = twilsockerror;
var OfflineProductStorage = /*#__PURE__*/function () {
function OfflineProductStorage(id) {
_classCallCheck$1(this, OfflineProductStorage);
this.id = id;
}
_createClass(OfflineProductStorage, null, [{
key: "create",
value: function create(productPayload) {
if (productPayload instanceof Object && 'storage_id' in productPayload) {
return new OfflineProductStorage(productPayload.storage_id);
} else {
throw new twilsockerror_1$2.TwilsockError('Field "storage_id" is missing');
}
}
}]);
return OfflineProductStorage;
}();
offlinestorage.OfflineProductStorage = OfflineProductStorage;
var tokenStorage = {};
Object.defineProperty(tokenStorage, "__esModule", {
value: true
});
var TokenStorage = /*#__PURE__*/function () {
function TokenStorage() {
_classCallCheck$1(this, TokenStorage);
}
_createClass(TokenStorage, null, [{
key: "sessionStorage",
get: function get() {
try {
return commonjsGlobal['sessionStorage'];
} catch (err) {
return null;
}
}
}, {
key: "window",
get: function get() {
try {
return commonjsGlobal['window'];
} catch (err) {
return null;
}
}
}, {
key: "storeToken",
value: function storeToken(continuationToken, productId) {
if (TokenStorage.canStore) {
TokenStorage.sessionStorage.setItem(TokenStorage.getKeyName(productId), continuationToken);
}
}
}, {
key: "getStoredToken",
value: function getStoredToken(productId) {
if (!TokenStorage.canStore) {
return null;
}
return TokenStorage.sessionStorage.getItem(TokenStorage.getKeyName(productId));
}
}, {
key: "initialize",
value: function initialize() {
if (TokenStorage.canStore) {
var flag = TokenStorage.sessionStorage.getItem(TokenStorage.initializedFlag); // Duplicated tab, cleaning up all stored keys
if (flag) {
this.clear();
}
TokenStorage.sessionStorage.setItem(TokenStorage.initializedFlag, 'true'); // When leaving page or refreshing
TokenStorage.window.addEventListener('unload', function () {
TokenStorage.sessionStorage.removeItem(TokenStorage.initializedFlag);
});
}
}
}, {
key: "clear",
value: function clear() {
if (TokenStorage.canStore) {
var keyToDelete = [];
for (var i = 0; i < TokenStorage.sessionStorage.length; i++) {
var key = TokenStorage.sessionStorage.key(i); // We manually removed startsWith here due to some problems with babel polyfill setup.
// Restore it when we figure out what's wrong.
//if (key.startsWith(TokenStorage.tokenStoragePrefix)) {
if (key.indexOf(TokenStorage.tokenStoragePrefix) === 0) {
keyToDelete.push(key);
}
}
keyToDelete.forEach(function (key) {
return TokenStorage.sessionStorage.removeItem(key);
});
TokenStorage.sessionStorage.removeItem(TokenStorage.initializedFlag);
}
}
}, {
key: "getKeyName",
value: function getKeyName(productId) {
return "".concat(TokenStorage.tokenStoragePrefix).concat(productId);
}
}, {
key: "canStore",
get: function get() {
return TokenStorage.sessionStorage && TokenStorage.window;
}
}]);
return TokenStorage;
}();
tokenStorage.TokenStorage = TokenStorage;
TokenStorage.initializedFlag = 'twilio_twilsock_token_storage';
TokenStorage.tokenStoragePrefix = 'twilio_continuation_token_';
TokenStorage.initialize();
var telemetrytracker = {};
Object.defineProperty(telemetrytracker, "__esModule", {
value: true
});
var telemetry_1 = telemetry;
var logger_1$d = logger$4;
var TelemetryEventDescription = /*#__PURE__*/function () {
function TelemetryEventDescription(title, details, start, end, type, id) {
_classCallCheck$1(this, TelemetryEventDescription);
this.title = title;
this.details = details;
this.start = start;
this.type = type;
this.id = id;
this.end = end;
} // Prepare telemetry event right before sending it.
// Convert times to relative.
_createClass(TelemetryEventDescription, [{
key: "toTelemetryEvent",
value: function toTelemetryEvent() {
// Fix dates
var now = new Date();
var actualStart = this.start;
var actualEnd = this.end ? this.end : now;
if (actualEnd < actualStart) {
var tmp = actualEnd;
actualEnd = actualStart;
actualStart = tmp;
} // Converting dates to relative offset from current moment in ms
var startOffset = actualStart.getTime() - now.getTime();
var endOffset = actualEnd.getTime() - now.getTime();
var result = new telemetry_1.TelemetryEvent(startOffset, endOffset, this.title, this.details, this.id, this.type);
return result;
}
}]);
return TelemetryEventDescription;
}();
var TelemetryEventDescription_1 = telemetrytracker.TelemetryEventDescription = TelemetryEventDescription;
var TelemetryPoint;
(function (TelemetryPoint) {
TelemetryPoint[TelemetryPoint["Start"] = 0] = "Start";
TelemetryPoint[TelemetryPoint["End"] = 1] = "End";
})(TelemetryPoint || (TelemetryPoint = {}));
var TelemetryPoint_1 = telemetrytracker.TelemetryPoint = TelemetryPoint;
var EventSendingLimitation;
(function (EventSendingLimitation) {
EventSendingLimitation[EventSendingLimitation["MinEventsPortion"] = 0] = "MinEventsPortion";
EventSendingLimitation[EventSendingLimitation["AnyEvents"] = 1] = "AnyEvents";
EventSendingLimitation[EventSendingLimitation["AnyEventsIncludingUnfinished"] = 2] = "AnyEventsIncludingUnfinished";
})(EventSendingLimitation || (EventSendingLimitation = {}));
telemetrytracker.EventSendingLimitation = EventSendingLimitation;
var TelemetryTracker = /*#__PURE__*/function () {
function TelemetryTracker(config, packetInterface) {
_classCallCheck$1(this, TelemetryTracker);
// accumulated events count that is big enough to be sent out of schedule (not on timer but on new event registration)
this.minEventsPortionToSend = 50; // max events batch size to be sent in a single Telemetry message
this.maxEventsPortionToSend = 100;
this.pendingEvents = new Map(); // started events: have TelemetryEvent::startTime only
this.readyEvents = []; // events ready to send
this.hasInitializationFinished = false;
this._canSendTelemetry = false;
this.config = config;
this.packetInterface = packetInterface;
} // Keeping this private prevents the type declaration from being generated properly.
// Ideally, this should be private.
_createClass(TelemetryTracker, [{
key: "isTelemetryEnabled",
get: function get() {
return this.config.confirmedCapabilities.has('telemetry.v1');
}
}, {
key: "canSendTelemetry",
get: function get() {
return this._canSendTelemetry && this.isTelemetryEnabled;
},
set: function set(enable) {
logger_1$d.log.debug("TelemetryTracker.canSendTelemetry: ".concat(enable, " TelemetryTracker.isTelemetryEnabled: ").concat(this.isTelemetryEnabled)); // We want to keep telemetry events added in advance but
// we need to purge events from previous connection when being disconnected
if (this._canSendTelemetry && !enable) {
this.pendingEvents.clear();
this.readyEvents = [];
}
this._canSendTelemetry = enable;
if (enable) {
this.sendTelemetry(EventSendingLimitation.AnyEvents);
}
if (enable && !this.hasInitializationFinished) {
this.hasInitializationFinished = true;
}
} // Add complete event
}, {
key: "addTelemetryEvent",
value: function addTelemetryEvent(event) {
// Allow adding events before initialization.
if (!this.canSendTelemetry && this.hasInitializationFinished) {
return;
}
this.readyEvents.push(event);
} // Add incomplete event (with either starting or ending time point)
}, {
key: "addPartialEvent",
value: function addPartialEvent(incompleteEvent, eventKey, point) {
logger_1$d.log.debug("Adding ".concat(point === TelemetryPoint.Start ? 'starting' : 'ending', " timepoint for '").concat(eventKey, "' event"));
var exists = this.pendingEvents.has(eventKey);
if (point === TelemetryPoint.Start) {
if (exists) {
logger_1$d.log.debug("Overwriting starting point for '".concat(eventKey, "' event"));
}
this.pendingEvents.set(eventKey, incompleteEvent);
} else {
if (!exists) {
logger_1$d.log.info("Could not find started event for '".concat(eventKey, "' event"));
return;
}
this.addTelemetryEvent(this.merge(this.pendingEvents.get(eventKey), incompleteEvent));
this.pendingEvents.delete(eventKey);
}
}
}, {
key: "getTelemetryToSend",
value: function getTelemetryToSend(sendingLimit) {
if (!this.canSendTelemetry || this.readyEvents.length == 0) {
return []; // Events are collected but not sent until telemetry is enabled
}
if (sendingLimit == EventSendingLimitation.MinEventsPortion && this.readyEvents.length < this.minEventsPortionToSend) {
return [];
}
return this.getTelemetryPortion(sendingLimit == EventSendingLimitation.AnyEventsIncludingUnfinished);
}
}, {
key: "getTelemetryPortion",
value: function getTelemetryPortion(includeUnfinished) {
var _this = this;
var eventsPortionToSend = Math.min(this.readyEvents.length, this.maxEventsPortionToSend);
var res = this.readyEvents.splice(0, eventsPortionToSend);
if (includeUnfinished && res.length < this.maxEventsPortionToSend) {
this.pendingEvents.forEach(function (value, key) {
if (res.length >= _this.maxEventsPortionToSend) {
return; // @fixme does not end the loop early
}
var event = _this.pendingEvents.get(key);
_this.pendingEvents.delete(key);
res.push(new TelemetryEventDescription("[UNFINISHED] ".concat(event.title), // add prefix title to mark unfinished events for CleanSock
event.details, event.start, null, // Not ended, on sending will be replaced with now
event.type, event.id));
});
}
return res;
} // Merging 2 partial events:
// use start.startTime & end.endTime.
// For other fields,
// if there are values in end, use them,
// else use values from start.
}, {
key: "merge",
value: function merge(start, end) {
return new TelemetryEventDescription(end.title ? end.title : start.title, end.details ? end.details : start.details, start.start, end.end, end.type ? end.type : start.type, end.id ? end.id : start.id);
}
}, {
key: "sendTelemetryIfMinimalPortionCollected",
value: function sendTelemetryIfMinimalPortionCollected() {
this.sendTelemetry(EventSendingLimitation.MinEventsPortion);
} // NB: getTelemetryToSend will return non-empty array only if we have already received initReply
// and telemetry.v1 capability is enabled there.
}, {
key: "sendTelemetry",
value: function sendTelemetry(limit) {
var events = this.getTelemetryToSend(limit);
if (events.length === 0) {
return; // not enough telemetry data collected
}
try {
this.packetInterface.send(new telemetry_1.Telemetry(events.map(function (e) {
return e.toTelemetryEvent();
})));
} catch (err) {
logger_1$d.log.debug("Error while sending ".concat(events.length, " telemetry events due to ").concat(err, "; they will be resubmitted"));
this.readyEvents = this.readyEvents.concat(events);
}
}
}]);
return TelemetryTracker;
}();
telemetrytracker.TelemetryTracker = TelemetryTracker;
function _createSuper$t(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$t(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$t() { 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; } }
Object.defineProperty(client$3, "__esModule", {
value: true
});
var events_1$c = require$$0;
var logger_1$c = logger$4;
var configuration_1$4 = configuration$3;
var twilsock_1$4 = twilsock;
var packetinterface_1 = packetinterface;
var websocketchannel_1 = websocketchannel;
var registrations_1 = registrations;
var upstream_1 = upstream;
var deferred_1 = deferred;
var twilsockerror_1$1 = twilsockerror;
var offlinestorage_1 = offlinestorage;
var tokenStorage_1 = tokenStorage;
var telemetrytracker_1 = telemetrytracker;
var TelemetryEvents = function TelemetryEvents() {
_classCallCheck$1(this, TelemetryEvents);
};
client$3.TelemetryEvents = TelemetryEvents;
TelemetryEvents.TWILSOCK_CONNECT = 'twilsock.sdk.connect'; // establish WebSocket connection (with WebSocket handshake finished)
TelemetryEvents.TWILSOCK_INIT = 'twilsock.sdk.init'; // send "init" message and receive reply
/**
* @alias Twilsock
* @classdesc Client library for the Twilsock service
* It allows to recevie service-generated updates as well as bi-directional transport
* @fires Twilsock#message
* @fires Twilsock#connected
* @fires Twilsock#disconnected
* @fires Twilsock#tokenAboutToExpire
* @fires Twilsock#stateChanged
* @fires Twilsock#connectionError
*/
var TwilsockClient = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(TwilsockClient, _events_1$EventEmitte);
var _super = _createSuper$t(TwilsockClient);
/**
* @param {string} token Twilio access token
* @param {string} productId Product identifier. Should be the same as a grant name in token
*/
function TwilsockClient(token, productId) {
var _this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck$1(this, TwilsockClient);
_this = _super.call(this);
_this.offlineStorageDeferred = new deferred_1.Deferred();
options.continuationToken = options.continuationToken ? options.continuationToken : tokenStorage_1.TokenStorage.getStoredToken(productId);
var config = _this.config = new configuration_1$4.Configuration(token, productId, options);
logger_1$c.log.setLevel(config.logLevel);
var websocket = new websocketchannel_1.WebSocketChannel(config.url);
var transport = options.transport ? options.transport : new packetinterface_1.PacketInterface(websocket, config);
_this.channel = options.channel ? options.channel : new twilsock_1$4.TwilsockImpl(websocket, transport, config);
_this.registrations = options.registrations ? options.registrations : new registrations_1.Registrations(transport);
_this.upstream = new upstream_1.Upstream(transport, _this.channel, config); // Send telemetry only when connected and initialised
_this.telemetryTracker = new telemetrytracker_1.TelemetryTracker(config, transport);
_this.channel.on('initialized', function () {
return _this.telemetryTracker.canSendTelemetry = true;
});
websocket.on('disconnected', function () {
return _this.telemetryTracker.canSendTelemetry = false;
});
_this.registrations.on('registered', function (id) {
return _this.emit('registered', id);
});
_this.channel.on('message', function (type, message) {
return setTimeout(function () {
return _this.emit('message', type, message);
}, 0);
});
_this.channel.on('stateChanged', function (state) {
return setTimeout(function () {
return _this.emit('stateChanged', state);
}, 0);
});
_this.channel.on('connectionError', function (connectionError) {
return setTimeout(function () {
return _this.emit('connectionError', connectionError);
}, 0);
});
_this.channel.on('tokenAboutToExpire', function () {
return setTimeout(function () {
return _this.emit('tokenAboutToExpire');
}, 0);
});
_this.channel.on('tokenExpired', function () {
return setTimeout(function () {
return _this.emit('tokenExpired');
}, 0);
});
_this.channel.on('connected', function () {
return _this.registrations.updateRegistrations();
});
_this.channel.on('connected', function () {
return _this.upstream.sendPendingMessages();
});
_this.channel.on('connected', function () {
return setTimeout(function () {
return _this.emit('connected');
}, 0);
}); // Twilsock telemetry events
_this.channel.on('beforeConnect', function () {
return _this.telemetryTracker.addPartialEvent(new telemetrytracker_1.TelemetryEventDescription('Establish WebSocket connection', '', new Date()), TelemetryEvents.TWILSOCK_CONNECT, telemetrytracker_1.TelemetryPoint.Start);
});
_this.channel.on('connected', function () {
return _this.telemetryTracker.addPartialEvent(new telemetrytracker_1.TelemetryEventDescription('Establish WebSocket connection', '', new Date(), new Date()), TelemetryEvents.TWILSOCK_CONNECT, telemetrytracker_1.TelemetryPoint.End);
});
_this.channel.on('beforeSendInit', function () {
return _this.telemetryTracker.addPartialEvent(new telemetrytracker_1.TelemetryEventDescription('Send Twilsock init', '', new Date()), TelemetryEvents.TWILSOCK_INIT, telemetrytracker_1.TelemetryPoint.Start);
});
_this.channel.on('initialized', function () {
return _this.telemetryTracker.addPartialEvent(new telemetrytracker_1.TelemetryEventDescription('Send Twilsock init', 'Succeeded', new Date(), new Date()), TelemetryEvents.TWILSOCK_INIT, telemetrytracker_1.TelemetryPoint.End);
});
_this.channel.on('sendInitFailed', function () {
return _this.telemetryTracker.addPartialEvent(new telemetrytracker_1.TelemetryEventDescription('Send Twilsock init', 'Failed', new Date(), new Date()), TelemetryEvents.TWILSOCK_INIT, telemetrytracker_1.TelemetryPoint.End);
});
_this.channel.on('initialized', function (initReply) {
_this.handleStorageId(productId, initReply);
tokenStorage_1.TokenStorage.storeToken(initReply.continuationToken, productId);
setTimeout(function () {
return _this.emit('initialized', initReply);
}, 0);
});
_this.channel.on('disconnected', function () {
return setTimeout(function () {
return _this.emit('disconnected');
}, 0);
});
_this.channel.on('disconnected', function () {
return _this.upstream.rejectPendingMessages();
});
_this.channel.on('disconnected', function () {
return _this.offlineStorageDeferred.fail(new twilsockerror_1$1.TwilsockError('Client disconnected'));
});
_this.offlineStorageDeferred.promise.catch(function () {});
return _this;
}
_createClass(TwilsockClient, [{
key: "emit",
value: function emit(event) {
var _get2;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
logger_1$c.log.debug("Emitting ".concat(event.toString(), "(").concat(args.map(function (a) {
return JSON.stringify(a);
}).join(', '), ")"));
return (_get2 = _get(_getPrototypeOf$1(TwilsockClient.prototype), "emit", this)).call.apply(_get2, [this, event].concat(args));
}
}, {
key: "handleStorageId",
value: function handleStorageId(productId, initReply) {
if (!initReply.offlineStorage) {
this.offlineStorageDeferred.fail(new twilsockerror_1$1.TwilsockError('No offline storage id'));
} else if (initReply.offlineStorage.hasOwnProperty(productId)) {
try {
this.offlineStorageDeferred.set(offlinestorage_1.OfflineProductStorage.create(initReply.offlineStorage[productId]));
logger_1$c.log.debug("Offline storage for '".concat(productId, "' product: ").concat(JSON.stringify(initReply.offlineStorage[productId]), "."));
} catch (e) {
this.offlineStorageDeferred.fail(new twilsockerror_1$1.TwilsockError("Failed to parse offline storage for ".concat(productId, " ").concat(JSON.stringify(initReply.offlineStorage[productId]), ". ").concat(e, ".")));
}
} else {
this.offlineStorageDeferred.fail(new twilsockerror_1$1.TwilsockError("No offline storage id for '".concat(productId, "' product: ").concat(JSON.stringify(initReply.offlineStorage))));
}
}
/**
* Get offline storage ID
* @returns {Promise}
*/
}, {
key: "storageId",
value: function storageId() {
return this.offlineStorageDeferred.promise;
}
/**
* Indicates if twilsock is connected now
* @returns {Boolean}
*/
}, {
key: "isConnected",
get: function get() {
return this.channel.isConnected;
}
/**
* Current state
* @returns {String}
*/
}, {
key: "state",
get: function get() {
return this.channel.state;
}
/**
* Update token
* @param {String} token
* @returns {Promise}
*/
}, {
key: "updateToken",
value: function () {
var _updateToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(token) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
logger_1$c.log.trace("updating token '".concat(token, "'"));
if (!(this.config.token === token)) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
this.config.updateToken(token);
return _context.abrupt("return", this.channel.updateToken(token));
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function updateToken(_x) {
return _updateToken.apply(this, arguments);
}
return updateToken;
}()
/**
* Updates notification context.
* This method shouldn't be used anyone except twilio notifications library
* @param contextId id of notification context
* @param context value of notification context
* @private
*/
}, {
key: "setNotificationsContext",
value: function setNotificationsContext(contextId, context) {
this.registrations.setNotificationsContext(contextId, context);
}
/**
* Remove notification context.
* This method shouldn't be used anyone except twilio notifications library
* @param contextId id of notification context
* @private
*/
}, {
key: "removeNotificationsContext",
value: function removeNotificationsContext(contextId) {
this.registrations.removeNotificationsContext(contextId);
}
/**
* Connect to the server
* @fires Twilsock#connected
* @public
* @returns {void}
*/
}, {
key: "connect",
value: function connect() {
return this.channel.connect();
}
/**
* Disconnect from the server
* @fires Twilsock#disconnected
* @public
* @returns {Promise}
*/
}, {
key: "disconnect",
value: function disconnect() {
this.telemetryTracker.sendTelemetry(telemetrytracker_1.EventSendingLimitation.AnyEventsIncludingUnfinished);
return this.channel.disconnect();
}
/**
* Get HTTP request to upstream service
* @param {string} url Upstream service url
* @param {headers} headers Set of custom headers
* @param {string} [grant] The product grant
* @returns {Promise}
*/
}, {
key: "get",
value: function get(url, headers, grant) {
this.telemetryTracker.sendTelemetry(telemetrytracker_1.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment
return this.upstream.send('GET', url, headers, undefined, grant);
}
/**
* Post HTTP request to upstream service
* @param {string} url Upstream service url
* @param {headers} headers Set of custom headers
* @param {body} body Body to send
* @param {string} [grant] The product grant
* @returns {Promise}
*/
}, {
key: "post",
value: function post(url, headers, body, grant) {
this.telemetryTracker.sendTelemetry(telemetrytracker_1.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment
return this.upstream.send('POST', url, headers, body, grant);
}
/**
* Put HTTP request to upstream service
* @param {string} url Upstream service url
* @param {headers} headers Set of custom headers
* @param {body} body Body to send
* @param {string} [grant] The product grant
* @returns {Promise}
*/
}, {
key: "put",
value: function put(url, headers, body, grant) {
this.telemetryTracker.sendTelemetry(telemetrytracker_1.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment
return this.upstream.send('PUT', url, headers, body, grant);
}
/**
* Delete HTTP request to upstream service
* @param {string} url Upstream service url
* @param {headers} headers Set of custom headers
* @param {string} [grant] The product grant
* @returns {Promise}
*/
}, {
key: "delete",
value: function _delete(url, headers, grant) {
this.telemetryTracker.sendTelemetry(telemetrytracker_1.EventSendingLimitation.AnyEvents); // send collected telemetry (if any) before upstream message shipment
return this.upstream.send('DELETE', url, headers, undefined, grant);
}
/**
* Submits internal telemetry event. Not to be used for any customer and/or sensitive data.
* @param {TelemetryEventDescription} event Event details.
* @returns {void}
*/
}, {
key: "addTelemetryEvent",
value: function addTelemetryEvent(event) {
this.telemetryTracker.addTelemetryEvent(event);
this.telemetryTracker.sendTelemetryIfMinimalPortionCollected(); // send telemetry if need
}
/**
* Submits internal telemetry event. Not to be used for any customer and/or sensitive data.
* @param {TelemetryEventDescription} event Event details.
* @param {string} eventKey Unique event key.
* @param {TelemetryPoint} point Is this partial event for start or end of measurement.
* @returns {void}
*/
}, {
key: "addPartialTelemetryEvent",
value: function addPartialTelemetryEvent(event, eventKey, point) {
this.telemetryTracker.addPartialEvent(event, eventKey, point);
if (point === telemetrytracker_1.TelemetryPoint.End) {
// this telemetry event is complete, so minimal portion could become ready to send
this.telemetryTracker.sendTelemetryIfMinimalPortionCollected(); // send telemetry if need
}
}
}]);
return TwilsockClient;
}(events_1$c.EventEmitter);
client$3.TwilsockClient = TwilsockClient;
client$3.Twilsock = TwilsockClient;
Object.defineProperty(lib$8, "__esModule", {
value: true
});
var client_1 = client$3;
lib$8.TwilsockClient = client_1.TwilsockClient;
var Twilsock = lib$8.Twilsock = client_1.TwilsockClient;
var twilsockerror_1 = twilsockerror;
lib$8.TwilsockError = twilsockerror_1.TwilsockError;
var transportunavailableerror_1 = transportunavailableerror;
lib$8.TransportUnavailableError = transportunavailableerror_1.TransportUnavailableError;
var lib$6 = {};
var client$2 = {};
var configuration$2 = {};
Object.defineProperty(configuration$2, "__esModule", {
value: true
});
configuration$2.Configuration = void 0;
var Configuration$2 = /*#__PURE__*/function () {
function Configuration(token) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck$1(this, Configuration);
var config = options.notifications || {};
var region = config.region || options.region || 'us1';
var defaultUrl = "https://ers.".concat(region, ".twilio.com/v1/registrations");
this.registrarUrl = config.ersUrl || defaultUrl;
this._token = token;
}
_createClass(Configuration, [{
key: "updateToken",
value: function updateToken(token) {
this._token = token;
}
}, {
key: "token",
get: function get() {
return this._token;
}
}]);
return Configuration;
}();
configuration$2.Configuration = Configuration$2;
var registrar = {};
var registrar_connector = {};
var lib$5 = {};
var retrier$2 = {};
function _createSuper$s(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$s(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$s() { 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; } }
Object.defineProperty(retrier$2, "__esModule", {
value: true
});
var events_1$b = require$$0;
/**
* Provides retrier service
*/
var Retrier$2 = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Retrier, _events_1$EventEmitte);
var _super = _createSuper$s(Retrier);
/**
* Creates a new Retrier instance
*/
function Retrier(options) {
var _this;
_classCallCheck$1(this, Retrier);
_this = _super.call(this);
_this.minDelay = options.min;
_this.maxDelay = options.max;
_this.initialDelay = options.initial || 0;
_this.maxAttemptsCount = options.maxAttemptsCount || 0;
_this.maxAttemptsTime = options.maxAttemptsTime || 0;
_this.randomness = options.randomness || 0;
_this.inProgress = false;
_this.attemptNum = 0;
_this.prevDelay = 0;
_this.currDelay = 0;
return _this;
}
_createClass(Retrier, [{
key: "attempt",
value: function attempt() {
clearTimeout(this.timeout);
this.attemptNum++;
this.timeout = null;
this.emit('attempt', this);
}
}, {
key: "nextDelay",
value: function nextDelay(delayOverride) {
if (typeof delayOverride === 'number') {
this.prevDelay = 0;
this.currDelay = delayOverride;
return delayOverride;
}
if (this.attemptNum == 0) {
return this.initialDelay;
}
if (this.attemptNum == 1) {
this.currDelay = this.minDelay;
return this.currDelay;
}
this.prevDelay = this.currDelay;
var delay = this.currDelay + this.prevDelay;
if (this.maxDelay && delay > this.maxDelay) {
this.currDelay = this.maxDelay;
delay = this.maxDelay;
}
this.currDelay = delay;
return delay;
}
}, {
key: "randomize",
value: function randomize(delay) {
var area = delay * this.randomness;
var corr = Math.round(Math.random() * area * 2 - area);
return Math.max(0, delay + corr);
}
}, {
key: "scheduleAttempt",
value: function scheduleAttempt(delayOverride) {
var _this2 = this;
if (this.maxAttemptsCount && this.attemptNum >= this.maxAttemptsCount) {
this.cleanup();
this.emit('failed', new Error('Maximum attempt count limit reached'));
this.reject(new Error('Maximum attempt count reached'));
return;
}
var delay = this.nextDelay(delayOverride);
delay = this.randomize(delay);
if (this.maxAttemptsTime && this.startTimestamp + this.maxAttemptsTime < Date.now() + delay) {
this.cleanup();
this.emit('failed', new Error('Maximum attempt time limit reached'));
this.reject(new Error('Maximum attempt time limit reached'));
return;
}
this.timeout = setTimeout(function () {
return _this2.attempt();
}, delay);
}
}, {
key: "cleanup",
value: function cleanup() {
clearTimeout(this.timeout);
this.timeout = null;
this.inProgress = false;
this.attemptNum = 0;
this.prevDelay = 0;
this.currDelay = 0;
}
}, {
key: "start",
value: function start() {
var _this3 = this;
if (this.inProgress) {
throw new Error('Retrier is already in progress');
}
this.inProgress = true;
return new Promise(function (resolve, reject) {
_this3.resolve = resolve;
_this3.reject = reject;
_this3.startTimestamp = Date.now();
_this3.scheduleAttempt(_this3.initialDelay);
});
}
}, {
key: "cancel",
value: function cancel() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
this.inProgress = false;
this.emit('cancelled');
this.reject(new Error('Cancelled'));
}
}
}, {
key: "succeeded",
value: function succeeded(arg) {
this.emit('succeeded', arg);
this.resolve(arg);
}
}, {
key: "failed",
value: function failed(err, nextAttemptDelayOverride) {
if (this.timeout) {
throw new Error('Retrier attempt is already in progress');
}
this.scheduleAttempt(nextAttemptDelayOverride);
}
}, {
key: "run",
value: function run(handler) {
var _this4 = this;
this.on('attempt', function () {
handler().then(function (v) {
return _this4.succeeded(v);
}).catch(function (e) {
return _this4.failed(e);
});
});
return this.start();
}
}]);
return Retrier;
}(events_1$b.EventEmitter);
retrier$2.Retrier = Retrier$2;
retrier$2.default = Retrier$2;
var backoff$2 = {};
function _createSuper$r(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$r(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$r() { 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; } }
Object.defineProperty(backoff$2, "__esModule", {
value: true
});
var events_1$a = require$$0;
function isDef$2(value) {
return value !== undefined && value !== null;
}
var Backoff$2 = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Backoff, _events_1$EventEmitte);
var _super = _createSuper$r(Backoff);
function Backoff(options) {
var _this;
_classCallCheck$1(this, Backoff);
_this = _super.call(this);
options = options || {};
if (isDef$2(options.initialDelay) && options.initialDelay < 1) {
throw new Error('The initial timeout must be equal to or greater than 1.');
} else if (isDef$2(options.maxDelay) && options.maxDelay <= 1) {
throw new Error('The maximal timeout must be greater than 1.');
} else if (isDef$2(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) {
throw new Error('The randomisation factor must be between 0 and 1.');
} else if (isDef$2(options.factor) && options.factor <= 1) {
throw new Error("Exponential factor should be greater than 1.");
}
_this.initialDelay = options.initialDelay || 100;
_this.maxDelay = options.maxDelay || 10000;
if (_this.maxDelay <= _this.initialDelay) {
throw new Error('The maximal backoff delay must be greater than the initial backoff delay.');
}
_this.randomisationFactor = options.randomisationFactor || 0;
_this.factor = options.factor || 2;
_this.maxNumberOfRetry = -1;
_this.reset();
return _this;
}
_createClass(Backoff, [{
key: "backoff",
value: function backoff(err) {
if (this.timeoutID == null) {
if (this.backoffNumber === this.maxNumberOfRetry) {
this.emit('fail', err);
this.reset();
} else {
this.backoffDelay = this.next();
this.timeoutID = setTimeout(this.onBackoff.bind(this), this.backoffDelay);
this.emit('backoff', this.backoffNumber, this.backoffDelay, err);
}
}
}
}, {
key: "reset",
value: function reset() {
this.backoffDelay = 0;
this.nextBackoffDelay = this.initialDelay;
this.backoffNumber = 0;
clearTimeout(this.timeoutID);
this.timeoutID = null;
}
}, {
key: "failAfter",
value: function failAfter(maxNumberOfRetry) {
if (maxNumberOfRetry <= 0) {
throw new Error("Expected a maximum number of retry greater than 0 but got ".concat(maxNumberOfRetry));
}
this.maxNumberOfRetry = maxNumberOfRetry;
}
}, {
key: "next",
value: function next() {
this.backoffDelay = Math.min(this.nextBackoffDelay, this.maxDelay);
this.nextBackoffDelay = this.backoffDelay * this.factor;
var randomisationMultiple = 1 + Math.random() * this.randomisationFactor;
return Math.min(this.maxDelay, Math.round(this.backoffDelay * randomisationMultiple));
}
}, {
key: "onBackoff",
value: function onBackoff() {
this.timeoutID = null;
this.emit('ready', this.backoffNumber, this.backoffDelay);
this.backoffNumber++;
}
}], [{
key: "exponential",
value: function exponential(options) {
return new Backoff(options);
}
}]);
return Backoff;
}(events_1$a.EventEmitter);
backoff$2.Backoff = Backoff$2;
backoff$2.default = Backoff$2;
Object.defineProperty(lib$5, "__esModule", {
value: true
});
var retrier_1$2 = retrier$2;
lib$5.Retrier = retrier_1$2.Retrier;
var backoff_1$2 = backoff$2;
lib$5.Backoff = backoff_1$2.Backoff;
lib$5.default = retrier_1$2.Retrier;
var logger$3 = {};
Object.defineProperty(logger$3, "__esModule", {
value: true
});
logger$3.log = logger$3.Logger = void 0;
var logger$2 = loglevel.exports;
function prepareLine$2(prefix, args) {
return ["".concat(new Date().toISOString(), " Notifications ").concat(prefix, ":")].concat(Array.from(args));
}
var Logger$1 = /*#__PURE__*/function () {
function Logger() {
_classCallCheck$1(this, Logger);
this.prefix = '';
}
_createClass(Logger, [{
key: "setLevel",
value: function setLevel(level) {
logger$2.setLevel(level);
}
}, {
key: "trace",
value: function trace() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
logger$2.debug.apply(null, prepareLine$2('T' + this.prefix, args));
}
}, {
key: "debug",
value: function debug() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
logger$2.debug.apply(null, prepareLine$2('D' + this.prefix, args));
}
}, {
key: "info",
value: function info() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
logger$2.info.apply(null, prepareLine$2('I' + this.prefix, args));
}
}, {
key: "warn",
value: function warn() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
logger$2.warn.apply(null, prepareLine$2('W' + this.prefix, args));
}
}, {
key: "error",
value: function error() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
logger$2.error.apply(null, prepareLine$2('E' + this.prefix, args));
}
}], [{
key: "scope",
value: function scope() {
// TBD this.prefix += ' ' + prefix;
return new Logger();
}
}]);
return Logger;
}();
logger$3.Logger = Logger$1;
var logInstance = Logger$1.scope();
logger$3.log = logInstance;
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$6(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$6(arr) || _nonIterableSpread();
}
var connector = {};
function _createSuper$q(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$q(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$q() { 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; } }
Object.defineProperty(connector, "__esModule", {
value: true
});
connector.Connector = connector.RegistrationState = void 0;
var events_1$9 = require$$0;
var logger_1$b = logger$3;
var RegistrationState = /*#__PURE__*/function () {
function RegistrationState() {
var token = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var notificationId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var messageTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
_classCallCheck$1(this, RegistrationState);
this.token = token;
this.notificationId = notificationId;
this.messageTypes = messageTypes;
}
_createClass(RegistrationState, [{
key: "clone",
value: function clone() {
return new RegistrationState(this.token, this.notificationId, new Set(this.messageTypes));
}
}]);
return RegistrationState;
}();
connector.RegistrationState = RegistrationState;
function setDifference(a, b) {
return [].concat(_toConsumableArray(_toConsumableArray(a).filter(function (x) {
return !b.has(x);
})), _toConsumableArray(_toConsumableArray(b).filter(function (x) {
return !a.has(x);
})));
}
function hasDifference(a, b) {
var reasons = new Set();
if (a.notificationId !== b.notificationId) {
reasons.add('notificationId');
}
if (a.token !== b.token) {
reasons.add('token');
}
if (setDifference(a.messageTypes, b.messageTypes).length > 0) {
reasons.add('messageType');
}
return [reasons.size > 0, reasons];
}
var Connector = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Connector, _events_1$EventEmitte);
var _super = _createSuper$q(Connector);
function Connector(config) {
var _this;
_classCallCheck$1(this, Connector);
_this = _super.call(this);
_this.config = config;
_this.desiredState = new RegistrationState();
_this.currentState = new RegistrationState();
_this.hasActiveAttempt = false;
return _this;
}
_createClass(Connector, [{
key: "subscribe",
value: function () {
var _subscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(messageType) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.desiredState.messageTypes.has(messageType)) {
_context.next = 3;
break;
}
logger_1$b.log.debug('message type already registered ', messageType);
return _context.abrupt("return");
case 3:
this.desiredState.messageTypes.add(messageType);
_context.next = 6;
return this.persistRegistration();
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function subscribe(_x) {
return _subscribe.apply(this, arguments);
}
return subscribe;
}()
}, {
key: "unsubscribe",
value: function () {
var _unsubscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(messageType) {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.desiredState.messageTypes.has(messageType)) {
_context2.next = 2;
break;
}
return _context2.abrupt("return");
case 2:
this.desiredState.messageTypes.delete(messageType);
_context2.next = 5;
return this.persistRegistration();
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function unsubscribe(_x2) {
return _unsubscribe.apply(this, arguments);
}
return unsubscribe;
}()
}, {
key: "updateToken",
value: function updateToken(token) {
this.desiredState.token = token;
this.persistRegistration();
}
}, {
key: "persistRegistration",
value: function () {
var _persistRegistration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
var _this2 = this;
var _hasDifference, _hasDifference2, needToUpdate, reasons, stateToPersist, persistedState;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(!this.config.token || this.config.token.length === 0)) {
_context3.next = 3;
break;
}
logger_1$b.log.trace('Can\'t persist registration: token is not set');
return _context3.abrupt("return");
case 3:
if (!this.hasActiveAttempt) {
_context3.next = 6;
break;
}
logger_1$b.log.trace('One registration attempt is already in progress');
return _context3.abrupt("return");
case 6:
_hasDifference = hasDifference(this.desiredState, this.currentState), _hasDifference2 = _slicedToArray(_hasDifference, 2), needToUpdate = _hasDifference2[0], reasons = _hasDifference2[1];
if (needToUpdate) {
_context3.next = 9;
break;
}
return _context3.abrupt("return");
case 9:
if (!this.currentState.notificationId) {
reasons.delete('notificationId');
}
logger_1$b.log.trace('Persisting registration', reasons, this.desiredState);
_context3.prev = 11;
this.hasActiveAttempt = true;
stateToPersist = this.desiredState.clone();
if (!(stateToPersist.messageTypes.size > 0)) {
_context3.next = 24;
break;
}
_context3.next = 17;
return this.updateRegistration(stateToPersist, reasons);
case 17:
persistedState = _context3.sent;
this.currentState.token = persistedState.token;
this.currentState.notificationId = persistedState.notificationId;
this.currentState.messageTypes = persistedState.messageTypes;
this.emit('stateChanged', 'registered');
_context3.next = 30;
break;
case 24:
_context3.next = 26;
return this.removeRegistration();
case 26:
this.currentState.token = stateToPersist.token;
this.currentState.notificationId = stateToPersist.notificationId;
this.currentState.messageTypes.clear();
this.emit('stateChanged', 'unregistered');
case 30:
_context3.prev = 30;
this.hasActiveAttempt = false;
setTimeout(function () {
return _this2.persistRegistration();
}, 0);
return _context3.finish(30);
case 34:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[11,, 30, 34]]);
}));
function persistRegistration() {
return _persistRegistration.apply(this, arguments);
}
return persistRegistration;
}()
}, {
key: "setNotificationId",
value: function setNotificationId(notificationId) {
this.desiredState.notificationId = notificationId;
this.persistRegistration();
}
}]);
return Connector;
}(events_1$9.EventEmitter);
connector.Connector = Connector;
function _createSuper$p(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$p(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$p() { 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 (exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RegistrarConnector = exports.Connector = void 0;
var operation_retrier_1 = lib$5;
var logger_1 = logger$3;
var connector_1 = connector;
Object.defineProperty(exports, "Connector", {
enumerable: true,
get: function get() {
return connector_1.Connector;
}
});
var retrierConfig = {
min: 2000,
max: 120000,
randomness: 0.2
};
/**
* Manages the registrations on ERS service.
* Deduplicates registrations and manages them automatically
*/
var RegistrarConnector = /*#__PURE__*/function (_connector_1$Connecto) {
_inherits$1(RegistrarConnector, _connector_1$Connecto);
var _super = _createSuper$p(RegistrarConnector);
/**
* Creates new instance of the ERS registrar
*
* @param Object configuration
* @param string notificationId
* @param string channelType
* @param Array messageTypes
*/
function RegistrarConnector(channelType, context, transport, config) {
var _this;
_classCallCheck$1(this, RegistrarConnector);
_this = _super.call(this, config);
_this.channelType = channelType;
_this.context = context;
_this.transport = transport;
return _this;
}
_createClass(RegistrarConnector, [{
key: "updateRegistration",
value: function () {
var _updateRegistration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(registration, reasons) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!reasons.has('notificationId')) {
_context.next = 3;
break;
}
_context.next = 3;
return this.removeRegistration();
case 3:
if (!(!registration.notificationId || !registration.notificationId.length)) {
_context.next = 5;
break;
}
return _context.abrupt("return", registration);
case 5:
_context.next = 7;
return this.register(registration);
case 7:
return _context.abrupt("return", registration);
case 8:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function updateRegistration(_x, _x2) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;
}()
}, {
key: "removeRegistration",
value: function () {
var _removeRegistration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
var _this2 = this;
var url, headers;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.registrationId) {
_context2.next = 2;
break;
}
return _context2.abrupt("return");
case 2:
url = "".concat(this.config.registrarUrl, "/").concat(this.registrationId, "?productId=").concat(this.context.productId);
headers = {
'Content-Type': 'application/json',
'X-Twilio-Token': this.config.token
};
_context2.prev = 4;
logger_1.log.trace('Removing registration for ', this.channelType);
_context2.next = 8;
return new operation_retrier_1.Retrier(Object.assign(retrierConfig, {
maxAttemptsCount: 3
})).run(function () {
return _this2.transport.delete(url, headers);
});
case 8:
logger_1.log.debug('Registration removed for', this.channelType);
_context2.next = 15;
break;
case 11:
_context2.prev = 11;
_context2.t0 = _context2["catch"](4);
logger_1.log.error('Failed to remove of registration ', this.channelType, _context2.t0);
throw _context2.t0;
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[4, 11]]);
}));
function removeRegistration() {
return _removeRegistration.apply(this, arguments);
}
return removeRegistration;
}()
}, {
key: "register",
value: function () {
var _register = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(registration) {
var _this3 = this;
var registrarRequest, url, headers, response;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
logger_1.log.trace('Registering', this.channelType, registration);
registrarRequest = {
endpoint_platform: this.context.platform,
channel_type: this.channelType,
version: this.context.protocolVersion.toString(),
message_types: Array.from(registration.messageTypes),
data: {
registration_id: registration.notificationId
},
ttl: 'PT24H'
};
url = "".concat(this.config.registrarUrl, "?productId=").concat(this.context.productId);
headers = {
'Content-Type': 'application/json',
'X-Twilio-Token': registration.token
};
logger_1.log.trace('Creating registration for channel ', this.channelType);
_context3.prev = 5;
_context3.next = 8;
return new operation_retrier_1.Retrier(retrierConfig).run(function () {
return _this3.transport.post(url, headers, registrarRequest);
});
case 8:
response = _context3.sent;
this.registrationId = response.body.id;
logger_1.log.debug('Registration created: ', response);
_context3.next = 17;
break;
case 13:
_context3.prev = 13;
_context3.t0 = _context3["catch"](5);
logger_1.log.error('Registration failed: ', _context3.t0);
throw _context3.t0;
case 17:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[5, 13]]);
}));
function register(_x3) {
return _register.apply(this, arguments);
}
return register;
}()
}]);
return RegistrarConnector;
}(connector_1.Connector);
exports.RegistrarConnector = RegistrarConnector;
})(registrar_connector);
var twilsock_connector = {};
function _createSuper$o(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$o(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$o() { 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; } }
Object.defineProperty(twilsock_connector, "__esModule", {
value: true
});
twilsock_connector.TwilsockConnector = void 0;
var uuid$1 = uuid_1$3;
var connector_1 = connector;
/**
* Registrar connector implementation for twilsock
*/
var TwilsockConnector = /*#__PURE__*/function (_connector_1$Connecto) {
_inherits$1(TwilsockConnector, _connector_1$Connecto);
var _super = _createSuper$o(TwilsockConnector);
function TwilsockConnector(context, twilsock, config) {
var _this;
_classCallCheck$1(this, TwilsockConnector);
_this = _super.call(this, config);
_this.twilsock = twilsock;
_this.context = context;
context.id = uuid$1.v4();
_this.twilsock.on('stateChanged', function (state) {
if (state !== 'connected') {
_this.emit('transportReady', false);
}
});
_this.twilsock.on('registered', function (id) {
if (context && id === context.id && twilsock.state === 'connected') {
_this.emit('transportReady', true);
}
});
return _this;
}
_createClass(TwilsockConnector, [{
key: "setNotificationId",
value: function setNotificationId() {}
}, {
key: "updateToken",
value: function updateToken(token) {// no need to do anything here, twilsock backend handles it on it's own
// so just ignoring here
}
}, {
key: "updateContextRequest",
value: function () {
var _updateContextRequest = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(messageTypes) {
var context;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
context = {
product_id: this.context.productId,
notification_protocol_version: 4,
endpoint_platform: this.context.platform,
message_types: messageTypes
};
this.emit('transportReady', false);
_context.next = 4;
return this.twilsock.setNotificationsContext(this.context.id, context);
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function updateContextRequest(_x) {
return _updateContextRequest.apply(this, arguments);
}
return updateContextRequest;
}()
}, {
key: "updateRegistration",
value: function () {
var _updateRegistration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(registration, reasons) {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (reasons.has('messageType')) {
_context2.next = 2;
break;
}
return _context2.abrupt("return");
case 2:
_context2.next = 4;
return this.updateContextRequest(Array.from(registration.messageTypes));
case 4:
return _context2.abrupt("return", registration);
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function updateRegistration(_x2, _x3) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;
}()
}, {
key: "removeRegistration",
value: function removeRegistration() {
return this.twilsock.removeNotificationsContext(this.context.id);
}
}]);
return TwilsockConnector;
}(connector_1.Connector);
twilsock_connector.TwilsockConnector = TwilsockConnector;
function _createSuper$n(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$n(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$n() { 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; } }
Object.defineProperty(registrar, "__esModule", {
value: true
});
registrar.Registrar = void 0;
var events_1$8 = require$$0;
var registrar_connector_1 = registrar_connector;
var twilsock_connector_1 = twilsock_connector;
/**
* Provides an interface to the ERS registrar
*/
var Registrar = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Registrar, _events_1$EventEmitte);
var _super = _createSuper$n(Registrar);
/**
* Creates the new instance of registrar client
*/
function Registrar(productId, transport, twilsock, config) {
var _this;
_classCallCheck$1(this, Registrar);
_this = _super.call(this);
_this.config = config;
_this.connectors = new Map();
var platform = _this.detectPlatform();
_this.connectors.set('gcm', new registrar_connector_1.RegistrarConnector('gcm', {
protocolVersion: 3,
productId: productId,
platform: platform
}, transport, config));
_this.connectors.set('fcm', new registrar_connector_1.RegistrarConnector('fcm', {
protocolVersion: 3,
productId: productId,
platform: platform
}, transport, config));
_this.connectors.set('apn', new registrar_connector_1.RegistrarConnector('apn', {
protocolVersion: 4,
productId: productId,
platform: platform
}, transport, config));
_this.connectors.set('twilsock', new twilsock_connector_1.TwilsockConnector({
productId: productId,
platform: platform
}, twilsock, config));
_this.connectors.get('twilsock').on('transportReady', function (state) {
return _this.emit('transportReady', state);
});
return _this;
}
/**
* Sets notification ID.
* If new URI is different from previous, it triggers updating of registration for given channel
*
* @param {string} channelType channel type (apn|gcm|fcm|twilsock)
* @param {string} notificationId The notification ID
*/
_createClass(Registrar, [{
key: "setNotificationId",
value: function setNotificationId(channelType, notificationId) {
this.connector(channelType).setNotificationId(notificationId);
}
/**
* Subscribe for given type of message
*
* @param {String} messageType Message type identifier
* @param {String} channelType Channel type, can be 'twilsock', 'gcm' or 'fcm'
* @public
*/
}, {
key: "subscribe",
value: function subscribe(messageType, channelType) {
return this.connector(channelType).subscribe(messageType);
}
/**
* Remove subscription
* @param {String} messageType Message type
* @param {String} channelType Channel type (twilsock or gcm/fcm)
*/
}, {
key: "unsubscribe",
value: function unsubscribe(messageType, channelType) {
return this.connector(channelType).unsubscribe(messageType);
}
}, {
key: "updateToken",
value: function updateToken(token) {
this.connectors.forEach(function (connector) {
return connector.updateToken(token);
});
}
/**
* @param {String} type Channel type
* @throws {Error} Error with description
*/
}, {
key: "connector",
value: function connector(type) {
var connector = this.connectors.get(type);
if (!connector) {
throw new Error("Unknown channel type: ".concat(type));
}
return connector;
}
/**
* Returns platform string limited to max 128 chars
*/
}, {
key: "detectPlatform",
value: function detectPlatform() {
var platform = '';
if (typeof navigator !== 'undefined') {
platform = 'unknown';
if (typeof navigator.product !== 'undefined') {
platform = navigator.product;
}
if (typeof navigator.userAgent !== 'undefined') {
platform = navigator.userAgent;
}
} else {
platform = 'web';
}
return platform.substring(0, 128);
}
}]);
return Registrar;
}(events_1$8.EventEmitter);
registrar.Registrar = Registrar;
function _createSuper$m(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$m(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _isNativeReflectConstruct$m() { 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; } }
Object.defineProperty(client$2, "__esModule", {
value: true
});
client$2.Client = void 0;
var events_1$7 = require$$0;
var twilsock_1$3 = lib$8;
var configuration_1$3 = configuration$2;
var registrar_1 = registrar;
var logger_1$a = logger$3;
/**
* @class
* @alias Notifications
* @classdesc The helper library for the notification service.
* Provides high level api for creating and managing notification subscriptions and receiving messages
* Creates the instance of Notification helper library
*
* @constructor
* @param {string} token - Twilio access token
* @param {Notifications#ClientOptions} options - Options to customize client behavior
*/
var Client$3 = /*#__PURE__*/function (_events_1$EventEmitte) {
_inherits$1(Client, _events_1$EventEmitte);
var _super = _createSuper$m(Client);
function Client(token) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck$1(this, Client);
_this = _super.call(this);
if (!token || token.length === 0) {
throw new Error('Token is required for Notifications client');
}
options.logLevel = options.logLevel || 'error';
logger_1$a.log.setLevel(options.logLevel);
options.minTokenRefreshInterval || 10000;
var productId = options.productId || 'notifications';
options.twilsockClient = options.twilsockClient || new twilsock_1$3.TwilsockClient(token, productId, options);
options.transport = options.transport || options.twilsockClient;
_this.services = {
twilsock: options.twilsockClient,
transport: options.transport,
config: new configuration_1$3.Configuration(null, options)
};
_this.registrar = new registrar_1.Registrar(productId, _this.services.transport, _this.services.twilsock, _this.services.config);
_this.reliableTransportState = {
overall: false,
transport: false,
registration: false,
lastEmitted: null
};
_this._onTransportStateChange(_this.services.twilsock.isCon