Created
May 23, 2024 18:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
@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 `[email protected]`, 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.isConnected); | |
_this.registrar.on('transportReady', function (state) { | |
_this._onRegistrationStateChange(state ? 'registered' : ''); | |
}); | |
_this.registrar.on('stateChanged', function (state) { | |
_this._onRegistrationStateChange(state); | |
}); | |
_this.registrar.on('needReliableTransport', _this._onNeedReliableTransport.bind(_assertThisInitialized(_this))); | |
_this.services.twilsock.on('message', function (type, message) { | |
return _this._routeMessage(type, message); | |
}); | |
_this.services.twilsock.on('connected', function (notificationId) { | |
_this._onTransportStateChange(true); | |
_this.registrar.setNotificationId('twilsock', notificationId); | |
}); | |
_this.services.twilsock.on('disconnected', function () { | |
_this._onTransportStateChange(false); | |
}); | |
_this.services.config.updateToken(token); | |
_this.registrar.updateToken(token); | |
return _this; | |
} | |
_createClass(Client, [{ | |
key: "connectionState", | |
get: function get() { | |
if (this.services.twilsock.state === 'disconnected') { | |
return 'disconnected'; | |
} else if (this.services.twilsock.state === 'disconnecting') { | |
return 'disconnecting'; | |
} else if (this.services.twilsock.state === 'connected' && this.reliableTransportState.registration) { | |
return 'connected'; | |
} else if (this.services.twilsock.state === 'rejected') { | |
return 'denied'; | |
} | |
return 'connecting'; | |
} | |
/** | |
* Routes messages to the external subscribers | |
* @private | |
*/ | |
}, { | |
key: "_routeMessage", | |
value: function _routeMessage(type, message) { | |
logger_1$a.log.trace('Message arrived: ', type, message); | |
this.emit('message', type, message); | |
} | |
}, { | |
key: "_onNeedReliableTransport", | |
value: function _onNeedReliableTransport(isNeeded) { | |
if (isNeeded) { | |
this.services.twilsock.connect(); | |
} else { | |
this.services.twilsock.disconnect(); | |
} | |
} | |
}, { | |
key: "_onRegistrationStateChange", | |
value: function _onRegistrationStateChange(state) { | |
this.reliableTransportState.registration = state === 'registered'; | |
this._updateTransportState(); | |
} | |
}, { | |
key: "_onTransportStateChange", | |
value: function _onTransportStateChange(connected) { | |
this.reliableTransportState.transport = connected; | |
this._updateTransportState(); | |
} | |
}, { | |
key: "_updateTransportState", | |
value: function _updateTransportState() { | |
var overallState = this.reliableTransportState.transport && this.reliableTransportState.registration; | |
if (this.reliableTransportState.overall !== overallState) { | |
this.reliableTransportState.overall = overallState; | |
logger_1$a.log.info('Transport ready:', overallState); | |
this.emit('transportReady', overallState); | |
} | |
if (this.reliableTransportState.lastEmitted !== this.connectionState) { | |
this.reliableTransportState.lastEmitted = this.connectionState; | |
this.emit('connectionStateChanged', this.connectionState); | |
} | |
} | |
/** | |
* Adds the subscription for the given message type | |
* @param {string} messageType The type of message that you want to receive | |
* @param {string} channelType. Supported are 'twilsock', 'gcm' and 'fcm' | |
*/ | |
}, { | |
key: "subscribe", | |
value: function subscribe(messageType) { | |
var channelType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'twilsock'; | |
logger_1$a.log.trace('Add subscriptions for message type: ', messageType, channelType); | |
return this.registrar.subscribe(messageType, channelType); | |
} | |
/** | |
* Remove the subscription for the particular message type | |
* @param {string} messageType The type of message that you don't want to receive anymore | |
* @param {string} channelType. Supported are 'twilsock', 'gcm' and 'fcm' | |
*/ | |
}, { | |
key: "unsubscribe", | |
value: function unsubscribe(messageType) { | |
var channelType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'twilsock'; | |
logger_1$a.log.trace('Remove subscriptions for message type: ', messageType, channelType); | |
return this.registrar.unsubscribe(messageType, channelType); | |
} | |
/** | |
* Handle incoming push notification. | |
* Client application should call this method when it receives push notifications and pass the received data | |
* @param {Object} message push message | |
* @return {PushNotification} | |
*/ | |
}, { | |
key: "handlePushNotification", | |
value: function handlePushNotification(message) { | |
return { | |
messageType: message.twi_message_type, | |
payload: message.payload | |
}; | |
} | |
/** | |
* Set APN/GCM/FCM token to enable application register for a push messages | |
* @param {string} gcmToken/fcmToken Token received from GCM/FCM system | |
*/ | |
}, { | |
key: "setPushRegistrationId", | |
value: function setPushRegistrationId(registrationId, channelType) { | |
logger_1$a.log.trace('Set push registration id', registrationId, channelType); | |
this.registrar.setNotificationId(channelType, registrationId); | |
} | |
/** | |
* Updates auth token for registration | |
* @param {string} token Authentication token for registrations | |
*/ | |
}, { | |
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$a.log.info('authTokenUpdated'); | |
if (!(this.services.config.token === token)) { | |
_context.next = 3; | |
break; | |
} | |
return _context.abrupt("return"); | |
case 3: | |
_context.next = 5; | |
return this.services.twilsock.updateToken(token); | |
case 5: | |
this.services.config.updateToken(token); | |
this.registrar.updateToken(token); | |
case 7: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function updateToken(_x) { | |
return _updateToken.apply(this, arguments); | |
} | |
return updateToken; | |
}() | |
}]); | |
return Client; | |
}(events_1$7.EventEmitter); | |
client$2.Client = Client$3; | |
(function (exports) { | |
Object.defineProperty(exports, "__esModule", { | |
value: true | |
}); | |
exports.Notifications = void 0; | |
var client_1 = client$2; | |
Object.defineProperty(exports, "Notifications", { | |
enumerable: true, | |
get: function get() { | |
return client_1.Client; | |
} | |
}); | |
})(lib$6); | |
var lib$4 = {exports: {}}; | |
var client$1 = {}; | |
var uri = {}; | |
Object.defineProperty(uri, "__esModule", { | |
value: true | |
}); | |
/** | |
* Construct URI with query parameters | |
*/ | |
var UriBuilder = /*#__PURE__*/function () { | |
function UriBuilder(base) { | |
_classCallCheck$1(this, UriBuilder); | |
this.base = base; | |
this.args = new Array(); | |
this.paths = new Array(); | |
} | |
_createClass(UriBuilder, [{ | |
key: "pathSegment", | |
value: function pathSegment(name) { | |
this.paths.push(encodeURIComponent(name)); | |
return this; | |
} | |
}, { | |
key: "queryParam", | |
value: function queryParam(name, value) { | |
if (typeof value !== 'undefined') { | |
this.args.push(encodeURIComponent(name) + '=' + encodeURIComponent(value)); | |
} | |
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; | |
}(); | |
uri.UriBuilder = UriBuilder; | |
var syncerror = {}; | |
function _createSuper$l(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(syncerror, "__esModule", { | |
value: true | |
}); | |
/** | |
* Generic SyncLibrary error class | |
*/ | |
var SyncError = /*#__PURE__*/function (_Error) { | |
_inherits$1(SyncError, _Error); | |
var _super = _createSuper$l(SyncError); | |
function SyncError(message) { | |
var _this; | |
var status = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; | |
var code = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; | |
_classCallCheck$1(this, SyncError); | |
_this = _super.call(this); | |
_this.name = _this.constructor.name; | |
_this.message = "".concat(message, " (status: ").concat(status, ", code: ").concat(code, ")"); | |
_this.status = status; | |
_this.code = code; | |
return _this; | |
} | |
return SyncError; | |
}( /*#__PURE__*/_wrapNativeSuper(Error)); | |
syncerror.SyncError = SyncError; | |
var SyncNetworkError = /*#__PURE__*/function (_SyncError) { | |
_inherits$1(SyncNetworkError, _SyncError); | |
var _super2 = _createSuper$l(SyncNetworkError); | |
function SyncNetworkError(message) { | |
var _this2; | |
var status = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; | |
var code = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; | |
var body = arguments.length > 3 ? arguments[3] : undefined; | |
_classCallCheck$1(this, SyncNetworkError); | |
_this2 = _super2.call(this, message, status, code); | |
_this2.body = body; | |
return _this2; | |
} | |
return SyncNetworkError; | |
}(SyncError); | |
syncerror.SyncNetworkError = SyncNetworkError; | |
syncerror.default = SyncError; | |
var sanitize = {}; | |
Object.defineProperty(sanitize, "__esModule", { | |
value: true | |
}); | |
var syncerror_1$7 = syncerror; | |
/** | |
* 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(obj) { | |
return JSON.parse(JSON.stringify(obj)); | |
} | |
sanitize.deepClone = deepClone; | |
function validateTtl(ttl, optional) { | |
if (optional && ttl === undefined) { | |
return; | |
} | |
var ttlType = _typeof$2(ttl); | |
if (ttlType !== 'number' || !isNonNegativeInteger(ttl)) { | |
var providedValue = ttlType === 'object' ? 'object' : "'".concat(ttl, "' of type '").concat(ttlType, "'"); | |
throw new syncerror_1$7.default("Invalid TTL, expected a positive integer of type number, was ".concat(providedValue), 400, 54011); | |
} | |
} | |
function validateId(id) { | |
if (id === undefined) { | |
return; | |
} | |
var idType = _typeof$2(id); | |
if (idType !== 'string') { | |
throw new Error("Invalid ID type, expected a string, got '".concat(idType, "'")); | |
} | |
} | |
sanitize.validateId = validateId; | |
function validateOptionalTtl(ttl) { | |
validateTtl(ttl, true); | |
} | |
sanitize.validateOptionalTtl = validateOptionalTtl; | |
function validateMandatoryTtl(ttl) { | |
validateTtl(ttl, false); | |
} | |
sanitize.validateMandatoryTtl = validateMandatoryTtl; | |
function validatePageSize(pageSize) { | |
var validPageSize = pageSize === undefined || isPositiveInteger(pageSize); | |
if (!validPageSize) { | |
throw new syncerror_1$7.default("Invalid pageSize parameter. Expected a positive integer, was '".concat(pageSize, "'."), 400, 20007); | |
} | |
} | |
sanitize.validatePageSize = validatePageSize; | |
function validateMode(mode) { | |
if (!['open_or_create', 'open_existing', 'create_new'].includes(mode)) { | |
throw new Error("Invalid open mode. Expected one of { 'create_new', 'open_or_create', 'open_existing' }"); | |
} | |
} | |
sanitize.validateMode = validateMode; | |
function isInteger(number) { | |
return !isNaN(parseInt(number)) && isFinite(number); | |
} | |
function isPositiveInteger(number) { | |
return isInteger(number) && number > 0; | |
} | |
function isNonNegativeInteger(number) { | |
return isInteger(number) && number >= 0; | |
} | |
var logger$1 = {}; | |
Object.defineProperty(logger$1, "__esModule", { | |
value: true | |
}); | |
var loglevelLog = loglevel.exports; | |
var log$d = loglevelLog.getLogger('twilio-sync'); // twilio-sync is used by Flex SDK. Please DO NOT change | |
function prepareLine$1(prefix, args) { | |
return ["".concat(new Date().toISOString(), " Sync ").concat(prefix, ":")].concat(Array.from(args)); | |
} | |
logger$1.default = { | |
setLevel: function setLevel(level) { | |
log$d.setLevel(level); | |
}, | |
trace: function trace() { | |
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
log$d.trace.apply(null, prepareLine$1('T', args)); | |
}, | |
debug: function debug() { | |
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | |
args[_key2] = arguments[_key2]; | |
} | |
log$d.debug.apply(null, prepareLine$1('D', args)); | |
}, | |
info: function info() { | |
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | |
args[_key3] = arguments[_key3]; | |
} | |
log$d.info.apply(null, prepareLine$1('I', args)); | |
}, | |
warn: function warn() { | |
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | |
args[_key4] = arguments[_key4]; | |
} | |
log$d.warn.apply(null, prepareLine$1('W', args)); | |
}, | |
error: function error() { | |
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { | |
args[_key5] = arguments[_key5]; | |
} | |
log$d.error.apply(null, prepareLine$1('E', args)); | |
} | |
}; | |
var configuration$1 = {}; | |
Object.defineProperty(configuration$1, "__esModule", { | |
value: true | |
}); | |
var SUBSCRIPTIONS_PATH = '/v4/Subscriptions'; | |
var MAPS_PATH = '/v3/Maps'; | |
var LISTS_PATH = '/v3/Lists'; | |
var DOCUMENTS_PATH = '/v3/Documents'; | |
var STREAMS_PATH = '/v3/Streams'; | |
var INSIGHTS_PATH = '/v3/Insights'; | |
function getWithDefault(container, key, defaultValue) { | |
if (container && typeof container[key] !== 'undefined') { | |
return container[key]; | |
} | |
return defaultValue; | |
} | |
/** | |
* Settings container for Sync library | |
*/ | |
var Configuration$1 = /*#__PURE__*/function () { | |
/** | |
* @param {Object} options | |
*/ | |
function Configuration() { | |
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | |
_classCallCheck$1(this, Configuration); | |
var region = options.region || 'us1'; | |
var defaultCdsUrl = "https://cds.".concat(region, ".twilio.com"); | |
var baseUri = options.cdsUri || defaultCdsUrl; | |
this.settings = { | |
subscriptionsUri: baseUri + SUBSCRIPTIONS_PATH, | |
documentsUri: baseUri + DOCUMENTS_PATH, | |
listsUri: baseUri + LISTS_PATH, | |
mapsUri: baseUri + MAPS_PATH, | |
streamsUri: baseUri + STREAMS_PATH, | |
insightsUri: baseUri + INSIGHTS_PATH, | |
sessionStorageEnabled: getWithDefault(options.Sync, 'enableSessionStorage', true), | |
productId: options.productId | |
}; | |
} | |
_createClass(Configuration, [{ | |
key: "subscriptionsUri", | |
get: function get() { | |
return this.settings.subscriptionsUri; | |
} | |
}, { | |
key: "documentsUri", | |
get: function get() { | |
return this.settings.documentsUri; | |
} | |
}, { | |
key: "listsUri", | |
get: function get() { | |
return this.settings.listsUri; | |
} | |
}, { | |
key: "mapsUri", | |
get: function get() { | |
return this.settings.mapsUri; | |
} | |
}, { | |
key: "streamsUri", | |
get: function get() { | |
return this.settings.streamsUri; | |
} | |
}, { | |
key: "insightsUri", | |
get: function get() { | |
return this.settings.insightsUri; | |
} | |
}, { | |
key: "backoffConfig", | |
get: function get() { | |
return this.settings.backoffConfig || {}; | |
} | |
}, { | |
key: "sessionStorageEnabled", | |
get: function get() { | |
return this.settings.sessionStorageEnabled; | |
} | |
}, { | |
key: "productId", | |
get: function get() { | |
return this.settings.productId; | |
} | |
}]); | |
return Configuration; | |
}(); | |
configuration$1.Configuration = Configuration$1; | |
var subscriptions = {}; | |
var lib$3 = {}; | |
var retrier$1 = {}; | |
function _createSuper$k(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(retrier$1, "__esModule", { | |
value: true | |
}); | |
var events_1$6 = require$$0; | |
/** | |
* Provides retrier service | |
*/ | |
var Retrier$1 = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Retrier, _events_1$EventEmitte); | |
var _super = _createSuper$k(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$6.EventEmitter); | |
retrier$1.Retrier = Retrier$1; | |
retrier$1.default = Retrier$1; | |
var backoff$1 = {}; | |
function _createSuper$j(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(backoff$1, "__esModule", { | |
value: true | |
}); | |
var events_1$5 = require$$0; | |
function isDef$1(value) { | |
return value !== undefined && value !== null; | |
} | |
var Backoff$1 = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Backoff, _events_1$EventEmitte); | |
var _super = _createSuper$j(Backoff); | |
function Backoff(options) { | |
var _this; | |
_classCallCheck$1(this, Backoff); | |
_this = _super.call(this); | |
options = options || {}; | |
if (isDef$1(options.initialDelay) && options.initialDelay < 1) { | |
throw new Error('The initial timeout must be equal to or greater than 1.'); | |
} else if (isDef$1(options.maxDelay) && options.maxDelay <= 1) { | |
throw new Error('The maximal timeout must be greater than 1.'); | |
} else if (isDef$1(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) { | |
throw new Error('The randomisation factor must be between 0 and 1.'); | |
} else if (isDef$1(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$5.EventEmitter); | |
backoff$1.Backoff = Backoff$1; | |
backoff$1.default = Backoff$1; | |
Object.defineProperty(lib$3, "__esModule", { | |
value: true | |
}); | |
var retrier_1$1 = retrier$1; | |
lib$3.Retrier = retrier_1$1.Retrier; | |
var backoff_1$1 = backoff$1; | |
lib$3.Backoff = backoff_1$1.Backoff; | |
lib$3.default = retrier_1$1.Retrier; | |
function _createForOfIteratorHelper$4(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(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$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(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$4(o, minLen); } | |
function _arrayLikeToArray$4(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; } | |
Object.defineProperty(subscriptions, "__esModule", { | |
value: true | |
}); | |
var operation_retrier_1$2 = lib$3; | |
var syncerror_1$6 = syncerror; | |
var logger_1$9 = logger$1; | |
var twilsock_1$2 = lib$8; | |
/** | |
* A data container used by the Subscriptions class to track subscribed entities' local | |
* representations and their state. | |
*/ | |
var SubscribedEntity = /*#__PURE__*/function () { | |
function SubscribedEntity(entity) { | |
_classCallCheck$1(this, SubscribedEntity); | |
this.localObject = entity; | |
this.pendingCorrelationId = null; | |
this.pendingAction = null; | |
this.established = false; | |
this.retryCount = 0; | |
} | |
_createClass(SubscribedEntity, [{ | |
key: "sid", | |
get: function get() { | |
return this.localObject.sid; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return this.localObject.type; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.localObject.lastEventId; | |
} // below properties are specific to Insights only | |
}, { | |
key: "indexName", | |
get: function get() { | |
return this.localObject.indexName; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return this.localObject.queryString; | |
} | |
}, { | |
key: "isEstablished", | |
get: function get() { | |
return this.established; | |
} | |
}, { | |
key: "update", | |
value: function update(event, isStrictlyOrdered) { | |
this.localObject._update(event, isStrictlyOrdered); | |
} | |
}, { | |
key: "updatePending", | |
value: function updatePending(action, correlationId) { | |
this.pendingAction = action; | |
this.pendingCorrelationId = correlationId; | |
} | |
}, { | |
key: "reset", | |
value: function reset() { | |
this.updatePending(null, null); | |
this.retryCount = 0; | |
this.established = false; | |
this.setSubscriptionState('none'); | |
} | |
}, { | |
key: "markAsFailed", | |
value: function markAsFailed(message) { | |
this.rejectedWithError = message.error; | |
this.updatePending(null, null); | |
this.localObject.reportFailure(new syncerror_1$6.SyncError("Failed to subscribe on service events: ".concat(message.error.message), message.error.status, message.error.code)); | |
} | |
}, { | |
key: "complete", | |
value: function complete(eventId) { | |
this.updatePending(null, null); | |
this.established = true; | |
this.localObject._advanceLastEventId(eventId); | |
} | |
}, { | |
key: "setSubscriptionState", | |
value: function setSubscriptionState(newState) { | |
this.localObject._setSubscriptionState(newState); | |
} | |
}]); | |
return SubscribedEntity; | |
}(); | |
/** | |
* @class Subscriptions | |
* @classdesc A manager which, in batches of varying size, continuously persists the | |
* subscription intent of the caller to the Sync backend until it achieves a | |
* converged state. | |
*/ | |
var Subscriptions = /*#__PURE__*/function () { | |
/** | |
* @constructor | |
* Prepares a new Subscriptions manager object with zero subscribed or persisted subscriptions. | |
* | |
* @param {object} config may include a key 'backoffConfig', wherein any of the parameters | |
* of Backoff.exponential (from npm 'backoff') are valid and will override the defaults. | |
* | |
* @param {Network} must be a viable running Sync Network object, useful for routing requests. | |
*/ | |
function Subscriptions(services) { | |
var _this = this; | |
_classCallCheck$1(this, Subscriptions); | |
this.isConnected = false; | |
this.maxBatchSize = 100; // If the server includes a `ttl_in_s` attribute in the poke response, subscriptionTtlTimer is started for that duration | |
// such that when it fires, it repokes the entire sync set (i.e., emulates a reconnect). Every reconnect resets the timer. | |
// After the timer has fired, the first poke request includes a `reason: ttl` attribute in the body. | |
this.subscriptionTtlTimer = null; | |
this.pendingPokeReason = null; | |
this.services = services; | |
this.subscriptions = new Map(); | |
this.persisted = new Map(); | |
this.latestPokeResponseArrivalTimestampByCorrelationId = new Map(); | |
var defaultBackoffConfig = { | |
randomisationFactor: 0.2, | |
initialDelay: 100, | |
maxDelay: 2 * 60 * 1000 | |
}; | |
this.backoff = operation_retrier_1$2.Backoff.exponential(Object.assign(defaultBackoffConfig, this.services.config.backoffConfig)); // This block is triggered by #_persist. Every request is executed in a series of (ideally 1) | |
// backoff 'ready' event, at which point a new subscription set is calculated. | |
this.backoff.on('ready', function () { | |
var _this$getSubscription = _this.getSubscriptionUpdateBatch(), | |
action = _this$getSubscription.action, | |
subscriptionRequests = _this$getSubscription.subscriptions; | |
if (action) { | |
_this.applyNewSubscriptionUpdateBatch(action, subscriptionRequests); | |
} else { | |
_this.backoff.reset(); | |
logger_1$9.default.debug('All subscriptions resolved.'); | |
} | |
}); | |
} | |
_createClass(Subscriptions, [{ | |
key: "getSubscriptionUpdateBatch", | |
value: function getSubscriptionUpdateBatch() { | |
function subtract(these, those, action, limit) { | |
var result = []; | |
var _iterator = _createForOfIteratorHelper$4(these), | |
_step; | |
try { | |
for (_iterator.s(); !(_step = _iterator.n()).done;) { | |
var _step$value = _slicedToArray(_step.value, 2), | |
thisKey = _step$value[0], | |
thisValue = _step$value[1]; | |
var otherValue = those.get(thisKey); | |
if (!otherValue && action !== thisValue.pendingAction && !thisValue.rejectedWithError) { | |
result.push(thisValue); | |
if (limit && result.length >= limit) { | |
break; | |
} | |
} | |
} | |
} catch (err) { | |
_iterator.e(err); | |
} finally { | |
_iterator.f(); | |
} | |
return result; | |
} | |
var listToAdd = subtract(this.subscriptions, this.persisted, 'establish', this.maxBatchSize); | |
if (listToAdd.length > 0) { | |
return { | |
action: 'establish', | |
subscriptions: listToAdd | |
}; | |
} | |
var listToRemove = subtract(this.persisted, this.subscriptions, 'cancel', this.maxBatchSize); | |
if (listToRemove.length > 0) { | |
return { | |
action: 'cancel', | |
subscriptions: listToRemove | |
}; | |
} | |
return { | |
action: null, | |
subscriptions: null | |
}; | |
} | |
}, { | |
key: "persist", | |
value: function persist() { | |
this.backoff.backoff(); | |
} | |
}, { | |
key: "applyNewSubscriptionUpdateBatch", | |
value: function () { | |
var _applyNewSubscriptionUpdateBatch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(action, requests) { | |
var _this2 = this; | |
var correlationId, _iterator2, _step2, subscribed, reason, response, newMaxBatchSize, subscriptionTtlInS, isNumeric, isValidTtl, estimatedDeliveryInMs, _isNumeric, isValidTimeout, _iterator3, _step3, attemptedSubscription; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
if (this.isConnected) { | |
_context.next = 4; | |
break; | |
} | |
logger_1$9.default.debug("Twilsock connection (required for subscription) not ready; waiting\u2026"); | |
this.backoff.reset(); | |
return _context.abrupt("return"); | |
case 4: | |
// Keeping in mind that events may begin flowing _before_ we receive the response | |
requests = this.processLocalActions(action, requests); | |
correlationId = new Date().getTime(); | |
_iterator2 = _createForOfIteratorHelper$4(requests); | |
try { | |
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { | |
subscribed = _step2.value; | |
this.recordActionAttemptOn(subscribed, action, correlationId); | |
} | |
} catch (err) { | |
_iterator2.e(err); | |
} finally { | |
_iterator2.f(); | |
} | |
reason = this.pendingPokeReason; | |
this.pendingPokeReason = null; // Send this batch to the service | |
_context.prev = 10; | |
_context.next = 13; | |
return this.request(action, correlationId, reason, requests); | |
case 13: | |
response = _context.sent; | |
newMaxBatchSize = response.body.max_batch_size; | |
if (!isNaN(parseInt(newMaxBatchSize)) && isFinite(newMaxBatchSize) && newMaxBatchSize > 0) { | |
this.maxBatchSize = newMaxBatchSize; | |
} | |
if (!this.subscriptionTtlTimer) { | |
subscriptionTtlInS = response.body.ttl_in_s; | |
isNumeric = !isNaN(parseFloat(subscriptionTtlInS)) && isFinite(subscriptionTtlInS); | |
isValidTtl = isNumeric && subscriptionTtlInS > 0; | |
if (isValidTtl) { | |
this.subscriptionTtlTimer = setTimeout(function () { | |
return _this2.onSubscriptionTtlElapsed(); | |
}, subscriptionTtlInS * 1000); | |
} | |
} | |
if (action === 'establish') { | |
estimatedDeliveryInMs = response.body.estimated_delivery_in_ms; | |
_isNumeric = !isNaN(parseFloat(estimatedDeliveryInMs)) && isFinite(estimatedDeliveryInMs); | |
isValidTimeout = _isNumeric && estimatedDeliveryInMs > 0; | |
if (isValidTimeout) { | |
setTimeout(function () { | |
return _this2.verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests); | |
}, estimatedDeliveryInMs); | |
} else { | |
logger_1$9.default.error("Invalid timeout: ".concat(estimatedDeliveryInMs)); | |
} | |
requests.filter(function (r) { | |
return r.pendingCorrelationId === correlationId; | |
}).forEach(function (r) { | |
return r.setSubscriptionState('response_in_flight'); | |
}); | |
} | |
this.backoff.reset(); | |
_context.next = 26; | |
break; | |
case 21: | |
_context.prev = 21; | |
_context.t0 = _context["catch"](10); | |
_iterator3 = _createForOfIteratorHelper$4(requests); | |
try { | |
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { | |
attemptedSubscription = _step3.value; | |
this.recordActionFailureOn(attemptedSubscription, action); | |
} | |
} catch (err) { | |
_iterator3.e(err); | |
} finally { | |
_iterator3.f(); | |
} | |
if (_context.t0 instanceof twilsock_1$2.TransportUnavailableError) { | |
logger_1$9.default.debug("Twilsock connection (required for subscription) not ready (c:".concat(correlationId, "); waiting\u2026")); | |
this.backoff.reset(); | |
} else { | |
logger_1$9.default.debug("Failed an attempt to ".concat(action, " subscriptions (c:").concat(correlationId, "); retrying"), _context.t0); | |
this.persist(); | |
} | |
case 26: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this, [[10, 21]]); | |
})); | |
function applyNewSubscriptionUpdateBatch(_x, _x2) { | |
return _applyNewSubscriptionUpdateBatch.apply(this, arguments); | |
} | |
return applyNewSubscriptionUpdateBatch; | |
}() | |
}, { | |
key: "verifyPokeDelivery", | |
value: function verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests) { | |
var _this3 = this; | |
var lastReceived = this.latestPokeResponseArrivalTimestampByCorrelationId.get(correlationId); | |
var silencePeriod = lastReceived ? new Date().getTime() - lastReceived : estimatedDeliveryInMs; | |
if (silencePeriod >= estimatedDeliveryInMs) { | |
// If we haven't received _any_ responses from that poke request for the duration of estimated_delivery_in_ms, poke again | |
requests.filter(function (r) { | |
return r.pendingCorrelationId === correlationId; | |
}).forEach(function (r) { | |
r.updatePending(null, null); | |
r.retryCount++; | |
_this3.persisted.delete(r.sid); | |
}); | |
this.persist(); | |
this.latestPokeResponseArrivalTimestampByCorrelationId.delete(correlationId); | |
} else { | |
// Otherwise, the poke responses are probably in transit and we should wait for them | |
var timeoutExtension = estimatedDeliveryInMs - silencePeriod; | |
setTimeout(function () { | |
return _this3.verifyPokeDelivery(correlationId, estimatedDeliveryInMs, requests); | |
}, timeoutExtension); | |
} | |
} | |
}, { | |
key: "processLocalActions", | |
value: function processLocalActions(action, requests) { | |
if (action === 'cancel') { | |
return requests.filter(function (request) { | |
return !request.rejectedWithError; | |
}); | |
} | |
return requests; | |
} | |
}, { | |
key: "recordActionAttemptOn", | |
value: function recordActionAttemptOn(attemptedSubscription, action, correlationId) { | |
attemptedSubscription.setSubscriptionState('request_in_flight'); | |
if (action === 'establish') { | |
this.persisted.set(attemptedSubscription.sid, attemptedSubscription); | |
attemptedSubscription.updatePending(action, correlationId); | |
} else { | |
// cancel | |
var persistedSubscription = this.persisted.get(attemptedSubscription.sid); | |
if (persistedSubscription) { | |
persistedSubscription.updatePending(action, correlationId); | |
} | |
} | |
} | |
}, { | |
key: "recordActionFailureOn", | |
value: function recordActionFailureOn(attemptedSubscription, action) { | |
attemptedSubscription.setSubscriptionState('none'); | |
attemptedSubscription.updatePending(null, null); | |
if (action === 'establish') { | |
this.persisted.delete(attemptedSubscription.sid); | |
} | |
} | |
}, { | |
key: "request", | |
value: function request(action, correlationId, reason, objects) { | |
var requests = objects.map(function (object) { | |
return { | |
object_sid: object.sid, | |
object_type: object.type, | |
last_event_id: action === 'establish' ? object.lastEventId : undefined, | |
index_name: action === 'establish' ? object.indexName : undefined, | |
query_string: action === 'establish' ? object.queryString : undefined | |
}; | |
}); | |
var retriedRequests = objects.filter(function (a) { | |
return a.retryCount > 0; | |
}).length; | |
logger_1$9.default.debug("Attempting '".concat(action, "' request (c:").concat(correlationId, "):"), requests); | |
var requestBody = { | |
event_protocol_version: 3, | |
action: action, | |
correlation_id: correlationId, | |
retried_requests: retriedRequests, | |
ttl_in_s: -1, | |
requests: requests | |
}; | |
if (reason === 'ttl') { | |
requestBody.reason = reason; | |
} | |
return this.services.network.post(this.services.config.subscriptionsUri, requestBody); | |
} | |
/** | |
* Establishes intent to be subscribed to this entity. That subscription will be effected | |
* asynchronously. | |
* If subscription to the given sid already exists, it will be overwritten. | |
* | |
* @param {String} sid should be a well-formed SID, uniquely identifying a single instance of a Sync entity. | |
* @param {Object} entity should represent the (singular) local representation of this entity. | |
* Incoming events and modifications to the entity will be directed at the _update() function | |
* of this provided reference. | |
* | |
* @return undefined | |
*/ | |
}, { | |
key: "add", | |
value: function add(sid, entity) { | |
logger_1$9.default.debug("Establishing intent to subscribe to ".concat(sid)); | |
var existingSubscription = this.subscriptions.get(sid); | |
if (existingSubscription && entity && existingSubscription.lastEventId === entity.lastEventId) { | |
// If last event id is the same as before - we're fine | |
return; | |
} | |
this.persisted.delete(sid); | |
this.subscriptions.set(sid, new SubscribedEntity(entity)); | |
this.persist(); | |
} | |
/** | |
* Establishes the caller's intent to no longer be subscribed to this entity. Following this | |
* call, no further events shall be routed to the local representation of the entity, even | |
* though a server-side subscription may take more time to actually terminate. | |
* | |
* @param {string} sid should be any well-formed SID, uniquely identifying a Sync entity. | |
* This call only has meaningful effect if that entity is subscribed at the | |
* time of call. Otherwise does nothing. | |
* | |
* @return undefined | |
*/ | |
}, { | |
key: "remove", | |
value: function remove(sid) { | |
logger_1$9.default.debug("Establishing intent to unsubscribe from ".concat(sid)); | |
var removed = this.subscriptions.delete(sid); | |
if (removed) { | |
this.persist(); | |
} | |
} | |
/** | |
* The point of ingestion for remote incoming messages (e.g. new data was written to a map | |
* to which we are subscribed). | |
* | |
* @param {object} message is the full, unaltered body of the incoming notification. | |
* | |
* @return undefined | |
*/ | |
}, { | |
key: "acceptMessage", | |
value: function acceptMessage(message, isStrictlyOrdered) { | |
logger_1$9.default.trace('Subscriptions received', message); | |
if (message.correlation_id) { | |
this.latestPokeResponseArrivalTimestampByCorrelationId.set(message.correlation_id, new Date().getTime()); | |
} | |
var event_type; | |
switch (message.event_type) { | |
case 'subscription_established': | |
this.applySubscriptionEstablishedMessage(message.event, message.correlation_id); | |
break; | |
case 'subscription_canceled': | |
this.applySubscriptionCancelledMessage(message.event, message.correlation_id); | |
break; | |
case 'subscription_failed': | |
this.applySubscriptionFailedMessage(message.event, message.correlation_id); | |
break; | |
case (event_type = message.event_type.match(/^(?:map|list|document|stream|live_query)_/) || {}).input: | |
{ | |
var typedSid; | |
switch (event_type[0]) { | |
case 'map_': | |
typedSid = message.event.map_sid; | |
break; | |
case 'list_': | |
typedSid = message.event.list_sid; | |
break; | |
case 'document_': | |
typedSid = message.event.document_sid; | |
break; | |
case 'stream_': | |
typedSid = message.event.stream_sid; | |
break; | |
case 'live_query_': | |
typedSid = message.event.query_id; // hack to mark replay events for LiveQuery as strictly ordered, due to lack of special type of notification for them | |
// (normally only replay events would have `twilio.sync.event` type, but LiveQuery non-replay events were also assigned | |
// to this type in legacy clients, which we have to support now; hence a hack) | |
isStrictlyOrdered = false; // explicitly override it due to code in router.ts does not know about LiveQueries | |
if (message.strictly_ordered === true) { | |
isStrictlyOrdered = true; | |
} | |
break; | |
default: | |
typedSid = undefined; | |
} | |
this.applyEventToSubscribedEntity(typedSid, message, isStrictlyOrdered); | |
} | |
break; | |
default: | |
logger_1$9.default.debug("Dropping unknown message type ".concat(message.event_type)); | |
break; | |
} | |
} | |
}, { | |
key: "applySubscriptionEstablishedMessage", | |
value: function applySubscriptionEstablishedMessage(message, correlationId) { | |
var sid = message.object_sid; | |
var subscriptionIntent = this.persisted.get(message.object_sid); | |
if (subscriptionIntent && subscriptionIntent.pendingCorrelationId === correlationId) { | |
if (message.replay_status === 'interrupted') { | |
logger_1$9.default.debug("Event Replay for subscription to ".concat(sid, " (c:").concat(correlationId, ") interrupted; continuing eagerly.")); | |
subscriptionIntent.updatePending(null, null); | |
this.persisted.delete(subscriptionIntent.sid); | |
this.backoff.reset(); | |
} else if (message.replay_status === 'completed') { | |
logger_1$9.default.debug("Event Replay for subscription to ".concat(sid, " (c:").concat(correlationId, ") completed. Subscription is ready.")); | |
subscriptionIntent.complete(message.last_event_id); | |
this.persisted.set(message.object_sid, subscriptionIntent); | |
subscriptionIntent.setSubscriptionState('established'); | |
this.backoff.reset(); | |
} | |
} else { | |
logger_1$9.default.debug("Late message for ".concat(message.object_sid, " (c:").concat(correlationId, ") dropped.")); | |
} | |
this.persist(); | |
} | |
}, { | |
key: "applySubscriptionCancelledMessage", | |
value: function applySubscriptionCancelledMessage(message, correlationId) { | |
var persistedSubscription = this.persisted.get(message.object_sid); | |
if (persistedSubscription && persistedSubscription.pendingCorrelationId === correlationId) { | |
persistedSubscription.updatePending(null, null); | |
persistedSubscription.setSubscriptionState('none'); | |
this.persisted.delete(message.object_sid); | |
} else { | |
logger_1$9.default.debug("Late message for ".concat(message.object_sid, " (c:").concat(correlationId, ") dropped.")); | |
} | |
this.persist(); | |
} | |
}, { | |
key: "applySubscriptionFailedMessage", | |
value: function applySubscriptionFailedMessage(message, correlationId) { | |
var sid = message.object_sid; | |
var subscriptionIntent = this.subscriptions.get(sid); | |
var subscription = this.persisted.get(sid); | |
if (subscriptionIntent && subscription) { | |
if (subscription.pendingCorrelationId === correlationId) { | |
logger_1$9.default.error("Failed to subscribe on ".concat(subscription.sid), message.error); | |
subscription.markAsFailed(message); | |
subscription.setSubscriptionState('none'); | |
} | |
} else if (!subscriptionIntent && subscription) { | |
this.persisted.delete(sid); | |
subscription.setSubscriptionState('none'); | |
} | |
this.persist(); | |
} | |
}, { | |
key: "applyEventToSubscribedEntity", | |
value: function applyEventToSubscribedEntity(sid, message, isStrictlyOrdered) { | |
var _this4 = this; | |
if (!sid) { | |
return; | |
} // Looking for subscription descriptor to check if poke has been completed | |
isStrictlyOrdered = isStrictlyOrdered || function () { | |
var subscription = _this4.persisted.get(sid); | |
return subscription && subscription.isEstablished; | |
}(); // Still searching for subscriptionIntents. User could remove subscription already | |
var subscriptionIntent = this.subscriptions.get(sid); | |
if (subscriptionIntent) { | |
message.event.type = message.event_type; | |
subscriptionIntent.update(message.event, isStrictlyOrdered); | |
} else { | |
logger_1$9.default.debug("Message dropped for SID '".concat(sid, "', for which there is no subscription.")); | |
} | |
} | |
}, { | |
key: "onConnectionStateChanged", | |
value: function onConnectionStateChanged(isConnected) { | |
this.isConnected = isConnected; | |
if (isConnected) { | |
this.poke('reconnect'); | |
} | |
} | |
}, { | |
key: "onSubscriptionTtlElapsed", | |
value: function onSubscriptionTtlElapsed() { | |
if (this.isConnected) { | |
this.poke('ttl'); | |
} | |
} | |
/** | |
* Prompts a playback of any missed changes made to any subscribed object. This method | |
* should be invoked whenever the connectivity layer has experienced cross-cutting | |
* delivery failures that would affect the entire local sync set. Any tangible result | |
* of this operation will result in calls to the _update() function of subscribed | |
* Sync entities. | |
*/ | |
}, { | |
key: "poke", | |
value: function poke(reason) { | |
logger_1$9.default.debug("Triggering event replay for all subscriptions, reason=".concat(reason)); | |
this.pendingPokeReason = reason; | |
if (this.subscriptionTtlTimer) { | |
clearTimeout(this.subscriptionTtlTimer); | |
this.subscriptionTtlTimer = null; | |
} | |
var failedSubscriptions = []; | |
var _iterator4 = _createForOfIteratorHelper$4(this.persisted.values()), | |
_step4; | |
try { | |
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { | |
var _it = _step4.value; | |
_it.reset(); | |
if (_it.rejectedWithError) { | |
failedSubscriptions.push(_it); | |
} | |
} | |
} catch (err) { | |
_iterator4.e(err); | |
} finally { | |
_iterator4.f(); | |
} | |
this.persisted.clear(); | |
for (var _i = 0, _failedSubscriptions = failedSubscriptions; _i < _failedSubscriptions.length; _i++) { | |
var it = _failedSubscriptions[_i]; | |
this.persisted.set(it.sid, it); | |
} | |
this.persist(); | |
} | |
/** | |
* Stops all communication, clears any subscription intent, and returns. | |
*/ | |
}, { | |
key: "shutdown", | |
value: function shutdown() { | |
this.backoff.reset(); | |
this.subscriptions.clear(); | |
} | |
}]); | |
return Subscriptions; | |
}(); | |
subscriptions.Subscriptions = Subscriptions; | |
var router = {}; | |
Object.defineProperty(router, "__esModule", { | |
value: true | |
}); | |
var logger_1$8 = logger$1; | |
var SYNC_DOCUMENT_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.document'; | |
var SYNC_LIST_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.list'; | |
var SYNC_MAP_NOTIFICATION_TYPE = 'com.twilio.rtd.cds.map'; | |
var SYNC_NOTIFICATION_TYPE = 'twilio.sync.event'; | |
/** | |
* @class Router | |
* @classdesc Routes all incoming messages to the consumers | |
*/ | |
var Router = /*#__PURE__*/function () { | |
function Router(params) { | |
var _this = this; | |
_classCallCheck$1(this, Router); | |
this.config = params.config; | |
this.subscriptions = params.subscriptions; | |
this.notifications = params.notifications; | |
this.notifications.subscribe(SYNC_NOTIFICATION_TYPE); | |
this.notifications.subscribe(SYNC_DOCUMENT_NOTIFICATION_TYPE); | |
this.notifications.subscribe(SYNC_LIST_NOTIFICATION_TYPE); | |
this.notifications.subscribe(SYNC_MAP_NOTIFICATION_TYPE); | |
this.notifications.on('message', function (messageType, payload) { | |
return _this.onMessage(messageType, payload); | |
}); | |
this.notifications.on('transportReady', function (isConnected) { | |
return _this.onConnectionStateChanged(isConnected); | |
}); | |
} | |
/** | |
* Entry point for all incoming messages | |
* @param {String} type - Type of incoming message | |
* @param {Object} message - Message to route | |
*/ | |
_createClass(Router, [{ | |
key: "onMessage", | |
value: function onMessage(type, message) { | |
logger_1$8.default.trace('Notification type:', type, 'content:', message); | |
switch (type) { | |
case SYNC_DOCUMENT_NOTIFICATION_TYPE: | |
case SYNC_LIST_NOTIFICATION_TYPE: | |
case SYNC_MAP_NOTIFICATION_TYPE: | |
this.subscriptions.acceptMessage(message, false); | |
break; | |
case SYNC_NOTIFICATION_TYPE: | |
this.subscriptions.acceptMessage(message, true); | |
break; | |
} | |
} | |
/** | |
* Subscribe for events | |
*/ | |
}, { | |
key: "subscribe", | |
value: function subscribe(sid, entity) { | |
this.subscriptions.add(sid, entity); | |
} | |
/** | |
* Unsubscribe from events | |
*/ | |
}, { | |
key: "unsubscribe", | |
value: function unsubscribe(sid) { | |
this.subscriptions.remove(sid); | |
} | |
/** | |
* Handle transport establishing event | |
* If we have any subscriptions - we should check object for modifications | |
*/ | |
}, { | |
key: "onConnectionStateChanged", | |
value: function onConnectionStateChanged(isConnected) { | |
this.subscriptions.onConnectionStateChanged(isConnected); | |
} | |
}]); | |
return Router; | |
}(); | |
router.Router = Router; | |
router.default = Router; | |
var network$1 = {}; | |
Object.defineProperty(network$1, "__esModule", { | |
value: true | |
}); | |
var uuid = uuid_1$3; | |
var syncerror_1$5 = syncerror; | |
var logger_1$7 = logger$1; | |
var operation_retrier_1$1 = lib$3; | |
var twilsock_1$1 = lib$8; | |
var MINIMUM_RETRY_DELAY$1 = 4000; | |
var MAXIMUM_RETRY_DELAY$1 = 60000; | |
var MAXIMUM_ATTEMPTS_TIME = 90000; | |
var RETRY_DELAY_RANDOMNESS = 0.2; | |
function messageFromErrorBody(transportError) { | |
if (transportError.body) { | |
if (transportError.body.message) { | |
return transportError.body.message; | |
} | |
} | |
switch (transportError.status) { | |
case 429: | |
return 'Throttled by server'; | |
case 404: | |
return 'Not found from server'; | |
default: | |
return 'Error from server'; | |
} | |
} | |
function codeFromErrorBody(trasportError) { | |
if (trasportError.body) { | |
return trasportError.body.code; | |
} | |
return 0; | |
} | |
function mapTransportError(transportError) { | |
if (transportError.status === 409) { | |
return new syncerror_1$5.SyncNetworkError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError), transportError.body); | |
} else if (transportError.status) { | |
return new syncerror_1$5.SyncError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError)); | |
} else if (transportError instanceof twilsock_1$1.TransportUnavailableError) { | |
return transportError; | |
} else { | |
return new syncerror_1$5.SyncError(transportError.message, 0, 0); | |
} | |
} | |
/** | |
* @classdesc Incapsulates network operations to make it possible to add some optimization/caching strategies | |
*/ | |
var NetworkService = /*#__PURE__*/function () { | |
function NetworkService(clientInfo, config, transport) { | |
_classCallCheck$1(this, NetworkService); | |
this.clientInfo = clientInfo; | |
this.config = config; | |
this.transport = transport; | |
} | |
_createClass(NetworkService, [{ | |
key: "createHeaders", | |
value: function createHeaders() { | |
return { | |
'Content-Type': 'application/json', | |
'Twilio-Sync-Client-Info': JSON.stringify(this.clientInfo), | |
'Twilio-Request-Id': 'RQ' + uuid.v4().replace(/-/g, '') | |
}; | |
} | |
}, { | |
key: "backoffConfig", | |
value: function backoffConfig() { | |
return Object.assign({ | |
min: MINIMUM_RETRY_DELAY$1, | |
max: MAXIMUM_RETRY_DELAY$1, | |
maxAttemptsTime: MAXIMUM_ATTEMPTS_TIME, | |
randomness: RETRY_DELAY_RANDOMNESS | |
}, this.config.backoffConfig); | |
} | |
}, { | |
key: "executeWithRetry", | |
value: function executeWithRetry(request) { | |
var _this = this; | |
var retryWhenThrottled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; | |
return new Promise(function (resolve, reject) { | |
var codesToRetryOn = [502, 503, 504]; | |
if (retryWhenThrottled) { | |
codesToRetryOn.push(429); | |
} | |
var retrier = new operation_retrier_1$1.Retrier(_this.backoffConfig()); | |
retrier.on('attempt', function () { | |
request().then(function (result) { | |
return retrier.succeeded(result); | |
}).catch(function (err) { | |
if (codesToRetryOn.includes(err.status)) { | |
var delayOverride = parseInt(err.headers ? err.headers['Retry-After'] : null); | |
retrier.failed(mapTransportError(err), isNaN(delayOverride) ? null : delayOverride * 1000); | |
} else if (err.message === 'Twilsock disconnected') { | |
// Ugly hack. We must make a proper exceptions for twilsock | |
retrier.failed(mapTransportError(err)); | |
} else { | |
// Fatal error | |
retrier.removeAllListeners(); | |
retrier.cancel(); | |
reject(mapTransportError(err)); | |
} | |
}); | |
}); | |
retrier.on('succeeded', function (result) { | |
resolve(result); | |
}); | |
retrier.on('cancelled', function (err) { | |
return reject(mapTransportError(err)); | |
}); | |
retrier.on('failed', function (err) { | |
return reject(mapTransportError(err)); | |
}); | |
retrier.start(); | |
}); | |
} | |
/** | |
* Make a GET request by given URI | |
* @Returns Promise<Response> Result of successful get request | |
*/ | |
}, { | |
key: "get", | |
value: function get(uri) { | |
var _this2 = this; | |
var headers = this.createHeaders(); | |
logger_1$7.default.debug('GET', uri, 'ID:', headers['Twilio-Request-Id']); | |
return this.executeWithRetry(function () { | |
return _this2.transport.get(uri, headers, _this2.config.productId); | |
}, true); | |
} | |
}, { | |
key: "post", | |
value: function post(uri, body, revision) { | |
var _this3 = this; | |
var retryWhenThrottled = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; | |
var headers = this.createHeaders(); | |
if (typeof revision !== 'undefined' && revision !== null) { | |
headers['If-Match'] = revision; | |
} | |
logger_1$7.default.debug('POST', uri, 'ID:', headers['Twilio-Request-Id']); | |
return this.executeWithRetry(function () { | |
return _this3.transport.post(uri, headers, body, _this3.config.productId); | |
}, retryWhenThrottled); | |
} | |
}, { | |
key: "put", | |
value: function put(uri, body, revision) { | |
var _this4 = this; | |
var headers = this.createHeaders(); | |
if (typeof revision !== 'undefined' && revision !== null) { | |
headers['If-Match'] = revision; | |
} | |
logger_1$7.default.debug('PUT', uri, 'ID:', headers['Twilio-Request-Id']); | |
return this.executeWithRetry(function () { | |
return _this4.transport.put(uri, headers, body, _this4.config.productId); | |
}, false); | |
} | |
}, { | |
key: "delete", | |
value: function _delete(uri) { | |
var _this5 = this; | |
var headers = this.createHeaders(); | |
logger_1$7.default.debug('DELETE', uri, 'ID:', headers['Twilio-Request-Id']); | |
return this.executeWithRetry(function () { | |
return _this5.transport.delete(uri, headers, _this5.config.productId); | |
}, false); | |
} | |
}]); | |
return NetworkService; | |
}(); | |
network$1.NetworkService = NetworkService; | |
var syncdocument = {}; | |
var entity = {}; | |
function _createForOfIteratorHelper$3(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$3(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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(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(o, minLen); } | |
function _arrayLikeToArray$3(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; } | |
Object.defineProperty(entity, "__esModule", { | |
value: true | |
}); | |
var SyncEntity = /*#__PURE__*/function () { | |
function SyncEntity(services, removalHandler) { | |
_classCallCheck$1(this, SyncEntity); | |
this.services = services; | |
this.removalHandler = removalHandler; | |
this.subscriptionState = 'none'; | |
this._attachedListeners = new Map(); | |
} | |
_createClass(SyncEntity, [{ | |
key: "_advanceLastEventId", | |
value: function _advanceLastEventId(eventId, revision) {} | |
}, { | |
key: "reportFailure", | |
value: function reportFailure(err) { | |
if (err.status === 404) { | |
// assume that 404 means that entity has been removed while we were away | |
this.onRemoved(false); | |
} else { | |
this.broadcastEventToListeners('failure', err); | |
} | |
} | |
/** | |
* Subscribe to changes of data entity | |
* @private | |
*/ | |
}, { | |
key: "_subscribe", | |
value: function _subscribe() { | |
this.services.router.subscribe(this.sid, this); | |
} | |
/** | |
* Unsubscribe from changes of current data entity | |
* @private | |
*/ | |
}, { | |
key: "_unsubscribe", | |
value: function _unsubscribe() { | |
this.services.router.unsubscribe(this.sid); | |
} | |
}, { | |
key: "_setSubscriptionState", | |
value: function _setSubscriptionState(newState) { | |
this.subscriptionState = newState; | |
this.broadcastEventToListeners('_subscriptionStateChanged', newState); | |
} | |
/** | |
* @public | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
this._unsubscribe(); | |
if (this.removalHandler != null) { | |
this.removalHandler(this.type, this.sid, this.uniqueName); | |
} | |
} | |
}, { | |
key: "attach", | |
value: function attach(closeable) { | |
var uuid = closeable.listenerUuid; | |
var existingRecord = this._attachedListeners.get(uuid); | |
if (existingRecord) { | |
return; | |
} | |
if (!this._attachedListeners.size) { | |
// the first one to arrive | |
this._subscribe(); | |
} | |
this._attachedListeners.set(uuid, closeable); | |
} | |
}, { | |
key: "detach", | |
value: function detach(listenerUuid) { | |
this._attachedListeners.delete(listenerUuid); | |
if (!this._attachedListeners.size) { | |
// last one out, turn off lights, shut the door | |
this.close(); // invokes unsubscribe and removal handler | |
} | |
} | |
}, { | |
key: "broadcastEventToListeners", | |
value: function broadcastEventToListeners(eventName, args) { | |
var _iterator = _createForOfIteratorHelper$3(this._attachedListeners.values()), | |
_step; | |
try { | |
for (_iterator.s(); !(_step = _iterator.n()).done;) { | |
var listener = _step.value; | |
listener.emit(eventName, args); | |
} | |
} catch (err) { | |
_iterator.e(err); | |
} finally { | |
_iterator.f(); | |
} | |
} | |
}]); | |
return SyncEntity; | |
}(); | |
entity.SyncEntity = SyncEntity; | |
entity.default = SyncEntity; | |
var mergingqueue = {}; | |
Object.defineProperty(mergingqueue, "__esModule", { | |
value: true | |
}); | |
var MergingQueue = /*#__PURE__*/function () { | |
function MergingQueue(inputMergingFunction) { | |
_classCallCheck$1(this, MergingQueue); | |
this.queuedRequests = []; | |
this.isRequestInFlight = false; | |
this.inputMergingFunction = inputMergingFunction; | |
} | |
_createClass(MergingQueue, [{ | |
key: "add", | |
value: function add(input, requestFunction) { | |
var _this = this; | |
var promise = new Promise(function (resolve, reject) { | |
return _this.queuedRequests.push({ | |
input: input, | |
requestFunction: requestFunction, | |
resolve: resolve, | |
reject: reject | |
}); | |
}); | |
this.wakeupQueue(); | |
return promise; | |
} | |
}, { | |
key: "squashAndAdd", | |
value: function squashAndAdd(input, requestFunction) { | |
var queueToSquash = this.queuedRequests; | |
this.queuedRequests = []; | |
var reducedInput; | |
if (queueToSquash.length > 0) { | |
reducedInput = queueToSquash.map(function (r) { | |
return r.input; | |
}).reduce(this.inputMergingFunction); | |
reducedInput = this.inputMergingFunction(reducedInput, input); | |
} else { | |
reducedInput = input; | |
} | |
var promise = this.add(reducedInput, requestFunction); | |
queueToSquash.forEach(function (request) { | |
return promise.then(request.resolve, request.reject); | |
}); | |
return promise; | |
} | |
}, { | |
key: "isEmpty", | |
value: function isEmpty() { | |
return this.queuedRequests.length === 0 && !this.isRequestInFlight; | |
} | |
}, { | |
key: "wakeupQueue", | |
value: function wakeupQueue() { | |
var _this2 = this; | |
if (this.queuedRequests.length === 0 || this.isRequestInFlight) { | |
return; | |
} else { | |
var requestToExecute = this.queuedRequests.shift(); | |
this.isRequestInFlight = true; | |
requestToExecute.requestFunction(requestToExecute.input).then(requestToExecute.resolve, requestToExecute.reject).then(function (__) { | |
_this2.isRequestInFlight = false; | |
_this2.wakeupQueue(); | |
}); | |
} | |
} | |
}]); | |
return MergingQueue; | |
}(); | |
mergingqueue.MergingQueue = MergingQueue; | |
var NamespacedMergingQueue = /*#__PURE__*/function () { | |
function NamespacedMergingQueue(inputReducer) { | |
_classCallCheck$1(this, NamespacedMergingQueue); | |
this.queueByNamespaceKey = new Map(); | |
this.inputReducer = inputReducer; | |
} | |
_createClass(NamespacedMergingQueue, [{ | |
key: "add", | |
value: function () { | |
var _add = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(namespaceKey, input, requestFunction) { | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
return _context.abrupt("return", this.invokeQueueMethod(namespaceKey, function (queue) { | |
return queue.add(input, requestFunction); | |
})); | |
case 1: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function add(_x, _x2, _x3) { | |
return _add.apply(this, arguments); | |
} | |
return add; | |
}() | |
}, { | |
key: "squashAndAdd", | |
value: function () { | |
var _squashAndAdd = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(namespaceKey, input, requestFunction) { | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
return _context2.abrupt("return", this.invokeQueueMethod(namespaceKey, function (queue) { | |
return queue.squashAndAdd(input, requestFunction); | |
})); | |
case 1: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function squashAndAdd(_x4, _x5, _x6) { | |
return _squashAndAdd.apply(this, arguments); | |
} | |
return squashAndAdd; | |
}() | |
}, { | |
key: "invokeQueueMethod", | |
value: function () { | |
var _invokeQueueMethod = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(namespaceKey, queueMethodInvoker) { | |
var queue, result; | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
if (!this.queueByNamespaceKey.has(namespaceKey)) { | |
this.queueByNamespaceKey.set(namespaceKey, new MergingQueue(this.inputReducer)); | |
} | |
queue = this.queueByNamespaceKey.get(namespaceKey); | |
result = queueMethodInvoker(queue); | |
if (this.queueByNamespaceKey.get(namespaceKey).isEmpty()) { | |
this.queueByNamespaceKey.delete(namespaceKey); | |
} | |
return _context3.abrupt("return", result); | |
case 5: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function invokeQueueMethod(_x7, _x8) { | |
return _invokeQueueMethod.apply(this, arguments); | |
} | |
return invokeQueueMethod; | |
}() | |
}]); | |
return NamespacedMergingQueue; | |
}(); | |
mergingqueue.NamespacedMergingQueue = NamespacedMergingQueue; | |
var closeable = {}; | |
function _createSuper$i(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(closeable, "__esModule", { | |
value: true | |
}); | |
var events_1$4 = require$$0; | |
var uuidv4 = uuid_1$3; | |
var Closeable = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Closeable, _events_1$EventEmitte); | |
var _super = _createSuper$i(Closeable); | |
function Closeable() { | |
var _this; | |
_classCallCheck$1(this, Closeable); | |
_this = _super.call(this); | |
_this.closed = false; | |
_this.uuid = uuidv4(); | |
return _this; | |
} | |
_createClass(Closeable, [{ | |
key: "listenerUuid", | |
get: function get() { | |
return this.uuid; | |
} | |
}, { | |
key: "close", | |
value: function close() { | |
this.removeAllListeners(); | |
this.closed = true; | |
} | |
}, { | |
key: "ensureNotClosed", | |
value: function ensureNotClosed() { | |
if (this.closed) { | |
throw new Error('Invalid operation on closed object'); | |
} | |
} | |
}]); | |
return Closeable; | |
}(events_1$4.EventEmitter); | |
closeable.Closeable = Closeable; | |
closeable.default = Closeable; | |
function _createSuper$h(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(syncdocument, "__esModule", { | |
value: true | |
}); | |
var syncerror_1$4 = syncerror; | |
var sanitize_1$4 = sanitize; | |
var logger_1$6 = logger$1; | |
var entity_1$4 = entity; | |
var mergingqueue_1$2 = mergingqueue; | |
var closeable_1$4 = closeable; | |
var SyncDocumentImpl = /*#__PURE__*/function (_entity_1$SyncEntity) { | |
_inherits$1(SyncDocumentImpl, _entity_1$SyncEntity); | |
var _super = _createSuper$h(SyncDocumentImpl); | |
/** | |
* @private | |
*/ | |
function SyncDocumentImpl(services, descriptor, removalHandler) { | |
var _this; | |
_classCallCheck$1(this, SyncDocumentImpl); | |
_this = _super.call(this, services, removalHandler); | |
_this.isDeleted = false; | |
var updateRequestReducer = function updateRequestReducer(acc, input) { | |
return typeof input.ttl === 'number' ? { | |
ttl: input.ttl | |
} : acc; | |
}; | |
_this.updateMergingQueue = new mergingqueue_1$2.MergingQueue(updateRequestReducer); | |
_this.descriptor = descriptor; | |
_this.descriptor.data = _this.descriptor.data || {}; | |
_this.descriptor.date_updated = new Date(_this.descriptor.date_updated); | |
return _this; | |
} // private props | |
_createClass(SyncDocumentImpl, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.url; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.descriptor.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.last_event_id; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.date_expires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return 'document'; | |
} // below properties are specific to Insights only | |
}, { | |
key: "indexName", | |
get: function get() { | |
return undefined; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return undefined; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.descriptor.sid; | |
} | |
}, { | |
key: "data", | |
get: function get() { | |
return this.descriptor.data; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.descriptor.date_updated; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.descriptor.unique_name || null; | |
} | |
/** | |
* Update data entity with new data | |
* @private | |
*/ | |
}, { | |
key: "_update", | |
value: function _update(update) { | |
update.date_created = new Date(update.date_created); | |
switch (update.type) { | |
case 'document_updated': | |
if (update.id <= this.lastEventId) { | |
logger_1$6.default.trace('Document update skipped, current:', this.lastEventId, ', remote:', update.id); | |
break; | |
} | |
var previousData = this.descriptor.data !== undefined ? sanitize_1$4.deepClone(this.descriptor.data) : null; | |
this.descriptor.last_event_id = update.id; | |
this.descriptor.revision = update.document_revision; | |
this.descriptor.date_updated = update.date_created; | |
this.descriptor.data = update.document_data; | |
this.broadcastEventToListeners('updated', { | |
data: update.document_data, | |
isLocal: false, | |
previousData: previousData | |
}); | |
this.services.storage.update(this.type, this.sid, this.uniqueName, { | |
last_event_id: update.id, | |
revision: update.document_revision, | |
date_updated: update.date_created, | |
data: update.document_data | |
}); | |
break; | |
case 'document_removed': | |
this.onRemoved(false); | |
break; | |
} | |
} | |
}, { | |
key: "set", | |
value: function () { | |
var _set = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(value, metadataUpdates) { | |
var _this2 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
input = metadataUpdates || {}; | |
sanitize_1$4.validateOptionalTtl(input.ttl); | |
return _context.abrupt("return", this.updateMergingQueue.squashAndAdd(input, function (input) { | |
return _this2._setUnconditionally(value, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function set(_x, _x2) { | |
return _set.apply(this, arguments); | |
} | |
return set; | |
}() | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(mutator, metadataUpdates) { | |
var _this3 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
input = metadataUpdates || {}; | |
sanitize_1$4.validateOptionalTtl(input.ttl); | |
return _context2.abrupt("return", this.updateMergingQueue.add(input, function (input) { | |
return _this3._setWithIfMatch(mutator, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function mutate(_x3, _x4) { | |
return _mutate.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
}, { | |
key: "update", | |
value: function () { | |
var _update2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(obj, metadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
return _context3.abrupt("return", this.mutate(function (remote) { | |
return Object.assign(remote, obj); | |
}, metadataUpdates)); | |
case 1: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function update(_x5, _x6) { | |
return _update2.apply(this, arguments); | |
} | |
return update; | |
}() | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ttl) { | |
var response; | |
return _regeneratorRuntime.wrap(function _callee4$(_context4) { | |
while (1) { | |
switch (_context4.prev = _context4.next) { | |
case 0: | |
sanitize_1$4.validateMandatoryTtl(ttl); | |
_context4.next = 3; | |
return this._postUpdateToServer({ | |
ttl: ttl | |
}); | |
case 3: | |
response = _context4.sent; | |
this.descriptor.date_expires = response.date_expires; | |
case 5: | |
case "end": | |
return _context4.stop(); | |
} | |
} | |
}, _callee4, this); | |
})); | |
function setTtl(_x7) { | |
return _setTtl.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_setUnconditionally", | |
value: function () { | |
var _setUnconditionally2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(value, ttl) { | |
var result; | |
return _regeneratorRuntime.wrap(function _callee5$(_context5) { | |
while (1) { | |
switch (_context5.prev = _context5.next) { | |
case 0: | |
_context5.next = 2; | |
return this._postUpdateToServer({ | |
data: value, | |
revision: undefined, | |
ttl: ttl | |
}); | |
case 2: | |
result = _context5.sent; | |
this._handleSuccessfulUpdateResult(result); | |
return _context5.abrupt("return", this.descriptor.data); | |
case 5: | |
case "end": | |
return _context5.stop(); | |
} | |
} | |
}, _callee5, this); | |
})); | |
function _setUnconditionally(_x8, _x9) { | |
return _setUnconditionally2.apply(this, arguments); | |
} | |
return _setUnconditionally; | |
}() | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_setWithIfMatch", | |
value: function () { | |
var _setWithIfMatch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(mutatorFunction, ttl) { | |
var data, revision, result; | |
return _regeneratorRuntime.wrap(function _callee6$(_context6) { | |
while (1) { | |
switch (_context6.prev = _context6.next) { | |
case 0: | |
data = mutatorFunction(sanitize_1$4.deepClone(this.descriptor.data)); | |
if (!data) { | |
_context6.next = 22; | |
break; | |
} | |
revision = this.revision; | |
_context6.prev = 3; | |
_context6.next = 6; | |
return this._postUpdateToServer({ | |
data: data, | |
revision: revision, | |
ttl: ttl | |
}); | |
case 6: | |
result = _context6.sent; | |
this._handleSuccessfulUpdateResult(result); | |
return _context6.abrupt("return", this.descriptor.data); | |
case 11: | |
_context6.prev = 11; | |
_context6.t0 = _context6["catch"](3); | |
if (!(_context6.t0.status === 412)) { | |
_context6.next = 19; | |
break; | |
} | |
_context6.next = 16; | |
return this._softSync(); | |
case 16: | |
return _context6.abrupt("return", this._setWithIfMatch(mutatorFunction)); | |
case 19: | |
throw _context6.t0; | |
case 20: | |
_context6.next = 23; | |
break; | |
case 22: | |
return _context6.abrupt("return", this.descriptor.data); | |
case 23: | |
case "end": | |
return _context6.stop(); | |
} | |
} | |
}, _callee6, this, [[3, 11]]); | |
})); | |
function _setWithIfMatch(_x10, _x11) { | |
return _setWithIfMatch2.apply(this, arguments); | |
} | |
return _setWithIfMatch; | |
}() | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_handleSuccessfulUpdateResult", | |
value: function _handleSuccessfulUpdateResult(result) { | |
// Ignore returned value if we already got a newer one | |
if (result.last_event_id <= this.descriptor.last_event_id) { | |
return; | |
} | |
var previousData = this.descriptor.data !== undefined ? sanitize_1$4.deepClone(this.descriptor.data) : null; | |
this.descriptor.revision = result.revision; | |
this.descriptor.data = result.data; | |
this.descriptor.last_event_id = result.last_event_id; | |
this.descriptor.date_expires = result.date_expires; | |
this.descriptor.date_updated = new Date(result.date_updated); | |
this.services.storage.update(this.type, this.sid, this.uniqueName, { | |
last_event_id: result.last_event_id, | |
revision: result.revision, | |
date_updated: result.date_updated, | |
data: result.data | |
}); | |
this.broadcastEventToListeners('updated', { | |
data: this.descriptor.data, | |
isLocal: true, | |
previousData: previousData | |
}); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_postUpdateToServer", | |
value: function () { | |
var _postUpdateToServer2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(request) { | |
var requestBody, ifMatch, response; | |
return _regeneratorRuntime.wrap(function _callee7$(_context7) { | |
while (1) { | |
switch (_context7.prev = _context7.next) { | |
case 0: | |
if (this.isDeleted) { | |
_context7.next = 17; | |
break; | |
} | |
requestBody = { | |
data: request.data | |
}; | |
if (request.ttl !== undefined) { | |
requestBody.ttl = request.ttl; | |
} | |
ifMatch = request.revision; | |
_context7.prev = 4; | |
_context7.next = 7; | |
return this.services.network.post(this.uri, requestBody, ifMatch); | |
case 7: | |
response = _context7.sent; | |
return _context7.abrupt("return", { | |
revision: response.body.revision, | |
data: request.data, | |
last_event_id: response.body.last_event_id, | |
date_updated: response.body.date_updated, | |
date_expires: response.body.date_expires | |
}); | |
case 11: | |
_context7.prev = 11; | |
_context7.t0 = _context7["catch"](4); | |
if (_context7.t0.status === 404) { | |
this.onRemoved(false); | |
} | |
throw _context7.t0; | |
case 15: | |
_context7.next = 18; | |
break; | |
case 17: | |
return _context7.abrupt("return", Promise.reject(new syncerror_1$4.SyncError('The Document has been removed', 404, 54100))); | |
case 18: | |
case "end": | |
return _context7.stop(); | |
} | |
} | |
}, _callee7, this, [[4, 11]]); | |
})); | |
function _postUpdateToServer(_x12) { | |
return _postUpdateToServer2.apply(this, arguments); | |
} | |
return _postUpdateToServer; | |
}() | |
/** | |
* Get new data from server | |
* @private | |
*/ | |
}, { | |
key: "_softSync", | |
value: function () { | |
var _softSync2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { | |
var _this4 = this; | |
return _regeneratorRuntime.wrap(function _callee8$(_context8) { | |
while (1) { | |
switch (_context8.prev = _context8.next) { | |
case 0: | |
return _context8.abrupt("return", this.services.network.get(this.uri).then(function (response) { | |
var event = { | |
type: 'document_updated', | |
id: response.body.last_event_id, | |
document_revision: response.body.revision, | |
document_data: response.body.data, | |
date_created: response.body.date_updated | |
}; | |
_this4._update(event); | |
return _this4; | |
}).catch(function (err) { | |
if (err.status === 404) { | |
_this4.onRemoved(false); | |
} else { | |
logger_1$6.default.error("Can't get updates for ".concat(_this4.sid, ":"), err); | |
} | |
})); | |
case 1: | |
case "end": | |
return _context8.stop(); | |
} | |
} | |
}, _callee8, this); | |
})); | |
function _softSync() { | |
return _softSync2.apply(this, arguments); | |
} | |
return _softSync; | |
}() | |
}, { | |
key: "onRemoved", | |
value: function onRemoved(locally) { | |
if (this.isDeleted) { | |
return; | |
} | |
var previousData = this.descriptor.data !== undefined ? sanitize_1$4.deepClone(this.descriptor.data) : null; | |
this.isDeleted = true; | |
this._unsubscribe(); | |
this.removalHandler(this.type, this.sid, this.uniqueName); | |
this.broadcastEventToListeners('removed', { | |
isLocal: locally, | |
previousData: previousData | |
}); | |
} | |
}, { | |
key: "removeDocument", | |
value: function () { | |
var _removeDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() { | |
return _regeneratorRuntime.wrap(function _callee9$(_context9) { | |
while (1) { | |
switch (_context9.prev = _context9.next) { | |
case 0: | |
if (this.isDeleted) { | |
_context9.next = 6; | |
break; | |
} | |
_context9.next = 3; | |
return this.services.network.delete(this.uri); | |
case 3: | |
this.onRemoved(true); | |
_context9.next = 7; | |
break; | |
case 6: | |
return _context9.abrupt("return", Promise.reject(new syncerror_1$4.SyncError('The Document has been removed', 404, 54100))); | |
case 7: | |
case "end": | |
return _context9.stop(); | |
} | |
} | |
}, _callee9, this); | |
})); | |
function removeDocument() { | |
return _removeDocument.apply(this, arguments); | |
} | |
return removeDocument; | |
}() | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'document'; | |
} | |
}]); | |
return SyncDocumentImpl; | |
}(entity_1$4.SyncEntity); | |
syncdocument.SyncDocumentImpl = SyncDocumentImpl; | |
/** | |
* @class | |
* @alias Document | |
* @classdesc Represents a Sync Document, the contents of which is a single JSON object. | |
* Use the {@link Client#document} method to obtain a reference to a Sync Document. | |
* Information about rate limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @property {String} sid The immutable identifier of this document, assigned by the system. | |
* @property {String} [uniqueName=null] An optional immutable identifier that may be assigned by the programmer | |
* to this document during creation. Globally unique among other Documents. | |
* @property {Date} dateUpdated Date when the Document was last updated. | |
* @property {Object} data The contents of this document. | |
* | |
* @fires Document#removed | |
* @fires Document#updated | |
*/ | |
var SyncDocument = /*#__PURE__*/function (_closeable_1$default) { | |
_inherits$1(SyncDocument, _closeable_1$default); | |
var _super2 = _createSuper$h(SyncDocument); | |
function SyncDocument(syncDocumentImpl) { | |
var _this5; | |
_classCallCheck$1(this, SyncDocument); | |
_this5 = _super2.call(this); | |
_this5.syncDocumentImpl = syncDocumentImpl; | |
_this5.syncDocumentImpl.attach(_assertThisInitialized(_this5)); | |
return _this5; | |
} // private props | |
_createClass(SyncDocument, [{ | |
key: "uri", | |
get: function get() { | |
return this.syncDocumentImpl.uri; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.syncDocumentImpl.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.syncDocumentImpl.lastEventId; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.syncDocumentImpl.dateExpires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return SyncDocumentImpl.type; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.syncDocumentImpl.sid; | |
} | |
}, { | |
key: "data", | |
get: function get() { | |
return this.syncDocumentImpl.data; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.syncDocumentImpl.dateUpdated; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.syncDocumentImpl.uniqueName; | |
} | |
/** | |
* Assign new contents to this document. The current data will be overwritten. | |
* @param {Object} data The new contents to assign. | |
* @param {Document#Metadata} [metadataUpdates] New document metadata. | |
* @returns {Promise<Object>} A promise resolving to the new data of the document. | |
* @public | |
* @example | |
* // Say, the Document data is { name: 'John Smith', age: 34 } | |
* document.set({ name: 'Barbara Oaks' }, { ttl: 86400 }) | |
* .then(function(newValue) { | |
* // Now the Document data is { name: 'Barbara Oaks' } | |
* console.log('Document set() successful, new data:', newValue); | |
* }) | |
* .catch(function(error) { | |
* console.error('Document set() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "set", | |
value: function () { | |
var _set2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(data, metadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee10$(_context10) { | |
while (1) { | |
switch (_context10.prev = _context10.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context10.abrupt("return", this.syncDocumentImpl.set(data, metadataUpdates)); | |
case 2: | |
case "end": | |
return _context10.stop(); | |
} | |
} | |
}, _callee10, this); | |
})); | |
function set(_x13, _x14) { | |
return _set2.apply(this, arguments); | |
} | |
return set; | |
}() | |
/** | |
* Schedules a modification to this document that will apply a mutation function. | |
* @param {Document~Mutator} mutator A function that outputs a new data based on the existing data. | |
* May be called multiple times, particularly if this Document is modified concurrently by remote code. | |
* If the mutation ultimately succeeds, the Document will have made the particular transition described | |
* by this function. | |
* @param {Document#Metadata} [metadataUpdates] New document metadata. | |
* @return {Promise<Object>} Resolves with the most recent Document state, whether the output of a | |
* successful mutation or a state that prompted graceful cancellation (mutator returned <code>null</code>). | |
* @public | |
* @example | |
* var mutatorFunction = function(currentValue) { | |
* currentValue.viewCount = (currentValue.viewCount || 0) + 1; | |
* return currentValue; | |
* }; | |
* document.mutate(mutatorFunction, { ttl: 86400 })) | |
* .then(function(newValue) { | |
* console.log('Document mutate() successful, new data:', newValue); | |
* }) | |
* .catch(function(error) { | |
* console.error('Document mutate() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(mutator, metadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee11$(_context11) { | |
while (1) { | |
switch (_context11.prev = _context11.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context11.abrupt("return", this.syncDocumentImpl.mutate(mutator, metadataUpdates)); | |
case 2: | |
case "end": | |
return _context11.stop(); | |
} | |
} | |
}, _callee11, this); | |
})); | |
function mutate(_x15, _x16) { | |
return _mutate2.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
/** | |
* Modify a document by appending new fields (or by overwriting existing ones) with the values from the provided Object. | |
* This is equivalent to | |
* <pre> | |
* document.mutate(function(currentValue) { | |
* return Object.assign(currentValue, obj)); | |
* }); | |
* </pre> | |
* @param {Object} obj Specifies the particular (top-level) attributes that will receive new values. | |
* @param {Document#Metadata} [metadataUpdates] New document metadata. | |
* @return {Promise<Object>} A promise resolving to the new data of the document. | |
* @public | |
* @example | |
* // Say, the Document data is { name: 'John Smith' } | |
* document.update({ age: 34 }, { ttl: 86400 }) | |
* .then(function(newValue) { | |
* // Now the Document data is { name: 'John Smith', age: 34 } | |
* console.log('Document update() successful, new data:', newValue); | |
* }) | |
* .catch(function(error) { | |
* console.error('Document update() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "update", | |
value: function () { | |
var _update3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(obj, metadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee12$(_context12) { | |
while (1) { | |
switch (_context12.prev = _context12.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context12.abrupt("return", this.syncDocumentImpl.update(obj, metadataUpdates)); | |
case 2: | |
case "end": | |
return _context12.stop(); | |
} | |
} | |
}, _callee12, this); | |
})); | |
function update(_x17, _x18) { | |
return _update3.apply(this, arguments); | |
} | |
return update; | |
}() | |
/** | |
* Update the time-to-live of the document. | |
* @param {Number} ttl Specifies the time-to-live in seconds after which the document is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* document.setTtl(3600) | |
* .then(function() { | |
* console.log('Document setTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Document setTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(ttl) { | |
return _regeneratorRuntime.wrap(function _callee13$(_context13) { | |
while (1) { | |
switch (_context13.prev = _context13.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context13.abrupt("return", this.syncDocumentImpl.setTtl(ttl)); | |
case 2: | |
case "end": | |
return _context13.stop(); | |
} | |
} | |
}, _callee13, this); | |
})); | |
function setTtl(_x19) { | |
return _setTtl2.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
/** | |
* Delete a document. | |
* @return {Promise<void>} A promise which resolves if (and only if) the document is ultimately deleted. | |
* @public | |
* @example | |
* document.removeDocument() | |
* .then(function() { | |
* console.log('Document removeDocument() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Document removeDocument() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "removeDocument", | |
value: function () { | |
var _removeDocument2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14() { | |
return _regeneratorRuntime.wrap(function _callee14$(_context14) { | |
while (1) { | |
switch (_context14.prev = _context14.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context14.abrupt("return", this.syncDocumentImpl.removeDocument()); | |
case 2: | |
case "end": | |
return _context14.stop(); | |
} | |
} | |
}, _callee14, this); | |
})); | |
function removeDocument() { | |
return _removeDocument2.apply(this, arguments); | |
} | |
return removeDocument; | |
}() | |
/** | |
* Conclude work with the document instance and remove all event listeners attached to it. | |
* Any subsequent operation on this object will be rejected with error. | |
* Other local copies of this document will continue operating and receiving events normally. | |
* @public | |
* @example | |
* document.close(); | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
_get(_getPrototypeOf$1(SyncDocument.prototype), "close", this).call(this); | |
this.syncDocumentImpl.detach(this.listenerUuid); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return SyncDocumentImpl.type; | |
} | |
}]); | |
return SyncDocument; | |
}(closeable_1$4.default); | |
syncdocument.SyncDocument = SyncDocument; | |
syncdocument.default = SyncDocument; | |
var synclist = {}; | |
var listitem = {}; | |
Object.defineProperty(listitem, "__esModule", { | |
value: true | |
}); | |
/** | |
* @class | |
* @classdesc Represents an individual element in a Sync List. | |
* @alias ListItem | |
* @property {Number} index The index, within the containing List, of this item. This index is stable; | |
* even if lower-indexed Items are removed, this index will remain as is. | |
* @property {Object} data The contents of the item. | |
* @property {Date} dateUpdated Date when the List Item was last updated. | |
*/ | |
var ListItem = /*#__PURE__*/function () { | |
/** | |
* @private | |
* @constructor | |
* @param {Object} data Item descriptor | |
* @param {Number} data.index Item identifier | |
* @param {String} data.uri Item URI | |
* @param {Object} data.data Item data | |
*/ | |
function ListItem(data) { | |
_classCallCheck$1(this, ListItem); | |
this.descriptor = data; | |
} | |
_createClass(ListItem, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.uri; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.descriptor.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.lastEventId; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.descriptor.dateUpdated; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.dateExpires; | |
} | |
}, { | |
key: "index", | |
get: function get() { | |
return this.descriptor.index; | |
} | |
}, { | |
key: "data", | |
get: function get() { | |
return this.descriptor.data; | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "update", | |
value: function update(eventId, revision, data, dateUpdated) { | |
this.descriptor.lastEventId = eventId; | |
this.descriptor.revision = revision; | |
this.descriptor.data = data; | |
this.descriptor.dateUpdated = dateUpdated; | |
return this; | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "updateDateExpires", | |
value: function updateDateExpires(dateExpires) { | |
this.descriptor.dateExpires = dateExpires; | |
} | |
}]); | |
return ListItem; | |
}(); | |
listitem.ListItem = ListItem; | |
listitem.default = ListItem; | |
var paginator = {}; | |
Object.defineProperty(paginator, "__esModule", { | |
value: true | |
}); | |
/** | |
* @class Paginator | |
* @classdesc Pagination helper class. | |
* | |
* @property {Array} items Array of elements on current page. | |
* @property {Boolean} hasNextPage Indicates the existence of next page. | |
* @property {Boolean} hasPrevPage Indicates the existence of previous page. | |
*/ | |
var Paginator = /*#__PURE__*/function () { | |
/* | |
* @constructor | |
* @param {Array} items Array of element for current page. | |
* @param {Object} params | |
* @private | |
*/ | |
function Paginator(items, source, prevToken, nextToken) { | |
_classCallCheck$1(this, Paginator); | |
this.prevToken = prevToken; | |
this.nextToken = nextToken; | |
this.items = items; | |
this.source = source; | |
} | |
_createClass(Paginator, [{ | |
key: "hasNextPage", | |
get: function get() { | |
return !!this.nextToken; | |
} | |
}, { | |
key: "hasPrevPage", | |
get: function get() { | |
return !!this.prevToken; | |
} | |
/** | |
* Request next page. | |
* Does not modify existing object. | |
* @return {Promise<Paginator>} | |
*/ | |
}, { | |
key: "nextPage", | |
value: function () { | |
var _nextPage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
if (this.hasNextPage) { | |
_context.next = 2; | |
break; | |
} | |
throw new Error('No next page'); | |
case 2: | |
return _context.abrupt("return", this.source(this.nextToken)); | |
case 3: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function nextPage() { | |
return _nextPage.apply(this, arguments); | |
} | |
return nextPage; | |
}() | |
/** | |
* Request previous page. | |
* Does not modify existing object. | |
* @return {Promise<Paginator>} | |
*/ | |
}, { | |
key: "prevPage", | |
value: function () { | |
var _prevPage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
if (this.hasPrevPage) { | |
_context2.next = 2; | |
break; | |
} | |
throw new Error('No previous page'); | |
case 2: | |
return _context2.abrupt("return", this.source(this.prevToken)); | |
case 3: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function prevPage() { | |
return _prevPage.apply(this, arguments); | |
} | |
return prevPage; | |
}() | |
}]); | |
return Paginator; | |
}(); | |
paginator.Paginator = Paginator; | |
var cache = {}; | |
var tree = {}; | |
function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(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(o, minLen); } | |
function _arrayLikeToArray$2(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; } | |
Object.defineProperty(tree, "__esModule", { | |
value: true | |
}); | |
var Node = /*#__PURE__*/function () { | |
function Node(key, value) { | |
_classCallCheck$1(this, Node); | |
this.balanceFactor = 0; | |
this.key = key; | |
this.value = value; | |
this.parent = null; | |
this.left = null; | |
this.right = null; | |
} | |
_createClass(Node, [{ | |
key: "isRoot", | |
get: function get() { | |
return this.parent === null; | |
} | |
}, { | |
key: "isLeaf", | |
get: function get() { | |
return this.left === null && this.right === null; | |
} | |
}, { | |
key: "isLeftChild", | |
get: function get() { | |
return this.parent.left === this; | |
} | |
}, { | |
key: "update", | |
value: function update(value) { | |
this.value = value; | |
} | |
}, { | |
key: "replace", | |
value: function replace(target, replacement) { | |
if (!target) { | |
return; | |
} | |
if (this.left === replacement) { | |
this.left = replacement; | |
} else if (this.right === replacement) { | |
this.right = replacement; | |
} | |
} | |
}]); | |
return Node; | |
}(); | |
/** | |
* @property length | |
*/ | |
var TreeMap = /*#__PURE__*/function () { | |
function TreeMap(less, equal) { | |
_classCallCheck$1(this, TreeMap); | |
this.isLessThan = less || function (x, y) { | |
return x < y; | |
}; | |
this.isEqual = equal || function (x, y) { | |
return x === y; | |
}; | |
this.root = null; | |
this.count = null; | |
} | |
_createClass(TreeMap, [{ | |
key: "size", | |
get: function get() { | |
return this.count; | |
} | |
}, { | |
key: "clear", | |
value: function clear() { | |
this.root = null; | |
this.count = 0; | |
} | |
}, { | |
key: "set", | |
value: function set(key, value) { | |
var node = this.getNode(key); | |
if (node) { | |
node.update(value); | |
} else { | |
this.insert(key, value); | |
} // return node; | |
} | |
}, { | |
key: "insert", | |
value: function insert(key, value) { | |
var node = new Node(key, value); | |
this.count++; | |
if (!this.root) { | |
this.root = node; // return node; | |
return; | |
} | |
var currNode = this.root; | |
for (;;) { | |
if (this.isLessThan(key, currNode.key)) { | |
if (currNode.left) { | |
currNode = currNode.left; | |
} else { | |
currNode.left = node; | |
break; | |
} | |
} else { | |
if (currNode.right) { | |
// eslint-disable-line no-lonely-if | |
currNode = currNode.right; | |
} else { | |
currNode.right = node; | |
break; | |
} | |
} | |
} | |
node.parent = currNode; | |
currNode = node; | |
while (currNode.parent) { | |
var parent = currNode.parent; | |
var prevBalanceFactor = parent.balanceFactor; | |
if (currNode.isLeftChild) { | |
parent.balanceFactor++; | |
} else { | |
parent.balanceFactor--; | |
} | |
if (Math.abs(parent.balanceFactor) < Math.abs(prevBalanceFactor)) { | |
break; | |
} | |
if (parent.balanceFactor < -1 || parent.balanceFactor > 1) { | |
this.rebalance(parent); | |
break; | |
} | |
currNode = parent; | |
} // return node; | |
} | |
}, { | |
key: "get", | |
value: function get(key) { | |
var currentNode = this.root; | |
while (currentNode) { | |
if (this.isEqual(key, currentNode.key)) { | |
return currentNode.value; | |
} | |
if (this.isLessThan(key, currentNode.key)) { | |
currentNode = currentNode.left; | |
} else { | |
currentNode = currentNode.right; | |
} | |
} | |
return null; | |
} | |
}, { | |
key: "delete", | |
value: function _delete(key) { | |
// update this algorithm and remove any | |
var node = this.getNode(key); | |
if (!node || node.key !== key) { | |
return null; | |
} | |
var parent = node.parent; | |
var left = node.left; | |
var right = node.right; | |
if (!!left !== !!right) { | |
// one child | |
var child = left || right; | |
if (!parent && !child) { | |
this.root = null; | |
} else if (parent && !child) { | |
this.root = child; | |
} else { | |
parent.replace(node, null); | |
this.rebalance(parent); | |
} | |
} else { | |
// two children | |
var maxLeft = node.left; | |
while (maxLeft.right) { | |
maxLeft = maxLeft.right; | |
} | |
if (node.left === maxLeft) { | |
if (node.isRoot) { | |
this.root = maxLeft; | |
maxLeft.parent = null; | |
} else { | |
if (node.isLeftChild) { | |
node.parent.left = maxLeft; | |
} else { | |
node.parent.right = maxLeft; | |
} | |
maxLeft.parent = node.parent; | |
} | |
maxLeft.right = node.right; | |
maxLeft.right.parent = maxLeft; | |
maxLeft.balanceFactor = node.balanceFactor; | |
node = { | |
parent: maxLeft, | |
isLeftChild: true | |
}; | |
} else { | |
var mlParent = maxLeft.parent; | |
var mlLeft = maxLeft.left; | |
mlParent.right = mlLeft; | |
if (mlLeft) { | |
mlLeft.parent = mlParent; | |
} | |
if (node.isRoot) { | |
this.root = maxLeft; | |
maxLeft.parent = null; | |
} else { | |
if (node.isLeftChild) { | |
node.parent.left = maxLeft; | |
} else { | |
node.parent.right = maxLeft; | |
} | |
maxLeft.parent = node.parent; | |
} | |
maxLeft.right = node.right; | |
maxLeft.right.parent = maxLeft; | |
maxLeft.left = node.left; | |
maxLeft.left.parent = maxLeft; | |
maxLeft.balanceFactor = node.balanceFactor; | |
node = { | |
parent: mlParent, | |
isLeftChild: false | |
}; | |
} | |
} | |
this.count--; | |
while (node.parent) { | |
var _parent = node.parent; | |
var prevBalanceFactor = _parent.balanceFactor; | |
if (node.isLeftChild) { | |
_parent.balanceFactor -= 1; | |
} else { | |
_parent.balanceFactor += 1; | |
} | |
if (Math.abs(_parent.balanceFactor) > Math.abs(prevBalanceFactor)) { | |
if (_parent.balanceFactor < -1 || _parent.balanceFactor > 1) { | |
this.rebalance(_parent); | |
if (_parent.parent.balanceFactor === 0) { | |
node = _parent.parent; | |
} else { | |
break; | |
} | |
} else { | |
break; | |
} | |
} else { | |
node = _parent; | |
} | |
} | |
return null; | |
} | |
}, { | |
key: "getNode", | |
value: function getNode(key) { | |
var currentNode = this.root; | |
while (currentNode) { | |
if (this.isEqual(key, currentNode.key)) { | |
return currentNode; | |
} | |
if (this.isLessThan(key, currentNode.key)) { | |
currentNode = currentNode.left; | |
} else { | |
currentNode = currentNode.right; | |
} | |
} | |
return null; | |
} | |
}, { | |
key: "rebalance", | |
value: function rebalance(node) { | |
if (node.balanceFactor < 0) { | |
if (node.right.balanceFactor > 0) { | |
this.rotateRight(node.right); | |
this.rotateLeft(node); | |
} else { | |
this.rotateLeft(node); | |
} | |
} else if (node.balanceFactor > 0) { | |
if (node.left.balanceFactor < 0) { | |
this.rotateLeft(node.left); | |
this.rotateRight(node); | |
} else { | |
this.rotateRight(node); | |
} | |
} | |
} | |
}, { | |
key: "rotateLeft", | |
value: function rotateLeft(pivot) { | |
var root = pivot.right; | |
pivot.right = root.left; | |
if (root.left !== null) { | |
root.left.parent = pivot; | |
} | |
root.parent = pivot.parent; | |
if (root.parent === null) { | |
this.root = root; | |
} else if (pivot.isLeftChild) { | |
root.parent.left = root; | |
} else { | |
root.parent.right = root; | |
} | |
root.left = pivot; | |
pivot.parent = root; | |
pivot.balanceFactor = pivot.balanceFactor + 1 - Math.min(root.balanceFactor, 0); | |
root.balanceFactor = root.balanceFactor + 1 - Math.max(pivot.balanceFactor, 0); | |
} | |
}, { | |
key: "rotateRight", | |
value: function rotateRight(pivot) { | |
var root = pivot.left; | |
pivot.left = root.right; | |
if (root.right !== null) { | |
root.right.parent = pivot; | |
} | |
root.parent = pivot.parent; | |
if (root.parent === null) { | |
this.root = root; | |
} else if (pivot.isLeftChild) { | |
root.parent.left = root; | |
} else { | |
root.parent.right = root; | |
} | |
root.right = pivot; | |
pivot.parent = root; | |
pivot.balanceFactor = pivot.balanceFactor - 1 - Math.min(root.balanceFactor, 0); | |
root.balanceFactor = root.balanceFactor - 1 - Math.max(pivot.balanceFactor, 0); | |
} | |
}, { | |
key: Symbol.iterator, | |
value: /*#__PURE__*/_regeneratorRuntime.mark(function value() { | |
var _iterator, _step, iter; | |
return _regeneratorRuntime.wrap(function value$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
_iterator = _createForOfIteratorHelper$2(this.getIterator()); | |
_context.prev = 1; | |
_iterator.s(); | |
case 3: | |
if ((_step = _iterator.n()).done) { | |
_context.next = 9; | |
break; | |
} | |
iter = _step.value; | |
_context.next = 7; | |
return iter; | |
case 7: | |
_context.next = 3; | |
break; | |
case 9: | |
_context.next = 14; | |
break; | |
case 11: | |
_context.prev = 11; | |
_context.t0 = _context["catch"](1); | |
_iterator.e(_context.t0); | |
case 14: | |
_context.prev = 14; | |
_iterator.f(); | |
return _context.finish(14); | |
case 17: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, value, this, [[1, 11, 14, 17]]); | |
}) | |
}, { | |
key: "getIterator", | |
value: /*#__PURE__*/_regeneratorRuntime.mark(function getIterator() { | |
var key, | |
currentNode, | |
fromleft, | |
_args2 = arguments; | |
return _regeneratorRuntime.wrap(function getIterator$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
key = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : null; | |
currentNode = this.root; | |
case 2: | |
if (!currentNode) { | |
_context2.next = 8; | |
break; | |
} | |
if (!(this.isEqual(key, currentNode.key) || key === null && !currentNode.left)) { | |
_context2.next = 5; | |
break; | |
} | |
return _context2.abrupt("break", 8); | |
case 5: | |
if (this.isLessThan(key, currentNode.key) || key === null) { | |
currentNode = currentNode.left; | |
} else { | |
currentNode = currentNode.right; | |
} | |
_context2.next = 2; | |
break; | |
case 8: | |
if (currentNode) { | |
_context2.next = 10; | |
break; | |
} | |
return _context2.abrupt("return", null); | |
case 10: | |
fromleft = true; | |
case 11: | |
if (!fromleft) { | |
_context2.next = 29; | |
break; | |
} | |
_context2.next = 14; | |
return [currentNode.key, currentNode.value]; | |
case 14: | |
fromleft = false; | |
if (!currentNode.right) { | |
_context2.next = 21; | |
break; | |
} | |
currentNode = currentNode.right; | |
while (currentNode.left) { | |
currentNode = currentNode.left; | |
} | |
fromleft = true; | |
_context2.next = 27; | |
break; | |
case 21: | |
if (!currentNode.parent) { | |
_context2.next = 26; | |
break; | |
} | |
fromleft = currentNode.parent.left === currentNode; | |
currentNode = currentNode.parent; | |
_context2.next = 27; | |
break; | |
case 26: | |
return _context2.abrupt("break", 37); | |
case 27: | |
_context2.next = 35; | |
break; | |
case 29: | |
if (!currentNode.parent) { | |
_context2.next = 34; | |
break; | |
} | |
fromleft = currentNode.parent.left === currentNode; | |
currentNode = currentNode.parent; | |
_context2.next = 35; | |
break; | |
case 34: | |
return _context2.abrupt("break", 37); | |
case 35: | |
_context2.next = 11; | |
break; | |
case 37: | |
return _context2.abrupt("return", null); | |
case 38: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, getIterator, this); | |
}) | |
}, { | |
key: "getReverseIterator", | |
value: /*#__PURE__*/_regeneratorRuntime.mark(function getReverseIterator() { | |
var key, | |
currentNode, | |
fromright, | |
_args3 = arguments; | |
return _regeneratorRuntime.wrap(function getReverseIterator$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
key = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : null; | |
currentNode = this.root; | |
case 2: | |
if (!currentNode) { | |
_context3.next = 8; | |
break; | |
} | |
if (!(this.isEqual(key, currentNode.key) || key === null && !currentNode.right)) { | |
_context3.next = 5; | |
break; | |
} | |
return _context3.abrupt("break", 8); | |
case 5: | |
if (!this.isLessThan(key, currentNode.key) || key === null) { | |
currentNode = currentNode.right; | |
} else { | |
currentNode = currentNode.left; | |
} | |
_context3.next = 2; | |
break; | |
case 8: | |
if (currentNode) { | |
_context3.next = 10; | |
break; | |
} | |
return _context3.abrupt("return", null); | |
case 10: | |
fromright = true; | |
case 11: | |
if (!fromright) { | |
_context3.next = 29; | |
break; | |
} | |
_context3.next = 14; | |
return [currentNode.key, currentNode.value]; | |
case 14: | |
fromright = false; | |
if (!currentNode.left) { | |
_context3.next = 21; | |
break; | |
} | |
currentNode = currentNode.left; | |
while (currentNode.right) { | |
currentNode = currentNode.right; | |
} | |
fromright = true; | |
_context3.next = 27; | |
break; | |
case 21: | |
if (!currentNode.parent) { | |
_context3.next = 26; | |
break; | |
} | |
fromright = currentNode.parent.right === currentNode; | |
currentNode = currentNode.parent; | |
_context3.next = 27; | |
break; | |
case 26: | |
return _context3.abrupt("break", 37); | |
case 27: | |
_context3.next = 35; | |
break; | |
case 29: | |
if (!currentNode.parent) { | |
_context3.next = 34; | |
break; | |
} | |
fromright = currentNode.parent.right === currentNode; | |
currentNode = currentNode.parent; | |
_context3.next = 35; | |
break; | |
case 34: | |
return _context3.abrupt("break", 37); | |
case 35: | |
_context3.next = 11; | |
break; | |
case 37: | |
return _context3.abrupt("return", null); | |
case 38: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, getReverseIterator, this); | |
}) | |
}]); | |
return TreeMap; | |
}(); | |
tree.TreeMap = TreeMap; | |
function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$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(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); } | |
function _arrayLikeToArray$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; } | |
Object.defineProperty(cache, "__esModule", { | |
value: true | |
}); | |
var tree_1 = tree; | |
var Entry = /*#__PURE__*/function () { | |
function Entry(value, revision) { | |
_classCallCheck$1(this, Entry); | |
this.value = value; | |
this.revision = revision || 0; | |
} | |
_createClass(Entry, [{ | |
key: "isValid", | |
get: function get() { | |
return true; | |
} | |
}]); | |
return Entry; | |
}(); | |
var Tombstone = /*#__PURE__*/function () { | |
function Tombstone(revision) { | |
_classCallCheck$1(this, Tombstone); | |
this.revision = revision; | |
} | |
_createClass(Tombstone, [{ | |
key: "isValid", | |
get: function get() { | |
return false; | |
} | |
}]); | |
return Tombstone; | |
}(); | |
var Cache = /*#__PURE__*/function () { | |
function Cache() { | |
_classCallCheck$1(this, Cache); | |
this.items = new tree_1.TreeMap(); | |
} | |
_createClass(Cache, [{ | |
key: "store", | |
value: function store(key, value, revision) { | |
var entry = this.items.get(key); | |
if (entry && entry.revision > revision) { | |
if (entry.isValid) { | |
return entry.value; | |
} | |
return null; | |
} | |
this.items.set(key, new Entry(value, revision)); | |
return value; | |
} | |
}, { | |
key: "delete", | |
value: function _delete(key, revision) { | |
var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; | |
var curr = this.items.get(key); | |
if (!curr || curr.revision < revision || curr && force === true | |
/* forced delete when revision is unknown */ | |
) { | |
this.items.set(key, new Tombstone(revision)); | |
} | |
} | |
}, { | |
key: "isKnown", | |
value: function isKnown(key, revision) { | |
var curr = this.items.get(key); | |
return curr && curr.revision >= revision; | |
} | |
}, { | |
key: "get", | |
value: function get(key) { | |
var entry = this.items.get(key); | |
if (entry && entry.isValid) { | |
return entry.value; | |
} | |
return null; | |
} | |
}, { | |
key: "has", | |
value: function has(key) { | |
var entry = this.items.get(key); | |
return entry && entry.isValid; | |
} | |
}, { | |
key: "forEach", | |
value: function forEach(callbackfn) { | |
if (this.items) { | |
var _iterator = _createForOfIteratorHelper$1(this.items), | |
_step; | |
try { | |
for (_iterator.s(); !(_step = _iterator.n()).done;) { | |
var _step$value = _slicedToArray(_step.value, 2), | |
key = _step$value[0], | |
entry = _step$value[1]; | |
if (entry.isValid) { | |
callbackfn(key, entry.value); | |
} | |
} | |
} catch (err) { | |
_iterator.e(err); | |
} finally { | |
_iterator.f(); | |
} | |
} | |
} | |
}]); | |
return Cache; | |
}(); | |
cache.Cache = Cache; | |
cache.default = Cache; | |
function _createSuper$g(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(synclist, "__esModule", { | |
value: true | |
}); | |
var sanitize_1$3 = sanitize; | |
var uri_1$3 = uri; | |
var syncerror_1$3 = syncerror; | |
var logger_1$5 = logger$1; | |
var entity_1$3 = entity; | |
var listitem_1 = listitem; | |
var paginator_1$1 = paginator; | |
var cache_1$2 = cache; | |
var mergingqueue_1$1 = mergingqueue; | |
var closeable_1$3 = closeable; | |
var SyncListImpl = /*#__PURE__*/function (_entity_1$SyncEntity) { | |
_inherits$1(SyncListImpl, _entity_1$SyncEntity); | |
var _super = _createSuper$g(SyncListImpl); | |
/** | |
* @private | |
*/ | |
function SyncListImpl(services, descriptor, removalHandler) { | |
var _this; | |
_classCallCheck$1(this, SyncListImpl); | |
_this = _super.call(this, services, removalHandler); | |
var updateRequestReducer = function updateRequestReducer(acc, input) { | |
return typeof input.ttl === 'number' ? { | |
ttl: input.ttl | |
} : acc; | |
}; | |
_this.updateMergingQueue = new mergingqueue_1$1.NamespacedMergingQueue(updateRequestReducer); | |
_this.cache = new cache_1$2.Cache(); | |
_this.descriptor = descriptor; | |
_this.descriptor.date_updated = new Date(_this.descriptor.date_updated); | |
return _this; | |
} // private props | |
_createClass(SyncListImpl, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.url; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.descriptor.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.last_event_id; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.descriptor.links; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.date_expires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return 'list'; | |
} // below properties are specific to Insights only | |
}, { | |
key: "indexName", | |
get: function get() { | |
return undefined; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return undefined; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.descriptor.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.descriptor.unique_name || null; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.descriptor.date_updated; | |
} | |
}, { | |
key: "_addOrUpdateItemOnServer", | |
value: function () { | |
var _addOrUpdateItemOnServer2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(url, data, ifMatch, ttl) { | |
var requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
requestBody = { | |
data: data | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
_context.next = 4; | |
return this.services.network.post(url, requestBody, ifMatch); | |
case 4: | |
response = _context.sent; | |
response.body.data = data; | |
response.body.date_updated = new Date(response.body.date_updated); | |
return _context.abrupt("return", response.body); | |
case 8: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function _addOrUpdateItemOnServer(_x, _x2, _x3, _x4) { | |
return _addOrUpdateItemOnServer2.apply(this, arguments); | |
} | |
return _addOrUpdateItemOnServer; | |
}() | |
}, { | |
key: "push", | |
value: function () { | |
var _push = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(value, itemMetadata) { | |
var ttl, item, index; | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
ttl = (itemMetadata || {}).ttl; | |
sanitize_1$3.validateOptionalTtl(ttl); | |
_context2.next = 4; | |
return this._addOrUpdateItemOnServer(this.links.items, value, undefined, ttl); | |
case 4: | |
item = _context2.sent; | |
index = Number(item.index); | |
this._handleItemMutated(index, item.url, item.last_event_id, item.revision, value, item.date_updated, item.date_expires, true, false); | |
return _context2.abrupt("return", this.cache.get(index)); | |
case 8: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function push(_x5, _x6) { | |
return _push.apply(this, arguments); | |
} | |
return push; | |
}() | |
}, { | |
key: "set", | |
value: function () { | |
var _set = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(index, value, itemMetadataUpdates) { | |
var _this2 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
input = itemMetadataUpdates || {}; | |
sanitize_1$3.validateOptionalTtl(input.ttl); | |
return _context3.abrupt("return", this.updateMergingQueue.squashAndAdd(index, input, function (input) { | |
return _this2._updateItemUnconditionally(index, value, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function set(_x7, _x8, _x9) { | |
return _set.apply(this, arguments); | |
} | |
return set; | |
}() | |
}, { | |
key: "_updateItemUnconditionally", | |
value: function () { | |
var _updateItemUnconditionally2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(index, data, ttl) { | |
var existingItem, itemDescriptor; | |
return _regeneratorRuntime.wrap(function _callee4$(_context4) { | |
while (1) { | |
switch (_context4.prev = _context4.next) { | |
case 0: | |
_context4.next = 2; | |
return this.get(index); | |
case 2: | |
existingItem = _context4.sent; | |
_context4.next = 5; | |
return this._addOrUpdateItemOnServer(existingItem.uri, data, undefined, ttl); | |
case 5: | |
itemDescriptor = _context4.sent; | |
this._handleItemMutated(index, itemDescriptor.url, itemDescriptor.last_event_id, itemDescriptor.revision, itemDescriptor.data, itemDescriptor.date_updated, itemDescriptor.date_expires, false, false); | |
return _context4.abrupt("return", this.cache.get(index)); | |
case 8: | |
case "end": | |
return _context4.stop(); | |
} | |
} | |
}, _callee4, this); | |
})); | |
function _updateItemUnconditionally(_x10, _x11, _x12) { | |
return _updateItemUnconditionally2.apply(this, arguments); | |
} | |
return _updateItemUnconditionally; | |
}() | |
}, { | |
key: "_updateItemWithIfMatch", | |
value: function () { | |
var _updateItemWithIfMatch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(index, mutatorFunction, ttl) { | |
var existingItem, data, ifMatch, itemDescriptor; | |
return _regeneratorRuntime.wrap(function _callee5$(_context5) { | |
while (1) { | |
switch (_context5.prev = _context5.next) { | |
case 0: | |
_context5.next = 2; | |
return this.get(index); | |
case 2: | |
existingItem = _context5.sent; | |
data = mutatorFunction(sanitize_1$3.deepClone(existingItem.data)); | |
if (!data) { | |
_context5.next = 25; | |
break; | |
} | |
ifMatch = existingItem.revision; | |
_context5.prev = 6; | |
_context5.next = 9; | |
return this._addOrUpdateItemOnServer(existingItem.uri, data, ifMatch, ttl); | |
case 9: | |
itemDescriptor = _context5.sent; | |
this._handleItemMutated(index, itemDescriptor.url, itemDescriptor.last_event_id, itemDescriptor.revision, itemDescriptor.data, itemDescriptor.date_updated, itemDescriptor.date_expires, false, false); | |
return _context5.abrupt("return", this.cache.get(index)); | |
case 14: | |
_context5.prev = 14; | |
_context5.t0 = _context5["catch"](6); | |
if (!(_context5.t0.status === 412)) { | |
_context5.next = 22; | |
break; | |
} | |
_context5.next = 19; | |
return this._getItemFromServer(index); | |
case 19: | |
return _context5.abrupt("return", this._updateItemWithIfMatch(index, mutatorFunction, ttl)); | |
case 22: | |
throw _context5.t0; | |
case 23: | |
_context5.next = 26; | |
break; | |
case 25: | |
return _context5.abrupt("return", existingItem); | |
case 26: | |
case "end": | |
return _context5.stop(); | |
} | |
} | |
}, _callee5, this, [[6, 14]]); | |
})); | |
function _updateItemWithIfMatch(_x13, _x14, _x15) { | |
return _updateItemWithIfMatch2.apply(this, arguments); | |
} | |
return _updateItemWithIfMatch; | |
}() | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(index, mutator, itemMetadataUpdates) { | |
var _this3 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee6$(_context6) { | |
while (1) { | |
switch (_context6.prev = _context6.next) { | |
case 0: | |
input = itemMetadataUpdates || {}; | |
sanitize_1$3.validateOptionalTtl(input.ttl); | |
return _context6.abrupt("return", this.updateMergingQueue.add(index, input, function (input) { | |
return _this3._updateItemWithIfMatch(index, mutator, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context6.stop(); | |
} | |
} | |
}, _callee6, this); | |
})); | |
function mutate(_x16, _x17, _x18) { | |
return _mutate.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
}, { | |
key: "update", | |
value: function () { | |
var _update2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(index, obj, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee7$(_context7) { | |
while (1) { | |
switch (_context7.prev = _context7.next) { | |
case 0: | |
return _context7.abrupt("return", this.mutate(index, function (remote) { | |
return Object.assign(remote, obj); | |
}, itemMetadataUpdates)); | |
case 1: | |
case "end": | |
return _context7.stop(); | |
} | |
} | |
}, _callee7, this); | |
})); | |
function update(_x19, _x20, _x21) { | |
return _update2.apply(this, arguments); | |
} | |
return update; | |
}() | |
}, { | |
key: "remove", | |
value: function () { | |
var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(index) { | |
var item, previousItemData, response; | |
return _regeneratorRuntime.wrap(function _callee8$(_context8) { | |
while (1) { | |
switch (_context8.prev = _context8.next) { | |
case 0: | |
_context8.next = 2; | |
return this.get(index); | |
case 2: | |
item = _context8.sent; | |
previousItemData = sanitize_1$3.deepClone(item.data); | |
_context8.next = 6; | |
return this.services.network.delete(item.uri); | |
case 6: | |
response = _context8.sent; | |
this._handleItemRemoved(index, response.body.last_event_id, previousItemData, new Date(response.body.date_updated), false); | |
case 8: | |
case "end": | |
return _context8.stop(); | |
} | |
} | |
}, _callee8, this); | |
})); | |
function remove(_x22) { | |
return _remove.apply(this, arguments); | |
} | |
return remove; | |
}() | |
}, { | |
key: "get", | |
value: function () { | |
var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(index) { | |
var cachedItem; | |
return _regeneratorRuntime.wrap(function _callee9$(_context9) { | |
while (1) { | |
switch (_context9.prev = _context9.next) { | |
case 0: | |
cachedItem = this.cache.get(index); | |
if (!cachedItem) { | |
_context9.next = 5; | |
break; | |
} | |
return _context9.abrupt("return", cachedItem); | |
case 5: | |
return _context9.abrupt("return", this._getItemFromServer(index)); | |
case 6: | |
case "end": | |
return _context9.stop(); | |
} | |
} | |
}, _callee9, this); | |
})); | |
function get(_x23) { | |
return _get.apply(this, arguments); | |
} | |
return get; | |
}() | |
}, { | |
key: "_getItemFromServer", | |
value: function () { | |
var _getItemFromServer2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(index) { | |
var result; | |
return _regeneratorRuntime.wrap(function _callee10$(_context10) { | |
while (1) { | |
switch (_context10.prev = _context10.next) { | |
case 0: | |
_context10.next = 2; | |
return this.queryItems({ | |
index: index | |
}); | |
case 2: | |
result = _context10.sent; | |
if (!(result.items.length < 1)) { | |
_context10.next = 7; | |
break; | |
} | |
throw new syncerror_1$3.SyncError("No item with index ".concat(index, " found"), 404, 54151); | |
case 7: | |
return _context10.abrupt("return", result.items[0]); | |
case 8: | |
case "end": | |
return _context10.stop(); | |
} | |
} | |
}, _callee10, this); | |
})); | |
function _getItemFromServer(_x24) { | |
return _getItemFromServer2.apply(this, arguments); | |
} | |
return _getItemFromServer; | |
}() | |
/** | |
* Query items from the List | |
* @private | |
*/ | |
}, { | |
key: "queryItems", | |
value: function () { | |
var _queryItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(arg) { | |
var _this4 = this; | |
var url, response, items, meta; | |
return _regeneratorRuntime.wrap(function _callee11$(_context11) { | |
while (1) { | |
switch (_context11.prev = _context11.next) { | |
case 0: | |
arg = arg || {}; | |
url = new uri_1$3.UriBuilder(this.links.items).queryParam('From', arg.from).queryParam('PageSize', arg.limit).queryParam('Index', arg.index).queryParam('PageToken', arg.pageToken).queryParam('Order', arg.order).build(); | |
_context11.next = 4; | |
return this.services.network.get(url); | |
case 4: | |
response = _context11.sent; | |
items = response.body.items.map(function (el) { | |
el.date_updated = new Date(el.date_updated); | |
var itemInCache = _this4.cache.get(el.index); | |
if (itemInCache) { | |
_this4._handleItemMutated(el.index, el.url, el.last_event_id, el.revision, el.data, el.date_updated, el.date_expires, false, true); | |
} else { | |
_this4.cache.store(Number(el.index), new listitem_1.ListItem({ | |
index: Number(el.index), | |
uri: el.url, | |
revision: el.revision, | |
lastEventId: el.last_event_id, | |
dateUpdated: el.date_updated, | |
dateExpires: el.date_expires, | |
data: el.data | |
}), el.last_event_id); | |
} | |
return _this4.cache.get(el.index); | |
}); | |
meta = response.body.meta; | |
return _context11.abrupt("return", new paginator_1$1.Paginator(items, function (pageToken) { | |
return _this4.queryItems({ | |
pageToken: pageToken | |
}); | |
}, meta.previous_token, meta.next_token)); | |
case 8: | |
case "end": | |
return _context11.stop(); | |
} | |
} | |
}, _callee11, this); | |
})); | |
function queryItems(_x25) { | |
return _queryItems.apply(this, arguments); | |
} | |
return queryItems; | |
}() | |
}, { | |
key: "getItems", | |
value: function () { | |
var _getItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(args) { | |
return _regeneratorRuntime.wrap(function _callee12$(_context12) { | |
while (1) { | |
switch (_context12.prev = _context12.next) { | |
case 0: | |
args = args || {}; | |
sanitize_1$3.validatePageSize(args.pageSize); | |
args.limit = args.pageSize || args.limit || 50; | |
args.order = args.order || 'asc'; | |
return _context12.abrupt("return", this.queryItems(args)); | |
case 5: | |
case "end": | |
return _context12.stop(); | |
} | |
} | |
}, _callee12, this); | |
})); | |
function getItems(_x26) { | |
return _getItems.apply(this, arguments); | |
} | |
return getItems; | |
}() | |
/** | |
* @return {Promise<Object>} Context of List | |
* @private | |
*/ | |
}, { | |
key: "getContext", | |
value: function () { | |
var _getContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13() { | |
var response; | |
return _regeneratorRuntime.wrap(function _callee13$(_context13) { | |
while (1) { | |
switch (_context13.prev = _context13.next) { | |
case 0: | |
if (this.context) { | |
_context13.next = 5; | |
break; | |
} | |
_context13.next = 3; | |
return this.services.network.get(this.links.context); | |
case 3: | |
response = _context13.sent; | |
// store fetched context if we have't received any newer update | |
this._updateContextIfRequired(response.body.data, response.body.last_event_id); | |
case 5: | |
return _context13.abrupt("return", this.context); | |
case 6: | |
case "end": | |
return _context13.stop(); | |
} | |
} | |
}, _callee13, this); | |
})); | |
function getContext() { | |
return _getContext.apply(this, arguments); | |
} | |
return getContext; | |
}() | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(ttl) { | |
var requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee14$(_context14) { | |
while (1) { | |
switch (_context14.prev = _context14.next) { | |
case 0: | |
sanitize_1$3.validateMandatoryTtl(ttl); | |
_context14.prev = 1; | |
requestBody = { | |
ttl: ttl | |
}; | |
_context14.next = 5; | |
return this.services.network.post(this.uri, requestBody); | |
case 5: | |
response = _context14.sent; | |
this.descriptor.date_expires = response.body.date_expires; | |
_context14.next = 13; | |
break; | |
case 9: | |
_context14.prev = 9; | |
_context14.t0 = _context14["catch"](1); | |
if (_context14.t0.status === 404) { | |
this.onRemoved(false); | |
} | |
throw _context14.t0; | |
case 13: | |
case "end": | |
return _context14.stop(); | |
} | |
} | |
}, _callee14, this, [[1, 9]]); | |
})); | |
function setTtl(_x27) { | |
return _setTtl.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
}, { | |
key: "setItemTtl", | |
value: function () { | |
var _setItemTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(index, ttl) { | |
var existingItem, requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee15$(_context15) { | |
while (1) { | |
switch (_context15.prev = _context15.next) { | |
case 0: | |
sanitize_1$3.validateMandatoryTtl(ttl); | |
_context15.next = 3; | |
return this.get(index); | |
case 3: | |
existingItem = _context15.sent; | |
requestBody = { | |
ttl: ttl | |
}; | |
_context15.next = 7; | |
return this.services.network.post(existingItem.uri, requestBody); | |
case 7: | |
response = _context15.sent; | |
existingItem.updateDateExpires(response.body.date_expires); | |
case 9: | |
case "end": | |
return _context15.stop(); | |
} | |
} | |
}, _callee15, this); | |
})); | |
function setItemTtl(_x28, _x29) { | |
return _setItemTtl.apply(this, arguments); | |
} | |
return setItemTtl; | |
}() | |
}, { | |
key: "removeList", | |
value: function () { | |
var _removeList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() { | |
return _regeneratorRuntime.wrap(function _callee16$(_context16) { | |
while (1) { | |
switch (_context16.prev = _context16.next) { | |
case 0: | |
_context16.next = 2; | |
return this.services.network.delete(this.uri); | |
case 2: | |
this.onRemoved(true); | |
case 3: | |
case "end": | |
return _context16.stop(); | |
} | |
} | |
}, _callee16, this); | |
})); | |
function removeList() { | |
return _removeList.apply(this, arguments); | |
} | |
return removeList; | |
}() | |
}, { | |
key: "onRemoved", | |
value: function onRemoved(locally) { | |
this._unsubscribe(); | |
this.removalHandler(this.type, this.sid, this.uniqueName); | |
this.broadcastEventToListeners('removed', { | |
isLocal: locally | |
}); | |
} | |
}, { | |
key: "shouldIgnoreEvent", | |
value: function shouldIgnoreEvent(key, eventId) { | |
return this.cache.isKnown(key, eventId); | |
} | |
/** | |
* Handle update, which came from the server. | |
* @private | |
*/ | |
}, { | |
key: "_update", | |
value: function _update(update, isStrictlyOrdered) { | |
var itemIndex = Number(update.item_index); | |
update.date_created = new Date(update.date_created); | |
switch (update.type) { | |
case 'list_item_added': | |
case 'list_item_updated': | |
{ | |
this._handleItemMutated(itemIndex, update.item_url, update.id, update.item_revision, update.item_data, update.date_created, undefined, // orchestration does not include date_expires | |
update.type === 'list_item_added', true); | |
} | |
break; | |
case 'list_item_removed': | |
{ | |
this._handleItemRemoved(itemIndex, update.id, update.item_data, update.date_created, true); | |
} | |
break; | |
case 'list_context_updated': | |
{ | |
this._handleContextUpdate(update.context_data, update.id, update.date_created); | |
} | |
break; | |
case 'list_removed': | |
{ | |
this.onRemoved(false); | |
} | |
break; | |
} | |
if (isStrictlyOrdered) { | |
this._advanceLastEventId(update.id, update.list_revision); | |
} | |
} | |
}, { | |
key: "_advanceLastEventId", | |
value: function _advanceLastEventId(eventId, revision) { | |
if (this.lastEventId < eventId) { | |
this.descriptor.last_event_id = eventId; | |
if (revision) { | |
this.descriptor.revision = revision; | |
} | |
} | |
} | |
}, { | |
key: "_updateRootDateUpdated", | |
value: function _updateRootDateUpdated(dateUpdated) { | |
if (!this.descriptor.date_updated || dateUpdated.getTime() > this.descriptor.date_updated.getTime()) { | |
this.descriptor.date_updated = dateUpdated; | |
this.services.storage.update(this.type, this.sid, this.uniqueName, { | |
date_updated: dateUpdated | |
}); | |
} | |
} | |
}, { | |
key: "_handleItemMutated", | |
value: function _handleItemMutated(index, uri, lastEventId, revision, data, dateUpdated, dateExpires, added, remote) { | |
if (this.shouldIgnoreEvent(index, lastEventId)) { | |
logger_1$5.default.trace('Item ', index, ' update skipped, current:', this.lastEventId, ', remote:', lastEventId); | |
return; | |
} | |
this._updateRootDateUpdated(dateUpdated); | |
var item = this.cache.get(index); | |
if (!item) { | |
var newItem = new listitem_1.ListItem({ | |
index: index, | |
uri: uri, | |
lastEventId: lastEventId, | |
revision: revision, | |
data: data, | |
dateUpdated: dateUpdated, | |
dateExpires: dateExpires | |
}); | |
this.cache.store(index, newItem, lastEventId); | |
this.emitItemMutationEvent(newItem, remote, added); | |
return; | |
} | |
var previousItemData = sanitize_1$3.deepClone(item.data); | |
item.update(lastEventId, revision, data, dateUpdated); | |
this.cache.store(index, item, lastEventId); | |
if (dateExpires !== undefined) { | |
item.updateDateExpires(dateExpires); | |
} | |
this.emitItemMutationEvent(item, remote, false, previousItemData); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "emitItemMutationEvent", | |
value: function emitItemMutationEvent(item, remote, added) { | |
var previousItemData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; | |
var eventName = added ? 'itemAdded' : 'itemUpdated'; | |
var args = { | |
item: item, | |
isLocal: !remote | |
}; | |
if (!added) { | |
args.previousItemData = previousItemData; | |
} | |
this.broadcastEventToListeners(eventName, args); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_handleItemRemoved", | |
value: function _handleItemRemoved(index, eventId, oldData, dateUpdated, remote) { | |
this._updateRootDateUpdated(dateUpdated); | |
this.cache.delete(index, eventId); | |
this.broadcastEventToListeners('itemRemoved', { | |
index: index, | |
isLocal: !remote, | |
previousItemData: oldData | |
}); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_handleContextUpdate", | |
value: function _handleContextUpdate(data, eventId, dateUpdated) { | |
this._updateRootDateUpdated(dateUpdated); | |
if (this._updateContextIfRequired(data, eventId)) { | |
this.broadcastEventToListeners('contextUpdated', { | |
context: data, | |
isLocal: false | |
}); | |
} | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_updateContextIfRequired", | |
value: function _updateContextIfRequired(data, eventId) { | |
if (!this.contextEventId || eventId > this.contextEventId) { | |
this.context = data; | |
this.contextEventId = eventId; | |
return true; | |
} else { | |
logger_1$5.default.trace('Context update skipped, current:', this.lastEventId, ', remote:', eventId); | |
return false; | |
} | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'list'; | |
} | |
}]); | |
return SyncListImpl; | |
}(entity_1$3.SyncEntity); | |
synclist.SyncListImpl = SyncListImpl; | |
/** | |
* @class | |
* @alias List | |
* @classdesc Represents a Sync List, which stores an ordered list of values. | |
* Use the {@link Client#list} method to obtain a reference to a Sync List. | |
* Information about rate limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @property {String} sid - List unique id, immutable identifier assigned by the system. | |
* @property {String} [uniqueName=null] - List unique name, immutable identifier that can be assigned to list during creation. | |
* @property {Date} dateUpdated Date when the List was last updated, given in UTC ISO 8601 format (e.g., '2018-04-26T15:23:19.732Z') | |
* | |
* @fires List#removed | |
* @fires List#itemAdded | |
* @fires List#itemRemoved | |
* @fires List#itemUpdated | |
*/ | |
var SyncList = /*#__PURE__*/function (_closeable_1$default) { | |
_inherits$1(SyncList, _closeable_1$default); | |
var _super2 = _createSuper$g(SyncList); | |
function SyncList(syncListImpl) { | |
var _this5; | |
_classCallCheck$1(this, SyncList); | |
_this5 = _super2.call(this); | |
_this5.syncListImpl = syncListImpl; | |
_this5.syncListImpl.attach(_assertThisInitialized(_this5)); | |
return _this5; | |
} // private props | |
_createClass(SyncList, [{ | |
key: "uri", | |
get: function get() { | |
return this.syncListImpl.uri; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.syncListImpl.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.syncListImpl.lastEventId; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.syncListImpl.links; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.syncListImpl.dateExpires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return SyncListImpl.type; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.syncListImpl.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.syncListImpl.uniqueName; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.syncListImpl.dateUpdated; | |
} | |
/** | |
* Add a new item to the list. | |
* @param {Object} data Data to be added. | |
* @param {List#ItemMetadata} [itemMetadata] Item metadata. | |
* @returns {Promise<ListItem>} A newly added item. | |
* @public | |
* @example | |
* list.push({ name: 'John Smith' }, { ttl: 86400 }) | |
* .then(function(item) { | |
* console.log('List Item push() successful, item index: ' + item.index + ', data: ', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item push() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "push", | |
value: function () { | |
var _push2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(data, itemMetadata) { | |
return _regeneratorRuntime.wrap(function _callee17$(_context17) { | |
while (1) { | |
switch (_context17.prev = _context17.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context17.abrupt("return", this.syncListImpl.push(data, itemMetadata)); | |
case 2: | |
case "end": | |
return _context17.stop(); | |
} | |
} | |
}, _callee17, this); | |
})); | |
function push(_x30, _x31) { | |
return _push2.apply(this, arguments); | |
} | |
return push; | |
}() | |
/** | |
* Assign new data to an existing item, given its index. | |
* @param {Number} index Index of the item to be updated. | |
* @param {Object} value New data to be assigned to an item. | |
* @param {List#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<ListItem>} A promise with updated item containing latest known data. | |
* The promise will be rejected if the item does not exist. | |
* @public | |
* @example | |
* list.set(42, { name: 'John Smith' }, { ttl: 86400 }) | |
* .then(function(item) { | |
* console.log('List Item set() successful, item data:', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item set() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "set", | |
value: function () { | |
var _set2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(index, value, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee18$(_context18) { | |
while (1) { | |
switch (_context18.prev = _context18.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context18.abrupt("return", this.syncListImpl.set(index, value, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context18.stop(); | |
} | |
} | |
}, _callee18, this); | |
})); | |
function set(_x32, _x33, _x34) { | |
return _set2.apply(this, arguments); | |
} | |
return set; | |
}() | |
/** | |
* Modify an existing item by applying a mutation function to it. | |
* @param {Number} index Index of an item to be changed. | |
* @param {List~Mutator} mutator A function that outputs a new data based on the existing data. | |
* @param {List#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<ListItem>} Resolves with the most recent item state, the output of a successful | |
* mutation or a state that prompted graceful cancellation (mutator returned <code>null</code>). This promise | |
* will be rejected if the indicated item does not already exist. | |
* @public | |
* @example | |
* var mutatorFunction = function(currentValue) { | |
* currentValue.viewCount = (currentValue.viewCount || 0) + 1; | |
* return currentValue; | |
* }; | |
* list.mutate(42, mutatorFunction, { ttl: 86400 }) | |
* .then(function(item) { | |
* console.log('List Item mutate() successful, new data:', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item mutate() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(index, mutator, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee19$(_context19) { | |
while (1) { | |
switch (_context19.prev = _context19.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context19.abrupt("return", this.syncListImpl.mutate(index, mutator, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context19.stop(); | |
} | |
} | |
}, _callee19, this); | |
})); | |
function mutate(_x35, _x36, _x37) { | |
return _mutate2.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
/** | |
* Modify an existing item by appending new fields (or overwriting existing ones) with the values from Object. | |
* This is equivalent to | |
* <pre> | |
* list.mutate(42, function(currentValue) { | |
* return Object.assign(currentValue, obj)); | |
* }); | |
* </pre> | |
* @param {Number} index Index of an item to be changed. | |
* @param {Object} obj Set of fields to update. | |
* @param {List#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<ListItem>} A promise with a modified item containing latest known data. | |
* The promise will be rejected if an item was not found. | |
* @public | |
* @example | |
* // Say, the List Item (index: 42) data is { name: 'John Smith' } | |
* list.update(42, { age: 34 }, { ttl: 86400 }) | |
* .then(function(item) { | |
* // Now the List Item data is { name: 'John Smith', age: 34 } | |
* console.log('List Item update() successful, new data:', item.data); | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item update() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "update", | |
value: function () { | |
var _update3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee20(index, obj, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee20$(_context20) { | |
while (1) { | |
switch (_context20.prev = _context20.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context20.abrupt("return", this.syncListImpl.update(index, obj, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context20.stop(); | |
} | |
} | |
}, _callee20, this); | |
})); | |
function update(_x38, _x39, _x40) { | |
return _update3.apply(this, arguments); | |
} | |
return update; | |
}() | |
/** | |
* Delete an item, given its index. | |
* @param {Number} index Index of an item to be removed. | |
* @returns {Promise<void>} A promise to remove an item. | |
* A promise will be rejected if an item was not found. | |
* @public | |
* @example | |
* list.remove(42) | |
* .then(function() { | |
* console.log('List Item remove() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item remove() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "remove", | |
value: function () { | |
var _remove2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee21(index) { | |
return _regeneratorRuntime.wrap(function _callee21$(_context21) { | |
while (1) { | |
switch (_context21.prev = _context21.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context21.abrupt("return", this.syncListImpl.remove(index)); | |
case 2: | |
case "end": | |
return _context21.stop(); | |
} | |
} | |
}, _callee21, this); | |
})); | |
function remove(_x41) { | |
return _remove2.apply(this, arguments); | |
} | |
return remove; | |
}() | |
/** | |
* Retrieve an item by List index. | |
* @param {Number} index Item index in a List. | |
* @returns {Promise<ListItem>} A promise with an item containing latest known data. | |
* A promise will be rejected if an item was not found. | |
* @public | |
* @example | |
* list.get(42) | |
* .then(function(item) { | |
* console.log('List Item get() successful, item data:', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('List Item get() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "get", | |
value: function () { | |
var _get3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee22(index) { | |
return _regeneratorRuntime.wrap(function _callee22$(_context22) { | |
while (1) { | |
switch (_context22.prev = _context22.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context22.abrupt("return", this.syncListImpl.get(index)); | |
case 2: | |
case "end": | |
return _context22.stop(); | |
} | |
} | |
}, _callee22, this); | |
})); | |
function get(_x42) { | |
return _get3.apply(this, arguments); | |
} | |
return get; | |
}() | |
/** | |
* Retrieve a List context | |
* @returns {Promise<Object>} A promise with a List's context | |
* @ignore | |
*/ | |
}, { | |
key: "getContext", | |
value: function () { | |
var _getContext2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() { | |
return _regeneratorRuntime.wrap(function _callee23$(_context23) { | |
while (1) { | |
switch (_context23.prev = _context23.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context23.abrupt("return", this.syncListImpl.getContext()); | |
case 2: | |
case "end": | |
return _context23.stop(); | |
} | |
} | |
}, _callee23, this); | |
})); | |
function getContext() { | |
return _getContext2.apply(this, arguments); | |
} | |
return getContext; | |
}() | |
/** | |
* Query a list of items from collection. | |
* Information about the query limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @param {Object} [queryOptions] Arguments for query | |
* @param {Number} [queryOptions.from] Item index, which should be used as the offset. | |
* If undefined, starts from the beginning or end depending on queryOptions.order. | |
* @param {Number} [queryOptions.pageSize=50] Results page size. | |
* @param {'asc'|'desc'} [queryOptions.order='asc'] Numeric order of results. | |
* @returns {Promise<Paginator<ListItem>>} | |
* @public | |
* @example | |
* var pageHandler = function(paginator) { | |
* paginator.items.forEach(function(item) { | |
* console.log('Item ' + item.index + ': ', item.data); | |
* }); | |
* return paginator.hasNextPage ? paginator.nextPage().then(pageHandler) | |
* : null; | |
* }; | |
* list.getItems({ from: 0, order: 'asc' }) | |
* .then(pageHandler) | |
* .catch(function(error) { | |
* console.error('List getItems() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "getItems", | |
value: function () { | |
var _getItems2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee24(queryOptions) { | |
return _regeneratorRuntime.wrap(function _callee24$(_context24) { | |
while (1) { | |
switch (_context24.prev = _context24.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context24.abrupt("return", this.syncListImpl.getItems(queryOptions)); | |
case 2: | |
case "end": | |
return _context24.stop(); | |
} | |
} | |
}, _callee24, this); | |
})); | |
function getItems(_x43) { | |
return _getItems2.apply(this, arguments); | |
} | |
return getItems; | |
}() | |
/** | |
* Update the time-to-live of the list. | |
* @param {Number} ttl Specifies the TTL in seconds after which the list is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* list.setTtl(3600) | |
* .then(function() { | |
* console.log('List setTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('List setTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee25(ttl) { | |
return _regeneratorRuntime.wrap(function _callee25$(_context25) { | |
while (1) { | |
switch (_context25.prev = _context25.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context25.abrupt("return", this.syncListImpl.setTtl(ttl)); | |
case 2: | |
case "end": | |
return _context25.stop(); | |
} | |
} | |
}, _callee25, this); | |
})); | |
function setTtl(_x44) { | |
return _setTtl2.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
/** | |
* Update the time-to-live of a list item. | |
* @param {Number} index Item index. | |
* @param {Number} ttl Specifies the TTL in seconds after which the list item is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* list.setItemTtl(42, 86400) | |
* .then(function() { | |
* console.log('List setItemTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('List setItemTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setItemTtl", | |
value: function () { | |
var _setItemTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee26(index, ttl) { | |
return _regeneratorRuntime.wrap(function _callee26$(_context26) { | |
while (1) { | |
switch (_context26.prev = _context26.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context26.abrupt("return", this.syncListImpl.setItemTtl(index, ttl)); | |
case 2: | |
case "end": | |
return _context26.stop(); | |
} | |
} | |
}, _callee26, this); | |
})); | |
function setItemTtl(_x45, _x46) { | |
return _setItemTtl2.apply(this, arguments); | |
} | |
return setItemTtl; | |
}() | |
/** | |
* Delete this list. It will be impossible to restore it. | |
* @return {Promise<void>} A promise that resolves when the list has been deleted. | |
* @public | |
* @example | |
* list.removeList() | |
* .then(function() { | |
* console.log('List removeList() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('List removeList() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "removeList", | |
value: function () { | |
var _removeList2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee27() { | |
return _regeneratorRuntime.wrap(function _callee27$(_context27) { | |
while (1) { | |
switch (_context27.prev = _context27.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context27.abrupt("return", this.syncListImpl.removeList()); | |
case 2: | |
case "end": | |
return _context27.stop(); | |
} | |
} | |
}, _callee27, this); | |
})); | |
function removeList() { | |
return _removeList2.apply(this, arguments); | |
} | |
return removeList; | |
}() | |
/** | |
* Conclude work with the list instance and remove all event listeners attached to it. | |
* Any subsequent operation on this object will be rejected with error. | |
* Other local copies of this list will continue operating and receiving events normally. | |
* @public | |
* @example | |
* list.close(); | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
_get(_getPrototypeOf$1(SyncList.prototype), "close", this).call(this); | |
this.syncListImpl.detach(this.listenerUuid); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return SyncListImpl.type; | |
} | |
}]); | |
return SyncList; | |
}(closeable_1$3.default); | |
synclist.SyncList = SyncList; | |
synclist.default = SyncList; | |
var syncmap = {}; | |
var mapitem = {}; | |
Object.defineProperty(mapitem, "__esModule", { | |
value: true | |
}); | |
/** | |
* @class | |
* @classdesc Represents an individual element in a Sync Map.` | |
* @alias MapItem | |
* @property {String} key The identifier that maps to this item within the containing Map. | |
* @property {Object} data The contents of the item. | |
* @property {Date} dateUpdated Date when the Map Item was last updated, given in UTC ISO 8601 format (e.g., '2018-04-26T15:23:19.732Z') | |
*/ | |
var MapItem = /*#__PURE__*/function () { | |
/** | |
* @private | |
* @constructor | |
*/ | |
function MapItem(descriptor) { | |
_classCallCheck$1(this, MapItem); | |
this.descriptor = descriptor; | |
} | |
_createClass(MapItem, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.url; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.descriptor.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.last_event_id; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.date_expires; | |
} | |
}, { | |
key: "key", | |
get: function get() { | |
return this.descriptor.key; | |
} | |
}, { | |
key: "data", | |
get: function get() { | |
return this.descriptor.data; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.descriptor.date_updated; | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "update", | |
value: function update(eventId, revision, value, dateUpdated) { | |
this.descriptor.last_event_id = eventId; | |
this.descriptor.revision = revision; | |
this.descriptor.data = value; | |
this.descriptor.date_updated = dateUpdated; | |
return this; | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "updateDateExpires", | |
value: function updateDateExpires(dateExpires) { | |
this.descriptor.date_expires = dateExpires; | |
} | |
}]); | |
return MapItem; | |
}(); | |
mapitem.MapItem = MapItem; | |
function _createSuper$f(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(syncmap, "__esModule", { | |
value: true | |
}); | |
var sanitize_1$2 = sanitize; | |
var uri_1$2 = uri; | |
var syncerror_1$2 = syncerror; | |
var logger_1$4 = logger$1; | |
var entity_1$2 = entity; | |
var mapitem_1 = mapitem; | |
var paginator_1 = paginator; | |
var cache_1$1 = cache; | |
var mergingqueue_1 = mergingqueue; | |
var closeable_1$2 = closeable; | |
var SyncMapImpl = /*#__PURE__*/function (_entity_1$SyncEntity) { | |
_inherits$1(SyncMapImpl, _entity_1$SyncEntity); | |
var _super = _createSuper$f(SyncMapImpl); | |
/** | |
* @private | |
*/ | |
function SyncMapImpl(services, descriptor, removalHandler) { | |
var _this; | |
_classCallCheck$1(this, SyncMapImpl); | |
_this = _super.call(this, services, removalHandler); | |
var updateRequestReducer = function updateRequestReducer(acc, input) { | |
return typeof input.ttl === 'number' ? { | |
ttl: input.ttl | |
} : acc; | |
}; | |
_this.updateMergingQueue = new mergingqueue_1.NamespacedMergingQueue(updateRequestReducer); | |
_this.cache = new cache_1$1.Cache(); | |
_this.descriptor = descriptor; | |
_this.descriptor.date_updated = new Date(_this.descriptor.date_updated); | |
if (descriptor.items) { | |
descriptor.items.forEach(function (itemDescriptor) { | |
itemDescriptor.date_updated = new Date(itemDescriptor.date_updated); | |
_this.cache.store(itemDescriptor.key, new mapitem_1.MapItem(itemDescriptor), itemDescriptor.last_event_id); | |
}); | |
} | |
return _this; | |
} // private props | |
_createClass(SyncMapImpl, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.url; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.descriptor.links; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.descriptor.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.last_event_id; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.date_expires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return 'map'; | |
} // below properties are specific to Insights only | |
}, { | |
key: "indexName", | |
get: function get() { | |
return undefined; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return undefined; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.descriptor.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.descriptor.unique_name || null; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.descriptor.date_updated; | |
} | |
}, { | |
key: "set", | |
value: function () { | |
var _set = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(key, value, itemMetadataUpdates) { | |
var _this2 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
input = itemMetadataUpdates || {}; | |
sanitize_1$2.validateOptionalTtl(input.ttl); | |
return _context.abrupt("return", this.updateMergingQueue.squashAndAdd(key, input, function (input) { | |
return _this2._putItemUnconditionally(key, value, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function set(_x, _x2, _x3) { | |
return _set.apply(this, arguments); | |
} | |
return set; | |
}() | |
}, { | |
key: "get", | |
value: function () { | |
var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(key) { | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
if (!(key === null || key === undefined)) { | |
_context2.next = 2; | |
break; | |
} | |
throw new syncerror_1$2.SyncError('Item key may not be empty', 400, 54209); | |
case 2: | |
if (!this.cache.has(key)) { | |
_context2.next = 6; | |
break; | |
} | |
return _context2.abrupt("return", this.cache.get(key)); | |
case 6: | |
return _context2.abrupt("return", this._getItemFromServer(key)); | |
case 7: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function get(_x4) { | |
return _get.apply(this, arguments); | |
} | |
return get; | |
}() | |
}, { | |
key: "_getItemFromServer", | |
value: function () { | |
var _getItemFromServer2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(key) { | |
var result; | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
_context3.next = 2; | |
return this.queryItems({ | |
key: key | |
}); | |
case 2: | |
result = _context3.sent; | |
if (!(result.items.length < 1)) { | |
_context3.next = 7; | |
break; | |
} | |
throw new syncerror_1$2.SyncError("The specified Map Item does not exist", 404, 54201); | |
case 7: | |
return _context3.abrupt("return", result.items[0]); | |
case 8: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function _getItemFromServer(_x5) { | |
return _getItemFromServer2.apply(this, arguments); | |
} | |
return _getItemFromServer; | |
}() | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(key, mutator, itemMetadataUpdates) { | |
var _this3 = this; | |
var input; | |
return _regeneratorRuntime.wrap(function _callee4$(_context4) { | |
while (1) { | |
switch (_context4.prev = _context4.next) { | |
case 0: | |
input = itemMetadataUpdates || {}; | |
sanitize_1$2.validateOptionalTtl(input.ttl); | |
return _context4.abrupt("return", this.updateMergingQueue.add(key, input, function (input) { | |
return _this3._putItemWithIfMatch(key, mutator, input.ttl); | |
})); | |
case 3: | |
case "end": | |
return _context4.stop(); | |
} | |
} | |
}, _callee4, this); | |
})); | |
function mutate(_x6, _x7, _x8) { | |
return _mutate.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
}, { | |
key: "update", | |
value: function () { | |
var _update2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(key, obj, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee5$(_context5) { | |
while (1) { | |
switch (_context5.prev = _context5.next) { | |
case 0: | |
return _context5.abrupt("return", this.mutate(key, function (remote) { | |
return Object.assign(remote, obj); | |
}, itemMetadataUpdates)); | |
case 1: | |
case "end": | |
return _context5.stop(); | |
} | |
} | |
}, _callee5, this); | |
})); | |
function update(_x9, _x10, _x11) { | |
return _update2.apply(this, arguments); | |
} | |
return update; | |
}() | |
}, { | |
key: "_putItemUnconditionally", | |
value: function () { | |
var _putItemUnconditionally2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(key, data, ttl) { | |
var result, item; | |
return _regeneratorRuntime.wrap(function _callee6$(_context6) { | |
while (1) { | |
switch (_context6.prev = _context6.next) { | |
case 0: | |
_context6.next = 2; | |
return this._putItemToServer(key, data, undefined, ttl); | |
case 2: | |
result = _context6.sent; | |
item = result.item; | |
this._handleItemMutated(item.key, item.url, item.last_event_id, item.revision, item.data, item.date_updated, item.date_expires, result.added, false); | |
return _context6.abrupt("return", this.cache.get(item.key)); | |
case 6: | |
case "end": | |
return _context6.stop(); | |
} | |
} | |
}, _callee6, this); | |
})); | |
function _putItemUnconditionally(_x12, _x13, _x14) { | |
return _putItemUnconditionally2.apply(this, arguments); | |
} | |
return _putItemUnconditionally; | |
}() | |
}, { | |
key: "_putItemWithIfMatch", | |
value: function () { | |
var _putItemWithIfMatch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(key, mutatorFunction, ttl) { | |
var currentItem, data, ifMatch, result, item; | |
return _regeneratorRuntime.wrap(function _callee7$(_context7) { | |
while (1) { | |
switch (_context7.prev = _context7.next) { | |
case 0: | |
_context7.next = 2; | |
return this.get(key).catch(function (error) { | |
if (error.status === 404) { | |
// PUT /Items/myKey with `If-Match: -1` acts as "put if not exists" | |
return new mapitem_1.MapItem({ | |
key: key, | |
data: {}, | |
last_event_id: -1, | |
revision: '-1', | |
url: null, | |
date_updated: null, | |
date_expires: null | |
}); | |
} else { | |
throw error; | |
} | |
}); | |
case 2: | |
currentItem = _context7.sent; | |
data = mutatorFunction(sanitize_1$2.deepClone(currentItem.data)); | |
if (!data) { | |
_context7.next = 26; | |
break; | |
} | |
ifMatch = currentItem.revision; | |
_context7.prev = 6; | |
_context7.next = 9; | |
return this._putItemToServer(key, data, ifMatch, ttl); | |
case 9: | |
result = _context7.sent; | |
item = result.item; | |
this._handleItemMutated(item.key, item.url, item.last_event_id, item.revision, item.data, item.date_updated, item.date_expires, result.added, false); | |
return _context7.abrupt("return", this.cache.get(item.key)); | |
case 15: | |
_context7.prev = 15; | |
_context7.t0 = _context7["catch"](6); | |
if (!(_context7.t0.status === 412)) { | |
_context7.next = 23; | |
break; | |
} | |
_context7.next = 20; | |
return this._getItemFromServer(key); | |
case 20: | |
return _context7.abrupt("return", this._putItemWithIfMatch(key, mutatorFunction, ttl)); | |
case 23: | |
throw _context7.t0; | |
case 24: | |
_context7.next = 27; | |
break; | |
case 26: | |
return _context7.abrupt("return", currentItem); | |
case 27: | |
case "end": | |
return _context7.stop(); | |
} | |
} | |
}, _callee7, this, [[6, 15]]); | |
})); | |
function _putItemWithIfMatch(_x15, _x16, _x17) { | |
return _putItemWithIfMatch2.apply(this, arguments); | |
} | |
return _putItemWithIfMatch; | |
}() | |
}, { | |
key: "_putItemToServer", | |
value: function () { | |
var _putItemToServer2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(key, data, ifMatch, ttl) { | |
var url, requestBody, response, mapItemDescriptor, added; | |
return _regeneratorRuntime.wrap(function _callee8$(_context8) { | |
while (1) { | |
switch (_context8.prev = _context8.next) { | |
case 0: | |
url = new uri_1$2.UriBuilder(this.links.items).pathSegment(key).build(); | |
requestBody = { | |
data: data | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
_context8.prev = 3; | |
_context8.next = 6; | |
return this.services.network.put(url, requestBody, ifMatch); | |
case 6: | |
response = _context8.sent; | |
mapItemDescriptor = response.body; | |
mapItemDescriptor.data = data; // The server does not return the data in the response | |
mapItemDescriptor.date_updated = new Date(mapItemDescriptor.date_updated); | |
added = response.status.code === 201; | |
return _context8.abrupt("return", { | |
added: added, | |
item: mapItemDescriptor | |
}); | |
case 14: | |
_context8.prev = 14; | |
_context8.t0 = _context8["catch"](3); | |
if (_context8.t0.status === 404) { | |
this.onRemoved(false); | |
} | |
throw _context8.t0; | |
case 18: | |
case "end": | |
return _context8.stop(); | |
} | |
} | |
}, _callee8, this, [[3, 14]]); | |
})); | |
function _putItemToServer(_x18, _x19, _x20, _x21) { | |
return _putItemToServer2.apply(this, arguments); | |
} | |
return _putItemToServer; | |
}() | |
}, { | |
key: "remove", | |
value: function () { | |
var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(key) { | |
var item, previousItemData, response; | |
return _regeneratorRuntime.wrap(function _callee9$(_context9) { | |
while (1) { | |
switch (_context9.prev = _context9.next) { | |
case 0: | |
_context9.next = 2; | |
return this.get(key); | |
case 2: | |
item = _context9.sent; | |
previousItemData = sanitize_1$2.deepClone(item.data); | |
_context9.next = 6; | |
return this.services.network.delete(item.uri); | |
case 6: | |
response = _context9.sent; | |
this._handleItemRemoved(key, response.body.last_event_id, previousItemData, new Date(response.body.date_updated), false); | |
case 8: | |
case "end": | |
return _context9.stop(); | |
} | |
} | |
}, _callee9, this); | |
})); | |
function remove(_x22) { | |
return _remove.apply(this, arguments); | |
} | |
return remove; | |
}() | |
/** | |
* @private | |
*/ | |
}, { | |
key: "queryItems", | |
value: function () { | |
var _queryItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(args) { | |
var _this4 = this; | |
var uri, response, items, meta; | |
return _regeneratorRuntime.wrap(function _callee10$(_context10) { | |
while (1) { | |
switch (_context10.prev = _context10.next) { | |
case 0: | |
args = args || {}; | |
uri = new uri_1$2.UriBuilder(this.links.items).queryParam('From', args.from).queryParam('PageSize', args.limit).queryParam('Key', args.key).queryParam('PageToken', args.pageToken).queryParam('Order', args.order).build(); | |
_context10.next = 4; | |
return this.services.network.get(uri); | |
case 4: | |
response = _context10.sent; | |
items = response.body.items.map(function (el) { | |
el.date_updated = new Date(el.date_updated); | |
var itemInCache = _this4.cache.get(el.key); | |
if (itemInCache) { | |
_this4._handleItemMutated(el.key, el.url, el.last_event_id, el.revision, el.data, el.date_updated, el.date_expires, false, true); | |
} else { | |
_this4.cache.store(el.key, new mapitem_1.MapItem(el), el.last_event_id); | |
} | |
return _this4.cache.get(el.key); | |
}); | |
meta = response.body.meta; | |
return _context10.abrupt("return", new paginator_1.Paginator(items, function (pageToken) { | |
return _this4.queryItems({ | |
pageToken: pageToken | |
}); | |
}, meta.previous_token, meta.next_token)); | |
case 8: | |
case "end": | |
return _context10.stop(); | |
} | |
} | |
}, _callee10, this); | |
})); | |
function queryItems(_x23) { | |
return _queryItems.apply(this, arguments); | |
} | |
return queryItems; | |
}() | |
}, { | |
key: "getItems", | |
value: function () { | |
var _getItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(args) { | |
return _regeneratorRuntime.wrap(function _callee11$(_context11) { | |
while (1) { | |
switch (_context11.prev = _context11.next) { | |
case 0: | |
args = args || {}; | |
sanitize_1$2.validatePageSize(args.pageSize); | |
args.limit = args.pageSize || args.limit || 50; | |
args.order = args.order || 'asc'; | |
return _context11.abrupt("return", this.queryItems(args)); | |
case 5: | |
case "end": | |
return _context11.stop(); | |
} | |
} | |
}, _callee11, this); | |
})); | |
function getItems(_x24) { | |
return _getItems.apply(this, arguments); | |
} | |
return getItems; | |
}() | |
}, { | |
key: "shouldIgnoreEvent", | |
value: function shouldIgnoreEvent(key, eventId) { | |
return this.cache.isKnown(key, eventId); | |
} | |
/** | |
* Handle update from the server | |
* @private | |
*/ | |
}, { | |
key: "_update", | |
value: function _update(update, isStrictlyOrdered) { | |
update.date_created = new Date(update.date_created); | |
switch (update.type) { | |
case 'map_item_added': | |
case 'map_item_updated': | |
{ | |
this._handleItemMutated(update.item_key, update.item_url, update.id, update.item_revision, update.item_data, update.date_created, undefined, // orchestration events do not include date_expires | |
update.type === 'map_item_added', true); | |
} | |
break; | |
case 'map_item_removed': | |
{ | |
this._handleItemRemoved(update.item_key, update.id, update.item_data, update.date_created, true); | |
} | |
break; | |
case 'map_removed': | |
{ | |
this.onRemoved(false); | |
} | |
break; | |
} | |
if (isStrictlyOrdered) { | |
this._advanceLastEventId(update.id, update.map_revision); | |
} | |
} | |
}, { | |
key: "_advanceLastEventId", | |
value: function _advanceLastEventId(eventId, revision) { | |
if (this.lastEventId < eventId) { | |
this.descriptor.last_event_id = eventId; | |
if (revision) { | |
this.descriptor.revision = revision; | |
} | |
} | |
} | |
}, { | |
key: "_updateRootDateUpdated", | |
value: function _updateRootDateUpdated(dateUpdated) { | |
if (!this.descriptor.date_updated || dateUpdated.getTime() > this.descriptor.date_updated.getTime()) { | |
this.descriptor.date_updated = dateUpdated; | |
this.services.storage.update(this.type, this.sid, this.uniqueName, { | |
date_updated: dateUpdated | |
}); | |
} | |
} | |
}, { | |
key: "_handleItemMutated", | |
value: function _handleItemMutated(key, url, lastEventId, revision, data, dateUpdated, dateExpires, added, remote) { | |
if (this.shouldIgnoreEvent(key, lastEventId)) { | |
logger_1$4.default.trace('Item ', key, ' update skipped, current:', this.lastEventId, ', remote:', lastEventId); | |
return; | |
} | |
this._updateRootDateUpdated(dateUpdated); | |
var item = this.cache.get(key); | |
if (!item) { | |
var newItem = new mapitem_1.MapItem({ | |
key: key, | |
url: url, | |
last_event_id: lastEventId, | |
revision: revision, | |
data: data, | |
date_updated: dateUpdated, | |
date_expires: dateExpires | |
}); | |
this.cache.store(key, newItem, lastEventId); | |
this.emitItemMutationEvent(newItem, remote, added); | |
return; | |
} | |
var previousItemData = sanitize_1$2.deepClone(item.data); | |
item.update(lastEventId, revision, data, dateUpdated); | |
this.cache.store(key, item, lastEventId); | |
if (dateExpires !== undefined) { | |
item.updateDateExpires(dateExpires); | |
} | |
this.emitItemMutationEvent(item, remote, false, previousItemData); | |
} | |
}, { | |
key: "emitItemMutationEvent", | |
value: function emitItemMutationEvent(item, remote, added) { | |
var previousItemData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; | |
var eventName = added ? 'itemAdded' : 'itemUpdated'; | |
var args = { | |
item: item, | |
isLocal: !remote | |
}; | |
if (!added) { | |
args.previousItemData = previousItemData; | |
} | |
this.broadcastEventToListeners(eventName, args); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_handleItemRemoved", | |
value: function _handleItemRemoved(key, eventId, oldData, dateUpdated, remote) { | |
this._updateRootDateUpdated(dateUpdated); | |
this.cache.delete(key, eventId); | |
this.broadcastEventToListeners('itemRemoved', { | |
key: key, | |
isLocal: !remote, | |
previousItemData: oldData | |
}); | |
} | |
}, { | |
key: "onRemoved", | |
value: function onRemoved(locally) { | |
this._unsubscribe(); | |
this.removalHandler(this.type, this.sid, this.uniqueName); | |
this.broadcastEventToListeners('removed', { | |
isLocal: locally | |
}); | |
} | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(ttl) { | |
var requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee12$(_context12) { | |
while (1) { | |
switch (_context12.prev = _context12.next) { | |
case 0: | |
sanitize_1$2.validateMandatoryTtl(ttl); | |
_context12.prev = 1; | |
requestBody = { | |
ttl: ttl | |
}; | |
_context12.next = 5; | |
return this.services.network.post(this.uri, requestBody); | |
case 5: | |
response = _context12.sent; | |
this.descriptor.date_expires = response.body.date_expires; | |
_context12.next = 13; | |
break; | |
case 9: | |
_context12.prev = 9; | |
_context12.t0 = _context12["catch"](1); | |
if (_context12.t0.status === 404) { | |
this.onRemoved(false); | |
} | |
throw _context12.t0; | |
case 13: | |
case "end": | |
return _context12.stop(); | |
} | |
} | |
}, _callee12, this, [[1, 9]]); | |
})); | |
function setTtl(_x25) { | |
return _setTtl.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
}, { | |
key: "setItemTtl", | |
value: function () { | |
var _setItemTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(key, ttl) { | |
var existingItem, requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee13$(_context13) { | |
while (1) { | |
switch (_context13.prev = _context13.next) { | |
case 0: | |
sanitize_1$2.validateMandatoryTtl(ttl); | |
_context13.next = 3; | |
return this.get(key); | |
case 3: | |
existingItem = _context13.sent; | |
requestBody = { | |
ttl: ttl | |
}; | |
_context13.next = 7; | |
return this.services.network.post(existingItem.uri, requestBody); | |
case 7: | |
response = _context13.sent; | |
existingItem.updateDateExpires(response.body.date_expires); | |
case 9: | |
case "end": | |
return _context13.stop(); | |
} | |
} | |
}, _callee13, this); | |
})); | |
function setItemTtl(_x26, _x27) { | |
return _setItemTtl.apply(this, arguments); | |
} | |
return setItemTtl; | |
}() | |
}, { | |
key: "removeMap", | |
value: function () { | |
var _removeMap = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14() { | |
return _regeneratorRuntime.wrap(function _callee14$(_context14) { | |
while (1) { | |
switch (_context14.prev = _context14.next) { | |
case 0: | |
_context14.next = 2; | |
return this.services.network.delete(this.uri); | |
case 2: | |
this.onRemoved(true); | |
case 3: | |
case "end": | |
return _context14.stop(); | |
} | |
} | |
}, _callee14, this); | |
})); | |
function removeMap() { | |
return _removeMap.apply(this, arguments); | |
} | |
return removeMap; | |
}() | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'map'; | |
} | |
}]); | |
return SyncMapImpl; | |
}(entity_1$2.SyncEntity); | |
syncmap.SyncMapImpl = SyncMapImpl; | |
/** | |
* @class | |
* @alias Map | |
* @classdesc Represents a Sync Map, which stores an unordered set of key:value pairs. | |
* Use the {@link Client#map} method to obtain a reference to a Sync Map. | |
* Information about rate limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @property {String} sid An immutable identifier (a SID) assigned by the system on creation. | |
* @property {String} [uniqueName=null] - An optional immutable identifier that may be assigned by the | |
* programmer to this map on creation. Unique among other Maps. | |
* @property {Date} dateUpdated Date when the Map was last updated. | |
* | |
* @fires Map#removed | |
* @fires Map#itemAdded | |
* @fires Map#itemRemoved | |
* @fires Map#itemUpdated | |
*/ | |
var SyncMap = /*#__PURE__*/function (_closeable_1$Closeabl) { | |
_inherits$1(SyncMap, _closeable_1$Closeabl); | |
var _super2 = _createSuper$f(SyncMap); | |
function SyncMap(syncMapImpl) { | |
var _this5; | |
_classCallCheck$1(this, SyncMap); | |
_this5 = _super2.call(this); | |
_this5.syncMapImpl = syncMapImpl; | |
_this5.syncMapImpl.attach(_assertThisInitialized(_this5)); | |
return _this5; | |
} // private props | |
_createClass(SyncMap, [{ | |
key: "uri", | |
get: function get() { | |
return this.syncMapImpl.uri; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.syncMapImpl.links; | |
} | |
}, { | |
key: "revision", | |
get: function get() { | |
return this.syncMapImpl.revision; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.syncMapImpl.lastEventId; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.syncMapImpl.dateExpires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return SyncMapImpl.type; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.syncMapImpl.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.syncMapImpl.uniqueName; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.syncMapImpl.dateUpdated; | |
} | |
/** | |
* Add a new item to the map with the given key:value pair. Overwrites any data that might already exist at that key. | |
* @param {String} key Unique item identifier. | |
* @param {Object} data Data to be set. | |
* @param {Map#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<MapItem>} Newly added item, or modified one if already exists, with the latest known data. | |
* @public | |
* @example | |
* map.set('myKey', { name: 'John Smith' }, { ttl: 86400 }) | |
* .then(function(item) { | |
* console.log('Map Item set() successful, item data:', item.data); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map Item set() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "set", | |
value: function () { | |
var _set2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(key, data, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee15$(_context15) { | |
while (1) { | |
switch (_context15.prev = _context15.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context15.abrupt("return", this.syncMapImpl.set(key, data, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context15.stop(); | |
} | |
} | |
}, _callee15, this); | |
})); | |
function set(_x28, _x29, _x30) { | |
return _set2.apply(this, arguments); | |
} | |
return set; | |
}() | |
/** | |
* Retrieve an item by key. | |
* @param {String} key Identifies the desired item. | |
* @returns {Promise<MapItem>} A promise that resolves when the item has been fetched. | |
* This promise will be rejected if item was not found. | |
* @public | |
* @example | |
* map.get('myKey') | |
* .then(function(item) { | |
* console.log('Map Item get() successful, item data:', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('Map Item get() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "get", | |
value: function () { | |
var _get3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(key) { | |
return _regeneratorRuntime.wrap(function _callee16$(_context16) { | |
while (1) { | |
switch (_context16.prev = _context16.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context16.abrupt("return", this.syncMapImpl.get(key)); | |
case 2: | |
case "end": | |
return _context16.stop(); | |
} | |
} | |
}, _callee16, this); | |
})); | |
function get(_x31) { | |
return _get3.apply(this, arguments); | |
} | |
return get; | |
}() | |
/** | |
* Schedules a modification to this Map Item that will apply a mutation function. | |
* If no Item with the given key exists, it will first be created, having the default data (<code>{}</code>). | |
* @param {String} key Selects the map item to be mutated. | |
* @param {Map~Mutator} mutator A function that outputs a new data based on the existing data. | |
* May be called multiple times, particularly if this Map Item is modified concurrently by remote code. | |
* If the mutation ultimately succeeds, the Map Item will have made the particular transition described | |
* by this function. | |
* @param {Map#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<MapItem>} Resolves with the most recent item state, the output of a successful | |
* mutation or a state that prompted graceful cancellation (mutator returned <code>null</code>). | |
* @public | |
* @example | |
* var mutatorFunction = function(currentData) { | |
* currentData.viewCount = (currentData.viewCount || 0) + 1; | |
* return currentData; | |
* }; | |
* map.mutate('myKey', mutatorFunction, { ttl: 86400 }) | |
* .then(function(item) { | |
* console.log('Map Item mutate() successful, new data:', item.data) | |
* }) | |
* .catch(function(error) { | |
* console.error('Map Item mutate() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "mutate", | |
value: function () { | |
var _mutate2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(key, mutator, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee17$(_context17) { | |
while (1) { | |
switch (_context17.prev = _context17.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context17.abrupt("return", this.syncMapImpl.mutate(key, mutator, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context17.stop(); | |
} | |
} | |
}, _callee17, this); | |
})); | |
function mutate(_x32, _x33, _x34) { | |
return _mutate2.apply(this, arguments); | |
} | |
return mutate; | |
}() | |
/** | |
* Modify a map item by appending new fields (or by overwriting existing ones) with the values from | |
* the provided Object. Creates a new item if no item by this key exists, copying all given fields and values | |
* into it. | |
* This is equivalent to | |
* <pre> | |
* map.mutate('myKey', function(currentData) { | |
* return Object.assign(currentData, obj)); | |
* }); | |
* </pre> | |
* @param {String} key Selects the map item to update. | |
* @param {Object} obj Specifies the particular (top-level) attributes that will receive new values. | |
* @param {Map#ItemMetadata} [itemMetadataUpdates] New item metadata. | |
* @returns {Promise<MapItem>} A promise resolving to the modified item in its new state. | |
* @public | |
* @example | |
* // Say, the Map Item (key: 'myKey') data is { name: 'John Smith' } | |
* map.update('myKey', { age: 34 }, { ttl: 86400 }) | |
* .then(function(item) { | |
* // Now the Map Item data is { name: 'John Smith', age: 34 } | |
* console.log('Map Item update() successful, new data:', item.data); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map Item update() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "update", | |
value: function () { | |
var _update3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(key, obj, itemMetadataUpdates) { | |
return _regeneratorRuntime.wrap(function _callee18$(_context18) { | |
while (1) { | |
switch (_context18.prev = _context18.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context18.abrupt("return", this.syncMapImpl.update(key, obj, itemMetadataUpdates)); | |
case 2: | |
case "end": | |
return _context18.stop(); | |
} | |
} | |
}, _callee18, this); | |
})); | |
function update(_x35, _x36, _x37) { | |
return _update3.apply(this, arguments); | |
} | |
return update; | |
}() | |
/** | |
* Delete an item, given its key. | |
* @param {String} key Selects the item to delete. | |
* @returns {Promise<void>} A promise to remove an item. | |
* The promise will be rejected if 'key' is undefined or an item was not found. | |
* @public | |
* @example | |
* map.remove('myKey') | |
* .then(function() { | |
* console.log('Map Item remove() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map Item remove() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "remove", | |
value: function () { | |
var _remove2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(key) { | |
return _regeneratorRuntime.wrap(function _callee19$(_context19) { | |
while (1) { | |
switch (_context19.prev = _context19.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context19.abrupt("return", this.syncMapImpl.remove(key)); | |
case 2: | |
case "end": | |
return _context19.stop(); | |
} | |
} | |
}, _callee19, this); | |
})); | |
function remove(_x38) { | |
return _remove2.apply(this, arguments); | |
} | |
return remove; | |
}() | |
/** | |
* Get a complete list of items from the map. | |
* Information about the query limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @param {Object} [queryOptions] Arguments for query. | |
* @param {String} [queryOptions.from] Item key, which should be used as the offset. If undefined, starts from the beginning or end depending on | |
* queryOptions.order. | |
* @param {Number} [queryOptions.pageSize=50] Result page size. | |
* @param {'asc'|'desc'} [queryOptions.order='asc'] Lexicographical order of results. | |
* @return {Promise<Paginator<MapItem>>} | |
* @public | |
* @example | |
* var pageHandler = function(paginator) { | |
* paginator.items.forEach(function(item) { | |
* console.log('Item ' + item.key + ': ', item.data); | |
* }); | |
* return paginator.hasNextPage ? paginator.nextPage().then(pageHandler) | |
* : null; | |
* }; | |
* map.getItems({ from: 'myKey', order: 'asc' }) | |
* .then(pageHandler) | |
* .catch(function(error) { | |
* console.error('Map getItems() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "getItems", | |
value: function () { | |
var _getItems2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee20(queryOptions) { | |
return _regeneratorRuntime.wrap(function _callee20$(_context20) { | |
while (1) { | |
switch (_context20.prev = _context20.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context20.abrupt("return", this.syncMapImpl.getItems(queryOptions)); | |
case 2: | |
case "end": | |
return _context20.stop(); | |
} | |
} | |
}, _callee20, this); | |
})); | |
function getItems(_x39) { | |
return _getItems2.apply(this, arguments); | |
} | |
return getItems; | |
}() | |
/** | |
* Update the time-to-live of the map. | |
* @param {Number} ttl Specifies the TTL in seconds after which the map is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* map.setTtl(3600) | |
* .then(function() { | |
* console.log('Map setTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map setTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee21(ttl) { | |
return _regeneratorRuntime.wrap(function _callee21$(_context21) { | |
while (1) { | |
switch (_context21.prev = _context21.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context21.abrupt("return", this.syncMapImpl.setTtl(ttl)); | |
case 2: | |
case "end": | |
return _context21.stop(); | |
} | |
} | |
}, _callee21, this); | |
})); | |
function setTtl(_x40) { | |
return _setTtl2.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
/** | |
* Update the time-to-live of a map item. | |
* @param {Number} key Item key. | |
* @param {Number} ttl Specifies the TTL in seconds after which the map item is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* map.setItemTtl('myKey', 86400) | |
* .then(function() { | |
* console.log('Map setItemTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map setItemTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setItemTtl", | |
value: function () { | |
var _setItemTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee22(key, ttl) { | |
return _regeneratorRuntime.wrap(function _callee22$(_context22) { | |
while (1) { | |
switch (_context22.prev = _context22.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context22.abrupt("return", this.syncMapImpl.setItemTtl(key, ttl)); | |
case 2: | |
case "end": | |
return _context22.stop(); | |
} | |
} | |
}, _callee22, this); | |
})); | |
function setItemTtl(_x41, _x42) { | |
return _setItemTtl2.apply(this, arguments); | |
} | |
return setItemTtl; | |
}() | |
/** | |
* Delete this map. It will be impossible to restore it. | |
* @return {Promise<void>} A promise that resolves when the map has been deleted. | |
* @public | |
* @example | |
* map.removeMap() | |
* .then(function() { | |
* console.log('Map removeMap() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Map removeMap() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "removeMap", | |
value: function () { | |
var _removeMap2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() { | |
return _regeneratorRuntime.wrap(function _callee23$(_context23) { | |
while (1) { | |
switch (_context23.prev = _context23.next) { | |
case 0: | |
this.ensureNotClosed(); | |
_context23.next = 3; | |
return this.syncMapImpl.removeMap(); | |
case 3: | |
case "end": | |
return _context23.stop(); | |
} | |
} | |
}, _callee23, this); | |
})); | |
function removeMap() { | |
return _removeMap2.apply(this, arguments); | |
} | |
return removeMap; | |
}() | |
/** | |
* Conclude work with the map instance and remove all event listeners attached to it. | |
* Any subsequent operation on this object will be rejected with error. | |
* Other local copies of this map will continue operating and receiving events normally. | |
* @public | |
* @example | |
* map.close(); | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
_get(_getPrototypeOf$1(SyncMap.prototype), "close", this).call(this); | |
this.syncMapImpl.detach(this.listenerUuid); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return SyncMapImpl.type; | |
} | |
}]); | |
return SyncMap; | |
}(closeable_1$2.Closeable); | |
syncmap.SyncMap = SyncMap; | |
syncmap.default = SyncMap; | |
var clientInfo = {}; | |
Object.defineProperty(clientInfo, "__esModule", { | |
value: true | |
}); | |
var platform = platform$4.exports; | |
var ClientInfo = function ClientInfo(version) { | |
_classCallCheck$1(this, ClientInfo); | |
this.sdk = 'js'; | |
this.sdkVer = version; | |
this.os = platform.os.family; | |
this.osVer = platform.os.version; | |
this.pl = platform.name; | |
this.plVer = platform.version; | |
}; | |
clientInfo.ClientInfo = ClientInfo; | |
clientInfo.default = ClientInfo; | |
var entitiesCache = {}; | |
Object.defineProperty(entitiesCache, "__esModule", { | |
value: true | |
}); | |
/** | |
* Container for entities which are known by the client | |
* It's needed for deduplication when client obtain the same object several times | |
*/ | |
var EntitiesCache = /*#__PURE__*/function () { | |
function EntitiesCache() { | |
_classCallCheck$1(this, EntitiesCache); | |
this.names = new Map(); | |
this.entities = new Map(); | |
} | |
_createClass(EntitiesCache, [{ | |
key: "store", | |
value: function store(entity) { | |
var stored = this.entities.get(entity.sid); | |
if (stored) { | |
return stored; | |
} | |
this.entities.set(entity.sid, entity); | |
if (entity.uniqueName) { | |
this.names.set(entity.type + '::' + entity.uniqueName, entity.sid); | |
} | |
return entity; | |
} | |
}, { | |
key: "getResolved", | |
value: function getResolved(id, type) { | |
var resolvedSid = this.names.get(type + '::' + id); | |
return resolvedSid ? this.entities.get(resolvedSid) : null; | |
} | |
}, { | |
key: "get", | |
value: function get(id, type) { | |
return this.entities.get(id) || this.getResolved(id, type) || null; | |
} | |
}, { | |
key: "remove", | |
value: function remove(sid) { | |
var cached = this.entities.get(sid); | |
if (cached) { | |
this.entities.delete(sid); | |
if (cached.uniqueName) { | |
this.names.delete(cached.type + '::' + cached.uniqueName); | |
} | |
} | |
} | |
}]); | |
return EntitiesCache; | |
}(); | |
entitiesCache.EntitiesCache = EntitiesCache; | |
var storage = {}; | |
Object.defineProperty(storage, "__esModule", { | |
value: true | |
}); | |
var SessionStorage = /*#__PURE__*/function () { | |
function SessionStorage(config, storage) { | |
_classCallCheck$1(this, SessionStorage); | |
this.config = config; | |
this.storageId = null; | |
try { | |
this.storage = storage || sessionStorage; | |
} catch (e) {} | |
} | |
_createClass(SessionStorage, [{ | |
key: "storageKey", | |
value: function storageKey(type, key) { | |
return "".concat(this.storageId, "::").concat(type, "::").concat(key); | |
} | |
}, { | |
key: "isReady", | |
get: function get() { | |
return this.config.sessionStorageEnabled && !!this.storageId; | |
} | |
}, { | |
key: "updateStorageId", | |
value: function updateStorageId(storageId) { | |
this.storageId = storageId; | |
} | |
}, { | |
key: "store", | |
value: function store(type, id, value) { | |
if (!this.isReady) { | |
return null; | |
} | |
return this._store(this.storageKey(type, id), value); | |
} | |
}, { | |
key: "read", | |
value: function read(type, id) { | |
if (!this.isReady) { | |
return null; | |
} | |
return this._read(this.storageKey(type, id)); | |
} | |
}, { | |
key: "remove", | |
value: function remove(type, sid, uniqueName) { | |
if (!this.isReady) { | |
return null; | |
} | |
try { | |
this.storage.removeItem(this.storageKey(type, sid)); | |
if (uniqueName) { | |
this.storage.removeItem(this.storageKey(type, uniqueName)); | |
} | |
} catch (e) {} | |
} | |
}, { | |
key: "update", | |
value: function update(type, sid, uniqueName, patch) { | |
if (!this.isReady) { | |
return null; | |
} // Currently cache may have root stored twice - by sid and by uniqueName | |
// Maybe need to create some index if needed | |
this._apply(this.storageKey(type, sid), patch); | |
if (uniqueName) { | |
this._apply(this.storageKey(type, uniqueName), patch); | |
} | |
} | |
}, { | |
key: "_store", | |
value: function _store(key, value) { | |
try { | |
this.storage.setItem(key, JSON.stringify(value)); | |
} catch (e) {} | |
} | |
}, { | |
key: "_read", | |
value: function _read(key) { | |
try { | |
var storedData = this.storage.getItem(key); | |
if (storedData) { | |
return JSON.parse(storedData); | |
} | |
} catch (e) {} | |
return null; | |
} | |
}, { | |
key: "_apply", | |
value: function _apply(key, patch) { | |
var value = this._read(key); | |
if (!value) { | |
return false; | |
} | |
this._store(key, Object.assign(value, patch)); | |
} | |
}]); | |
return SessionStorage; | |
}(); | |
storage.SessionStorage = SessionStorage; | |
var syncstream = {}; | |
function _createSuper$e(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$e(); 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$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; } } | |
Object.defineProperty(syncstream, "__esModule", { | |
value: true | |
}); | |
var entity_1$1 = entity; | |
var sanitize_1$1 = sanitize; | |
var closeable_1$1 = closeable; | |
var SyncStreamImpl = /*#__PURE__*/function (_entity_1$SyncEntity) { | |
_inherits$1(SyncStreamImpl, _entity_1$SyncEntity); | |
var _super = _createSuper$e(SyncStreamImpl); | |
/** | |
* @private | |
*/ | |
function SyncStreamImpl(services, descriptor, removalHandler) { | |
var _this; | |
_classCallCheck$1(this, SyncStreamImpl); | |
_this = _super.call(this, services, removalHandler); | |
_this.descriptor = descriptor; | |
return _this; | |
} // private props | |
_createClass(SyncStreamImpl, [{ | |
key: "uri", | |
get: function get() { | |
return this.descriptor.url; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.descriptor.links; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.descriptor.date_expires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return 'stream'; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return null; | |
} // below properties are specific to Insights only | |
}, { | |
key: "indexName", | |
get: function get() { | |
return undefined; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return undefined; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.descriptor.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.descriptor.unique_name || null; | |
} | |
}, { | |
key: "publishMessage", | |
value: function () { | |
var _publishMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(value) { | |
var requestBody, response, responseBody, event; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
requestBody = { | |
data: value | |
}; | |
_context.next = 3; | |
return this.services.network.post(this.links.messages, requestBody); | |
case 3: | |
response = _context.sent; | |
responseBody = response.body; | |
event = this._handleMessagePublished(responseBody.sid, value, false); | |
return _context.abrupt("return", event); | |
case 7: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function publishMessage(_x) { | |
return _publishMessage.apply(this, arguments); | |
} | |
return publishMessage; | |
}() | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(ttl) { | |
var requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
sanitize_1$1.validateMandatoryTtl(ttl); | |
_context2.prev = 1; | |
requestBody = { | |
ttl: ttl | |
}; | |
_context2.next = 5; | |
return this.services.network.post(this.uri, requestBody); | |
case 5: | |
response = _context2.sent; | |
this.descriptor.date_expires = response.body.date_expires; | |
_context2.next = 13; | |
break; | |
case 9: | |
_context2.prev = 9; | |
_context2.t0 = _context2["catch"](1); | |
if (_context2.t0.status === 404) { | |
this.onRemoved(false); | |
} | |
throw _context2.t0; | |
case 13: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this, [[1, 9]]); | |
})); | |
function setTtl(_x2) { | |
return _setTtl.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
}, { | |
key: "removeStream", | |
value: function () { | |
var _removeStream = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
_context3.next = 2; | |
return this.services.network.delete(this.uri); | |
case 2: | |
this.onRemoved(true); | |
case 3: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function removeStream() { | |
return _removeStream.apply(this, arguments); | |
} | |
return removeStream; | |
}() | |
/** | |
* Handle event from the server | |
* @private | |
*/ | |
}, { | |
key: "_update", | |
value: function _update(update) { | |
switch (update.type) { | |
case 'stream_message_published': | |
{ | |
this._handleMessagePublished(update.message_sid, update.message_data, true); | |
break; | |
} | |
case 'stream_removed': | |
{ | |
this.onRemoved(false); | |
break; | |
} | |
} | |
} | |
}, { | |
key: "_handleMessagePublished", | |
value: function _handleMessagePublished(sid, data, remote) { | |
var event = { | |
sid: sid, | |
value: data | |
}; | |
this.broadcastEventToListeners('messagePublished', { | |
message: event, | |
isLocal: !remote | |
}); | |
return event; | |
} | |
}, { | |
key: "onRemoved", | |
value: function onRemoved(isLocal) { | |
this._unsubscribe(); | |
this.removalHandler(this.type, this.sid, this.uniqueName); | |
this.broadcastEventToListeners('removed', { | |
isLocal: isLocal | |
}); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'stream'; | |
} | |
}]); | |
return SyncStreamImpl; | |
}(entity_1$1.SyncEntity); | |
syncstream.SyncStreamImpl = SyncStreamImpl; | |
/** | |
* @class | |
* @alias Stream | |
* @classdesc A Sync primitive for pub-sub messaging. Stream Messages are not persisted, exist | |
* only in transit, and will be dropped if (due to congestion or network anomalies) they | |
* cannot be delivered promptly. Use the {@link Client#stream} method to obtain a reference to a Sync Message Stream. | |
* Information about rate limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. | |
* @property {String} sid The immutable system-assigned identifier of this stream. Never null. | |
* @property {String} [uniqueName=null] A unique identifier optionally assigned to the stream on creation. | |
* | |
* @fires Stream#messagePublished | |
* @fires Stream#removed | |
*/ | |
var SyncStream = /*#__PURE__*/function (_closeable_1$default) { | |
_inherits$1(SyncStream, _closeable_1$default); | |
var _super2 = _createSuper$e(SyncStream); | |
function SyncStream(syncStreamImpl) { | |
var _this2; | |
_classCallCheck$1(this, SyncStream); | |
_this2 = _super2.call(this); | |
_this2.syncStreamImpl = syncStreamImpl; | |
_this2.syncStreamImpl.attach(_assertThisInitialized(_this2)); | |
return _this2; | |
} // private props | |
_createClass(SyncStream, [{ | |
key: "uri", | |
get: function get() { | |
return this.syncStreamImpl.uri; | |
} | |
}, { | |
key: "links", | |
get: function get() { | |
return this.syncStreamImpl.links; | |
} | |
}, { | |
key: "dateExpires", | |
get: function get() { | |
return this.syncStreamImpl.dateExpires; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return SyncStreamImpl.type; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return null; | |
} // public props, documented along with class description | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.syncStreamImpl.sid; | |
} | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return this.syncStreamImpl.uniqueName; | |
} | |
/** | |
* Publish a Message to the Stream. The system will attempt delivery to all online subscribers. | |
* @param {Object} value The body of the dispatched message. Maximum size in serialized JSON: 4KB. | |
* A rate limit applies to this operation, refer to the [Sync API documentation]{@link https://www.twilio.com/docs/api/sync} for details. | |
* @return {Promise<StreamMessage>} A promise which resolves after the message is successfully published | |
* to the Sync service. Resolves irrespective of ultimate delivery to any subscribers. | |
* @public | |
* @example | |
* stream.publishMessage({ x: 42, y: 123 }) | |
* .then(function(message) { | |
* console.log('Stream publishMessage() successful, message SID:' + message.sid); | |
* }) | |
* .catch(function(error) { | |
* console.error('Stream publishMessage() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "publishMessage", | |
value: function () { | |
var _publishMessage2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(value) { | |
return _regeneratorRuntime.wrap(function _callee4$(_context4) { | |
while (1) { | |
switch (_context4.prev = _context4.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context4.abrupt("return", this.syncStreamImpl.publishMessage(value)); | |
case 2: | |
case "end": | |
return _context4.stop(); | |
} | |
} | |
}, _callee4, this); | |
})); | |
function publishMessage(_x3) { | |
return _publishMessage2.apply(this, arguments); | |
} | |
return publishMessage; | |
}() | |
/** | |
* Update the time-to-live of the stream. | |
* @param {Number} ttl Specifies the TTL in seconds after which the stream is subject to automatic deletion. The value 0 means infinity. | |
* @return {Promise<void>} A promise that resolves after the TTL update was successful. | |
* @public | |
* @example | |
* stream.setTtl(3600) | |
* .then(function() { | |
* console.log('Stream setTtl() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Stream setTtl() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "setTtl", | |
value: function () { | |
var _setTtl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(ttl) { | |
return _regeneratorRuntime.wrap(function _callee5$(_context5) { | |
while (1) { | |
switch (_context5.prev = _context5.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context5.abrupt("return", this.syncStreamImpl.setTtl(ttl)); | |
case 2: | |
case "end": | |
return _context5.stop(); | |
} | |
} | |
}, _callee5, this); | |
})); | |
function setTtl(_x4) { | |
return _setTtl2.apply(this, arguments); | |
} | |
return setTtl; | |
}() | |
/** | |
* Permanently delete this Stream. | |
* @return {Promise<void>} A promise which resolves after the Stream is successfully deleted. | |
* @public | |
* @example | |
* stream.removeStream() | |
* .then(function() { | |
* console.log('Stream removeStream() successful'); | |
* }) | |
* .catch(function(error) { | |
* console.error('Stream removeStream() failed', error); | |
* }); | |
*/ | |
}, { | |
key: "removeStream", | |
value: function () { | |
var _removeStream2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { | |
return _regeneratorRuntime.wrap(function _callee6$(_context6) { | |
while (1) { | |
switch (_context6.prev = _context6.next) { | |
case 0: | |
this.ensureNotClosed(); | |
return _context6.abrupt("return", this.syncStreamImpl.removeStream()); | |
case 2: | |
case "end": | |
return _context6.stop(); | |
} | |
} | |
}, _callee6, this); | |
})); | |
function removeStream() { | |
return _removeStream2.apply(this, arguments); | |
} | |
return removeStream; | |
}() | |
/** | |
* Conclude work with the stream instance and remove all event listeners attached to it. | |
* Any subsequent operation on this object will be rejected with error. | |
* Other local copies of this stream will continue operating and receiving events normally. | |
* @public | |
* @example | |
* stream.close(); | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
_get(_getPrototypeOf$1(SyncStream.prototype), "close", this).call(this); | |
this.syncStreamImpl.detach(this.listenerUuid); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return SyncStreamImpl.type; | |
} | |
}]); | |
return SyncStream; | |
}(closeable_1$1.default); | |
syncstream.SyncStream = SyncStream; | |
syncstream.default = SyncStream; | |
var livequery = {}; | |
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(livequery, "__esModule", { | |
value: true | |
}); | |
var uri_1$1 = uri; | |
var syncerror_1$1 = syncerror; | |
var logger_1$3 = logger$1; | |
var events_1$3 = require$$0; | |
var entity_1 = entity; | |
var closeable_1 = closeable; | |
var cache_1 = cache; | |
var InsightsItem = function InsightsItem() { | |
_classCallCheck$1(this, InsightsItem); | |
}; | |
livequery.InsightsItem = InsightsItem; | |
var LiveQueryImpl = /*#__PURE__*/function (_entity_1$SyncEntity) { | |
_inherits$1(LiveQueryImpl, _entity_1$SyncEntity); | |
var _super = _createSuper$d(LiveQueryImpl); | |
function LiveQueryImpl(descriptor, services, removalHandler, items) { | |
var _this; | |
_classCallCheck$1(this, LiveQueryImpl); | |
_this = _super.call(this, services, removalHandler); | |
_this.descriptor = descriptor; | |
_this.cache = new cache_1.Cache(); | |
if (items) { | |
items.forEach(function (item) { | |
_this.cache.store(item.key, { | |
key: item.key, | |
value: item.data | |
}, item.revision); | |
}); | |
} | |
return _this; | |
} // public | |
_createClass(LiveQueryImpl, [{ | |
key: "sid", | |
get: function get() { | |
return this.descriptor.sid; | |
} // private extension of SyncEntity | |
}, { | |
key: "uniqueName", | |
get: function get() { | |
return null; | |
} | |
}, { | |
key: "type", | |
get: function get() { | |
return LiveQueryImpl.type; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.descriptor.last_event_id; | |
} | |
}, { | |
key: "indexName", | |
get: function get() { | |
return this.descriptor.indexName; | |
} | |
}, { | |
key: "queryString", | |
get: function get() { | |
return this.descriptor.queryExpression; | |
} // custom private props | |
}, { | |
key: "queryUri", | |
get: function get() { | |
return this.descriptor.queryUri; | |
} | |
}, { | |
key: "liveQueryDescriptor", | |
get: function get() { | |
return this.descriptor; | |
} // dummy stub from iface | |
}, { | |
key: "onRemoved", | |
value: function onRemoved() {} | |
}, { | |
key: "getItems", | |
value: function getItems() { | |
var dataByKey = {}; | |
this.cache.forEach(function (key, item) { | |
dataByKey[key] = item.value; | |
}); | |
return dataByKey; | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_update", | |
value: function _update(message, isStrictlyOrdered) { | |
switch (message.type) { | |
case 'live_query_item_updated': | |
this.handleItemMutated(message.item_key, message.item_data, message.item_revision); | |
break; | |
case 'live_query_item_removed': | |
this.handleItemRemoved(message.item_key, message.item_revision); | |
break; | |
case 'live_query_updated': | |
this.handleBatchUpdate(message.items); | |
break; | |
} | |
if (isStrictlyOrdered) { | |
this._advanceLastEventId(message.last_event_id); | |
} | |
} | |
}, { | |
key: "handleItemMutated", | |
value: function handleItemMutated(key, value, revision) { | |
if (this.shouldIgnoreEvent(key, revision)) { | |
logger_1$3.default.trace("Item ".concat(key, " update skipped, revision: ").concat(revision)); | |
} else { | |
var newItem = { | |
key: key, | |
value: value | |
}; | |
this.cache.store(key, newItem, revision); | |
this.broadcastEventToListeners('itemUpdated', newItem); | |
} | |
} | |
}, { | |
key: "handleItemRemoved", | |
value: function handleItemRemoved(key, revision) { | |
var force = revision === null; | |
if (this.shouldIgnoreEvent(key, revision)) { | |
logger_1$3.default.trace("Item ".concat(key, " delete skipped, revision: ").concat(revision)); | |
} else { | |
this.cache.delete(key, revision, force); | |
this.broadcastEventToListeners('itemRemoved', { | |
key: key | |
}); | |
} | |
} | |
}, { | |
key: "handleBatchUpdate", | |
value: function handleBatchUpdate(items) { | |
var _this2 = this; | |
// preprocess item set for easy key-based access (it's a one-time constant time operation) | |
var newItems = {}; | |
if (items != null) { | |
items.forEach(function (item) { | |
newItems[item.key] = { | |
data: item.data, | |
revision: item.revision | |
}; | |
}); | |
} // go through existing items and generate update/remove events for them | |
this.cache.forEach(function (key, item) { | |
var newItem = newItems[key]; | |
if (newItem != null) { | |
_this2.handleItemMutated(key, newItem.data, newItem.revision); | |
} else { | |
_this2.handleItemRemoved(key, null); // force deletion w/o revision | |
} // once item is handled, remove it from incoming array | |
delete newItems[key]; | |
}); // once we handled all the known items, handle remaining pack | |
for (var key in newItems) { | |
this.handleItemMutated(key, newItems[key].data, newItems[key].revision); | |
} | |
} | |
}, { | |
key: "shouldIgnoreEvent", | |
value: function shouldIgnoreEvent(key, eventId) { | |
return key != null && eventId != null && this.cache.isKnown(key, eventId); | |
} | |
/** | |
* @private | |
*/ | |
}, { | |
key: "_advanceLastEventId", | |
value: function _advanceLastEventId(eventId, revision) { | |
// LiveQuery is not revisioned in any way, so simply ignore second param and act upon lastEventId only | |
if (this.lastEventId < eventId) { | |
this.descriptor.last_event_id = eventId; | |
} | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'live_query'; | |
} | |
}]); | |
return LiveQueryImpl; | |
}(entity_1.SyncEntity); | |
livequery.LiveQueryImpl = LiveQueryImpl; | |
function queryItems(_x) { | |
return _queryItems.apply(this, arguments); | |
} | |
function _queryItems() { | |
_queryItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(params) { | |
var network, queryString, uri, type, liveQueryRequestBody, response; | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
network = params.network, queryString = params.queryString, uri = params.uri, type = params.type; | |
if (!(queryString == null)) { | |
_context3.next = 3; | |
break; | |
} | |
throw new syncerror_1$1.SyncError("Invalid query", 400, 54507); | |
case 3: | |
liveQueryRequestBody = { | |
query_string: queryString // raw query string (like `key == "value" AND key2 != "value2"`) | |
}; | |
if (type === LiveQuery.type) { | |
liveQueryRequestBody.type = type; | |
} | |
_context3.next = 7; | |
return network.post(uri, liveQueryRequestBody, undefined, true); | |
case 7: | |
response = _context3.sent; | |
return _context3.abrupt("return", response.body); | |
case 9: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3); | |
})); | |
return _queryItems.apply(this, arguments); | |
} | |
livequery.queryItems = queryItems; | |
/** | |
* @class | |
* @alias LiveQuery | |
* @classdesc Represents a long-running query against Flex data wherein the returned result set | |
* subsequently receives pushed updates whenever new (or updated) records would match the | |
* given expression. Updated results are presented row-by-row until this query is explicitly | |
* closed. | |
* | |
* Use the {@link Client#liveQuery} method to create a live query. | |
* | |
* @property {String} sid The immutable identifier of this query object, assigned by the system. | |
* | |
* @fires LiveQuery#itemUpdated | |
* @fires LiveQuery#itemRemoved | |
*/ | |
var LiveQuery = /*#__PURE__*/function (_closeable_1$Closeabl) { | |
_inherits$1(LiveQuery, _closeable_1$Closeabl); | |
var _super2 = _createSuper$d(LiveQuery); | |
/** | |
* @private | |
*/ | |
function LiveQuery(liveQueryImpl) { | |
var _this3; | |
_classCallCheck$1(this, LiveQuery); | |
_this3 = _super2.call(this); | |
_this3.liveQueryImpl = liveQueryImpl; | |
_this3.liveQueryImpl.attach(_assertThisInitialized(_this3)); | |
return _this3; | |
} // private props | |
_createClass(LiveQuery, [{ | |
key: "type", | |
get: function get() { | |
return LiveQueryImpl.type; | |
} | |
}, { | |
key: "lastEventId", | |
get: function get() { | |
return this.liveQueryImpl.lastEventId; | |
} // public | |
}, { | |
key: "sid", | |
get: function get() { | |
return this.liveQueryImpl.sid; | |
} | |
/** | |
* Closes this query instance and unsubscribes from further service events. | |
* This will eventually stop the physical inflow of updates over the network, when all other instances of this query are closed as well. | |
* @public | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
_get(_getPrototypeOf$1(LiveQuery.prototype), "close", this).call(this); | |
this.liveQueryImpl.detach(this.listenerUuid); | |
} | |
/** | |
* @returns {LiveQuery#ItemsSnapshot} A snapshot of items matching the current query expression. | |
* @public | |
*/ | |
}, { | |
key: "getItems", | |
value: function getItems() { | |
this.ensureNotClosed(); | |
return this.liveQueryImpl.getItems(); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return LiveQueryImpl.type; | |
} | |
}]); | |
return LiveQuery; | |
}(closeable_1.Closeable); | |
livequery.LiveQuery = LiveQuery; | |
/** | |
* @class | |
* @alias InstantQuery | |
* @classdesc Allows repetitive quick searches against a specific Flex data. Unlike a | |
* LiveQuery, this result set does not subscribe to any updates and therefore receives no events | |
* beyond the initial result set. | |
* | |
* Use the {@link Client#instantQuery} method to create an Instant Query. | |
* | |
* @fires InstantQuery#searchResult | |
*/ | |
var InstantQuery = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(InstantQuery, _events_1$EventEmitte); | |
var _super3 = _createSuper$d(InstantQuery); | |
/** | |
* @private | |
*/ | |
function InstantQuery(params) { | |
var _this4; | |
_classCallCheck$1(this, InstantQuery); | |
_this4 = _super3.call(this); | |
_this4.queryExpression = null; | |
_this4.items = {}; | |
Object.assign(_assertThisInitialized(_this4), params); | |
_this4.updateIndexName(params.indexName); | |
return _this4; | |
} // private props | |
_createClass(InstantQuery, [{ | |
key: "type", | |
get: function get() { | |
return InstantQuery.type; | |
} | |
/** | |
* Spawns a new search request. The result will be provided asynchronously via the {@link InstantQuery#event:searchResult} | |
* event. | |
* @param {String} queryExpression A query expression to be executed against the given data index. For more information | |
* on the syntax read {@link Client#liveQuery}. | |
* @returns {Promise<void>} A promise that resolves when query result has been received. | |
* @public | |
*/ | |
}, { | |
key: "search", | |
value: function () { | |
var _search = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(queryExpression) { | |
var _this5 = this; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
this.items = {}; | |
return _context.abrupt("return", queryItems({ | |
network: this.network, | |
uri: this.queryUri, | |
queryString: queryExpression | |
}).then(function (response) { | |
_this5.queryExpression = queryExpression; | |
if (response.items) { | |
response.items.forEach(function (item) { | |
_this5.items[item.key] = item.data; | |
}); | |
} | |
_this5.emit('searchResult', _this5.getItems()); | |
}).catch(function (err) { | |
logger_1$3.default.error("Error '".concat(err.message, "' while executing query '").concat(queryExpression, "'")); | |
_this5.queryExpression = null; | |
throw err; | |
})); | |
case 2: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function search(_x2) { | |
return _search.apply(this, arguments); | |
} | |
return search; | |
}() | |
/** | |
* Instantiates a LiveQuery object based on the last known query expression that was passed to the | |
* {@link InstantQuery#search} method. This LiveQuery will start receiving updates with new results, | |
* while current object can be still used to execute repetitive searches. | |
* @returns {Promise<LiveQuery>} A promise which resolves when the LiveQuery object is ready. | |
* @public | |
*/ | |
}, { | |
key: "subscribe", | |
value: function () { | |
var _subscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
if (!(this.queryExpression == null)) { | |
_context2.next = 2; | |
break; | |
} | |
return _context2.abrupt("return", Promise.reject(new syncerror_1$1.SyncError("Invalid query", 400, 54507))); | |
case 2: | |
return _context2.abrupt("return", this.liveQueryCreator(this.indexName, this.queryExpression)); | |
case 3: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function subscribe() { | |
return _subscribe.apply(this, arguments); | |
} | |
return subscribe; | |
}() | |
/** | |
* @returns {LiveQuery#ItemsSnapshot} A snapshot of items matching current query expression. | |
* @public | |
*/ | |
}, { | |
key: "getItems", | |
value: function getItems() { | |
return this.items; | |
} | |
/** | |
* Set new index name | |
* @param {String} indexName New index name to set | |
* @returns void | |
* @public | |
*/ | |
}, { | |
key: "updateIndexName", | |
value: function updateIndexName(indexName) { | |
if (!indexName || typeof indexName !== 'string') { | |
throw new Error('Index name must contain a non-empty string value'); | |
} | |
this.indexName = indexName; | |
this.queryUri = this.generateQueryUri(this.indexName); | |
} | |
}, { | |
key: "generateQueryUri", | |
value: function generateQueryUri(indexName) { | |
return new uri_1$1.UriBuilder(this.insightsUri).pathSegment(indexName).pathSegment('Items').build(); | |
} | |
}], [{ | |
key: "type", | |
get: function get() { | |
return 'instant_query'; | |
} | |
}]); | |
return InstantQuery; | |
}(events_1$3.EventEmitter); | |
livequery.InstantQuery = InstantQuery; | |
livequery.default = LiveQuery; | |
var name$1 = "twilio-sync"; | |
var version$2 = "1.0.0"; | |
var description$1 = "Twilio Sync client library"; | |
var main$1 = "lib/index.js"; | |
var types$1 = "./lib/index.d.ts"; | |
var author$1 = "Twilio"; | |
var license$1 = "MIT"; | |
var dependencies$1 = { | |
"twilio-notifications": "^0.5.12", | |
twilsock: "^0.6.2", | |
loglevel: "^1.6.3", | |
"operation-retrier": "^3.0.0", | |
platform: "^1.3.6", | |
uuid: "^3.3.2" | |
}; | |
var devDependencies$1 = { | |
"@types/chai": "^4.1.7", | |
"@types/chai-as-promised": "7.1.0", | |
"@types/chai-string": "^1.4.1", | |
"@types/mocha": "^5.2.7", | |
"@types/node": "^12.0.4", | |
"@types/sinon": "^7.0.12", | |
"@types/sinon-chai": "^3.2.2", | |
"async-test-tools": "^1.0.7", | |
"babel-core": "^6.26.0", | |
"babel-plugin-transform-builtin-extend": "^1.1.2", | |
"babel-plugin-transform-runtime": "^6.23.0", | |
"babel-preset-env": "^1.6.1", | |
"babel-runtime": "^6.26.0", | |
babelify: "^8.0.0", | |
browserify: "^16.2.3", | |
chai: "^4.2.0", | |
"chai-as-promised": "^7.1.1", | |
"chai-string": "^1.5.0", | |
cheerio: "^1.0.0-rc.2", | |
"cross-env": "^5.2.0", | |
del: "^4.1.1", | |
"fancy-log": "^1.3.3", | |
fs: "0.0.2", | |
gulp: "^4.0.2", | |
"gulp-babel": "^7.0.1", | |
"gulp-derequire": "^2.1.0", | |
"gulp-if": "^2.0.2", | |
"gulp-insert": "^0.5.0", | |
"gulp-rename": "^1.4.0", | |
"gulp-sourcemaps": "^2.6.5", | |
"gulp-tap": "^1.0.1", | |
"gulp-tslint": "^8.1.4", | |
"gulp-typescript": "^5.0.1", | |
"gulp-uglify-es": "^1.0.4", | |
"ink-docstrap": "^1.3.2", | |
jsdoc: "~3.5.5", | |
jsonwebtoken: "^8.5.1", | |
karma: "^4.1.0", | |
"karma-browserify": "^6.0.0", | |
"karma-browserstack-launcher": "^1.5.1", | |
"karma-mocha": "^1.3.0", | |
"karma-mocha-reporter": "^2.2.5", | |
mocha: "^6.1.4", | |
nyc: "^14.1.1", | |
path: "^0.12.7", | |
sinon: "^7.3.2", | |
"sinon-chai": "^3.3.0", | |
"ts-node": "^8.2.0", | |
tslint: "^5.17.0", | |
twilio: "^3.31.1", | |
typescript: "^3.5.1", | |
"uglify-es": "^3.3.10", | |
"uglify-save-license": "^0.4.1", | |
underscore: "^1.9.1", | |
"vinyl-buffer": "^1.0.1", | |
"vinyl-source-stream": "^2.0.0", | |
watchify: "^3.11.1" | |
}; | |
var browserify$1 = { | |
transform: ["babelify"] | |
}; | |
var scripts$1 = { | |
unitTest: "npx gulp unitTest", | |
integrationTest: "npx gulp integrationTest" | |
}; | |
var engines$1 = { | |
node: ">=8" | |
}; | |
var require$$19 = { | |
name: name$1, | |
version: version$2, | |
description: description$1, | |
main: main$1, | |
types: types$1, | |
author: author$1, | |
license: license$1, | |
dependencies: dependencies$1, | |
devDependencies: devDependencies$1, | |
browserify: browserify$1, | |
scripts: scripts$1, | |
engines: engines$1 | |
}; | |
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(client$1, "__esModule", { | |
value: true | |
}); | |
var events_1$2 = require$$0; | |
var twilsock_1 = lib$8; | |
var twilio_notifications_1 = lib$6; | |
var uri_1 = uri; | |
var syncerror_1 = syncerror; | |
var sanitize_1 = sanitize; | |
var logger_1$2 = logger$1; | |
var configuration_1$2 = configuration$1; | |
var subscriptions_1 = subscriptions; | |
var router_1 = router; | |
var network_1$1 = network$1; | |
var syncdocument_1 = syncdocument; | |
var synclist_1 = synclist; | |
var syncmap_1 = syncmap; | |
var clientInfo_1 = clientInfo; | |
var entitiesCache_1 = entitiesCache; | |
var storage_1 = storage; | |
var syncstream_1 = syncstream; | |
var livequery_1 = livequery; | |
var livequery_2 = livequery; | |
var SYNC_PRODUCT_ID = 'data_sync'; | |
var SDK_VERSION$3 = require$$19.version; | |
function decompose(arg) { | |
if (!arg) { | |
return { | |
mode: 'create_new' | |
}; | |
} else if (typeof arg === 'string') { | |
return { | |
id: arg, | |
mode: 'open_or_create' | |
}; | |
} else { | |
sanitize_1.validateOptionalTtl(arg.ttl); | |
sanitize_1.validateId(arg.id); | |
if (arg.mode) { | |
sanitize_1.validateMode(arg.mode); | |
} | |
var mode = arg.mode || (arg.id ? 'open_or_create' : 'create_new'); | |
return Object.assign(Object.assign({}, arg), { | |
mode: mode | |
}); | |
} | |
} | |
/** | |
* @class Client | |
* @classdesc | |
* Client for the Twilio Sync service. | |
* @constructor | |
* @param {String} token - Twilio access token. | |
* @param {Client#ClientOptions} [options] - Options to customize the Client. | |
* @example | |
* // Using NPM | |
* var SyncClient = require('twilio-sync'); | |
* var syncClient = new SyncClient(token, { logLevel: 'debug' }); | |
* | |
* // Using CDN | |
* var SyncClient = new Twilio.Sync.Client(token, { logLevel: 'debug' }); | |
* | |
* @property {Client#ConnectionState} connectionState - Contains current service connection state. | |
* Valid options are ['connecting', 'connected', 'disconnecting', 'disconnected', 'denied', 'error']. | |
*/ | |
var Client$2 = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Client, _events_1$EventEmitte); | |
var _super = _createSuper$c(Client); | |
function Client(fpaToken) { | |
var _this; | |
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | |
_classCallCheck$1(this, Client); | |
_this = _super.call(this); | |
if (!fpaToken) { | |
throw new Error('Sync library needs a valid Twilio token to be passed'); | |
} | |
if (options.hasOwnProperty('logLevel')) { | |
logger_1$2.default.setLevel(options.logLevel); | |
} else { | |
logger_1$2.default.setLevel('silent'); | |
} | |
var productId = options.productId = options.productId || SYNC_PRODUCT_ID; // Filling ClientMetadata | |
options.clientMetadata = options.clientMetadata || {}; | |
if (!options.clientMetadata.hasOwnProperty('type')) { | |
options.clientMetadata.type = 'sync'; | |
} | |
if (!options.clientMetadata.hasOwnProperty('sdk')) { | |
options.clientMetadata.sdk = 'JS'; | |
options.clientMetadata.sdkv = SDK_VERSION$3; | |
} | |
var twilsock = options.twilsockClient = options.twilsockClient || new twilsock_1.Twilsock(fpaToken, productId, options); | |
twilsock.on('tokenAboutToExpire', function (ttl) { | |
return _this.emit('tokenAboutToExpire', ttl); | |
}); | |
twilsock.on('tokenExpired', function () { | |
return _this.emit('tokenExpired'); | |
}); | |
twilsock.on('connectionError', function (err) { | |
return _this.emit('connectionError', err); | |
}); | |
var notifications = options.notificationsClient = options.notificationsClient || new twilio_notifications_1.Notifications(fpaToken, options); | |
var config = new configuration_1$2.Configuration(options); | |
var network = new network_1$1.NetworkService(new clientInfo_1.ClientInfo(SDK_VERSION$3), config, twilsock); | |
var storage = new storage_1.SessionStorage(config); | |
_this.localStorageId = null; | |
twilsock.connect(); | |
_this.services = { | |
config: config, | |
twilsock: twilsock, | |
notifications: notifications, | |
network: network, | |
storage: storage, | |
router: null, | |
subscriptions: null | |
}; | |
var subscriptions = new subscriptions_1.Subscriptions(_this.services); | |
var router = new router_1.Router({ | |
config: config, | |
subscriptions: subscriptions, | |
notifications: notifications | |
}); | |
_this.services.router = router; | |
_this.services.subscriptions = subscriptions; | |
_this.entities = new entitiesCache_1.EntitiesCache(); | |
notifications.on('connectionStateChanged', function () { | |
_this.emit('connectionStateChanged', _this.services.notifications.connectionState); | |
}); | |
return _this; | |
} | |
/** | |
* Current version of Sync client. | |
* @name Client#version | |
* @type String | |
* @readonly | |
*/ | |
_createClass(Client, [{ | |
key: "connectionState", | |
get: function get() { | |
return this.services.notifications.connectionState; | |
} | |
/** | |
* Returns promise which resolves when library is correctly initialized | |
* Or throws if initialization is impossible | |
* @private | |
*/ | |
}, { | |
key: "ensureReady", | |
value: function () { | |
var _ensureReady = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { | |
var storageSettings; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
if (this.services.config.sessionStorageEnabled) { | |
_context.next = 2; | |
break; | |
} | |
return _context.abrupt("return"); | |
case 2: | |
_context.prev = 2; | |
_context.next = 5; | |
return this.services.twilsock.storageId(); | |
case 5: | |
storageSettings = _context.sent; | |
this.services.storage.updateStorageId(storageSettings.id); | |
_context.next = 12; | |
break; | |
case 9: | |
_context.prev = 9; | |
_context.t0 = _context["catch"](2); | |
logger_1$2.default.warn('Failed to initialize storage', _context.t0); | |
case 12: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this, [[2, 9]]); | |
})); | |
function ensureReady() { | |
return _ensureReady.apply(this, arguments); | |
} | |
return ensureReady; | |
}() | |
}, { | |
key: "storeRootInSessionCache", | |
value: function storeRootInSessionCache(type, id, value) { | |
// can't store without id | |
if (!this.services.config.sessionStorageEnabled || !id) { | |
return; | |
} | |
var valueToStore = sanitize_1.deepClone(value); | |
if (type === synclist_1.SyncList.type || type === syncmap_1.SyncMap.type) { | |
valueToStore['last_event_id'] = null; | |
delete valueToStore['items']; | |
} | |
this.services.storage.store(type, id, valueToStore); | |
} | |
}, { | |
key: "readRootFromSessionCache", | |
value: function readRootFromSessionCache(type, id) { | |
if (!this.services.config.sessionStorageEnabled || !id) { | |
return null; | |
} | |
return this.services.storage.read(type, id); | |
} | |
}, { | |
key: "_get", | |
value: function () { | |
var _get2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(baseUri, id) { | |
var optimistic, | |
uri, | |
response, | |
_args2 = arguments; | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
optimistic = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false; | |
if (id) { | |
_context2.next = 3; | |
break; | |
} | |
throw new syncerror_1.SyncError("Cannot get entity without id", 404); | |
case 3: | |
uri = new uri_1.UriBuilder(baseUri).pathSegment(id).queryParam('Include', optimistic ? 'items' : undefined).build(); | |
_context2.next = 6; | |
return this.services.network.get(uri); | |
case 6: | |
response = _context2.sent; | |
return _context2.abrupt("return", response.body); | |
case 8: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this); | |
})); | |
function _get(_x, _x2) { | |
return _get2.apply(this, arguments); | |
} | |
return _get; | |
}() | |
}, { | |
key: "_createDocument", | |
value: function _createDocument(id, data, ttl) { | |
var requestBody = { | |
unique_name: id, | |
data: data || {} | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
return this.services.network.post(this.services.config.documentsUri, requestBody).then(function (response) { | |
response.body.data = requestBody.data; | |
return response.body; | |
}); | |
} | |
}, { | |
key: "_getDocument", | |
value: function () { | |
var _getDocument2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(id) { | |
return _regeneratorRuntime.wrap(function _callee3$(_context3) { | |
while (1) { | |
switch (_context3.prev = _context3.next) { | |
case 0: | |
return _context3.abrupt("return", this.readRootFromSessionCache(syncdocument_1.SyncDocument.type, id) || this._get(this.services.config.documentsUri, id)); | |
case 1: | |
case "end": | |
return _context3.stop(); | |
} | |
} | |
}, _callee3, this); | |
})); | |
function _getDocument(_x3) { | |
return _getDocument2.apply(this, arguments); | |
} | |
return _getDocument; | |
}() | |
}, { | |
key: "_createList", | |
value: function _createList(id, purpose, context, ttl) { | |
var requestBody = { | |
unique_name: id, | |
purpose: purpose, | |
context: context | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
return this.services.network.post(this.services.config.listsUri, requestBody).then(function (response) { | |
return response.body; | |
}); | |
} | |
}, { | |
key: "_getList", | |
value: function () { | |
var _getList2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(id) { | |
return _regeneratorRuntime.wrap(function _callee4$(_context4) { | |
while (1) { | |
switch (_context4.prev = _context4.next) { | |
case 0: | |
return _context4.abrupt("return", this.readRootFromSessionCache(synclist_1.SyncList.type, id) || this._get(this.services.config.listsUri, id)); | |
case 1: | |
case "end": | |
return _context4.stop(); | |
} | |
} | |
}, _callee4, this); | |
})); | |
function _getList(_x4) { | |
return _getList2.apply(this, arguments); | |
} | |
return _getList; | |
}() | |
}, { | |
key: "_createMap", | |
value: function _createMap(id, ttl) { | |
var requestBody = { | |
unique_name: id | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
return this.services.network.post(this.services.config.mapsUri, requestBody).then(function (response) { | |
return response.body; | |
}); | |
} | |
}, { | |
key: "_getMap", | |
value: function () { | |
var _getMap2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(id) { | |
var optimistic, | |
_args5 = arguments; | |
return _regeneratorRuntime.wrap(function _callee5$(_context5) { | |
while (1) { | |
switch (_context5.prev = _context5.next) { | |
case 0: | |
optimistic = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : false; | |
return _context5.abrupt("return", this.readRootFromSessionCache(syncmap_1.SyncMap.type, id) || this._get(this.services.config.mapsUri, id, optimistic)); | |
case 2: | |
case "end": | |
return _context5.stop(); | |
} | |
} | |
}, _callee5, this); | |
})); | |
function _getMap(_x5) { | |
return _getMap2.apply(this, arguments); | |
} | |
return _getMap; | |
}() | |
}, { | |
key: "_getStream", | |
value: function () { | |
var _getStream2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(id) { | |
return _regeneratorRuntime.wrap(function _callee6$(_context6) { | |
while (1) { | |
switch (_context6.prev = _context6.next) { | |
case 0: | |
return _context6.abrupt("return", this.readRootFromSessionCache(syncstream_1.SyncStream.type, id) || this._get(this.services.config.streamsUri, id, false)); | |
case 1: | |
case "end": | |
return _context6.stop(); | |
} | |
} | |
}, _callee6, this); | |
})); | |
function _getStream(_x6) { | |
return _getStream2.apply(this, arguments); | |
} | |
return _getStream; | |
}() | |
}, { | |
key: "_createStream", | |
value: function () { | |
var _createStream2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(id, ttl) { | |
var requestBody, response; | |
return _regeneratorRuntime.wrap(function _callee7$(_context7) { | |
while (1) { | |
switch (_context7.prev = _context7.next) { | |
case 0: | |
requestBody = { | |
unique_name: id | |
}; | |
if (ttl !== undefined) { | |
requestBody.ttl = ttl; | |
} | |
_context7.next = 4; | |
return this.services.network.post(this.services.config.streamsUri, requestBody); | |
case 4: | |
response = _context7.sent; | |
return _context7.abrupt("return", response.body); | |
case 6: | |
case "end": | |
return _context7.stop(); | |
} | |
} | |
}, _callee7, this); | |
})); | |
function _createStream(_x7, _x8) { | |
return _createStream2.apply(this, arguments); | |
} | |
return _createStream; | |
}() | |
}, { | |
key: "_getLiveQuery", | |
value: function _getLiveQuery(sid) { | |
return this.readRootFromSessionCache(livequery_1.LiveQuery.type, sid); | |
} | |
}, { | |
key: "getCached", | |
value: function getCached(id, type) { | |
if (id) { | |
return this.entities.get(id, type) || null; | |
} | |
return null; | |
} | |
}, { | |
key: "removeFromCacheAndSession", | |
value: function removeFromCacheAndSession(type, sid, uniqueName) { | |
this.entities.remove(sid); | |
if (this.services.config.sessionStorageEnabled) { | |
this.services.storage.remove(type, sid, uniqueName); | |
} | |
} | |
/** | |
* Read or create a Sync Document. | |
* @param {String | Client#OpenOptions} [arg] One of: | |
* <li>Unique name or SID identifying a Sync Document - opens a Document with the given identifier or creates one if it does not exist.</li> | |
* <li>none - creates a new Document with a randomly assigned SID and no unique name.</li> | |
* <li>{@link Client#OpenOptions} object for more granular control.</li> | |
* @return {Promise<Document>} a promise which resolves after the Document is successfully read (or created). | |
* This promise may reject if the Document could not be created or if this endpoint lacks the necessary permissions to access it. | |
* @public | |
* @example | |
* syncClient.document('MyDocument') | |
* .then(function(document) { | |
* console.log('Successfully opened a Document. SID: ' + document.sid); | |
* document.on('updated', function(event) { | |
* console.log('Received updated event: ', event); | |
* }); | |
* }) | |
* .catch(function(error) { | |
* console.log('Unexpected error', error); | |
* }); | |
*/ | |
}, { | |
key: "document", | |
value: function () { | |
var _document = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(arg) { | |
var _this2 = this; | |
var opts, docDescriptor, docFromInMemoryCache, syncDocumentImpl; | |
return _regeneratorRuntime.wrap(function _callee8$(_context8) { | |
while (1) { | |
switch (_context8.prev = _context8.next) { | |
case 0: | |
_context8.next = 2; | |
return this.ensureReady(); | |
case 2: | |
opts = decompose(arg); | |
if (!(opts.mode === 'create_new')) { | |
_context8.next = 9; | |
break; | |
} | |
_context8.next = 6; | |
return this._createDocument(opts.id, opts.data, opts.ttl); | |
case 6: | |
docDescriptor = _context8.sent; | |
_context8.next = 39; | |
break; | |
case 9: | |
docFromInMemoryCache = this.getCached(opts.id, syncdocument_1.SyncDocument.type); | |
if (!docFromInMemoryCache) { | |
_context8.next = 14; | |
break; | |
} | |
return _context8.abrupt("return", new syncdocument_1.SyncDocument(docFromInMemoryCache)); | |
case 14: | |
_context8.prev = 14; | |
_context8.next = 17; | |
return this._getDocument(opts.id); | |
case 17: | |
docDescriptor = _context8.sent; | |
_context8.next = 39; | |
break; | |
case 20: | |
_context8.prev = 20; | |
_context8.t0 = _context8["catch"](14); | |
if (!(_context8.t0.status !== 404 || opts.mode === 'open_existing')) { | |
_context8.next = 26; | |
break; | |
} | |
throw _context8.t0; | |
case 26: | |
_context8.prev = 26; | |
_context8.next = 29; | |
return this._createDocument(opts.id, opts.data, opts.ttl); | |
case 29: | |
docDescriptor = _context8.sent; | |
_context8.next = 39; | |
break; | |
case 32: | |
_context8.prev = 32; | |
_context8.t1 = _context8["catch"](26); | |
if (!(_context8.t1.status === 409)) { | |
_context8.next = 38; | |
break; | |
} | |
return _context8.abrupt("return", this.document(arg)); | |
case 38: | |
throw _context8.t1; | |
case 39: | |
this.storeRootInSessionCache(syncdocument_1.SyncDocument.type, opts.id, docDescriptor); | |
syncDocumentImpl = new syncdocument_1.SyncDocumentImpl(this.services, docDescriptor, function (type, sid, uniqueName) { | |
return _this2.removeFromCacheAndSession(type, sid, uniqueName); | |
}); | |
syncDocumentImpl = this.entities.store(syncDocumentImpl); | |
return _context8.abrupt("return", new syncdocument_1.SyncDocument(syncDocumentImpl)); | |
case 43: | |
case "end": | |
return _context8.stop(); | |
} | |
} | |
}, _callee8, this, [[14, 20], [26, 32]]); | |
})); | |
function document(_x9) { | |
return _document.apply(this, arguments); | |
} | |
return document; | |
}() | |
/** | |
* Read or create a Sync Map. | |
* @param {String | Client#OpenOptions} [arg] One of: | |
* <li>Unique name or SID identifying a Sync Map - opens a Map with the given identifier or creates one if it does not exist.</li> | |
* <li>none - creates a new Map with a randomly assigned SID and no unique name.</li> | |
* <li>{@link Client#OpenOptions} object for more granular control.</li> | |
* @return {Promise<Map>} a promise which resolves after the Map is successfully read (or created). | |
* This promise may reject if the Map could not be created or if this endpoint lacks the necessary permissions to access it. | |
* @public | |
* @example | |
* syncClient.map('MyMap') | |
* .then(function(map) { | |
* console.log('Successfully opened a Map. SID: ' + map.sid); | |
* map.on('itemUpdated', function(event) { | |
* console.log('Received itemUpdated event: ', event); | |
* }); | |
* }) | |
* .catch(function(error) { | |
* console.log('Unexpected error', error); | |
* }); | |
*/ | |
}, { | |
key: "map", | |
value: function () { | |
var _map = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(arg) { | |
var _this3 = this; | |
var opts, mapDescriptor, mapFromInMemoryCache, syncMapImpl; | |
return _regeneratorRuntime.wrap(function _callee9$(_context9) { | |
while (1) { | |
switch (_context9.prev = _context9.next) { | |
case 0: | |
_context9.next = 2; | |
return this.ensureReady(); | |
case 2: | |
opts = decompose(arg); | |
if (!(opts.mode === 'create_new')) { | |
_context9.next = 9; | |
break; | |
} | |
_context9.next = 6; | |
return this._createMap(opts.id, opts.ttl); | |
case 6: | |
mapDescriptor = _context9.sent; | |
_context9.next = 39; | |
break; | |
case 9: | |
mapFromInMemoryCache = this.getCached(opts.id, syncmap_1.SyncMap.type); | |
if (!mapFromInMemoryCache) { | |
_context9.next = 14; | |
break; | |
} | |
return _context9.abrupt("return", new syncmap_1.SyncMap(mapFromInMemoryCache)); | |
case 14: | |
_context9.prev = 14; | |
_context9.next = 17; | |
return this._getMap(opts.id, opts.includeItems); | |
case 17: | |
mapDescriptor = _context9.sent; | |
_context9.next = 39; | |
break; | |
case 20: | |
_context9.prev = 20; | |
_context9.t0 = _context9["catch"](14); | |
if (!(_context9.t0.status !== 404 || opts.mode === 'open_existing')) { | |
_context9.next = 26; | |
break; | |
} | |
throw _context9.t0; | |
case 26: | |
_context9.prev = 26; | |
_context9.next = 29; | |
return this._createMap(opts.id, opts.ttl); | |
case 29: | |
mapDescriptor = _context9.sent; | |
_context9.next = 39; | |
break; | |
case 32: | |
_context9.prev = 32; | |
_context9.t1 = _context9["catch"](26); | |
if (!(_context9.t1.status === 409)) { | |
_context9.next = 38; | |
break; | |
} | |
return _context9.abrupt("return", this.map(arg)); | |
case 38: | |
throw _context9.t1; | |
case 39: | |
this.storeRootInSessionCache(syncmap_1.SyncMap.type, opts.id, mapDescriptor); | |
syncMapImpl = new syncmap_1.SyncMapImpl(this.services, mapDescriptor, function (type, sid, uniqueName) { | |
return _this3.removeFromCacheAndSession(type, sid, uniqueName); | |
}); | |
syncMapImpl = this.entities.store(syncMapImpl); | |
return _context9.abrupt("return", new syncmap_1.SyncMap(syncMapImpl)); | |
case 43: | |
case "end": | |
return _context9.stop(); | |
} | |
} | |
}, _callee9, this, [[14, 20], [26, 32]]); | |
})); | |
function map(_x10) { | |
return _map.apply(this, arguments); | |
} | |
return map; | |
}() | |
/** | |
* Read or create a Sync List. | |
* @param {String | Client#OpenOptions} [arg] One of: | |
* <li>Unique name or SID identifying a Sync List - opens a List with the given identifier or creates one if it does not exist.</li> | |
* <li>none - creates a new List with a randomly assigned SID and no unique name.</li> | |
* <li>{@link Client#OpenOptions} object for more granular control.</li> | |
* @return {Promise<List>} a promise which resolves after the List is successfully read (or created). | |
* This promise may reject if the List could not be created or if this endpoint lacks the necessary permissions to access it. | |
* @public | |
* @example | |
* syncClient.list('MyList') | |
* .then(function(list) { | |
* console.log('Successfully opened a List. SID: ' + list.sid); | |
* list.on('itemAdded', function(event) { | |
* console.log('Received itemAdded event: ', event); | |
* }); | |
* }) | |
* .catch(function(error) { | |
* console.log('Unexpected error', error); | |
* }); | |
*/ | |
}, { | |
key: "list", | |
value: function () { | |
var _list = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(arg) { | |
var _this4 = this; | |
var opts, listDescriptor, listFromInMemoryCache, syncListImpl; | |
return _regeneratorRuntime.wrap(function _callee10$(_context10) { | |
while (1) { | |
switch (_context10.prev = _context10.next) { | |
case 0: | |
_context10.next = 2; | |
return this.ensureReady(); | |
case 2: | |
opts = decompose(arg); | |
if (!(opts.mode === 'create_new')) { | |
_context10.next = 9; | |
break; | |
} | |
_context10.next = 6; | |
return this._createList(opts.id, opts.purpose, opts.context, opts.ttl); | |
case 6: | |
listDescriptor = _context10.sent; | |
_context10.next = 39; | |
break; | |
case 9: | |
listFromInMemoryCache = this.getCached(opts.id, synclist_1.SyncList.type); | |
if (!listFromInMemoryCache) { | |
_context10.next = 14; | |
break; | |
} | |
return _context10.abrupt("return", new synclist_1.SyncList(listFromInMemoryCache)); | |
case 14: | |
_context10.prev = 14; | |
_context10.next = 17; | |
return this._getList(opts.id); | |
case 17: | |
listDescriptor = _context10.sent; | |
_context10.next = 39; | |
break; | |
case 20: | |
_context10.prev = 20; | |
_context10.t0 = _context10["catch"](14); | |
if (!(_context10.t0.status !== 404 || opts.mode === 'open_existing')) { | |
_context10.next = 26; | |
break; | |
} | |
throw _context10.t0; | |
case 26: | |
_context10.prev = 26; | |
_context10.next = 29; | |
return this._createList(opts.id, opts.purpose, opts.context, opts.ttl); | |
case 29: | |
listDescriptor = _context10.sent; | |
_context10.next = 39; | |
break; | |
case 32: | |
_context10.prev = 32; | |
_context10.t1 = _context10["catch"](26); | |
if (!(_context10.t1.status === 409)) { | |
_context10.next = 38; | |
break; | |
} | |
return _context10.abrupt("return", this.list(arg)); | |
case 38: | |
throw _context10.t1; | |
case 39: | |
this.storeRootInSessionCache(synclist_1.SyncList.type, opts.id, listDescriptor); | |
syncListImpl = new synclist_1.SyncListImpl(this.services, listDescriptor, function (type, sid, uniqueName) { | |
return _this4.removeFromCacheAndSession(type, sid, uniqueName); | |
}); | |
syncListImpl = this.entities.store(syncListImpl); | |
return _context10.abrupt("return", new synclist_1.SyncList(syncListImpl)); | |
case 43: | |
case "end": | |
return _context10.stop(); | |
} | |
} | |
}, _callee10, this, [[14, 20], [26, 32]]); | |
})); | |
function list(_x11) { | |
return _list.apply(this, arguments); | |
} | |
return list; | |
}() | |
/** | |
* Read or create a Sync Message Stream. | |
* @param {String | Client#OpenOptions} [arg] One of: | |
* <li>Unique name or SID identifying a Stream - opens a Stream with the given identifier or creates one if it does not exist.</li> | |
* <li>none - creates a new Stream with a randomly assigned SID and no unique name.</li> | |
* <li>{@link Client#OpenOptions} object for more granular control.</li> | |
* @return {Promise<Stream>} a promise which resolves after the Stream is successfully read (or created). | |
* The flow of messages will begin imminently (but not necessarily immediately) upon resolution. | |
* This promise may reject if the Stream could not be created or if this endpoint lacks the necessary permissions to access it. | |
* @public | |
* @example | |
* syncClient.stream('MyStream') | |
* .then(function(stream) { | |
* console.log('Successfully opened a Message Stream. SID: ' + stream.sid); | |
* stream.on('messagePublished', function(event) { | |
* console.log('Received messagePublished event: ', event); | |
* }); | |
* }) | |
* .catch(function(error) { | |
* console.log('Unexpected error', error); | |
* }); | |
*/ | |
}, { | |
key: "stream", | |
value: function () { | |
var _stream = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(arg) { | |
var _this5 = this; | |
var opts, streamDescriptor, streamFromInMemoryCache, streamRemovalHandler, syncStreamImpl; | |
return _regeneratorRuntime.wrap(function _callee11$(_context11) { | |
while (1) { | |
switch (_context11.prev = _context11.next) { | |
case 0: | |
_context11.next = 2; | |
return this.ensureReady(); | |
case 2: | |
opts = decompose(arg); | |
if (!(opts.mode === 'create_new')) { | |
_context11.next = 9; | |
break; | |
} | |
_context11.next = 6; | |
return this._createStream(opts.id, opts.ttl); | |
case 6: | |
streamDescriptor = _context11.sent; | |
_context11.next = 39; | |
break; | |
case 9: | |
streamFromInMemoryCache = this.getCached(opts.id, syncstream_1.SyncStream.type); | |
if (!streamFromInMemoryCache) { | |
_context11.next = 14; | |
break; | |
} | |
return _context11.abrupt("return", new syncstream_1.SyncStream(streamFromInMemoryCache)); | |
case 14: | |
_context11.prev = 14; | |
_context11.next = 17; | |
return this._getStream(opts.id); | |
case 17: | |
streamDescriptor = _context11.sent; | |
_context11.next = 39; | |
break; | |
case 20: | |
_context11.prev = 20; | |
_context11.t0 = _context11["catch"](14); | |
if (!(_context11.t0.status !== 404 || opts.mode === 'open_existing')) { | |
_context11.next = 26; | |
break; | |
} | |
throw _context11.t0; | |
case 26: | |
_context11.prev = 26; | |
_context11.next = 29; | |
return this._createStream(opts.id, opts.ttl); | |
case 29: | |
streamDescriptor = _context11.sent; | |
_context11.next = 39; | |
break; | |
case 32: | |
_context11.prev = 32; | |
_context11.t1 = _context11["catch"](26); | |
if (!(_context11.t1.status === 409)) { | |
_context11.next = 38; | |
break; | |
} | |
return _context11.abrupt("return", this.stream(arg)); | |
case 38: | |
throw _context11.t1; | |
case 39: | |
this.storeRootInSessionCache(syncstream_1.SyncStream.type, opts.id, streamDescriptor); | |
streamRemovalHandler = function streamRemovalHandler(type, sid, uniqueName) { | |
return _this5.removeFromCacheAndSession(type, sid, uniqueName); | |
}; | |
syncStreamImpl = new syncstream_1.SyncStreamImpl(this.services, streamDescriptor, streamRemovalHandler); | |
syncStreamImpl = this.entities.store(syncStreamImpl); | |
return _context11.abrupt("return", new syncstream_1.SyncStream(syncStreamImpl)); | |
case 44: | |
case "end": | |
return _context11.stop(); | |
} | |
} | |
}, _callee11, this, [[14, 20], [26, 32]]); | |
})); | |
function stream(_x12) { | |
return _stream.apply(this, arguments); | |
} | |
return stream; | |
}() | |
/** | |
* Gracefully shuts the Sync client down. | |
*/ | |
}, { | |
key: "shutdown", | |
value: function () { | |
var _shutdown = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12() { | |
return _regeneratorRuntime.wrap(function _callee12$(_context12) { | |
while (1) { | |
switch (_context12.prev = _context12.next) { | |
case 0: | |
_context12.next = 2; | |
return this.services.subscriptions.shutdown(); | |
case 2: | |
_context12.next = 4; | |
return this.services.twilsock.disconnect(); | |
case 4: | |
case "end": | |
return _context12.stop(); | |
} | |
} | |
}, _callee12, this); | |
})); | |
function shutdown() { | |
return _shutdown.apply(this, arguments); | |
} | |
return shutdown; | |
}() | |
/** | |
* Set new authentication token. | |
* @param {String} token New token to set. | |
* @return {Promise<void>} | |
* @public | |
*/ | |
}, { | |
key: "updateToken", | |
value: function () { | |
var _updateToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(token) { | |
return _regeneratorRuntime.wrap(function _callee13$(_context13) { | |
while (1) { | |
switch (_context13.prev = _context13.next) { | |
case 0: | |
if (token) { | |
_context13.next = 2; | |
break; | |
} | |
return _context13.abrupt("return", Promise.reject(new Error('A valid Twilio token should be provided'))); | |
case 2: | |
return _context13.abrupt("return", this.services.twilsock.updateToken(token).catch(function (error) { | |
var _a; | |
var status = (_a = error === null || error === void 0 ? void 0 : error.reply) === null || _a === void 0 ? void 0 : _a.status; | |
if ((status === null || status === void 0 ? void 0 : status.code) === 401 && (status === null || status === void 0 ? void 0 : status.status) === 'UNAUTHORIZED') { | |
throw new syncerror_1.SyncError('Updated token was rejected by server', 400, 51130); | |
} | |
throw error; | |
})); | |
case 3: | |
case "end": | |
return _context13.stop(); | |
} | |
} | |
}, _callee13, this); | |
})); | |
function updateToken(_x13) { | |
return _updateToken.apply(this, arguments); | |
} | |
return updateToken; | |
}() | |
/** | |
* For Flex customers only. Establishes a long-running query against Flex data wherein the returned | |
* result set is updated whenever new (or updated) records match the given expression. Updated results | |
* are presented row-by-row according to the lifetime of the returned LiveQuery object. | |
* | |
* @param indexName {String} Must specify one of the Flex data classes for which Live Queries are available. | |
* @param queryExpression {String} A query expression to be executed against the given data index. | |
* Please review <a href="https://www.twilio.com/docs/sync/live-query" target="_blank">Live Query Language</a> | |
* page for Sync Client limits and full list of operators currently supported in query expressions. | |
* | |
* @return {Promise<LiveQuery>} a promise that resolves when the query has been successfully executed. | |
* @public | |
* @example | |
* syncClient.liveQuery('tr-worker', 'data.attributes.worker_name == "Bob"') | |
* .then(function(args) { | |
* console.log('Subscribed to live data updates for worker Bob'); | |
* let items = args.getItems(); | |
* Object.entries(items).forEach(([key, value]) => { | |
* console.log('Search result item key: ' + key); | |
* console.log('Search result item value: ' + value); | |
* }); | |
* }) | |
* .catch(function(err) { | |
* console.log('Error when subscribing to live updates for worker Bob', err); | |
* }); | |
*/ | |
}, { | |
key: "liveQuery", | |
value: function () { | |
var _liveQuery = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(indexName, queryExpression) { | |
var _this6 = this; | |
var queryUri, response, liveQueryImpl, descriptor, liveQueryRemovalHandler; | |
return _regeneratorRuntime.wrap(function _callee14$(_context14) { | |
while (1) { | |
switch (_context14.prev = _context14.next) { | |
case 0: | |
_context14.next = 2; | |
return this.ensureReady(); | |
case 2: | |
if (!(!indexName || typeof indexName !== 'string')) { | |
_context14.next = 4; | |
break; | |
} | |
throw new Error('Index name must contain a non-empty string value'); | |
case 4: | |
queryUri = new uri_1.UriBuilder(this.services.config.insightsUri).pathSegment(indexName).pathSegment('Items').build(); // send query to CDS to get server-generated sid and item list | |
_context14.next = 7; | |
return livequery_2.queryItems({ | |
network: this.services.network, | |
uri: queryUri, | |
queryString: queryExpression, | |
type: livequery_1.LiveQuery.type | |
}); | |
case 7: | |
response = _context14.sent; | |
liveQueryImpl = this.getCached(response.query_id, livequery_1.LiveQuery.type); | |
if (!liveQueryImpl) { | |
descriptor = this._getLiveQuery(response.query_id); | |
if (!descriptor) { | |
descriptor = { | |
indexName: indexName, | |
queryExpression: queryExpression, | |
sid: response.query_id, | |
queryUri: queryUri, | |
last_event_id: response.last_event_id | |
}; | |
} | |
liveQueryRemovalHandler = function liveQueryRemovalHandler(type, sid, uniqueName) { | |
return _this6.removeFromCacheAndSession(type, sid, uniqueName); | |
}; | |
liveQueryImpl = new livequery_1.LiveQueryImpl(descriptor, this.services, liveQueryRemovalHandler, response.items); | |
} | |
this.storeRootInSessionCache(livequery_1.LiveQuery.type, response.query_id, liveQueryImpl.liveQueryDescriptor); | |
liveQueryImpl = this.entities.store(liveQueryImpl); | |
return _context14.abrupt("return", new livequery_1.LiveQuery(liveQueryImpl)); | |
case 13: | |
case "end": | |
return _context14.stop(); | |
} | |
} | |
}, _callee14, this); | |
})); | |
function liveQuery(_x14, _x15) { | |
return _liveQuery.apply(this, arguments); | |
} | |
return liveQuery; | |
}() | |
/** | |
* For Flex customers only. Creates a query object that can be used to issue one-time queries repeatedly | |
* against the target index. | |
* | |
* @param indexName {String} Must specify one of the Flex data classes for which Live Queries are available. | |
* @return {Promise<InstantQuery>} a promise which resolves after the InstantQuery is successfully created. | |
* @public | |
* @example | |
* syncClient.instantQuery('tr-worker') | |
* .then(function(q) { | |
* q.on('searchResult', function(items) { | |
* Object.entries(items).forEach(([key, value]) => { | |
* console.log('Search result item key: ' + key); | |
* console.log('Search result item value: ' + value); | |
* }); | |
* }); | |
* }); | |
*/ | |
}, { | |
key: "instantQuery", | |
value: function () { | |
var _instantQuery = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(indexName) { | |
var _this7 = this; | |
var liveQueryCreator, search; | |
return _regeneratorRuntime.wrap(function _callee15$(_context15) { | |
while (1) { | |
switch (_context15.prev = _context15.next) { | |
case 0: | |
_context15.next = 2; | |
return this.ensureReady(); | |
case 2: | |
liveQueryCreator = function liveQueryCreator(indexName, queryExpression) { | |
return _this7.liveQuery(indexName, queryExpression); | |
}; | |
search = new livequery_1.InstantQuery({ | |
indexName: indexName, | |
network: this.services.network, | |
insightsUri: this.services.config.insightsUri, | |
liveQueryCreator: liveQueryCreator | |
}); | |
return _context15.abrupt("return", search); | |
case 5: | |
case "end": | |
return _context15.stop(); | |
} | |
} | |
}, _callee15, this); | |
})); | |
function instantQuery(_x16) { | |
return _instantQuery.apply(this, arguments); | |
} | |
return instantQuery; | |
}() | |
}], [{ | |
key: "version", | |
get: function get() { | |
return SDK_VERSION$3; | |
} | |
}]); | |
return Client; | |
}(events_1$2.EventEmitter); | |
client$1.Client = Client$2; | |
client$1.SyncClient = Client$2; | |
client$1.default = Client$2; | |
(function (module, exports) { | |
Object.defineProperty(exports, "__esModule", { | |
value: true | |
}); | |
var client_1 = client$1; | |
exports.SyncClient = client_1.SyncClient; | |
var syncdocument_1 = syncdocument; | |
exports.SyncDocument = syncdocument_1.SyncDocument; | |
var synclist_1 = synclist; | |
exports.SyncList = synclist_1.SyncList; | |
var listitem_1 = listitem; | |
exports.SyncListItem = listitem_1.ListItem; | |
var syncmap_1 = syncmap; | |
exports.SyncMap = syncmap_1.SyncMap; | |
var mapitem_1 = mapitem; | |
exports.SyncMapItem = mapitem_1.MapItem; | |
exports.default = client_1.SyncClient; | |
module.exports = client_1.SyncClient; | |
module.exports.SyncClient = client_1.SyncClient; | |
})(lib$4, lib$4.exports); | |
var client = {}; | |
var logger = {}; | |
Object.defineProperty(logger, "__esModule", { | |
value: true | |
}); | |
var log$c = loglevel.exports; | |
function prepareLine(prefix, args) { | |
return ["".concat(new Date().toISOString(), " MCS Client ").concat(prefix, ":")].concat(Array.from(args)); | |
} | |
var Logger = /*#__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$c.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$c.trace.apply(null, prepareLine(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$c.debug.apply(null, prepareLine(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$c.info.apply(null, prepareLine(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$c.warn.apply(null, prepareLine(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$c.error.apply(null, prepareLine(this.prefix + 'E', args)); | |
} | |
}], [{ | |
key: "scope", | |
value: function scope(prefix) { | |
return new Logger(prefix); | |
} | |
}, { | |
key: "setLevel", | |
value: function setLevel(level) { | |
log$c.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$c.trace.apply(null, prepareLine('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$c.debug.apply(null, prepareLine('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$c.info.apply(null, prepareLine('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$c.warn.apply(null, prepareLine('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$c.error.apply(null, prepareLine('E', args)); | |
} | |
}]); | |
return Logger; | |
}(); | |
logger.Logger = Logger; | |
var configuration = {}; | |
Object.defineProperty(configuration, "__esModule", { | |
value: true | |
}); | |
var MINIMUM_RETRY_DELAY = 1000; | |
var MAXIMUM_RETRY_DELAY = 4000; | |
var MAXIMUM_ATTEMPTS_COUNT = 3; | |
var RETRY_WHEN_THROTTLED = true; | |
var Configuration = /*#__PURE__*/function () { | |
function Configuration(token, baseUrl, options) { | |
_classCallCheck$1(this, Configuration); | |
var constructorOptions = options.MCS || options || {}; | |
this.region = constructorOptions.region || options.region; | |
this.baseUrl = (typeof this.region === 'undefined' ? 'https://mcs.us1.twilio.com' : "https://mcs.".concat(this.region, ".twilio.com")) + baseUrl; | |
this.token = token; | |
this.retryWhenThrottledOverride = constructorOptions.retryWhenThrottledOverride; | |
this.backoffConfigOverride = constructorOptions.backoffConfigOverride; | |
} | |
_createClass(Configuration, [{ | |
key: "updateToken", | |
value: function updateToken(token) { | |
this.token = token; | |
} | |
}], [{ | |
key: "backoffConfigDefault", | |
get: function get() { | |
return { | |
min: MINIMUM_RETRY_DELAY, | |
max: MAXIMUM_RETRY_DELAY, | |
maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT | |
}; | |
} | |
}, { | |
key: "retryWhenThrottledDefault", | |
get: function get() { | |
return RETRY_WHEN_THROTTLED; | |
} | |
}]); | |
return Configuration; | |
}(); | |
configuration.Configuration = Configuration; | |
var media = {}; | |
Object.defineProperty(media, "__esModule", { | |
value: true | |
}); | |
/** | |
* @classdesc A Media represents a metadata information for the media upload | |
* @property {String} sid - The server-assigned unique identifier for Media | |
* @property {String} serviceSid - Service instance id which Media belongs/uploaded to | |
* @property {Date} dateCreated - When the Media was created | |
* @property {Date} dateUpdated - When the Media was updated | |
* @property {Number} size - Size of media, bytes | |
* @property {String} contentType - content type of media | |
* @property {String} fileName - file name, if present, null otherwise | |
*/ | |
var Media$1 = /*#__PURE__*/function () { | |
function Media(config, network, data) { | |
_classCallCheck$1(this, Media); | |
this.config = config; | |
this.network = network; | |
this._update(data); | |
} | |
_createClass(Media, [{ | |
key: "sid", | |
get: function get() { | |
return this.state.sid; | |
} | |
}, { | |
key: "serviceSid", | |
get: function get() { | |
return this.state.serviceSid; | |
} | |
}, { | |
key: "dateCreated", | |
get: function get() { | |
return this.state.dateCreated; | |
} | |
}, { | |
key: "dateUpdated", | |
get: function get() { | |
return this.state.dateUpdated; | |
} | |
}, { | |
key: "contentType", | |
get: function get() { | |
return this.state.contentType; | |
} | |
}, { | |
key: "size", | |
get: function get() { | |
return this.state.size; | |
} | |
}, { | |
key: "fileName", | |
get: function get() { | |
return this.state.filename; | |
} | |
/** | |
* Returns direct content URL to uploaded binary | |
* @public | |
* @returns {Promise<string>} | |
*/ | |
}, { | |
key: "getContentUrl", | |
value: function () { | |
var _getContentUrl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { | |
var response; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
_context.next = 2; | |
return this.network.get("".concat(this.config.baseUrl, "/").concat(this.sid)); | |
case 2: | |
response = _context.sent; | |
this._update(response.body); | |
return _context.abrupt("return", Promise.resolve(this.state.contentDirectUrl)); | |
case 5: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function getContentUrl() { | |
return _getContentUrl.apply(this, arguments); | |
} | |
return getContentUrl; | |
}() | |
}, { | |
key: "_update", | |
value: function _update(data) { | |
this.state = { | |
sid: data.sid, | |
serviceSid: data.service_sid, | |
channelSid: data.channel_sid, | |
messageSid: data.message_sid, | |
dateCreated: data.date_created ? new Date(data.date_created) : null, | |
dateUpdated: data.date_updated ? new Date(data.date_updated) : null, | |
size: data.size, | |
contentType: data.content_type, | |
url: data.url, | |
contentUrl: data.links.content, | |
contentDirectUrl: data.links.content_direct_temporary, | |
filename: data.filename ? data.filename : null | |
}; | |
} | |
}]); | |
return Media; | |
}(); | |
media.Media = Media$1; | |
var transport = {}; | |
var transporterror = {}; | |
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(transporterror, "__esModule", { | |
value: true | |
}); | |
var TransportError = /*#__PURE__*/function (_Error) { | |
_inherits$1(TransportError, _Error); | |
var _super = _createSuper$b(TransportError); | |
function TransportError(message, code, body, status, headers) { | |
var _this; | |
_classCallCheck$1(this, TransportError); | |
_this = _super.call(this, message); | |
_this.code = code; | |
_this.body = body; | |
_this.status = status; | |
_this.headers = headers; | |
return _this; | |
} | |
return TransportError; | |
}( /*#__PURE__*/_wrapNativeSuper(Error)); | |
transporterror.TransportError = TransportError; | |
Object.defineProperty(transport, "__esModule", { | |
value: true | |
}); | |
var transporterror_1 = transporterror; | |
var XHR = commonjsGlobal['XMLHttpRequest'] || require$$1.XMLHttpRequest; | |
function parseResponseHeaders(headerString) { | |
if (!headerString) { | |
return {}; | |
} | |
return headerString.split("\r\n").map(function (el) { | |
return el.split(": "); | |
}).filter(function (el) { | |
return el.length === 2 && el[1].length > 0; | |
}).reduce(function (prev, curr) { | |
prev[curr[0]] = curr[1]; | |
return prev; | |
}, {}); | |
} | |
function extractBody(xhr) { | |
var contentType = xhr.getResponseHeader('Content-Type'); | |
if (!contentType || contentType.indexOf('application/json') !== 0 || xhr.responseText.length === 0) { | |
return xhr.responseText; | |
} | |
try { | |
return JSON.parse(xhr.responseText); | |
} catch (e) { | |
return xhr.responseText; | |
} | |
} | |
/** | |
* Provides generic network interface | |
*/ | |
var Transport = /*#__PURE__*/function () { | |
function Transport() { | |
_classCallCheck$1(this, Transport); | |
} | |
_createClass(Transport, [{ | |
key: "get", | |
value: | |
/** | |
* Make a GET request by given URL | |
*/ | |
function get(url, headers) { | |
return Transport.request('GET', url, headers); | |
} | |
/** | |
* Make a POST request by given URL | |
*/ | |
}, { | |
key: "post", | |
value: function post(url, headers, body) { | |
return Transport.request('POST', url, headers, body); | |
} | |
}], [{ | |
key: "request", | |
value: function request(method, url, headers, body) { | |
return new Promise(function (resolve, reject) { | |
var xhr = new XHR(); | |
xhr.open(method, url, true); | |
xhr.onreadystatechange = function onreadystatechange() { | |
if (xhr.readyState !== 4) { | |
return; | |
} | |
var headers = parseResponseHeaders(xhr.getAllResponseHeaders()); | |
var body = extractBody(xhr); | |
if (200 <= xhr.status && xhr.status < 300) { | |
resolve({ | |
status: xhr.status, | |
headers: headers, | |
body: body | |
}); | |
} else { | |
var status = xhr.statusText && xhr.statusText.code ? xhr.statusText.code : 'NONE'; | |
var bodyRepresentation; | |
if (typeof body === 'string') { | |
bodyRepresentation = body && body.split('\n', 2).length === 1 ? body : ''; | |
} else { | |
bodyRepresentation = JSON.stringify(body); | |
} | |
var message = "".concat(xhr.status, ": [").concat(status, "] ").concat(bodyRepresentation); | |
reject(new transporterror_1.TransportError(message, xhr.status, body, status, headers)); | |
} | |
}; | |
for (var headerName in headers) { | |
xhr.setRequestHeader(headerName, headers[headerName]); | |
if (headerName === 'Content-Type' && headers[headerName] === 'application/json') { | |
body = JSON.stringify(body); | |
} | |
} | |
xhr.send(body); | |
}); | |
} | |
}]); | |
return Transport; | |
}(); | |
transport.Transport = Transport; | |
var network = {}; | |
var lib$2 = {}; | |
var retrier = {}; | |
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(retrier, "__esModule", { | |
value: true | |
}); | |
var events_1$1 = require$$0; | |
/** | |
* Provides retrier service | |
*/ | |
var Retrier = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Retrier, _events_1$EventEmitte); | |
var _super = _createSuper$a(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$1.EventEmitter); | |
retrier.Retrier = Retrier; | |
retrier.default = Retrier; | |
var backoff = {}; | |
function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); 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$9() { 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, "__esModule", { | |
value: true | |
}); | |
var events_1 = require$$0; | |
function isDef(value) { | |
return value !== undefined && value !== null; | |
} | |
var Backoff = /*#__PURE__*/function (_events_1$EventEmitte) { | |
_inherits$1(Backoff, _events_1$EventEmitte); | |
var _super = _createSuper$9(Backoff); | |
function Backoff(options) { | |
var _this; | |
_classCallCheck$1(this, Backoff); | |
_this = _super.call(this); | |
options = options || {}; | |
if (isDef(options.initialDelay) && options.initialDelay < 1) { | |
throw new Error('The initial timeout must be equal to or greater than 1.'); | |
} else if (isDef(options.maxDelay) && options.maxDelay <= 1) { | |
throw new Error('The maximal timeout must be greater than 1.'); | |
} else if (isDef(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) { | |
throw new Error('The randomisation factor must be between 0 and 1.'); | |
} else if (isDef(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.EventEmitter); | |
backoff.Backoff = Backoff; | |
backoff.default = Backoff; | |
Object.defineProperty(lib$2, "__esModule", { | |
value: true | |
}); | |
var retrier_1 = retrier; | |
lib$2.Retrier = retrier_1.Retrier; | |
var backoff_1 = backoff; | |
lib$2.Backoff = backoff_1.Backoff; | |
lib$2.default = retrier_1.Retrier; | |
Object.defineProperty(network, "__esModule", { | |
value: true | |
}); | |
var operation_retrier_1 = lib$2; | |
var logger_1$1 = logger; | |
var configuration_1$1 = configuration; | |
var log$b = logger_1$1.Logger.scope('Network'); | |
var Network = /*#__PURE__*/function () { | |
function Network(config, transport) { | |
_classCallCheck$1(this, Network); | |
this.config = config; | |
this.transport = transport; | |
} | |
_createClass(Network, [{ | |
key: "backoffConfig", | |
value: function backoffConfig() { | |
return Object.assign(configuration_1$1.Configuration.backoffConfigDefault, this.config.backoffConfigOverride); | |
} | |
}, { | |
key: "retryWhenThrottled", | |
value: function retryWhenThrottled() { | |
if (typeof this.config.retryWhenThrottledOverride !== 'undefined') { | |
return this.config.retryWhenThrottledOverride; | |
} | |
if (typeof configuration_1$1.Configuration.retryWhenThrottledDefault !== 'undefined') { | |
return configuration_1$1.Configuration.retryWhenThrottledDefault; | |
} | |
return false; | |
} | |
}, { | |
key: "executeWithRetry", | |
value: function executeWithRetry(request) { | |
var _this = 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 operation_retrier_1.Retrier(_this.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 _this2 = this; | |
var headers, response; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
headers = { | |
'X-Twilio-Token': this.config.token | |
}; | |
log$b.trace('sending GET request to ', url, ' headers ', headers); | |
_context.next = 4; | |
return this.executeWithRetry(function () { | |
return _this2.transport.get(url, headers); | |
}, this.retryWhenThrottled()); | |
case 4: | |
response = _context.sent; | |
log$b.trace('response', response); | |
return _context.abrupt("return", response); | |
case 7: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function get(_x) { | |
return _get.apply(this, arguments); | |
} | |
return get; | |
}() | |
}, { | |
key: "post", | |
value: function () { | |
var _post = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(url, media, contentType) { | |
var headers, response; | |
return _regeneratorRuntime.wrap(function _callee2$(_context2) { | |
while (1) { | |
switch (_context2.prev = _context2.next) { | |
case 0: | |
headers = { | |
'X-Twilio-Token': this.config.token | |
}; | |
if ((typeof FormData === 'undefined' || !(media instanceof FormData)) && contentType) { | |
Object.assign(headers, { | |
'Content-Type': contentType | |
}); | |
} | |
log$b.trace('sending POST request to ', url, ' headers ', headers); | |
_context2.prev = 3; | |
_context2.next = 6; | |
return this.transport.post(url, headers, media); | |
case 6: | |
response = _context2.sent; | |
_context2.next = 17; | |
break; | |
case 9: | |
_context2.prev = 9; | |
_context2.t0 = _context2["catch"](3); | |
if (!(_context2.t0 instanceof TypeError)) { | |
_context2.next = 16; | |
break; | |
} | |
log$b.trace('got error in post response', _context2.t0); | |
throw new TypeError('Posting FormData supported only with browser engine\'s FormData'); | |
case 16: | |
throw _context2.t0; | |
case 17: | |
log$b.trace('response', response); | |
return _context2.abrupt("return", response); | |
case 19: | |
case "end": | |
return _context2.stop(); | |
} | |
} | |
}, _callee2, this, [[3, 9]]); | |
})); | |
function post(_x2, _x3, _x4) { | |
return _post.apply(this, arguments); | |
} | |
return post; | |
}() | |
}]); | |
return Network; | |
}(); | |
network.Network = Network; | |
var name = "twilio-mcs-client"; | |
var version$1 = "0.3.3"; | |
var description = "Twilio Media Content Service client library"; | |
var main = "lib/index.js"; | |
var types = "./lib/client.d.ts"; | |
var author = "Twilio"; | |
var license = "MIT"; | |
var scripts = {}; | |
var dependencies = { | |
loglevel: "^1.6.4", | |
"operation-retrier": "^3.0.1", | |
xmlhttprequest: "^1.8.0" | |
}; | |
var devDependencies = { | |
"@types/chai": "^4.2.2", | |
"@types/chai-as-promised": "^7.1.2", | |
"@types/chai-datetime": "0.0.33", | |
"@types/chai-string": "^1.4.2", | |
"@types/core-js": "^2.5.2", | |
"@types/mocha": "^5.2.7", | |
"@types/node": "^12.7.4", | |
"@types/sinon": "^7.0.13", | |
"@types/sinon-chai": "^3.2.3", | |
async: "^3.1.0", | |
"async-test-tools": "^1.0.7", | |
"babel-core": "^6.26.0", | |
"babel-plugin-transform-builtin-extend": "^1.1.2", | |
"babel-plugin-transform-runtime": "^6.23.0", | |
"babel-preset-env": "^1.6.1", | |
"babel-runtime": "^6.26.0", | |
babelify: "^8.0.0", | |
browserify: "^16.0.0", | |
chai: "^4.2.0", | |
"chai-as-promised": "^7.1.1", | |
"chai-datetime": "^1.5.0", | |
"chai-string": "^1.5.0", | |
cheerio: "^1.0.0-rc.2", | |
"cross-env": "^5.2.1", | |
del: "^5.1.0", | |
dotenv: "^8.1.0", | |
express: "^4.17.1", | |
gulp: "^4.0.2", | |
"gulp-babel": "^7.0.1", | |
"gulp-derequire": "^2.1.0", | |
"gulp-if": "^3.0.0", | |
"gulp-insert": "^0.5.0", | |
"gulp-mocha": "^7.0.1", | |
"gulp-rename": "^1.4.0", | |
"gulp-sourcemaps": "^2.6.5", | |
"gulp-tap": "^2.0.0", | |
"gulp-tslint": "^8.1.4", | |
"gulp-typescript": "^5.0.1", | |
"gulp-uglify-es": "^1.0.0", | |
"ink-docstrap": "^1.3.2", | |
"isomorphic-form-data": "^2.0.0", | |
jsdoc: "~3.5.5", | |
"jsdoc-strip-async-await": "^0.1.0", | |
mocha: "^6.2.0", | |
ngrok: "^3.2.5", | |
nyc: "^14.1.1", | |
sinon: "^7.4.2", | |
"sinon-chai": "^3.3.0", | |
"source-map-explorer": "^2.0.1", | |
"ts-node": "^8.3.0", | |
tslint: "^5.19.0", | |
twilio: "^3.34.0", | |
typescript: "^3.6.2", | |
"uglify-save-license": "^0.4.1", | |
"vinyl-buffer": "^1.0.1", | |
"vinyl-source-stream": "^2.0.0" | |
}; | |
var browserify = { | |
transform: ["babelify"] | |
}; | |
var browser = { | |
xmlhttprequest: false | |
}; | |
var engines = { | |
node: ">=6" | |
}; | |
var require$$5 = { | |
name: name, | |
version: version$1, | |
description: description, | |
main: main, | |
types: types, | |
author: author, | |
license: license, | |
scripts: scripts, | |
dependencies: dependencies, | |
devDependencies: devDependencies, | |
browserify: browserify, | |
browser: browser, | |
engines: engines | |
}; | |
Object.defineProperty(client, "__esModule", { | |
value: true | |
}); | |
var logger_1 = logger; | |
var configuration_1 = configuration; | |
var media_1 = media; | |
client.Media = media_1.Media; | |
client.McsMedia = media_1.Media; | |
var transport_1 = transport; | |
var network_1 = network; | |
var log$a = logger_1.Logger.scope(''); //log.setLevel('trace'); | |
var SDK_VERSION$2 = require$$5.version; | |
var MSG_NO_TOKEN = 'A valid Twilio token should be provided'; | |
/** | |
* @classdesc A Client provides an interface for Media Content Service | |
*/ | |
var Client$1 = /*#__PURE__*/function () { | |
/** | |
* @param {String} token - Access token | |
* @param {String} baseUrl - Base URL for Media Content Service, i.e. /v1/Services/{serviceSid}/Media | |
* @param {Client#ClientOptions} [options] - Options to customize the Client | |
*/ | |
function Client(token, baseUrl) { | |
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | |
_classCallCheck$1(this, Client); | |
this.options = options; | |
this.options.logLevel = this.options.logLevel || 'silent'; | |
this.config = new configuration_1.Configuration(token, baseUrl, this.options); | |
if (!token) { | |
throw new Error(MSG_NO_TOKEN); | |
} | |
log$a.setLevel(this.options.logLevel); | |
this.options.transport = this.options.transport || new transport_1.Transport(); | |
this.transport = this.options.transport; | |
this.network = new network_1.Network(this.config, this.transport); | |
} | |
/** | |
* These options can be passed to Client constructor | |
* @typedef {Object} Client#ClientOptions | |
* @property {String} [logLevel='error'] - The level of logging to enable. Valid options | |
* (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace'] | |
*/ | |
/** | |
* Update the token used for Client operations | |
* @param {String} token - The JWT string of the new token | |
* @public | |
* @returns {void} | |
*/ | |
_createClass(Client, [{ | |
key: "updateToken", | |
value: function updateToken(token) { | |
log$a.info('updateToken'); | |
if (!token) { | |
throw new Error(MSG_NO_TOKEN); | |
} | |
this.config.updateToken(token); | |
} | |
/** | |
* Gets media from media service | |
* @param {String} sid - Media's SID | |
* @public | |
* @returns {Promise<Media>} | |
*/ | |
}, { | |
key: "get", | |
value: function () { | |
var _get = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(sid) { | |
var response; | |
return _regeneratorRuntime.wrap(function _callee$(_context) { | |
while (1) { | |
switch (_context.prev = _context.next) { | |
case 0: | |
_context.next = 2; | |
return this.network.get("".concat(this.config.baseUrl, "/").concat(sid)); | |
case 2: | |
response = _context.sent; | |
return _context.abrupt("return", new media_1.Media(this.config, this.network, response.body)); | |
case 4: | |
case "end": | |
return _context.stop(); | |
} | |
} | |
}, _callee, this); | |
})); | |
function get |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment