diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js index 4ed9299703fba82ea2ee76faa56d117a13a5e149..7d0b4670e4d0460fe7168207ff2fbad675416c81 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js @@ -1,12485 +1,2 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.jsonqlWsClient = factory()); -}(this, (function () { 'use strict'; - - /* base.js */ - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - var HEADERS_KEY = 'headers'; - - var JSONQL_PATH = 'jsonql'; - - // export const INDEX = 'index' use INDEX_KEY instead - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json' - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js' - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - var QUERY_ARG_NAME = 'args'; - var TIMESTAMP_PARAM_NAME = 'TS'; - // for contract-cli - var KEY_WORD = 'continue'; - var PUBLIC_KEY = 'public'; - var PRIVATE_KEY = 'private'; - var LOGIN_FN_NAME = 'login'; - // export const ISSUER_NAME = LOGIN_NAME // legacy issue need to replace them later - var LOGOUT_FN_NAME = 'logout'; - var DISCONNECT_FN_NAME = 'disconnect'; - var SWITCH_USER_FN_NAME = 'switch-user'; - - var AUTH_HEADER = 'Authorization'; - var BEARER = 'Bearer'; - // headers - var CSRF_HEADER_KEY = 'X-CSRF-Token'; - - /* prop.js */ - - // this is all the key name for the config check map - // all subfix with prop_key - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var ENABLE_AUTH_PROP_KEY = 'enableAuth'; - var USE_JWT_PROP_KEY = 'useJwt'; - var LOGIN_FN_NAME_PROP_KEY = 'loginHandlerName'; - var LOGOUT_FN_NAME_PROP_KEY = 'logoutHandlerName'; - var DISCONNECT_FN_NAME_PROP_KEY = 'disconnectHandlerName'; - var SWITCH_USER_FN_NAME_PROP_KEY = 'switchUserHandlerName'; - // type name and Alias - var SOCKET_TYPE_PROP_KEY = 'serverType'; //1.9.1 - var SOCKET_TYPE_CLIENT_ALIAS = 'socketClientType'; // 1.9.0 - - var CSRF_PROP_KEY = 'csrf'; - - var STANDALONE_PROP_KEY = 'standalone'; - var DEBUG_ON_PROP_KEY = 'debugOn'; - - var HOSTNAME_PROP_KEY = 'hostname'; - var NAMESAPCE_PROP_KEY = 'namespace'; - - var WS_OPT_PROP_KEY = 'wsOptions'; - - var CONTRACT_PROP_KEY = 'contract'; - var TOKEN_PROP_KEY = 'token'; - - var CONNECTED_PROP_KEY = 'connected'; - // track this key if we want to suspend event on start - var SUSPEND_EVENT_PROP_KEY = 'suspendOnStart'; - // we could pass the token in the header instead when init the WebSocket - var TOKEN_DELIVER_LOCATION_PROP_KEY = 'tokenDeliverLocation'; - - // the constants file is gettig too large - // we need to split up and group the related constant in one file - // also it makes the other module easiler to id what they are importing - // use throughout the clients - var SOCKET_PING_EVENT_NAME = '__ping__'; // when init connection do a ping - var LOGIN_EVENT_NAME = '__login__'; - var LOGOUT_EVENT_NAME$1 = '__logout__'; - // at the moment we only have __logout__ regardless enableAuth is enable - // this is incorrect, because logout suppose to come after login - // and it should only logout from auth nsp, instead of clear out the - // connection, the following new event @1.9.2 will correct this edge case - // although it should never happens, but in some edge case might want to - // disconnect from the current server, then re-establish connection later - var CONNECT_EVENT_NAME = '__connect__'; - // we still need the connected event because after the connection establish - // we need to change a state within the client to let the front end know that - // it's current hook up to the server but we don't want to loop back the client - // inside the setup phrase, intead just trigger a connected event and the listener - // setup this property - var CONNECTED_EVENT_NAME = '__connected__'; - var DISCONNECT_EVENT_NAME = '__disconnect__'; - // instead of using an event name in place of resolverName in the param - // we use this internal resolverName instead, and in type using the event names - var INTERCOM_RESOLVER_NAME = '__intercom__'; - // for ws servers - var WS_REPLY_TYPE = '__reply__'; - var WS_EVT_NAME = '__event__'; - var WS_DATA_NAME = '__data__'; - - // for ws client, 1.9.3 breaking change to name them as FN instead of PROP - var ON_MESSAGE_FN_NAME = 'onMessage'; - var ON_RESULT_FN_NAME = 'onResult'; // this will need to be internal from now on - var ON_ERROR_FN_NAME = 'onError'; - var ON_READY_FN_NAME = 'onReady'; - var ON_LOGIN_FN_NAME = 'onLogin'; // new @1.8.6 - // the actual method name client.resolverName.send - var SEND_MSG_FN_NAME = 'send'; - - // this is somewhat vague about what is suppose to do - var EMIT_REPLY_TYPE = 'emit_reply'; - - var NSP_GROUP = 'nspGroup'; - var PUBLIC_NAMESPACE = 'publicNamespace'; - var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; - var HSA_ALGO = 'HS256'; - var TOKEN_PARAM_NAME = 'token'; - - // this is the value for TOKEN_DELIVER_LOCATION_PROP_KEY - var TOKEN_IN_HEADER = 'header'; - var TOKEN_IN_URL = 'url'; - - /* validation.js */ - - // validation related constants - - - var OR_SEPERATOR = '|'; - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Built-in value references. */ - var Symbol = root.Symbol; - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Built-in value references. */ - var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$1 = Object.prototype; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$1 = objectProto$1.toString; - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString$1.call(value); - } - - /** `Object#toString` result references. */ - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - - /** Built-in value references. */ - var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag$1 && symToStringTag$1 in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** `Object#toString` result references. */ - var objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** `Object#toString` result references. */ - var symbolTag = '[object Symbol]'; - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsZWJ = '\\u200d'; - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsAstral = '[' + rsAstralRange$1 + ']', - rsCombo = '[' + rsComboRange$1 + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange$1 + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$1 = '\\u200d'; - - /** Used to compose unicode regexes. */ - var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange$1 + ']?', - rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g; - - /** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ - function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); - } - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - // quick and dirty to turn non array to array - var toArray = function (arg) { return isArray(arg) ? arg : [arg]; }; - - /** - * parse string to json or just return the original value if error happened - * @param {*} n input - * @param {boolean} [t=true] or throw - * @return {*} json object on success - */ - var parseJson = function(n, t) { - if ( t === void 0 ) t=true; - - try { - return JSON.parse(n) - } catch(e) { - if (t) { - return n - } - throw new Error(e) - } - }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false - } - }; - - /** - * create a event name - * @param {string[]} args - * @return {string} event name for use - */ - var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); - }; - - /** - * small util to make sure the return value is valid JSON object - * @param {*} n input - * @return {object} correct JSON object - */ - var toJson = function (n) { - if (typeof n === 'string') { - return parseJson(n) - } - return parseJson(JSON.stringify(n)) - }; - - /** - * Simple check if the prop is function - * @param {*} prop input - * @return {boolean} true on success - */ - var isFunc = function (prop) { - if (typeof prop === 'function') { - return true; - } - console.error(("Expect to be Function type! Got " + (typeof prop))); - }; - - /** - * generic placeholder function - * @return {boolean} false - */ - var nil = function () { return false; }; - - /** - * using just the map reduce to chain multiple functions together - * @param {function} mainFn the init function - * @param {array} moreFns as many as you want to take the last value and return a new one - * @return {function} accept value for the mainFn - */ - var chainFns = function (mainFn) { - var moreFns = [], len = arguments.length - 1; - while ( len-- > 0 ) moreFns[ len ] = arguments[ len + 1 ]; - - return ( - function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - moreFns.reduce(function (value, nextFn) { return ( - // change here to check if the return value is array then we spread it - Reflect.apply(nextFn, null, toArray(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); - } - ); - }; - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString$1.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$3 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$2.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$3.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$5.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** Built-in value references. */ - var Uint8Array = root.Uint8Array; - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$6; - - return value === proto; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$7 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$7.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$5.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$1 ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$1 = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag$1 = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$2 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$2 && freeModule$2.require && freeModule$2.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$6.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$7.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$a.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$8.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * this is essentially the same as the injectToFn - * but this will not allow overwrite and set the setter and getter - * @param {object} obj to get injected - * @param {string} name of the property - * @param {function} setter for set - * @param {function} [getter=null] for get default return null fn - * @return {object} the injected obj - */ - function objDefineProps(obj, name, setter, getter) { - if ( getter === void 0 ) getter = null; - - if (Object.getOwnPropertyDescriptor(obj, name) === undefined) { - Object.defineProperty(obj, name, { - set: setter, - get: getter === null ? function() { return null; } : getter - }); - } - return obj - } - - /** - * check if the object has name property - * @param {object} obj the object to check - * @param {string} name the prop name - * @return {*} the value or undefined - */ - function objHasProp(obj, name) { - var prop = Object.getOwnPropertyDescriptor(obj, name); - return prop !== undefined && prop.value ? prop.value : prop - } - - /** - * After the user login we will use this Object.define add a new property - * to the resolver with the decoded user data - * @param {function} resolver target resolver - * @param {string} name the name of the object to get inject also for checking - * @param {object} data to inject into the function static interface - * @param {boolean} [overwrite=false] if we want to overwrite the existing data - * @return {function} added property resolver - */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; - - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver - } - /* this will throw error! @TODO how to remove props? - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property - } - */ - // console.info(`INJECTED`) - Object.defineProperty(resolver, name, { - value: data, - writable: overwrite // if its set to true then we should able to overwrite it - }); - - return resolver - } - - var NO_ERROR_MSG = 'No message'; - var NO_STATUS_CODE = -1; - var UNAUTHORIZED_STATUS = 401; - var FORBIDDEN_STATUS = 403; - var NOT_FOUND_STATUS = 404; - var NOT_ACCEPTABLE_STATUS = 406; - var SERVER_INTERNAL_STATUS = 500; - - /** - * This is a custom error to throw when server throw a 406 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return NOT_ACCEPTABLE_STATUS - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error' - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return SERVER_INTERNAL_STATUS - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error' - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * this is the 403 Forbidden error - * that means this user is not login - * use the 401 for try to login and failed - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlForbiddenError = /*@__PURE__*/(function (Error) { - function JsonqlForbiddenError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlForbiddenError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlForbiddenError); - } - } - - if ( Error ) JsonqlForbiddenError.__proto__ = Error; - JsonqlForbiddenError.prototype = Object.create( Error && Error.prototype ); - JsonqlForbiddenError.prototype.constructor = JsonqlForbiddenError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return FORBIDDEN_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlForbiddenError'; - }; - - Object.defineProperties( JsonqlForbiddenError, staticAccessors ); - - return JsonqlForbiddenError; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return UNAUTHORIZED_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return UNAUTHORIZED_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError' - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return SERVER_INTERNAL_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError' - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return NOT_FOUND_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError' - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError' - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError' - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError' - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError$1 = /*@__PURE__*/(function (Error) { - function JsonqlError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); - // this.detail = this.stack; - } - } - - if ( Error ) JsonqlError.__proto__ = Error; - JsonqlError.prototype = Object.create( Error && Error.prototype ); - JsonqlError.prototype.constructor = JsonqlError; - - var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlError' - }; - - staticAccessors.statusCode.get = function () { - return NO_STATUS_CODE - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; - }(Error)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return SERVER_INTERNAL_STATUS - }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError' - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e) - } - var msg = e.message || NO_ERROR_MSG; - var detail = e.detail || e; - // @BUG the instance of not always work for some reason! - // need to figure out a better way to find out the type of the error - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail) - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail) - case e instanceof JsonqlForbiddenError: - throw new JsonqlForbiddenError(msg, detail) - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail) - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail) - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail) - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail) - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail) - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail) - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail) - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail) - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail) - default: - throw new JsonqlError$1(msg, detail) - } - } - - // split the contract into the node side and the generic side - /** - * Check if the json is a contract file or not - * @param {object} contract json object - * @return {boolean} true - */ - function checkIsContract(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey(contract, QUERY_NAME) - || isObjectHasKey(contract, MUTATION_NAME) - || isObjectHasKey(contract, SOCKET_NAME) - ) - } - - /** - * Wrapper method that check if it's contract then return the contract or false - * @param {object} contract the object to check - * @return {boolean | object} false when it's not - */ - function isContract(contract) { - return checkIsContract(contract) ? contract : false - } - - /** - * Ported from jsonql-params-validator but different - * if we don't find the socket part then return false - * @param {object} contract the contract object - * @return {object|boolean} false on failed - */ - function extractSocketPart(contract) { - if (isObjectHasKey(contract, SOCKET_NAME)) { - return contract[SOCKET_NAME] - } - return false - } - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time - }; - - /** `Object#toString` result references. */ - var stringTag$1 = '[object String]'; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag$1); - } - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName name of the resolver - * @param {*} payload what is sending - * @param {object} extra additonal property we want to merge into the deliverable - * @return {object} delierable - */ - function createDeliverable(resolverName, payload, extra) { - var obj; - - if ( extra === void 0 ) extra = {}; - return Object.assign(( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp() ], obj ), extra) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload - } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError('utils:params-api:createQuery', { - message: "expect resolverName to be string and args to be array!", - resolverName: resolverName, - args: args - }) - } - - /** - * string version of the createQuery - * @return {string} - */ - function createQueryStr(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - return JSON.stringify(createQuery(resolverName, args, jsonp)) - } - - // take out all the namespace related methods in one place for easy to find - var SOCKET_NOT_FOUND_ERR = "socket not found in contract!"; - var SIZE = 'size'; - - /** - * create the group using publicNamespace when there is only public - * @param {object} socket from contract - * @param {string} publicNamespace - */ - function groupPublicNamespace(socket, publicNamespace) { - var obj; - - var g = {}; - for (var resolverName in socket) { - var params = socket[resolverName]; - g[resolverName] = params; - } - return { size: 1, nspGroup: ( obj = {}, obj[publicNamespace] = g, obj ), publicNamespace: publicNamespace} - } - - - /** - * @BUG we should check the socket part instead of expect the downstream to read the menu! - * We only need this when the enableAuth is true otherwise there is only one namespace - * @param {object} contract the socket part of the contract file - * @return {object} 1. remap the contract using the namespace --> resolvers - * 2. the size of the object (1 all private, 2 mixed public with private) - * 3. which namespace is public - */ - function groupByNamespace(contract) { - var socket = extractSocketPart(contract); - if (socket === false) { - throw new JsonqlError('groupByNamespace', SOCKET_NOT_FOUND_ERR) - } - var prop = {}; - prop[NSP_GROUP] = {}; - prop[PUBLIC_NAMESPACE] = null; - prop[SIZE] = 0; - - for (var resolverName in socket) { - var params = socket[resolverName]; - var namespace = params.namespace; - if (namespace) { - if (!prop[NSP_GROUP][namespace]) { - ++prop[SIZE]; - prop[NSP_GROUP][namespace] = {}; - } - prop[NSP_GROUP][namespace][resolverName] = params; - // get the public namespace - if (!prop[PUBLIC_NAMESPACE] && params[PUBLIC_KEY]) { - prop[PUBLIC_NAMESPACE] = namespace; - } - } - } - - return prop - } - - /** - * @TODO this might change, what if we want to do room with ws - * 1. there will only be max two namespace - * 2. when it's normal we will have the stock path as namespace - * 3. when enableAuth then we will have two, one is jsonql/public + private - * @param {object} config options - * @return {array} of namespace(s) - */ - function getNamespace(config) { - var base = JSONQL_PATH; - if (config.enableAuth) { - // the public come first @1.0.1 we use the constants instead of the user supplied value - // @1.0.4 we use the config value again, because we could control this via the post init - return [ - [ base , config.privateNamespace ].join('/'), - [ base , config.publicNamespace ].join('/') - ] - } - return [ base ] - } - - /** - * get the private namespace - * @param {array} namespaces array - * @return {*} string on success - */ - function getPrivateNamespace$1(namespaces) { - return namespaces.length > 1 ? namespaces[0] : false - } - - /** - * Got a problem with a contract that is public only the groupByNamespace is wrong - * which is actually not a problem when using a fallback, but to be sure things in order - * we could combine with the config to group it - * @param {object} config configuration - * @return {object} nspInfo object - */ - function getNspInfoByConfig(config) { - var contract = config.contract; - var enableAuth = config.enableAuth; - var namespaces = getNamespace(config); - var nspInfo = enableAuth ? groupByNamespace(contract) - : groupPublicNamespace(contract.socket, namespaces[0]); - // add the namespaces into it as well - return Object.assign(nspInfo, { namespaces: namespaces }) - } - - // There are the socket related methods ported back from - - var PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'; - var WS_KEYS = [ - WS_REPLY_TYPE, - WS_EVT_NAME, - WS_DATA_NAME - ]; - - /** - * @param {string|object} payload should be string when reply but could be transformed - * @return {boolean} true is OK - */ - var isWsReply = function (payload) { - var json = isString(payload) ? toJson(payload) : payload; - var data = json.data; - if (data) { - var result = WS_KEYS.filter(function (key) { return isObjectHasKey(data, key); }); - return (result.length === WS_KEYS.length) ? data : false - } - return false - }; - - /** - * @param {string|object} data received data - * @param {function} [cb=nil] this is for extracting the TS field or when it's error - * @return {object} false on failed - */ - var extractWsPayload = function (payload, cb) { - if ( cb === void 0 ) cb = nil; - - try { - var json = toJson(payload); - // now handle the data - var _data; - if ((_data = isWsReply(json)) !== false) { - // note the ts property is on its own - cb('_data', _data); - - return { - data: toJson(_data[WS_DATA_NAME]), - resolverName: _data[WS_EVT_NAME], - type: _data[WS_REPLY_TYPE] - } - } - throw new JsonqlError$1(PAYLOAD_NOT_DECODED_ERR, payload) - } catch(e) { - return cb(ERROR_KEY, e) - } - }; - - // this will be part of the init client sequence - var CSRF_HEADER_NOT_EXIST_ERR = 'CSRF header is not in the received payload'; - - /** - * Util method - * @param {string} payload return from server - * @return {object} the useful bit - */ - function extractSrvPayload(payload) { - var json = toJson(payload); - - if (json && typeof json === 'object') { - // note this method expect the json.data inside - return extractWsPayload(json) - } - - throw new JsonqlError$1('extractSrvPayload', json) - } - - /** - * call the server to get a csrf token - * @return {string} formatted payload to send to the server - */ - function createInitPing() { - var ts = timestamp(); - - return createQueryStr(INTERCOM_RESOLVER_NAME, [SOCKET_PING_EVENT_NAME, ts]) - } - - /** - * Take the raw on.message result back then decoded it - * @param {*} payload the raw result from server - * @return {object} the csrf payload - */ - function extractPingResult(payload) { - var obj; - - var result = extractSrvPayload(payload); - - if (result && result[DATA_KEY] && result[DATA_KEY][CSRF_HEADER_KEY]) { - return ( obj = {}, obj[HEADERS_KEY] = result[DATA_KEY], obj ) - } - - throw new JsonqlError$1('extractPingResult', CSRF_HEADER_NOT_EXIST_ERR) - } - - - /** - * Create a generic intercom method - * @param {string} type the event type - * @param {array} args if any - * @return {string} formatted payload to send - */ - function createIntercomPayload(type) { - var args = [], len = arguments.length - 1; - while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; - - var ts = timestamp(); - var payload = [type].concat(args); - payload.push(ts); - return createQueryStr(INTERCOM_RESOLVER_NAME, payload) - } - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - var isNotEmpty = function (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== '' - }; - - /** `Object#toString` result references. */ - var numberTag$1 = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag$1); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN$1(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN$1( parseFloat(value) ) - }; - - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE: - return checkIsNumber - case STRING_TYPE: - return checkIsString - case BOOLEAN_TYPE: - return checkIsBoolean - default: - return checkIsAny - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike$1 = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, ''); - if (_type.indexOf(OR_SEPERATOR)) { - return _type.split(OR_SEPERATOR) - } - return [_type] - } - return false - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length - }; - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (_value !== undefined) { - if ((tmp = isArrayLike$1(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true - }).length) - }).length; - } - } - return false - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return Reflect.apply(checkIsObject, null, _args) - }; - - // move the index.js code here that make more sense to find where things are - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (isNotEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike$1(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (arg !== undefined) { - return arg - } - return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlValidationError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return [] - } - if (!checkIsArray(args)) { - console.info(args); - throw new JsonqlValidationError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }) - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }) - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length: - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE ]; - // we only looking at the first one, this might be a @BUG - /* - if ((tmp = isArrayLike(params[0].type[0])) !== false) { - _type = tmp; - } */ - // if we use the params as guide then the rest will get throw out - // which is not what we want, instead, anything without the param - // will get a any type and optional flag - return args.map(function (arg, i) { - var optional = i >= ctn ? true : !!params[i].optional; - var param = params[i] || { type: _type, name: ("_" + i) }; - return { - arg: optional ? getOptionalValue(arg, param) : arg, - index: i, - param: param, - optional: optional - } - }) - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError$1(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - // v1.4.4 this fixed the problem, the root level optional is from the last fn - if (p.optional === true || p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$b = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$b.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$9.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$1 = '[object Map]', - numberTag$2 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$1 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$1 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$1: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$2: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$1: - var convert = mapToArray; - - case setTag$1: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** `Object#toString` result references. */ - var mapTag$2 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$2 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$2 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) || - (Map$1 && getTag(new Map$1) != mapTag$2) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$2) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$2; - case mapCtorString: return mapTag$2; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$2; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length - }; - - var isObjectHasKey$1 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // just not to make my head hurt - var isEmpty = function (value) { return !isNotEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return isObjectHasKey$1(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$1(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - config[key] === undefined || (value[OPTIONAL_KEY] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY] = config[key], obj$1[TYPE_KEY] = value[TYPE_KEY], obj$1[OPTIONAL_KEY] = value[OPTIONAL_KEY] || false, obj$1[ENUM_KEY] = value[ENUM_KEY] || false, obj$1[CHECKER_KEY] = value[CHECKER_KEY] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray$1 = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY] ], - [( obj = {}, obj[TYPE_KEY] = toArray$1(value[TYPE_KEY]), obj[OPTIONAL_KEY] = value[OPTIONAL_KEY], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray$1(enumv, value) - } - return true - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false - } catch (e) { - return false - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD]) { - return value[ARGS_KEY] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // log('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) { - // log(ENUM_KEY, value[ENUM_KEY]) - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) { - // log(CHECKER_KEY, value[CHECKER_KEY]) - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - /// this is port back from the client to share across all projects - - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:check-options-async') - - /** - * Quick transform - * @param {object} config that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - var configToArgs = function (config, appProps) { - return Promise.resolve( - prepareArgsForValidation(config, appProps) - ) - }; - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsAsync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return configToArgs(config, appProps) - .then(function (args1) { return runValidation(args1, cb); }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) - } - - // create function to construct the config entry so we don't need to keep building object - // import checkIsBoolean from '../boolean' - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfig.apply(null, [value, type, o, e, c, a]) - }; - - /** - * construct the actual end user method, rename with prefix get since 1.5.2 - * @param {function} validateSync validation method - * @return {function} for performaning the actual valdiation - */ - var getCheckConfigAsync = function(validateSync) { - /** - * We recreate the method here to avoid the circlar import - * @param {object} config user supply configuration - * @param {object} appProps mutation options - * @param {object} [constantProps={}] optional: immutation options - * @return {object} all checked configuration - */ - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - // construct the final output 1.5.2 - var checkConfigAsync = getCheckConfigAsync(validateSync); - - // move the get logger stuff here - - // it does nothing - var dummyLogger = function () {}; - - /** - * re-use the debugOn prop to control this log method - * @param {object} opts configuration - * @return {function} the log function - */ - var getLogger = function (opts) { - var debugOn = opts.debugOn; - if (debugOn) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Reflect.apply(console.info, console, ['[jsonql-ws-client-core]' ].concat( args)); - } - } - return dummyLogger - }; - - /** - * Make sure there is a log method - * @param {object} opts configuration - * @return {object} opts - */ - var getLogFn = function (opts) { - var log = opts.log; // 1.3.9 if we pass a log method here then we use this - if (!log || typeof log !== 'function') { - return getLogger(opts) - } - opts.log('---> getLogFn user supplied log function <---', opts); - return log - }; - - // group all the repetitive message here - - var TAKEN_BY_OTHER_TYPE_ERR = 'You are trying to register an event already been taken by other type:'; - - // use constants for type - var ON_TYPE = 'on'; - var ONLY_TYPE = 'only'; - var ONCE_TYPE = 'once'; - var ONLY_ONCE_TYPE = 'onlyOnce'; - var NEG_RETURN = -1; - - var AVAILABLE_TYPES = [ - ON_TYPE, - ONLY_TYPE, - ONCE_TYPE, - ONLY_ONCE_TYPE - ]; - // the type which the callMax can execute on - var ON_MAX_TYPES = [ - ON_TYPE, - ONLY_TYPE - ]; - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - /** - * wrapper to make sure it string - * @param {*} input whatever - * @return {string} output - */ - function hashCode2Str(s) { - return hashCode(s) + '' - } - - /** - * Just check if a pattern is an RegExp object - * @param {*} pat whatever - * @return {boolean} false when its not - */ - function isRegExp(pat) { - return pat instanceof RegExp - } - - /** - * check if its string - * @param {*} arg whatever - * @return {boolean} false when it's not - */ - function isString$2(arg) { - return typeof arg === 'string' - } - - /** - * check if it's an integer - * @param {*} num input number - * @return {boolean} - */ - function isInt(num) { - if (isString$2(num)) { - throw new Error("Wrong type, we want number!") - } - return !isNaN(parseInt(num)) - } - - /** - * Find from the array by matching the pattern - * @param {*} pattern a string or RegExp object - * @return {object} regex object or false when we can not id the input - */ - function getRegex(pattern) { - switch (true) { - case isRegExp(pattern) === true: - return pattern - case isString$2(pattern) === true: - return new RegExp(pattern) - default: - return false - } - } - - - /** - * in array - * @param {array} arr to search - * @param {*} prop to search - */ - var inArray$2 = function (arr, prop) { return !!arr.filter(function (v) { return prop === v; }).length; }; - - // Create two WeakMap store as a private keys - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - // setup a base class to put all the don't know where to put methods - - var BaseClass = function BaseClass() {}; - - var prototypeAccessors = { $name: { configurable: true },is: { configurable: true } }; - - /** - * logger function for overwrite - */ - BaseClass.prototype.logger = function logger () {}; - - // for id if the instance is this class - prototypeAccessors.$name.get = function () { - return 'to1source-event' - }; - - // take this down in the next release - prototypeAccessors.is.get = function () { - return this.$name - }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - BaseClass.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (!isString$2(e)) { - this$1.logger('(validateEvt)', e); - - throw new Error(("Event name must be string type! we got " + (typeof e))) - } - }); - - return true - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - BaseClass.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - - return true - } - } - throw new Error(("callback required to be function type! we got " + (typeof callback))) - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - BaseClass.prototype.validateType = function validateType (type) { - this.validateEvt(type); - - return !!AVAILABLE_TYPES.filter(function (t) { return type === t; }).length - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - BaseClass.prototype.run = function run (callback, payload, ctx) { - this.logger('(run) callback:', callback, 'payload:', payload, 'context:', ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - - return this.$done // return it here first - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - BaseClass.prototype.hashFnToKey = function hashFnToKey (fn) { - - return hashCode2Str(fn.toString()) - }; - - Object.defineProperties( BaseClass.prototype, prototypeAccessors ); - - // making all the functionality on it's own - - var SuspendClass = /*@__PURE__*/(function (BaseClass) { - function SuspendClass() { - BaseClass.call(this); - // suspend, release and queue - this.__suspend_state__ = null; - // to do this proper we don't use a new prop to hold the event name pattern - // @1.2.2 this become an array so we can hold different events - this.__pattern__ = []; - // key value pair store to store the queued calls - this.queueStore = new Set(); - } - - if ( BaseClass ) SuspendClass.__proto__ = BaseClass; - SuspendClass.prototype = Object.create( BaseClass && BaseClass.prototype ); - SuspendClass.prototype.constructor = SuspendClass; - - var prototypeAccessors = { $queues: { configurable: true } }; - - /** - * start suspend - * @return {void} - */ - SuspendClass.prototype.$suspend = function $suspend () { - this.logger("---> SUSPEND ALL OPS <---"); - this.__suspend__(true); - }; - - /** - * release the queue - * @return {void} - */ - SuspendClass.prototype.$release = function $release () { - this.logger("---> RELEASE ALL SUSPENDED QUEUE <---"); - this.__suspend__(false); - }; - - /** - * suspend event by pattern - * @param {array.} patterns the pattern search matches the event name - * @return {array} if the pattern return is registered or not - */ - SuspendClass.prototype.$suspendEvent = function $suspendEvent () { - var this$1 = this; - var patterns = [], len = arguments.length; - while ( len-- ) patterns[ len ] = arguments[ len ]; - - return patterns.map(function (pattern) { - var regex = getRegex(pattern); - if (isRegExp(regex)) { - // check if it's already added - if (this$1.__isPatternRegisterd(regex) === false) { - this$1.__pattern__.push(regex); - - return this$1.__pattern__.length - } - return false - } - throw new Error(("We expect a pattern variable to be string or RegExp, but we got \"" + (typeof regex) + "\" instead")) - }) - }; - - /** - * This is pair with $suspnedEvent to release part of the event queue by the pattern (eventName) - * @param {array.<*>} patterns a eventName of partial eventName to create a RegExp - * @return {number} should be the number of queue got released - */ - SuspendClass.prototype.$releaseEvent = function $releaseEvent () { - var this$1 = this; - var patterns = [], len = arguments.length; - while ( len-- ) patterns[ len ] = arguments[ len ]; - - return patterns.map(function (pattern) { - this$1.logger("($releaseEvent)", pattern); - var regex = getRegex(pattern); - if (isRegExp(regex) && this$1.__isPatternRegisterd(regex)) { - var self = this$1; - - return this$1.__getToReleaseQueue(regex) - .map(function (args, i) { - - Reflect.apply(self.$trigger, self, args); - - return i - }).reduce(function (a, b) { return ++b; }, 0) - } - - this$1.logger('$releaseEvent throw error ==========================>', this$1.__pattern__, regex); - throw new Error(("We expect a pattern variable to be string or RegExp, but we got \"" + (typeof regex) + "\" instead")) - }) - .reduce(function (x, y) { return x + y; }, 0) - }; - - /** - * queuing call up when it's in suspend mode, - * it's currently suspending then add to store then the $trigger will do nothing - * @param {string} evt the event name - * @param {*} args unknown number of arguments - * @return {boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue (evt) { - var args = [], len = arguments.length - 1; - while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; - - switch (true) { - case this.__suspend_state__ === true: // this will take priority over the pattern - - return this.__addToQueueStore(evt, args) - case !!this.__pattern__.length === true: - // check the pattern and decide if we want to suspend it or not - if (!!this.__pattern__.filter(function (p) { return p.test(evt); }).length) { - - return this.__addToQueueStore(evt, args) - } - this.logger(("($queue) " + evt + " NOT added to $queueStore"), this.__pattern__); - - return false - default: - this.logger('($queue) get called NOTHING added'); - return false - } - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - - /** - * The reason is before we call $trigger we need to remove the pattern from queue - * otherwise, it will never get release - * @param {*} pattern to find the queue - * @return {array} queue to get execute - */ - SuspendClass.prototype.__getToReleaseQueue = function __getToReleaseQueue (regex) { - var this$1 = this; - - // first get the list of events in the queue store that match this pattern - var list = this.$queues - // first index is the eventName - .filter(function (content) { return regex.test(content[0]); }) - .map(function (content) { - this$1.logger(("[release] execute " + (content[0]) + " matches " + regex), content); - // we just remove it - this$1.queueStore.delete(content); - - return content - }); - if (list.length > 0) { - // we need to remove this event from the pattern queue array - this.__pattern__ = this.__pattern__.filter(function (p) { return p.toString() !== regex.toString(); }); - } - - return list - }; - - /** - * Wrapper method with a logger - * @param {*} evt - * @param {*} args - * @return {boolean} - */ - SuspendClass.prototype.__addToQueueStore = function __addToQueueStore (evt, args) { - this.logger(("($queue) " + evt + " added to $queueStore"), args); - - // @TODO should we check if this already added? - // what if that is a multiple call like $on - this.queueStore.add([evt].concat(args)); - - return true - }; - - /** - * check if certain pattern already registered in the queue - * @param {*} pattern - * @return {boolean} - */ - SuspendClass.prototype.__isPatternRegisterd = function __isPatternRegisterd (pattern) { - // this is a bit of a hack to compare two regex Object - return !!this.__pattern__.filter(function (p) { return ( - p.toString() === pattern.toString() - ); }).length - }; - - /** - * to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - SuspendClass.prototype.__suspend__ = function __suspend__ (value) { - if (typeof value === 'boolean') { - var lastValue = this.__suspend_state__; - this.__suspend_state__ = value; - this.logger(("($suspend) Change from \"" + lastValue + "\" --> \"" + value + "\"")); - if (lastValue === true && value === false) { - this.__release__(); - } - } else { - throw new Error(("$suspend only accept Boolean value! we got " + (typeof value))) - } - }; - - /** - * Release the queue, this is a wholesale release ALL - * @return {int} size if any - */ - SuspendClass.prototype.__release__ = function __release__ () { - var this$1 = this; - - var size = this.queueStore.size; - var pattern = this.__pattern__; - this.__pattern__ = []; - - this.logger(("(release) was called with " + size + (pattern.length ? ' for "' + pattern.join(',') + '"': '') + " item" + (size > 1 ? 's' : ''))); - - if (size > 0) { - var queue = Array.from(this.queueStore); - this.logger('(release queue)', queue); - - queue.forEach(function (args) { - this$1.logger(("[release] execute " + (args[0])), args); - - Reflect.apply(this$1.$trigger, this$1, args); - }); - - this.queueStore.clear(); - this.logger(("Release size " + (this.queueStore.size))); - } - - return size - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors ); - - return SuspendClass; - }(BaseClass)); - - // break up the main file because its getting way too long - - var StoreService = /*@__PURE__*/(function (SuspendClass) { - function StoreService(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - // this is the new throw away map - this.maxCountStore = new Map(); - } - - if ( SuspendClass ) StoreService.__proto__ = SuspendClass; - StoreService.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - StoreService.prototype.constructor = StoreService; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * We need this to pre-check the store, otherwise - * the execution will be unable to determine the number of calls - * @param {string} evtName event name - * @return {number} the count of this store - */ - StoreService.prototype.getMaxStore = function getMaxStore (evtName) { - return this.maxCountStore.get(evtName) || NEG_RETURN - }; - - /** - * This is one stop shop to check and munipulate the maxStore - * @param {*} evtName - * @param {*} [max=null] - * @return {number} when return -1 means removed - */ - StoreService.prototype.checkMaxStore = function checkMaxStore (evtName, max) { - if ( max === void 0 ) max = null; - - this.logger("==========================================="); - this.logger('checkMaxStore start', evtName, max); - // init the store - if (max !== null && isInt(max)) { - // because this is the setup phrase we just return the max value - this.maxCountStore.set(evtName, max); - this.logger(("Setup max store for " + evtName + " with " + max)); - return max - } - if (max === null) { - // first check if this exist in the maxStore - var value = this.getMaxStore(evtName); - - this.logger('getMaxStore value', value); - - if (value !== NEG_RETURN) { - if (value > 0) { - --value; - } - if (value > 0) { - this.maxCountStore.set(evtName, value); // just update the value - } else { - this.maxCountStore.delete(evtName); // just remove it - this.logger(("remove " + evtName + " from maxStore")); - return NEG_RETURN - } - } - return value - } - throw new Error(("Expect max to be an integer, but we got " + (typeof max) + " " + max)) - }; - - /** - * Wrap several get filter ops together to return the callback we are looking for - * @param {string} evtName to search for - * @return {array} empty array when not found - */ - StoreService.prototype.searchMapEvt = function searchMapEvt (evtName) { - var evts = this.$get(evtName, true); // return in full - var search = evts.filter(function (result) { - var type = result[3]; - - return inArray$2(ON_MAX_TYPES, type) - }); - - return search.length ? search : [] - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - StoreService.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - - if (store.has(evt)) { - var content = store.get(evt); - this.logger(("(takeFromStore) has \"" + evt + "\""), content); - store.delete(evt); - - return content - } - - return false - } - throw new Error(("\"" + storeName + "\" is not supported!")) - }; - - /** - * This was part of the $get. We take it out - * so we could use a regex to remove more than one event - * @param {object} store the store to return from - * @param {string} evt event name - * @param {boolean} full return just the callback or everything - * @return {array|boolean} false when not found - */ - StoreService.prototype.findFromStore = function findFromStore (evt, store, full) { - if ( full === void 0 ) full = false; - - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l - } - var callback = l[1]; - - return callback - }) - } - return false - }; - - /** - * Similar to the findFromStore, but remove - * @param {string} evt event name - * @param {object} store the store to remove from - * @return {boolean} false when not found - */ - StoreService.prototype.removeFromStore = function removeFromStore (evt, store) { - if (store.has(evt)) { - this.logger('($off)', evt); - - store.delete(evt); - - return true - } - return false - }; - - /** - * Take out from addToStore for reuse - * @param {object} store the store to use - * @param {string} evt event name - * @return {object} the set within the store - */ - StoreService.prototype.getStoreSet = function getStoreSet (store, evt) { - var fnSet; - if (store.has(evt)) { - this.logger(("(addToStore) \"" + evt + "\" existed")); - fnSet = store.get(evt); - } else { - this.logger(("(addToStore) create new Set for \"" + evt + "\"")); - // this is new - fnSet = new Set(); - } - return fnSet - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - StoreService.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet = this.getStoreSet(store, evt); - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger("(addToStore) insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - StoreService.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (li) { - var hash = li[0]; - return hash === args[0] - }).length - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - StoreService.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t - }).length - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - StoreService.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - - this.logger('(checkTypeInLazyStore)', store); - - if (store) { - - return !!Array - .from(store) - .filter(function (li) { - var t = li[2]; - return t !== type - }).length - } - - return false - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - StoreService.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger(("(addToNormalStore) try to add \"" + type + "\" --> \"" + evt + "\" to normal store")); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - - this.logger('(addToNormalStore)', ("\"" + type + "\" --> \"" + evt + "\" can add to normal store")); - - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - - return size - } - - return false - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - StoreService.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - this.logger(("(addToLazyStore) size: " + size)); - - return size - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - StoreService.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg] - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - Object.defineProperties( StoreService.prototype, prototypeAccessors ); - - return StoreService; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (StoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - StoreService.call(this, config); - } - - if ( StoreService ) EventService.__proto__ = StoreService; - EventService.prototype = Object.create( StoreService && StoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger(("($on) \"" + evt + "\" is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - return this.addToNormalStore(evt, type, callback, context) - } - this.logger(("($on) " + evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error((TAKEN_BY_OTHER_TYPE_ERR + " " + t)) - } - this$1.logger("($on)", ("call run \"" + evt + "\"")); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - - this.logger(("($on) return size " + size)); - return size - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - // let nStore = this.normalStore - if (lazyStoreContent === false) { - this.logger(("($once) \"" + evt + "\" is not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, ONCE_TYPE, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== ONCE_TYPE) { - throw new Error((TAKEN_BY_OTHER_TYPE_ERR + " " + t)) - } - this.logger('($once)', ("call run \"" + evt + "\"")); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - - if (!nStore.has(evt)) { - this.logger(("($only) \"" + evt + "\" add to normalStore")); - - added = this.addToNormalStore(evt, ONLY_TYPE, callback, context); - } - - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger(("($only) \"" + evt + "\" found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (li) { - var payload = li[0]; - var ctx = li[1]; - var t = li[2]; - if (t && t !== ONLY_TYPE) { - throw new Error((TAKEN_BY_OTHER_TYPE_ERR + " " + t)) - } - this$1.logger(("($only) call run \"" + evt + "\"")); - this$1.run(callback, payload, context || ctx); - }); - } - - return added - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD added in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger(("($onlyOnce) \"" + evt + "\" add to normalStore")); - - added = this.addToNormalStore(evt, ONLY_ONCE_TYPE, callback, context); - } - - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== ONLY_ONCE_TYPE) { - throw new Error((TAKEN_BY_OTHER_TYPE_ERR + " " + t)) - } - this.logger(("($onlyOnce) call run \"" + evt + "\"")); - - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added - }; - - /** - * change the way how it suppose to work, instead of create another new store - * We perform this check on the trigger end, so we set the number max - * whenever we call the callback, we increment a value in the store - * once it reaches that number we remove that event from the store, - * also this will not get add to the lazy store, - * which means the event must register before we can fire it - * therefore we don't have to deal with the backward check - * @param {string} evtName the event to get pre-registered - * @param {number} max pass the max amount of callback can add to this event - * @param {*} [ctx=null] the context the callback execute in - * @return {function} the event handler - */ - EventService.prototype.$max = function $max (evtName, max, ctx) { - if ( ctx === void 0 ) ctx = null; - - this.validateEvt(evtName); - if (isInt(max) && max > 0) { - // find this in the normalStore - var fnSet = this.$get(evtName, true); - if (fnSet !== false) { - var evts = this.searchMapEvt(evtName); - if (evts.length) { - // should only have one anyway - var ref = evts[0]; - var type = ref[3]; - // now init the max store - var value = this.checkMaxStore(evtName, max); - var _self = this; - /** - * construct the callback - * @param {array<*>} args - * @return {number} - */ - return function executeMaxCall() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var ctn = _self.getMaxStore(evtName); - var value = NEG_RETURN; - if (ctn > 0) { - var fn = _self.$call(evtName, type, ctx); - Reflect.apply(fn, _self, args); - - value = _self.checkMaxStore(evtName); - if (value === NEG_RETURN) { - _self.$off(evtName); - return NEG_RETURN - } - } - return value - } - } - } - // change in 1.1.1 because we might just call it without knowing if it's register or not - this.logger(("The " + evtName + " is not registered, can not execute non-existing event at the moment")); - return NEG_RETURN - } - throw new Error(("Expect max to be an integer and greater than zero! But we got [" + (typeof max) + "]" + max + " instead")) - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {*} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = ON_TYPE; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - - this.logger("($replace)", evt, callback); - - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger) normalStore', nStore); - if (nStore.has(evt)) { - this.logger(("($trigger) \"" + evt + "\" found")); - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - if (added) { - this.logger(("($trigger) Currently suspended \"" + evt + "\" added to queue, nothing executed. Exit now.")); - return false // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - // let hasOnly = false - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var _type = ref[3]; - this.logger(("($trigger) call run for " + type + ":" + evt)); - - this.run(callback, payload, context || ctx); - - if (_type === 'once' || _type === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter aroun - * @NOTE breaking change: v1.9.1 it return an function to accept the params as spread - * @param {string} evt event name - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var ctx = this; - - return function executeCall() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var _args = [evt, args, context, type]; - - return Reflect.apply(ctx.$trigger, ctx, _args) - } - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - var this$1 = this; - - // @TODO we will allow a regex pattern to mass remove event - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - - return !!stores - .filter(function (store) { return store.has(evt); }) - .map(function (store) { return this$1.removeFromStore(evt, store); }) - .length - }; - - /** - * return all the listener bind to that event name - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - // @TODO should we allow the same Regex to search for all? - this.validateEvt(evt); - var store = this.normalStore; - return this.findFromStore(evt, store, full) - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done) set value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - this.logger('($done) get result:', this.result); - if (this.keep) { - return this.result[this.result.length - 1] - } - return this.result - }; - - /** - * Take a look inside the stores - * @param {number|null} idx of the store, null means all - * @return {void} - */ - EventService.prototype.$debug = function $debug (idx) { - var this$1 = this; - if ( idx === void 0 ) idx = null; - - var names = ['lazyStore', 'normalStore']; - var stores = [this.lazyStore, this.normalStore]; - if (stores[idx]) { - this.logger(names[idx], stores[idx]); - } else { - stores.map(function (store, i) { - this$1.logger(names[i], store); - }); - } - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(StoreService)); - - // default - - // this will generate a event emitter and will be use everywhere - // create a clone version so we know which one we actually is using - var JsonqlWsEvt = /*@__PURE__*/(function (EventEmitterClass) { - function JsonqlWsEvt(logger) { - if (typeof logger !== 'function') { - throw new Error("Just die here the logger is not a function!") - } - logger("---> Create a new EventEmitter <---"); - // this ee will always come with the logger - // because we should take the ee from the configuration - EventEmitterClass.call(this, { logger: logger }); - } - - if ( EventEmitterClass ) JsonqlWsEvt.__proto__ = EventEmitterClass; - JsonqlWsEvt.prototype = Object.create( EventEmitterClass && EventEmitterClass.prototype ); - JsonqlWsEvt.prototype.constructor = JsonqlWsEvt; - - var prototypeAccessors = { name: { configurable: true } }; - - prototypeAccessors.name.get = function () { - return 'jsonql-ws-client-core' - }; - - Object.defineProperties( JsonqlWsEvt.prototype, prototypeAccessors ); - - return JsonqlWsEvt; - }(EventService)); - - /** - * getting the event emitter - * @param {object} opts configuration - * @return {object} the event emitter instance - */ - var getEventEmitter = function (opts) { - var log = opts.log; - var eventEmitter = opts.eventEmitter; - - if (eventEmitter) { - log("eventEmitter is:", eventEmitter.name); - return eventEmitter - } - - return new JsonqlWsEvt( opts.log ) - }; - - // group all the small functions here - - - /** - * WebSocket is strict about the path, therefore we need to make sure before it goes in - * @param {string} url input url - * @return {string} url with correct path name - */ - var fixWss = function (url) { - var pattern = new RegExp('^(http|https)\:\/\/', 'i'); - var result = url.match(pattern); - if (result && result.length) { - var target = result[1].toLowerCase(); - var replacement = target === 'https' ? 'wss' : 'ws'; - - return url.replace(pattern, replacement + '://') - } - - return url - }; - - - /** - * get a stock host name from browser - */ - var getHostName = function () { - try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - throw new JsonqlValidationError(e) - } - }; - - /** - * Unbind the event, this should only get call when it's disconnected - * @param {object} ee EventEmitter - * @param {string} namespace - * @return {void} - */ - var clearMainEmitEvt = function (ee, namespace) { - var nsps = toArray(namespace); - nsps.forEach(function (n) { - ee.$off(createEvt(n, EMIT_REPLY_TYPE)); - }); - }; - - // constants - - var EMIT_EVT = EMIT_REPLY_TYPE; - - var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; - - var MY_NAMESPACE = 'myNamespace'; - - // breaking it up further to share between methods - - /** - * break out to use in different places to handle the return from server - * @param {object} data from server - * @param {function} resolver NOT from promise - * @param {function} rejecter NOT from promise - * @return {void} nothing - */ - function respondHandler(data, resolver, rejecter) { - if (isObjectHasKey(data, ERROR_KEY)) { - // debugFn('-- rejecter called --', data[ERROR_KEY]) - rejecter(data[ERROR_KEY]); - } else if (isObjectHasKey(data, DATA_KEY)) { - // debugFn('-- resolver called --', data[DATA_KEY]) - // @NOTE we change from calling it directly to use reflect - // this could have another problem later when the return data is no in an array structure - Reflect.apply(resolver, null, [].concat( data[DATA_KEY] )); - } else { - // debugFn('-- UNKNOWN_RESULT --', data) - rejecter({message: UNKNOWN_RESULT, error: data}); - } - } - - // the actual trigger call method - - /** - * just wrapper - * @param {object} ee EventEmitter - * @param {string} namespace where this belongs - * @param {string} resolverName resolver - * @param {array} args arguments - * @param {function} log function - * @return {void} nothing - */ - function actionCall(ee, namespace, resolverName, args, log) { - if ( args === void 0 ) args = []; - - // reply event - var outEventName = createEvt(namespace, EMIT_REPLY_TYPE); - - log(("actionCall: " + outEventName + " --> " + resolverName), args); - // This is the out going call - ee.$trigger(outEventName, [resolverName, toArray(args)]); - - // then we need to listen to the event callback here as well - return new Promise(function (resolver, rejecter) { - var inEventName = createEvt(namespace, resolverName, ON_RESULT_FN_NAME); - // this cause the onResult got the result back first - // and it should be the promise resolve first - // @TODO we need to rewrote the respondHandler to change the problem stated above - ee.$on( - inEventName, - function actionCallResultHandler(result) { - log("got the first result", result); - respondHandler(result, resolver, rejecter); - } - ); - }) - } - - // setting up the send method - - /** - * pairing with the server vesrion SEND_MSG_FN_NAME - * last of the chain so only return the resolver (fn) - * This is now change to a getter / setter method - * and call like this: resolver.send(...args) - * @param {function} fn the resolver function - * @param {object} ee event emitter instance - * @param {string} namespace the namespace it belongs to - * @param {string} resolverName name of the resolver - * @param {object} params from contract - * @param {function} log a logger function - * @return {function} return the resolver itself - */ - var setupSendMethod = function (fn, ee, namespace, resolverName, params, log) { return ( - objDefineProps( - fn, - SEND_MSG_FN_NAME, - nil, - function sendHandler() { - log("running call getter method"); - // let _log = (...args) => Reflect.apply(console.info, console, ['[SEND]'].concat(args)) - /** - * This will follow the same pattern like the resolver - * @param {array} args list of unknown argument follow the resolver - * @return {promise} resolve the result - */ - return function sendCallback() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return validateAsync$1(args, params.params, true) - .then(function (_args) { - // @TODO check the result - // because the validation could failed with the list of fail properties - log('execute send', namespace, resolverName, _args); - return actionCall(ee, namespace, resolverName, _args, log) - }) - .catch(function (err) { - // @TODO it shouldn't be just a validation error - // it could be server return error, so we need to check - // what error we got back here first - log('send error', err); - // @TODO it might not an validation error need the finalCatch here - ee.$call( - createEvt(namespace, resolverName, ON_ERROR_FN_NAME), - [new JsonqlValidationError(resolverName, err)] - ); - }) - } - }) - ); }; - - // break up the original setup resolver method here - - - /** - * moved back from generator-methods - * create the actual function to send message to server - * @param {object} ee EventEmitter instance - * @param {string} namespace this resolver end point - * @param {string} resolverName name of resolver as event name - * @param {object} params from contract - * @param {function} log pass the log function - * @return {function} resolver - */ - function createResolver(ee, namespace, resolverName, params, log) { - // note we pass the new withResult=true option - return function resolver() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return validateAsync$1(args, params.params, true) - .then(function (_args) { return actionCall(ee, namespace, resolverName, _args, log); }) - .catch(finalCatch) - } - } - - /** - * The first one in the chain, just setup a namespace prop - * the rest are passing through - * @param {function} fn the resolver function - * @param {object} ee the event emitter - * @param {string} resolverName what it said - * @param {object} params for resolver from contract - * @param {function} log the logger function - * @return {array} - */ - var setupNamespace = function (fn, ee, namespace, resolverName, params, log) { return [ - injectToFn(fn, MY_NAMESPACE, namespace), - ee, - namespace, - resolverName, - params, - log - ]; }; - - /** - * onResult handler - */ - var setupOnResult = function (fn, ee, namespace, resolverName, params, log) { return [ - objDefineProps(fn, ON_RESULT_FN_NAME, function(resultCallback) { - if (isFunc(resultCallback)) { - ee.$on( - createEvt(namespace, resolverName, ON_RESULT_FN_NAME), - function resultHandler(result) { - respondHandler(result, resultCallback, function (error) { - log(("Catch error: \"" + resolverName + "\""), error); - ee.$trigger( - createEvt(namespace, resolverName, ON_ERROR_FN_NAME), - error - ); - }); - } - ); - } - }), - ee, - namespace, - resolverName, - params, - log - ]; }; - - /** - * we do need to add the send prop back because it's the only way to deal with - * bi-directional data stream - */ - var setupOnMessage = function (fn, ee, namespace, resolverName, params, log) { return [ - objDefineProps(fn, ON_MESSAGE_FN_NAME, function(messageCallback) { - // we expect this to be a function - if (isFunc(messageCallback)) { - // did that add to the callback - var onMessageCallback = function (args) { - log("onMessageCallback", args); - respondHandler( - args, - messageCallback, - function (error) { - log(("Catch error: \"" + resolverName + "\""), error); - ee.$trigger( - createEvt(namespace, resolverName, ON_ERROR_FN_NAME), - error - ); - }); - }; - // register the handler for this message event - ee.$only( - createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME), - onMessageCallback - ); - } - }), - ee, - namespace, - resolverName, - params, - log - ]; }; - - /** - * ON_ERROR_FN_NAME handler - */ - var setupOnError = function (fn, ee, namespace, resolverName, params, log) { return [ - objDefineProps(fn, ON_ERROR_FN_NAME, function(resolverErrorHandler) { - if (isFunc(resolverErrorHandler)) { - // please note ON_ERROR_FN_NAME can add multiple listners - ee.$only( - createEvt(namespace, resolverName, ON_ERROR_FN_NAME), - resolverErrorHandler - ); - } - }), - ee, - namespace, - resolverName, - params, - log - ]; }; - - /** - * Add extra property / listeners to the resolver - * @param {string} namespace where this belongs - * @param {string} resolverName name as event name - * @param {object} params from contract - * @param {function} fn resolver function - * @param {object} ee EventEmitter - * @param {function} log function - * @return {function} resolver - */ - function setupResolver(namespace, resolverName, params, fn, ee, log) { - var fns = [ - setupNamespace, - setupOnResult, - setupOnMessage, - setupOnError, - setupSendMethod - ]; - var executor = Reflect.apply(chainFns, null, fns); - // get the executor - return executor(fn, ee, namespace, resolverName, params, log) - } - - // put all the resolver related methods here to make it more clear - - /** - * step one get the clientmap with the namespace - * @param {object} opts configuration - * @param {object} ee EventEmitter - * @param {object} nspGroup resolvers index by their namespace - * @return {promise} resolve the clientmapped, and start the chain - */ - function generateResolvers(opts, ee, nspGroup) { - var log = opts.log; - var client= {}; - - for (var namespace in nspGroup) { - var list = nspGroup[namespace]; - for (var resolverName in list) { - // resolverNames.push(resolverName) - var params = list[resolverName]; - var fn = createResolver(ee, namespace, resolverName, params, log); - // this should set as a getter therefore can not be overwrite by accident - client = injectToFn( - client, - resolverName, - setupResolver(namespace, resolverName, params, fn, ee, log) - ); - } - } - // resolve the clientto start the chain - // chain the result to allow the chain processing - return [ client, opts, ee, nspGroup ] - } - - // move from generator-methods - - /** - * This event will fire when the socket.io.on('connection') and ws.onopen - * @param {object} client client itself - * @param {object} opts configuration - * @param {object} ee Event Emitter - * @return {array} [ obj, opts, ee ] - */ - function setupOnReadyListener(client, opts, ee) { - return [ - objDefineProps( - client, - ON_READY_FN_NAME, - function onReadyCallbackHandler(onReadyCallback) { - if (isFunc(onReadyCallback)) { - // reduce it down to just one flat level - // @2020-03-19 only allow ONE onReady callback otherwise - // it will get fire multiple times which is not what we want - ee.$only(ON_READY_FN_NAME, onReadyCallback); - } - } - ), - opts, - ee - ] - } - - /** - * The problem is the namespace can have more than one - * and we only have on onError message - * @param {object} clientthe client itself - * @param {object} opts configuration - * @param {object} ee Event Emitter - * @param {object} nspGroup namespace keys - * @return {array} [obj, opts, ee] - */ - function setupNamespaceErrorListener(client, opts, ee, nspGroup) { - return [ - objDefineProps( - client, - ON_ERROR_FN_NAME, - function namespaceErrorCallbackHandler(namespaceErrorHandler) { - if (isFunc(namespaceErrorHandler)) { - // please note ON_ERROR_FN_NAME can add multiple listners - for (var namespace in nspGroup) { - // this one is very tricky, we need to make sure the trigger is calling - // with the namespace as well as the error - ee.$on(createEvt(namespace, ON_ERROR_FN_NAME), namespaceErrorHandler); - } - } - } - ), - opts, - ee - ] - } - - // take out from the resolver-methods - - - /** - * @UPDATE it might be better if we decoup the two http-client only emit a login event - * Here should catch it and reload the ws client @TBC - * break out from createAuthMethods to allow chaining call - * @param {object} obj the main client object - * @param {object} opts configuration - * @param {object} ee event emitter - * @return {array} [ obj, opts, ee ] what comes in what goes out - */ - var setupLoginHandler = function (obj, opts, ee) { return [ - injectToFn(obj, opts.loginHandlerName, function loginHandler(token) { - if (token && isString$1(token)) { - opts.log(("Received " + LOGIN_EVENT_NAME + " with " + token)); - // @TODO add the interceptor hook - return ee.$trigger(LOGIN_EVENT_NAME, [token]) - } - // should trigger a global error instead @TODO - throw new JsonqlValidationError(opts.loginHandlerName, ("Unexpected token " + token)) - }), - opts, - ee - ]; }; - - - /** - * break out from createAuthMethods to allow chaining call - final in chain - * @param {object} obj the main client object - * @param {object} opts configuration - * @param {object} ee event emitter - * @return {array} [ obj, opts, ee ] what comes in what goes out - */ - var setupLogoutHandler = function (obj, opts, ee) { return [ - injectToFn(obj, opts.logoutHandlerName, function logoutHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - ee.$trigger(LOGOUT_EVENT_NAME$1, args); - }), - opts, - ee - ]; }; - - - /** - * This event will fire when the socket.io.on('connection') and ws.onopen - * Plus this will check if it's the private namespace that fired the event - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @return {array} [ obj, opts, ee] what comes in what goes out - */ - var setupOnLoginhandler = function (obj, opts, ee) { return [ - objDefineProps(obj, ON_LOGIN_FN_NAME, function onLoginCallbackHandler(onLoginCallback) { - if (isFunc(onLoginCallback)) { - // only one callback can registered with it, TBC - // Should this be a $onlyOnce listener after the logout - // we add it back? - ee.$only(ON_LOGIN_FN_NAME, onLoginCallback); - } - }), - opts, - ee - ]; }; - - // @TODO future feature setup switch user - - - /** - * Create auth related methods - * @param {object} obj the client itself - * @param {object} opts configuration - * @param {object} ee Event Emitter - * @return {array} [ obj, opts, ee ] what comes in what goes out - */ - function setupAuthMethods(obj, opts, ee) { - return chainFns( - setupLoginHandler, - setupLogoutHandler, - setupOnLoginhandler - )(obj, opts, ee) - } - - // this is a new method that will create several - - /** - * Set up the CONNECTED_PROP_KEY to the client - * @param {*} client - * @param {*} opts - * @param {*} ee - */ - function setupConnectPropKey(client, opts, ee) { - var log = opts.log; - log('[1] setupConnectPropKey'); - // we just inject a helloWorld method here - // set up the init state of the connect - client = injectToFn(client, CONNECTED_PROP_KEY , false, true); - return [ client, opts, ee ] - } - - - /** - * setup listener to the connect event - * @param {*} client - * @param {*} opts - * @param {*} ee - */ - function setupConnectEvtListener(client, opts, ee) { - // @TODO do what at this point? - var log = opts.log; - - log("[2] setupConnectEvtListener"); - - ee.$on(CONNECT_EVENT_NAME, function() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - log("setupConnectEvtListener pass and do nothing at the moment", args); - }); - - return [client, opts, ee] - } - - /** - * setup listener to the connected event - * @param {*} client - * @param {*} opts - * @param {*} ee - */ - function setupConnectedEvtListener(client, opts, ee) { - var log = opts.log; - - log("[3] setupConnectedEvtListener"); - - ee.$on(CONNECTED_EVENT_NAME, function() { - var obj; - - client[CONNECTED_PROP_KEY] = true; - // new action to take release the holded event queue - var ctn = ee.$release(); - - log("CONNECTED_EVENT_NAME", true, 'queue count', ctn); - - return ( obj = {}, obj[CONNECTED_PROP_KEY] = true, obj ) - }); - - return [client, opts, ee] - } - - /** - * Listen to the disconnect event and set the property to the client - * @param {*} client - * @param {*} opts - * @param {*} ee - */ - function setupDisconnectListener(client, opts, ee) { - var log = opts.log; - - log("[4] setupDisconnectListener"); - - ee.$on(DISCONNECT_EVENT_NAME, function() { - var obj; - - client[CONNECTED_PROP_KEY] = false; - log("CONNECTED_EVENT_NAME", false); - - return ( obj = {}, obj[CONNECTED_PROP_KEY] = false, obj ) - }); - - return [client, opts, ee] - } - - /** - * disconnect action - * @param {*} client - * @param {*} opts - * @param {*} ee - * @return {object} this is the final step to return the client - */ - function setupDisconectAction(client, opts, ee) { - var disconnectHandlerName = opts.disconnectHandlerName; - var log = opts.log; - log("[5] setupDisconectAction"); - - return injectToFn( - client, - disconnectHandlerName, - function disconnectHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - ee.$trigger(DISCONNECT_EVENT_NAME, args); - } - ) - } - - /** - * this is the new method that setup the intercom handler - * also this serve as the final call in the then chain to - * output the client - * @param {object} client the client - * @param {object} opts configuration - * @param {object} ee the event emitter - * @return {object} client - */ - function setupInterCom(client, opts, ee) { - var fns = [ - setupConnectPropKey, - setupConnectEvtListener, - setupConnectedEvtListener, - setupDisconnectListener, - setupDisconectAction - ]; - - var executor = Reflect.apply(chainFns, null, fns); - return executor(client, opts, ee) - } - - // The final step of the setup before it returns the client - - /** - * The final step to return the client - * @param {object} obj the client - * @param {object} opts configuration - * @param {object} ee the event emitter - * @return {object} client - */ - function setupFinalStep(obj, opts, ee) { - - var client = setupInterCom(obj, opts, ee); - // opts.log(`---> The final step to return the ws-client <---`) - // add some debug functions - client.verifyEventEmitter = function () { return ee.is; }; - // we add back the two things into the client - // then when we do integration, we run it in reverse, - // create the ws client first then the host client - client.eventEmitter = opts.eventEmitter; - client.log = opts.log; - - // now at this point, we are going to call the connect event - ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]); // just passing back the entire opts object - // also we can release the queue here - if (opts[SUSPEND_EVENT_PROP_KEY] === true) { - opts.$releaseNamespace(); - } - - return client - } - - // resolvers generator - - /** - * This is the starting point of binding callable method to the - * ws, and we have to determine which is actually active - * if enableAuth but we don't have a token, when the connection - * to ws establish we only release the public related event - * and the private one remain hold until the LOGIN_EVENT get trigger - * @param {object} opts configuration - * @param {object} nspMap resolvers index by their namespace - * @param {object} ee EventEmitter - * @return {object} of resolvers - * @public - */ - function callersGenerator(opts, nspMap, ee) { - - - var fns = [ - generateResolvers, - setupOnReadyListener, - setupNamespaceErrorListener - ]; - if (opts.enableAuth) { - // there is a problem here, when this is a public namespace - // it should not have a login logout event attach to it - fns.push(setupAuthMethods); - } - // we will always get back the [ obj, opts, ee ] - // then we only return the obj (wsClient) - // This has move outside of here, into the main method - // the reason is we could switch around the sequence much easier - fns.push(setupFinalStep); - // stupid reaon!!! - var executer = Reflect.apply(chainFns, null, fns); - // run it - return executer(opts, ee, nspMap[NSP_GROUP]) - } - - var obj, obj$1; - - - - var configCheckMap = {}; - configCheckMap[STANDALONE_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); - configCheckMap[DEBUG_ON_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); - configCheckMap[LOGIN_FN_NAME_PROP_KEY] = createConfig$1(LOGIN_FN_NAME, [STRING_TYPE]); - configCheckMap[LOGOUT_FN_NAME_PROP_KEY] = createConfig$1(LOGOUT_FN_NAME, [STRING_TYPE]); - configCheckMap[DISCONNECT_FN_NAME_PROP_KEY] = createConfig$1(DISCONNECT_FN_NAME, [STRING_TYPE]); - configCheckMap[SWITCH_USER_FN_NAME_PROP_KEY] = createConfig$1(SWITCH_USER_FN_NAME, [STRING_TYPE]); - configCheckMap[HOSTNAME_PROP_KEY] = createConfig$1(false, [STRING_TYPE]); - configCheckMap[NAMESAPCE_PROP_KEY] = createConfig$1(JSONQL_PATH, [STRING_TYPE]); - configCheckMap[WS_OPT_PROP_KEY] = createConfig$1({}, [OBJECT_TYPE]); - configCheckMap[CONTRACT_PROP_KEY] = createConfig$1({}, [OBJECT_TYPE], ( obj = {}, obj[CHECKER_KEY] = isContract, obj )); - configCheckMap[ENABLE_AUTH_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); - configCheckMap[TOKEN_PROP_KEY] = createConfig$1(false, [STRING_TYPE]); - configCheckMap[CSRF_PROP_KEY] = createConfig$1(CSRF_HEADER_KEY, [STRING_TYPE]); - configCheckMap[SUSPEND_EVENT_PROP_KEY] = createConfig$1(false, [BOOLEAN_TYPE]); - - // socket client - var socketCheckMap = {}; - socketCheckMap[SOCKET_TYPE_PROP_KEY] = createConfig$1(null, [STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = SOCKET_TYPE_CLIENT_ALIAS, obj$1 )); - - var wsCoreCheckMap = Object.assign(configCheckMap, socketCheckMap); - - // constant props - var wsCoreConstProps = {}; - wsCoreConstProps[USE_JWT_PROP_KEY] = true; - wsCoreConstProps.log = null; - wsCoreConstProps.eventEmitter = null; - wsCoreConstProps.nspClient = null; - wsCoreConstProps.nspAuthClient = null; - wsCoreConstProps.wssPath = ''; - wsCoreConstProps.publicNamespace = PUBLIC_KEY; - wsCoreConstProps.privateNamespace = PRIVATE_KEY; - - // create options - - - /** - * wrapper method to check this already did the pre check - * @param {object} config user supply config - * @param {object} defaultOptions for checking - * @param {object} constProps user supply const props - * @return {promise} resolve to the checked opitons - */ - function checkConfiguration(config, defaultOptions, constProps) { - var defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions); - var wsConstProps = Object.assign(wsCoreConstProps, constProps); - - return checkConfigAsync(config, defaultCheckMap, wsConstProps) - } - - /** - * Taking the `then` part from the method below - * @param {object} opts - * @return {promise} opts all done - */ - function postCheckInjectOpts(opts) { - - return Promise.resolve(opts) - .then(function (opts) { - if (!opts.hostname) { - opts.hostname = getHostName(); - } - // @TODO the contract now will supply the namespace information - // and we need to use that to group the namespace call - - opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType); - // get the log function here - opts.log = getLogFn(opts); - - opts.eventEmitter = getEventEmitter(opts); - - return opts - }) - } - - /** - * Don't want to make things confusing - * Breaking up the opts process in one place - * then generate the necessary parameter in another step - * @2020-3-20 here we suspend operation by it's namespace first - * Then in the framework part, after the connection establish we release - * the queue - * @param {object} opts checked --> merge --> injected - * @return {object} {opts, nspMap, ee} - */ - function createRequiredParams(opts) { - var nspMap = getNspInfoByConfig(opts); - var ee = opts.eventEmitter; - // @TODO here we are going to add suspend event to the namespace related methods - var log = opts.log; - var namespaces = nspMap.namespaces; - log("namespaces", namespaces); - // next we loop the namespace and suspend all the events prefix with namespace - if (opts[SUSPEND_EVENT_PROP_KEY] === true) { - // we create this as a function then we can call it again - opts.$suspendNamepsace = function () { return namespaces.forEach(function (namespace) { return ee.$suspendEvent(namespace); }); }; - // then we create a new method to releas the queue - // we prefix it with the $ to notify this is not a jsonql part methods - opts.$releaseNamespace = function () { return ee.$release(); }; - // now run it - opts.$suspendNamepsace(); - } - - return { opts: opts, nspMap: nspMap, ee: ee } - } - - // the top level API - - - /** - * 0.5.0 we break up the wsClientCore in two parts one without the config check - * @param {function} setupSocketClientListener just make sure what it said it does - * @return {function} to actually generate the client - */ - function wsClientCoreAction(setupSocketClientListener) { - /** - * This is a breaking change, to continue the onion skin design - * @param {object} config the already checked config - * @return {promise} resolve the client - */ - return function createClientAction(config) { - if ( config === void 0 ) config = {}; - - - return postCheckInjectOpts(config) - .then(createRequiredParams) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return setupSocketClientListener(opts, nspMap, ee); - } - ) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return callersGenerator(opts, nspMap, ee); - } - ) - .catch(function (err) { - console.error("[jsonql-ws-core-client init error]", err); - }) - } - } - - /** - * The main interface which will generate the socket clients and map all events - * @param {object} socketClientListerner this is the one method export by various clients - * @param {object} [configCheckMap={}] we should do all the checking in the core instead of the client - * @param {object} [constProps={}] add this to supply the constProps from the downstream client - * @return {function} accept a config then return the wsClient instance with all the available API - */ - function wsClientCore(socketClientListener, configCheckMap, constProps) { - if ( configCheckMap === void 0 ) configCheckMap = {}; - if ( constProps === void 0 ) constProps = {}; - - // we need to inject property to this client later - return function (config) { - if ( config === void 0 ) config = {}; - - return checkConfiguration(config, configCheckMap, constProps) - .then( - wsClientCoreAction(socketClientListener) - ); - } - } - - // this use by client-event-handler - - /** - * trigger errors on all the namespace onError handler - * @param {object} ee Event Emitter - * @param {array} namespaces nsps string - * @param {string} message optional - * @return {void} - */ - function triggerNamespacesOnError(ee, namespaces, message) { - namespaces.forEach( function (namespace) { - ee.$trigger( - createEvt(namespace, ON_ERROR_FN_NAME), - [{ message: message, namespace: namespace }] - ); - }); - } - - /** - * Handle the onerror callback - * @param {object} ee event emitter - * @param {string} namespace which namespace has error - * @param {*} err error object - * @return {void} - */ - var handleNamespaceOnError = function (ee, namespace, err) { - ee.$trigger(createEvt(namespace, ON_ERROR_FN_NAME), [err]); - }; - - // NOT IN USE AT THE MOMENT JUST KEEP IT HERE FOR THE TIME BEING - - /** - * A Event Listerner placeholder when it's not connect to the private nsp - * @param {string} namespace nsp - * @param {object} ee EventEmitter - * @param {object} opts configuration - * @return {void} - */ - var notLoginListener = function (namespace, ee, opts) { - var log = opts.log; - - ee.$only( - createEvt(namespace, EMIT_EVT), - function notLoginListernerCallback(resolverName, args) { - log('[notLoginListerner] hijack the ws call', namespace, resolverName, args); - var error = { message: NOT_LOGIN_ERR_MSG }; - // It should just throw error here and should not call the result - // because that's channel for handling normal event not the fake one - ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ]); - // also trigger the result Listerner, but wrap inside the error key - ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error: error }]); - } - ); - }; - - /** - * Only when there is a private namespace then we bind to this event - * @param {object} nsps the available nsp(s) - * @param {array} namespaces available namespace - * @param {object} ee eventEmitter - * @param {object} opts configuration - * @return {void} - */ - var logoutEvtListener = function (nsps, namespaces, ee, opts) { - var log = opts.log; - // this will be available regardless enableAuth - // because the server can log the client out - ee.$on( - LOGOUT_EVENT_NAME$1, - function logoutEvtCallback() { - var privateNamespace = getPrivateNamespace(namespaces); - log((LOGOUT_EVENT_NAME$1 + " event triggered")); - // disconnect(nsps, opts.serverType) - // we need to issue error to all the namespace onError Listerner - triggerNamespacesOnError(ee, [privateNamespace], LOGOUT_EVENT_NAME$1); - // rebind all of the Listerner to the fake one - log(("logout from " + privateNamespace)); - - clearMainEmitEvt(ee, privateNamespace); - // we need to issue one more call to the server before we disconnect - // now this is a catch 22, here we are not suppose to do anything platform specific - // so that should fire before trigger this event - // clear out the nsp - nsps[privateNamespace] = null; - // add a NOT LOGIN error if call - notLoginWsListerner(privateNamespace, ee, opts); - } - ); - }; - - // This is share between different clients so we export it - - /** - * centralize all the comm in one place - * @param {function} bindSocketEventHandler binding the ee to ws --> this is the core bit - * @param {object} nsps namespaced nsp - * @return {void} nothing - */ - function namespaceEventListener(bindSocketEventListener, nsps) { - /** - * BREAKING CHANGE instead of one flat structure - * we return a function to accept the two - * @param {object} opts configuration - * @param {object} nspMap this is not in the opts - * @param {object} ee Event Emitter instance - * @return {array} although we return something but this is the last step and nothing to do further - */ - return function (opts, nspMap, ee) { - // since all these params already in the opts - var log = opts.log; - var namespaces = nspMap.namespaces; - // @1.1.3 add isPrivate prop to id which namespace is the private nsp - // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event - var privateNamespace = getPrivateNamespace$1(namespaces); - // The total number of namespaces (which is 2 at the moment) minus the private namespace number - var ctn = namespaces.length - 1; - // @NOTE we need to somehow id if this namespace already been connected - // and the event been released before - return namespaces.map(function (namespace) { - var isPrivate = privateNamespace === namespace; - log(namespace, (" --> " + (isPrivate ? 'private': 'public') + " nsp --> "), nsps[namespace] !== false); - if (nsps[namespace]) { - log('[call bindWsHandler]', isPrivate, namespace); - // we need to add one more property here to tell the bindSocketEventListener - // how many times it should call the onReady - var args = [namespace, nsps[namespace], ee, isPrivate, opts, --ctn]; - // Finally we binding everything together - Reflect.apply(bindSocketEventListener, null, args); - - } else { - log(("binding notLoginWsHandler to " + namespace)); - // a dummy placeholder - // @TODO but it should be a not connect handler - // when it's not login (or fail) this should be handle differently - notLoginListener(namespace, ee, opts); - } - if (isPrivate) { - log("Has private and add logoutEvtHandler"); - logoutEvtListener(nsps, namespaces, ee, opts); - } - // just return something its not going to get use anywhere - return isPrivate - }) - } - } - - /* - This two client is the final one that gets call - all it does is to create the url that connect to - and actually trigger the connection and return the socket - therefore they are as generic as it can be - */ - - /** - * wrapper method to create a nsp without login - * @param {string|boolean} namespace namespace url could be false - * @param {object} opts configuration - * @return {object} ws client instance - */ - function createNspClient(namespace, opts) { - var hostname = opts.hostname; - var wssPath = opts.wssPath; - var nspClient = opts.nspClient; - var log = opts.log; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - log("createNspClient with URL --> ", url); - - return nspClient(url, opts) - } - - /** - * wrapper method to create a nsp with token auth - * @param {string} namespace namespace url - * @param {object} opts configuration - * @return {object} ws client instance - */ - function createNspAuthClient(namespace, opts) { - var hostname = opts.hostname; - var wssPath = opts.wssPath; - var token = opts.token; - var nspAuthClient = opts.nspAuthClient; - var log = opts.log; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - - log("createNspAuthClient with URL -->", url); - - if (token && typeof token !== 'string') { - throw new Error(("Expect token to be string, but got " + token)) - } - // now we need to get an extra options for framework specific method, which is not great - // instead we just pass the entrie opts to the authClient - - return nspAuthClient(url, opts, token) - } - - // same with the invalid-token-error - - /* - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - */ - - var InvalidCharacterError = /*@__PURE__*/(function (Error) { - function InvalidCharacterError(message) { - this.message = message; - } - - if ( Error ) InvalidCharacterError.__proto__ = Error; - InvalidCharacterError.prototype = Object.create( Error && Error.prototype ); - InvalidCharacterError.prototype.constructor = InvalidCharacterError; - - var prototypeAccessors = { name: { configurable: true } }; - - prototypeAccessors.name.get = function () { - return 'InvalidCharacterError' - }; - - Object.defineProperties( InvalidCharacterError.prototype, prototypeAccessors ); - - return InvalidCharacterError; - }(Error)); - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - /** - * Polyfill the non ASCII code - * @param {*} input - * @return {*} usable output - */ - function atob(input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.") - } - for ( - // initialize result and counters - var bc = 0, bs = (void 0), buffer = (void 0), idx = 0, output$1 = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output$1 += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output - } - - // polyfill the window object - try { - typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob; - } catch(e) {} - - var obj$2, obj$1$1, obj$2$1, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'exp', obj$2[OPTIONAL_KEY] = true, obj$2 )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1$1 = {}, obj$1$1[ALIAS_KEY] = 'nbf', obj$1$1[OPTIONAL_KEY] = true, obj$1$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2$1 = {}, obj$2$1[ALIAS_KEY] = 'iss', obj$2$1[OPTIONAL_KEY] = true, obj$2$1 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - // this method is re-use in several clients - // move back to jsonql-constants later - - /** - * extract the new options for authorization - * @param {*} opts configuration - * @return {string} the header option - */ - function extractConfig(opts) { - // we don't really need to do any validation here - // because the opts should be clean before calling here - return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL - } - - /** - * When running the CSRF token, and have a Auth token - * the csrf is missing so we need to take that into account as well - * @param {object} config configuration - * @param {string} token auth token - * @return {object} constructed the full options to pass to the WS object - */ - function prepareHeaderOpts(config, token) { - var obj, obj$1; - - if ( token === void 0 ) token = false; - var wsOptions = config[WS_OPT_PROP_KEY] || {}; - var headers = config[HEADERS_KEY] || {}; - if (token) { - headers = Object.assign(headers, ( obj = {}, obj[AUTH_HEADER] = (BEARER + " " + token), obj )); - } - // we might have to use the merge here - return Object.assign({}, wsOptions, ( obj$1 = {}, obj$1[HEADERS_KEY] = headers, obj$1 )) - } - - /** - * prepare the url and options to the WebSocket - * @param {*} url - * @param {*} config - * @param {*} [token = false] - * @return {object} with url and opts key - */ - function prepareConnectConfig(url, config, token) { - if ( config === void 0 ) config = {}; - if ( token === void 0 ) token = false; - - var tokenOpt = extractConfig(config); - - switch (tokenOpt) { - case TOKEN_IN_URL: - return { - url: token ? (url + "?" + TOKEN_PARAM_NAME + "=" + token) : url, - opts: prepareHeaderOpts(config, false) - } - case TOKEN_IN_HEADER: - default: - return { - url: url, - opts: prepareHeaderOpts(config, token) - } - } - } - - /* base.js */ - var ERROR_KEY$1 = 'error'; - var QUERY_ARG_NAME$1 = 'args'; - var TIMESTAMP_PARAM_NAME$1 = 'TS'; - - /* prop.js */ - - // this is all the key name for the config check map - // all subfix with prop_key - - var TYPE_KEY$1 = 'type'; - var OPTIONAL_KEY$1 = 'optional'; - var ENUM_KEY$1 = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY$1 = 'args'; - var CHECKER_KEY$1 = 'checker'; - var ALIAS_KEY$1 = 'alias'; - var ENABLE_AUTH_PROP_KEY$1 = 'enableAuth'; - // we could pass the token in the header instead when init the WebSocket - var TOKEN_DELIVER_LOCATION_PROP_KEY$1 = 'tokenDeliverLocation'; - var LOGIN_EVENT_NAME$1 = '__login__'; - // at the moment we only have __logout__ regardless enableAuth is enable - // this is incorrect, because logout suppose to come after login - // and it should only logout from auth nsp, instead of clear out the - // connection, the following new event @1.9.2 will correct this edge case - // although it should never happens, but in some edge case might want to - // disconnect from the current server, then re-establish connection later - var CONNECT_EVENT_NAME$1 = '__connect__'; - var DISCONNECT_EVENT_NAME$1 = '__disconnect__'; - // for ws servers - var WS_REPLY_TYPE$1 = '__reply__'; - var WS_EVT_NAME$1 = '__event__'; - var WS_DATA_NAME$1 = '__data__'; - - // for ws client, 1.9.3 breaking change to name them as FN instead of PROP - var ON_MESSAGE_FN_NAME$1 = 'onMessage'; - var ON_RESULT_FN_NAME$1 = 'onResult'; // this will need to be internal from now on - var ON_ERROR_FN_NAME$1 = 'onError'; - var ON_READY_FN_NAME$1 = 'onReady'; - var ON_LOGIN_FN_NAME$1 = 'onLogin'; // new @1.8.6 - - // this is somewhat vague about what is suppose to do - var EMIT_REPLY_TYPE$1 = 'emit_reply'; - var ACKNOWLEDGE_REPLY_TYPE = 'emit_acknowledge'; - var JS_WS_NAME = 'ws'; - - var NSP_AUTH_CLIENT = 'nspAuthClient'; - var NSP_CLIENT = 'nspClient'; - - // this is the value for TOKEN_DELIVER_LOCATION_PROP_KEY - var TOKEN_IN_HEADER$1 = 'header'; - var TOKEN_IN_URL$1 = 'url'; - var STRING_TYPE$1 = 'string'; - var BOOLEAN_TYPE$1 = 'boolean'; - - var NUMBER_TYPE$1 = 'number'; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal$1 = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - - /** Detect free variable `self`. */ - var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root$1 = freeGlobal$1 || freeSelf$1 || Function('return this')(); - - /** Built-in value references. */ - var Symbol$1 = root$1.Symbol; - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap$1(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray$1 = Array.isArray; - - /** Used for built-in method references. */ - var objectProto$f = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$c = objectProto$f.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$2 = objectProto$f.toString; - - /** Built-in value references. */ - var symToStringTag$2 = Symbol$1 ? Symbol$1.toStringTag : undefined; - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag$1(value) { - var isOwn = hasOwnProperty$c.call(value, symToStringTag$2), - tag = value[symToStringTag$2]; - - try { - value[symToStringTag$2] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$2.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$2] = tag; - } else { - delete value[symToStringTag$2]; - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$g = Object.prototype; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$3 = objectProto$g.toString; - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString$1(value) { - return nativeObjectToString$3.call(value); - } - - /** `Object#toString` result references. */ - var nullTag$1 = '[object Null]', - undefinedTag$1 = '[object Undefined]'; - - /** Built-in value references. */ - var symToStringTag$3 = Symbol$1 ? Symbol$1.toStringTag : undefined; - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag$1(value) { - if (value == null) { - return value === undefined ? undefinedTag$1 : nullTag$1; - } - return (symToStringTag$3 && symToStringTag$3 in Object(value)) - ? getRawTag$1(value) - : objectToString$1(value); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike$1(value) { - return value != null && typeof value == 'object'; - } - - /** `Object#toString` result references. */ - var symbolTag$2 = '[object Symbol]'; - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol$1(value) { - return typeof value == 'symbol' || - (isObjectLike$1(value) && baseGetTag$1(value) == symbolTag$2); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$2 = 1 / 0; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined, - symbolToString$1 = symbolProto$2 ? symbolProto$2.toString : undefined; - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString$1(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray$1(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap$1(value, baseToString$1) + ''; - } - if (isSymbol$1(value)) { - return symbolToString$1 ? symbolToString$1.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result; - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice$1(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice$1(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice$1(array, start, end); - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex$1(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN$1(value) { - return value !== value; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf$1(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf$1(array, value, fromIndex) { - return value === value - ? strictIndexOf$1(array, value, fromIndex) - : baseFindIndex$1(array, baseIsNaN$1, fromIndex); - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex$1(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf$1(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex$1(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf$1(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray$1(string) { - return string.split(''); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange$2 = '\\ud800-\\udfff', - rsComboMarksRange$2 = '\\u0300-\\u036f', - reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$2 = '\\u20d0-\\u20ff', - rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2, - rsVarRange$2 = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsZWJ$2 = '\\u200d'; - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode$1 = RegExp('[' + rsZWJ$2 + rsAstralRange$2 + rsComboRange$2 + rsVarRange$2 + ']'); - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode$1(string) { - return reHasUnicode$1.test(string); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange$3 = '\\ud800-\\udfff', - rsComboMarksRange$3 = '\\u0300-\\u036f', - reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$3 = '\\u20d0-\\u20ff', - rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3, - rsVarRange$3 = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsAstral$1 = '[' + rsAstralRange$3 + ']', - rsCombo$1 = '[' + rsComboRange$3 + ']', - rsFitz$1 = '\\ud83c[\\udffb-\\udfff]', - rsModifier$1 = '(?:' + rsCombo$1 + '|' + rsFitz$1 + ')', - rsNonAstral$1 = '[^' + rsAstralRange$3 + ']', - rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$3 = '\\u200d'; - - /** Used to compose unicode regexes. */ - var reOptMod$1 = rsModifier$1 + '?', - rsOptVar$1 = '[' + rsVarRange$3 + ']?', - rsOptJoin$1 = '(?:' + rsZWJ$3 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*', - rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1, - rsSymbol$1 = '(?:' + [rsNonAstral$1 + rsCombo$1 + '?', rsCombo$1, rsRegional$1, rsSurrPair$1, rsAstral$1].join('|') + ')'; - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode$1 = RegExp(rsFitz$1 + '(?=' + rsFitz$1 + ')|' + rsSymbol$1 + rsSeq$1, 'g'); - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray$1(string) { - return string.match(reUnicode$1) || []; - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray$1(string) { - return hasUnicode$1(string) - ? unicodeToArray$1(string) - : asciiToArray$1(string); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString$1(value) { - return value == null ? '' : baseToString$1(value); - } - - /** Used to match leading and trailing whitespace. */ - var reTrim$1 = /^\s+|\s+$/g; - - /** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ - function trim$1(string, chars, guard) { - string = toString$1(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim$1, ''); - } - if (!string || !(chars = baseToString$1(chars))) { - return string; - } - var strSymbols = stringToArray$1(string), - chrSymbols = stringToArray$1(chars), - start = charsStartIndex$1(strSymbols, chrSymbols), - end = charsEndIndex$1(strSymbols, chrSymbols) + 1; - - return castSlice$1(strSymbols, start, end).join(''); - } - - /** `Object#toString` result references. */ - var numberTag$3 = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber$1(value) { - return typeof value == 'number' || - (isObjectLike$1(value) && baseGetTag$1(value) == numberTag$3); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN$2(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber$1(value) && value != +value; - } - - /** `Object#toString` result references. */ - var stringTag$3 = '[object String]'; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString$3(value) { - return typeof value == 'string' || - (!isArray$1(value) && isObjectLike$1(value) && baseGetTag$1(value) == stringTag$3); - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a chck if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber$1 = function(value) { - return isString$3(value) ? false : !isNaN$2( parseFloat(value) ) - }; - - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString$1 = function(value) { - return (trim$1(value) !== '') ? isString$3(value) : false - }; - - // check for boolean - - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean$1 = function(value) { - return value !== null && value !== undefined && typeof value === 'boolean' - }; - - // validate any thing only check if there is something - - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny$1 = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (value !== undefined && value !== '' && trim$1(value) !== '') { - if (checkNull === false || (checkNull === true && value !== null)) { - return true; - } - } - return false; - }; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn$1 = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber$1 - case STRING_TYPE$1: - return checkIsString$1 - case BOOLEAN_TYPE$1: - return checkIsBoolean$1 - default: - return checkIsAny$1 - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray$1 = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray$1(value)) { - if (type === '' || trim$1(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn$1(type)(v); }); - return !(c.length > 0) - } - return false - }; - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg$1(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** Built-in value references. */ - var getPrototype$1 = overArg$1(Object.getPrototypeOf, Object); - - /** `Object#toString` result references. */ - var objectTag$4 = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto$3 = Function.prototype, - objectProto$h = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$3 = funcProto$3.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$d = objectProto$h.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString$1 = funcToString$3.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject$1(value) { - if (!isObjectLike$1(value) || baseGetTag$1(value) != objectTag$4) { - return false; - } - var proto = getPrototype$1(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$d.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$3.call(Ctor) == objectCtorString$1; - } - - // custom validation error class - // when validaton failed - var JsonqlValidationError$1 = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError' - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - var NO_STATUS_CODE$1 = -1; - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError$2 = /*@__PURE__*/(function (Error) { - function JsonqlError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); - // this.detail = this.stack; - } - } - - if ( Error ) JsonqlError.__proto__ = Error; - JsonqlError.prototype = Object.create( Error && Error.prototype ); - JsonqlError.prototype.constructor = JsonqlError; - - var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlError' - }; - - staticAccessors.statusCode.get = function () { - return NO_STATUS_CODE$1 - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; - }(Error)); - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear$1() { - this.__data__ = []; - this.size = 0; - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq$1(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf$1(array, key) { - var length = array.length; - while (length--) { - if (eq$1(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto$1 = Array.prototype; - - /** Built-in value references. */ - var splice$1 = arrayProto$1.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete$1(key) { - var data = this.__data__, - index = assocIndexOf$1(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice$1.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet$1(key) { - var data = this.__data__, - index = assocIndexOf$1(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas$1(key) { - return assocIndexOf$1(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet$1(key, value) { - var data = this.__data__, - index = assocIndexOf$1(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache$1(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache$1.prototype.clear = listCacheClear$1; - ListCache$1.prototype['delete'] = listCacheDelete$1; - ListCache$1.prototype.get = listCacheGet$1; - ListCache$1.prototype.has = listCacheHas$1; - ListCache$1.prototype.set = listCacheSet$1; - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear$1() { - this.__data__ = new ListCache$1; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete$1(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet$1(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas$1(key) { - return this.__data__.has(key); - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject$1(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** `Object#toString` result references. */ - var asyncTag$1 = '[object AsyncFunction]', - funcTag$2 = '[object Function]', - genTag$1 = '[object GeneratorFunction]', - proxyTag$1 = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction$1(value) { - if (!isObject$1(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag$1(value); - return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag$1 || tag == proxyTag$1; - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData$1 = root$1['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey$1 = (function() { - var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked$1(func) { - return !!maskSrcKey$1 && (maskSrcKey$1 in func); - } - - /** Used for built-in method references. */ - var funcProto$4 = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$4 = funcProto$4.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource$1(func) { - if (func != null) { - try { - return funcToString$4.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor$1 = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$5 = Function.prototype, - objectProto$i = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$5 = funcProto$5.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$e = objectProto$i.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative$1 = RegExp('^' + - funcToString$5.call(hasOwnProperty$e).replace(reRegExpChar$1, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative$1(value) { - if (!isObject$1(value) || isMasked$1(value)) { - return false; - } - var pattern = isFunction$1(value) ? reIsNative$1 : reIsHostCtor$1; - return pattern.test(toSource$1(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue$1(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative$1(object, key) { - var value = getValue$1(object, key); - return baseIsNative$1(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var Map$2 = getNative$1(root$1, 'Map'); - - /* Built-in method references that are verified to be native. */ - var nativeCreate$1 = getNative$1(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear$1() { - this.__data__ = nativeCreate$1 ? nativeCreate$1(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete$1(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$3 = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$j = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$f = objectProto$j.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet$1(key) { - var data = this.__data__; - if (nativeCreate$1) { - var result = data[key]; - return result === HASH_UNDEFINED$3 ? undefined : result; - } - return hasOwnProperty$f.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$k = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$g = objectProto$k.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas$1(key) { - var data = this.__data__; - return nativeCreate$1 ? (data[key] !== undefined) : hasOwnProperty$g.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$4 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet$1(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate$1 && value === undefined) ? HASH_UNDEFINED$4 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash$1(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash$1.prototype.clear = hashClear$1; - Hash$1.prototype['delete'] = hashDelete$1; - Hash$1.prototype.get = hashGet$1; - Hash$1.prototype.has = hashHas$1; - Hash$1.prototype.set = hashSet$1; - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear$1() { - this.size = 0; - this.__data__ = { - 'hash': new Hash$1, - 'map': new (Map$2 || ListCache$1), - 'string': new Hash$1 - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable$1(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData$1(map, key) { - var data = map.__data__; - return isKeyable$1(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete$1(key) { - var result = getMapData$1(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet$1(key) { - return getMapData$1(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas$1(key) { - return getMapData$1(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet$1(key, value) { - var data = getMapData$1(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache$1(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache$1.prototype.clear = mapCacheClear$1; - MapCache$1.prototype['delete'] = mapCacheDelete$1; - MapCache$1.prototype.get = mapCacheGet$1; - MapCache$1.prototype.has = mapCacheHas$1; - MapCache$1.prototype.set = mapCacheSet$1; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE$1 = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet$1(key, value) { - var data = this.__data__; - if (data instanceof ListCache$1) { - var pairs = data.__data__; - if (!Map$2 || (pairs.length < LARGE_ARRAY_SIZE$1 - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache$1(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack$1(entries) { - var data = this.__data__ = new ListCache$1(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack$1.prototype.clear = stackClear$1; - Stack$1.prototype['delete'] = stackDelete$1; - Stack$1.prototype.get = stackGet$1; - Stack$1.prototype.has = stackHas$1; - Stack$1.prototype.set = stackSet$1; - - var defineProperty$1 = (function() { - try { - var func = getNative$1(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue$1(object, key, value) { - if (key == '__proto__' && defineProperty$1) { - defineProperty$1(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue$1(object, key, value) { - if ((value !== undefined && !eq$1(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue$1(object, key, value); - } - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor$1(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor$1 = createBaseFor$1(); - - /** Detect free variable `exports`. */ - var freeExports$3 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$3 = freeExports$3 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$3 = freeModule$3 && freeModule$3.exports === freeExports$3; - - /** Built-in value references. */ - var Buffer$2 = moduleExports$3 ? root$1.Buffer : undefined, - allocUnsafe$1 = Buffer$2 ? Buffer$2.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer$1(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe$1 ? allocUnsafe$1(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** Built-in value references. */ - var Uint8Array$1 = root$1.Uint8Array; - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer$1(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray$1(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer$1(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray$1(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Built-in value references. */ - var objectCreate$1 = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate$1 = (function() { - function object() {} - return function(proto) { - if (!isObject$1(proto)) { - return {}; - } - if (objectCreate$1) { - return objectCreate$1(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** Used for built-in method references. */ - var objectProto$l = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype$1(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$l; - - return value === proto; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject$1(object) { - return (typeof object.constructor == 'function' && !isPrototype$1(object)) - ? baseCreate$1(getPrototype$1(object)) - : {}; - } - - /** `Object#toString` result references. */ - var argsTag$3 = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments$1(value) { - return isObjectLike$1(value) && baseGetTag$1(value) == argsTag$3; - } - - /** Used for built-in method references. */ - var objectProto$m = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$h = objectProto$m.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable$2 = objectProto$m.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments$1 = baseIsArguments$1(function() { return arguments; }()) ? baseIsArguments$1 : function(value) { - return isObjectLike$1(value) && hasOwnProperty$h.call(value, 'callee') && - !propertyIsEnumerable$2.call(value, 'callee'); - }; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$2 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength$1(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$2; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$2(value) { - return value != null && isLength$1(value.length) && !isFunction$1(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject$1(value) { - return isObjectLike$1(value) && isArrayLike$2(value); - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse$1() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports$4 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$4 = freeExports$4 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$4 = freeModule$4 && freeModule$4.exports === freeExports$4; - - /** Built-in value references. */ - var Buffer$3 = moduleExports$4 ? root$1.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer$1 = Buffer$3 ? Buffer$3.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer$1 = nativeIsBuffer$1 || stubFalse$1; - - /** `Object#toString` result references. */ - var argsTag$4 = '[object Arguments]', - arrayTag$2 = '[object Array]', - boolTag$2 = '[object Boolean]', - dateTag$2 = '[object Date]', - errorTag$2 = '[object Error]', - funcTag$3 = '[object Function]', - mapTag$3 = '[object Map]', - numberTag$4 = '[object Number]', - objectTag$5 = '[object Object]', - regexpTag$2 = '[object RegExp]', - setTag$3 = '[object Set]', - stringTag$4 = '[object String]', - weakMapTag$2 = '[object WeakMap]'; - - var arrayBufferTag$2 = '[object ArrayBuffer]', - dataViewTag$3 = '[object DataView]', - float32Tag$1 = '[object Float32Array]', - float64Tag$1 = '[object Float64Array]', - int8Tag$1 = '[object Int8Array]', - int16Tag$1 = '[object Int16Array]', - int32Tag$1 = '[object Int32Array]', - uint8Tag$1 = '[object Uint8Array]', - uint8ClampedTag$1 = '[object Uint8ClampedArray]', - uint16Tag$1 = '[object Uint16Array]', - uint32Tag$1 = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags$1 = {}; - typedArrayTags$1[float32Tag$1] = typedArrayTags$1[float64Tag$1] = - typedArrayTags$1[int8Tag$1] = typedArrayTags$1[int16Tag$1] = - typedArrayTags$1[int32Tag$1] = typedArrayTags$1[uint8Tag$1] = - typedArrayTags$1[uint8ClampedTag$1] = typedArrayTags$1[uint16Tag$1] = - typedArrayTags$1[uint32Tag$1] = true; - typedArrayTags$1[argsTag$4] = typedArrayTags$1[arrayTag$2] = - typedArrayTags$1[arrayBufferTag$2] = typedArrayTags$1[boolTag$2] = - typedArrayTags$1[dataViewTag$3] = typedArrayTags$1[dateTag$2] = - typedArrayTags$1[errorTag$2] = typedArrayTags$1[funcTag$3] = - typedArrayTags$1[mapTag$3] = typedArrayTags$1[numberTag$4] = - typedArrayTags$1[objectTag$5] = typedArrayTags$1[regexpTag$2] = - typedArrayTags$1[setTag$3] = typedArrayTags$1[stringTag$4] = - typedArrayTags$1[weakMapTag$2] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray$1(value) { - return isObjectLike$1(value) && - isLength$1(value.length) && !!typedArrayTags$1[baseGetTag$1(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary$1(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$5 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$5 = freeExports$5 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$5 = freeModule$5 && freeModule$5.exports === freeExports$5; - - /** Detect free variable `process` from Node.js. */ - var freeProcess$1 = moduleExports$5 && freeGlobal$1.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil$1 = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$5 && freeModule$5.require && freeModule$5.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess$1 && freeProcess$1.binding && freeProcess$1.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray$1 = nodeUtil$1 && nodeUtil$1.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray$1 = nodeIsTypedArray$1 ? baseUnary$1(nodeIsTypedArray$1) : baseIsTypedArray$1; - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet$1(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** Used for built-in method references. */ - var objectProto$n = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$i = objectProto$n.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue$1(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$i.call(object, key) && eq$1(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue$1(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject$1(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue$1(object, key, newValue); - } else { - assignValue$1(object, key, newValue); - } - } - return object; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes$1(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$3 = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint$1 = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex$1(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$3 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint$1.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** Used for built-in method references. */ - var objectProto$o = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$j = objectProto$o.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys$1(value, inherited) { - var isArr = isArray$1(value), - isArg = !isArr && isArguments$1(value), - isBuff = !isArr && !isArg && isBuffer$1(value), - isType = !isArr && !isArg && !isBuff && isTypedArray$1(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes$1(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$j.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex$1(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn$1(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$p = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$k = objectProto$p.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn$1(object) { - if (!isObject$1(object)) { - return nativeKeysIn$1(object); - } - var isProto = isPrototype$1(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$k.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn$1(object) { - return isArrayLike$2(object) ? arrayLikeKeys$1(object, true) : baseKeysIn$1(object); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject$1(value) { - return copyObject$1(value, keysIn$1(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep$1(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet$1(object, key), - srcValue = safeGet$1(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue$1(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray$1(srcValue), - isBuff = !isArr && isBuffer$1(srcValue), - isTyped = !isArr && !isBuff && isTypedArray$1(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray$1(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject$1(objValue)) { - newValue = copyArray$1(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer$1(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray$1(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject$1(srcValue) || isArguments$1(srcValue)) { - newValue = objValue; - if (isArguments$1(objValue)) { - newValue = toPlainObject$1(objValue); - } - else if (!isObject$1(objValue) || isFunction$1(objValue)) { - newValue = initCloneObject$1(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue$1(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge$1(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor$1(source, function(srcValue, key) { - stack || (stack = new Stack$1); - if (isObject$1(srcValue)) { - baseMergeDeep$1(object, source, key, srcIndex, baseMerge$1, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet$1(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue$1(object, key, newValue); - } - }, keysIn$1); - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity$1(value) { - return value; - } - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply$1(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax$1 = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest$1(func, start, transform) { - start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax$1(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply$1(func, this, otherArgs); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant$1(value) { - return function() { - return value; - }; - } - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString$1 = !defineProperty$1 ? identity$1 : function(func, string) { - return defineProperty$1(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant$1(string), - 'writable': true - }); - }; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT$1 = 800, - HOT_SPAN$1 = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow$1 = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut$1(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow$1(), - remaining = HOT_SPAN$1 - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT$1) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString$1 = shortOut$1(baseSetToString$1); - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest$1(func, start) { - return setToString$1(overRest$1(func, start, identity$1), func + ''); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall$1(value, index, object) { - if (!isObject$1(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike$2(object) && isIndex$1(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq$1(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner$1(assigner) { - return baseRest$1(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall$1(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge$1 = createAssigner$1(function(object, source, srcIndex) { - baseMerge$1(object, source, srcIndex); - }); - - // create function to construct the config entry so we don't need to keep building object - // import checkIsBoolean from '../boolean' - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfig$1(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY$1] = args; - base[TYPE_KEY$1] = type; - if (optional === true) { - base[OPTIONAL_KEY$1] = true; - } - if (checkIsArray$1(enumv)) { - base[ENUM_KEY$1] = enumv; - } - if (isFunction$1(checker)) { - base[CHECKER_KEY$1] = checker; - } - if (isString$3(alias)) { - base[ALIAS_KEY$1] = alias; - } - return base - } - - // export also create wrapper methods - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig$2 = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY$1]; - var e = params[ENUM_KEY$1]; - var c = params[CHECKER_KEY$1]; - var a = params[ALIAS_KEY$1]; - return constructConfig$1.apply(null, [value, type, o, e, c, a]) - }; - - // export - - var createConfig$3 = createConfig$2; - - var obj$9; - - var AVAILABLE_PLACES = [ - TOKEN_IN_URL$1, - TOKEN_IN_HEADER$1 - ]; - - // constant props - var wsClientConstProps = { - version: 'version: 1.2.0 module: umd', // will get replace - serverType: JS_WS_NAME - }; - - var wsClientCheckMap = {}; - wsClientCheckMap[TOKEN_DELIVER_LOCATION_PROP_KEY$1] = createConfig$3(TOKEN_IN_URL$1, [STRING_TYPE$1], ( obj$9 = {}, obj$9[ENUM_KEY$1] = AVAILABLE_PLACES, obj$9 )); - - // this is all the isormophic-ws is - var ws = null; - - if (typeof WebSocket !== 'undefined') { - ws = WebSocket; - } else if (typeof MozWebSocket !== 'undefined') { - ws = MozWebSocket; - } else if (typeof global$1 !== 'undefined') { - ws = global$1.WebSocket || global$1.MozWebSocket; - } else if (typeof window !== 'undefined') { - ws = window.WebSocket || window.MozWebSocket; - } else if (typeof self !== 'undefined') { - ws = self.WebSocket || self.MozWebSocket; - } - - var ws$1 = ws; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var js_cookie = createCommonjsModule(function (module, exports) { - (function (factory) { - var registeredInModuleLoader; - { - module.exports = factory(); - registeredInModuleLoader = true; - } - if (!registeredInModuleLoader) { - var OldCookies = window.Cookies; - var api = window.Cookies = factory(); - api.noConflict = function () { - window.Cookies = OldCookies; - return api; - }; - } - }(function () { - function extend () { - var arguments$1 = arguments; - - var i = 0; - var result = {}; - for (; i < arguments.length; i++) { - var attributes = arguments$1[ i ]; - for (var key in attributes) { - result[key] = attributes[key]; - } - } - return result; - } - - function decode (s) { - return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent); - } - - function init (converter) { - function api() {} - - function set (key, value, attributes) { - if (typeof document === 'undefined') { - return; - } - - attributes = extend({ - path: '/' - }, api.defaults, attributes); - - if (typeof attributes.expires === 'number') { - attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5); - } - - // We're using "expires" because "max-age" is not supported by IE - attributes.expires = attributes.expires ? attributes.expires.toUTCString() : ''; - - try { - var result = JSON.stringify(value); - if (/^[\{\[]/.test(result)) { - value = result; - } - } catch (e) {} - - value = converter.write ? - converter.write(value, key) : - encodeURIComponent(String(value)) - .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); - - key = encodeURIComponent(String(key)) - .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) - .replace(/[\(\)]/g, escape); - - var stringifiedAttributes = ''; - for (var attributeName in attributes) { - if (!attributes[attributeName]) { - continue; - } - stringifiedAttributes += '; ' + attributeName; - if (attributes[attributeName] === true) { - continue; - } - - // Considers RFC 6265 section 5.2: - // ... - // 3. If the remaining unparsed-attributes contains a %x3B (";") - // character: - // Consume the characters of the unparsed-attributes up to, - // not including, the first %x3B (";") character. - // ... - stringifiedAttributes += '=' + attributes[attributeName].split(';')[0]; - } - - return (document.cookie = key + '=' + value + stringifiedAttributes); - } - - function get (key, json) { - if (typeof document === 'undefined') { - return; - } - - var jar = {}; - // To prevent the for loop in the first place assign an empty array - // in case there are no cookies at all. - var cookies = document.cookie ? document.cookie.split('; ') : []; - var i = 0; - - for (; i < cookies.length; i++) { - var parts = cookies[i].split('='); - var cookie = parts.slice(1).join('='); - - if (!json && cookie.charAt(0) === '"') { - cookie = cookie.slice(1, -1); - } - - try { - var name = decode(parts[0]); - cookie = (converter.read || converter)(cookie, name) || - decode(cookie); - - if (json) { - try { - cookie = JSON.parse(cookie); - } catch (e) {} - } - - jar[name] = cookie; - - if (key === name) { - break; - } - } catch (e) {} - } - - return key ? jar[key] : jar; - } - - api.set = set; - api.get = function (key) { - return get(key, false /* read as raw */); - }; - api.getJSON = function (key) { - return get(key, true /* read as json */); - }; - api.remove = function (key, attributes) { - set(key, '', extend(attributes, { - expires: -1 - })); - }; - - api.defaults = {}; - - api.withConverter = init; - - return api; - } - - return init(function () {}); - })); - }); - - // bunch of generic helpers - - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray$3 = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; - - /** - * parse string to json or just return the original value if error happened - * @param {*} n input - * @param {boolean} [t=true] or throw - * @return {*} json object on success - */ - var parseJson$1 = function(n, t) { - if ( t === void 0 ) t=true; - - try { - return JSON.parse(n) - } catch(e) { - if (t) { - return n - } - throw new Error(e) - } - }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey$2 = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray$3(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false - } - }; - - /** - * create a event name - * @param {string[]} args - * @return {string} event name for use - */ - var createEvt$1 = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); - }; - - /** - * small util to make sure the return value is valid JSON object - * @param {*} n input - * @return {object} correct JSON object - */ - var toJson$1 = function (n) { - if (typeof n === 'string') { - return parseJson$1(n) - } - return parseJson$1(JSON.stringify(n)) - }; - - /** - * Simple check if the prop is function - * @param {*} prop input - * @return {boolean} true on success - */ - var isFunc$1 = function (prop) { - if (typeof prop === 'function') { - return true; - } - console.error(("Expect to be Function type! Got " + (typeof prop))); - }; - - /** - * generic placeholder function - * @return {boolean} false - */ - var nil$1 = function () { return false; }; - - // break it out on its own because - - /** - * previously we already make sure the order of the namespaces - * and attach the auth client to it - * @param {array} promises array of unresolved promises - * @param {boolean} asObject if true then merge the result object - * @return {object} promise resolved with the array of promises resolved results - */ - function chainPromises(promises, asObject) { - if ( asObject === void 0 ) asObject = false; - - return promises.reduce(function (promiseChain, currentTask) { return ( - promiseChain.then(function (chainResults) { return ( - currentTask.then(function (currentResult) { return ( - asObject === false ? chainResults.concat( [currentResult]) : merge$1(chainResults, currentResult) - ); }) - ); }) - ); }, Promise.resolve( - asObject === false ? [] : (isPlainObject$1(asObject) ? asObject : {}) - )) - } - - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp$1 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time - }; - - // ported from jsonql-params-validator - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload$1 = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME$1] = args, obj ) - ); - }; - - /** - * wrapper method to add the timestamp as well - * @param {string} resolverName name of the resolver - * @param {*} payload what is sending - * @param {object} extra additonal property we want to merge into the deliverable - * @return {object} delierable - */ - function createDeliverable$1(resolverName, payload, extra) { - var obj; - - if ( extra === void 0 ) extra = {}; - return Object.assign(( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME$1] = [ timestamp$1() ], obj ), extra) - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery$1(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - if (isString$3(resolverName) && isArray$1(args)) { - var payload = formatPayload$1(args); - if (jsonp === true) { - return payload - } - return createDeliverable$1(resolverName, payload) - } - throw new JsonqlValidationError$1('utils:params-api:createQuery', { - message: "expect resolverName to be string and args to be array!", - resolverName: resolverName, - args: args - }) - } - - /** - * string version of the createQuery - * @return {string} - */ - function createQueryStr$1(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - return JSON.stringify(createQuery$1(resolverName, args, jsonp)) - } - - // There are the socket related methods ported back from - - var PAYLOAD_NOT_DECODED_ERR$1 = 'payload can not decoded'; - var WS_KEYS$1 = [ - WS_REPLY_TYPE$1, - WS_EVT_NAME$1, - WS_DATA_NAME$1 - ]; - - /** - * @param {string|object} payload should be string when reply but could be transformed - * @return {boolean} true is OK - */ - var isWsReply$1 = function (payload) { - var json = isString$3(payload) ? toJson$1(payload) : payload; - var data = json.data; - if (data) { - var result = WS_KEYS$1.filter(function (key) { return isObjectHasKey$2(data, key); }); - return (result.length === WS_KEYS$1.length) ? data : false - } - return false - }; - - /** - * @param {string|object} data received data - * @param {function} [cb=nil] this is for extracting the TS field or when it's error - * @return {object} false on failed - */ - var extractWsPayload$1 = function (payload, cb) { - if ( cb === void 0 ) cb = nil$1; - - try { - var json = toJson$1(payload); - // now handle the data - var _data; - if ((_data = isWsReply$1(json)) !== false) { - // note the ts property is on its own - cb('_data', _data); - - return { - data: toJson$1(_data[WS_DATA_NAME$1]), - resolverName: _data[WS_EVT_NAME$1], - type: _data[WS_REPLY_TYPE$1] - } - } - throw new JsonqlError$2(PAYLOAD_NOT_DECODED_ERR$1, payload) - } catch(e) { - return cb(ERROR_KEY$1, e) - } - }; - - /** - * This will get re-use when we start using the disconnect event method - * @param {*} ws - * @return {void} - */ - function disconnect(ws) { - if (ws.terminate && isFunc$1(ws.terminate)) { - ws.terminate(); - } else if (ws.close && isFunc$1(ws.close)) { - ws.close(); - } - } - - // pass the different type of ws to generate the client - - /** - * - * @param {*} WebSocketClass - * @param {*} url - * @param {*} type - * @param {*} options - */ - function createWs(WebSocketClass, type, url, options) { - if (type === 'browser') { - var headers = options.headers; - if (headers) { - for (var key in headers) { - if (!js_cookie.get(key)) { - js_cookie.set(key, headers[key]); - } - } - } - } - var wsUrl = fixWss(url); - return type === 'node' ? new WebSocketClass(wsUrl, options) : new WebSocketClass(wsUrl) - } - - /** - * Group the ping and get respond create new client in one - * @param {object} ws - * @param {object} WebSocket - * @param {string} url - * @param {function} resolver - * @param {function} rejecter - * @param {boolean} auth client or not - * @return {promise} resolve the confirm client - */ - function initPingAction(ws, WebSocketClass, type, url, wsOptions, resolver, rejecter) { - - // @TODO how to we id this client can issue a CSRF - // by origin? - ws.onopen = function onOpenCallback() { - ws.send(createInitPing()); - }; - - ws.onmessage = function onMessageCallback(payload) { - try { - var header = extractPingResult(payload.data); - // delay or not show no different but just on the safe side - setTimeout(function () { - disconnect(ws); - }, 50); - var newWs = createWs(WebSocketClass, type, url, Object.assign(wsOptions, header)); - - resolver(newWs); - - } catch(e) { - rejecter(e); - } - }; - - ws.onerror = function onErrorCallback(err) { - rejecter(err); - }; - } - - /** - * less duplicated code the better - * @param {object} WebSocket - * @param {string} type we need to change the way how it deliver header for different platform - * @param {string} url formatted url - * @param {object} options or not - * @return {promise} resolve the actual verified client - */ - function asyncConnect(WebSocketClass, type, url, options) { - - return new Promise(function (resolver, rejecter) { - var unconfirmClient = createWs(WebSocketClass, type, url, options); - - return initPingAction(unconfirmClient, WebSocketClass, type, url, options, resolver, rejecter) - }) - } - - /** - * The bug was in the wsOptions where ws don't need it but socket.io do - * therefore the object was pass as second parameter! - * @NOTE here we only return a method to create the client, it might not get call - * @param {object} WebSocket the client or node version of ws - * @param {string} [type = 'browser'] we need to tell if this is browser or node - * @param {boolean} [auth = false] if it's auth then 3 param or just one - * @return {function} the client method to connect to the ws socket server - */ - function setupWebsocketClientFn(WebSocketClass, type, auth) { - if ( type === void 0 ) type = 'browser'; - if ( auth === void 0 ) auth = false; - - if (auth === false) { - /** - * Create a non-protected client - * @param {string} uri already constructed url - * @param {object} config from the ws-client-core this will be wsOptions taken out from opts - * @return {promise} resolve to the confirmed client - */ - return function createWsClient(uri, config) { - // const { log } = config - var ref = prepareConnectConfig(uri, config, false); - var url = ref.url; - var opts = ref.opts; - - return asyncConnect(WebSocketClass, type, url, opts) - } - } - - /** - * Create a client with auth token - * @param {string} uri start with ws:// @TODO check this? - * @param {object} config this is the full configuration because we need something from it - * @param {string} token the jwt token - * @return {object} ws instance - */ - return function createWsAuthClient(uri, config, token) { - // const { log } = config - var ref = prepareConnectConfig(uri, config, token); - var url = ref.url; - var opts = ref.opts; - - return asyncConnect(WebSocketClass, type, url, opts) - } - } - - // @BUG when call disconnected - - /** - * when we received a login event - * from the http-client or the standalone login call - * we received a token here --> update the opts then trigger - * the CONNECT_EVENT_NAME again - * @param {object} opts configurations - * @param {object} nspMap contain all the required info - * @param {object} ee event emitter - * @return {void} - */ - function loginEventListener(opts, nspMap, ee) { - var log = opts.log; - var namespaces = nspMap.namespaces; - - log("[4] loginEventHandler"); - - ee.$only(LOGIN_EVENT_NAME$1, function loginEventHandlerCallback(tokenFromLoginAction) { - - log('createClient LOGIN_EVENT_NAME $only handler'); - // @NOTE this is wrong because whenever start it will connect the to the public - // but when login it should just start binding the private event - clearMainEmitEvt(ee, namespaces); - // reload the nsp and rebind all the events - opts.token = tokenFromLoginAction; - ee.$trigger(CONNECT_EVENT_NAME$1, [opts, ee]); // don't need to pass the nspMap - }); - } - - // actually binding the event client to the socket client - - /** - * Because the nsps can be throw away so it doesn't matter the scope - * this will get reuse again - * @NOTE when we enable the standalone method this sequence will not change - * only call and reload - * @param {object} opts configuration - * @param {object} nspMap from contract - * @param {string|null} token whether we have the token at run time - * @return {promise} resolve the nsps namespace with namespace as key - */ - var createNsp = function(opts, nspMap, token) { - if ( token === void 0 ) token = null; - - // we leave the token param out because it could get call by another method - token = token || opts.token; - var publicNamespace = nspMap.publicNamespace; - var namespaces = nspMap.namespaces; - var log = opts.log; - log("createNspAction", 'publicNamespace', publicNamespace, 'namespaces', namespaces); - - // reverse the namespaces because it got stuck for some reason - // const reverseNamespaces = namespaces.reverse() - if (opts.enableAuth) { - return chainPromises( - namespaces.map(function (namespace, i) { - if (i === 0) { - if (token) { - opts.token = token; - log('create createNspAuthClient at run time'); - return createNspAuthClient(namespace, opts) - } - return Promise.resolve(false) - } - return createNspClient(namespace, opts) - }) - ) - .then(function (results) { return results.map(function (result, i) { - var obj; - - return (( obj = {}, obj[namespaces[i]] = result, obj )); - }) - .reduce(function (a, b) { return Object.assign(a, b); }, {}); } - ) - } - - return createNspClient(false, opts) - .then(function (nsp) { - var obj; - - return (( obj = {}, obj[publicNamespace] = nsp, obj )); - }) - }; - - // taken out from the bind-socket-event-handler - - /** - * This is the actual logout (terminate socket connection) handler - * There is another one that is handle what should do when this happen - * @param {object} ee eventEmitter - * @param {object} ws the WebSocket instance - * @return {void} - */ - function disconnectEventListener(ee, ws) { - // listen to the LOGOUT_EVENT_NAME when this is a private nsp - ee.$on(DISCONNECT_EVENT_NAME$1, function closeEvtHandler() { - try { - // @TODO we need find a way to get the userdata - ws.send(createIntercomPayload(LOGOUT_EVENT_NAME)); - log('terminate ws connection'); - ws.terminate(); - } catch(e) { - console.error('ws.terminate error', e); - } - }); - } - - // the WebSocket main handler - - /** - * in some edge case we might not even have a resolverName, then - * we issue a global error for the developer to catch it - * @param {object} ee event emitter - * @param {string} namespace nsp - * @param {string} resolverName resolver - * @param {object} json decoded payload or error object - * @return {undefined} nothing return - */ - var errorTypeHandler = function (ee, namespace, resolverName, json) { - var evt = [namespace]; - if (resolverName) { - evt.push(resolverName); - } - evt.push(ON_ERROR_FN_NAME$1); - var evtName = Reflect.apply(createEvt$1, null, evt); - // test if there is a data field - var payload = json.data || json; - ee.$trigger(evtName, [payload]); - }; - - /** - * Binding the event to socket normally - * @param {string} namespace - * @param {object} ws the nsp - * @param {object} ee EventEmitter - * @param {boolean} isPrivate to id if this namespace is private or not - * @param {object} opts configuration - * @param {number} ctnLeft in the namespaceEventListener count down how many namespace left to call - * @return {object} promise resolve after the onopen event - */ - function bindSocketEventHandler(namespace, ws, ee, isPrivate, opts, ctnLeft) { - var log = opts.log; - // setup the logut event listener - // this will hear the event and actually call the ws.terminate - if (isPrivate) { - log('Private namespace', namespace, ' binding to the DISCONNECT ws.terminate'); - disconnectEventListener(ee, ws); - } - // log(`log test, isPrivate:`, isPrivate) - // connection open - ws.onopen = function onOpenCallback() { - - log('client.ws.onopen listened -->', namespace); - /* - This is the change from before about the hooks - now only the public namespace will get trigger the onReady - and the private one will get the onLogin - this way, we won't get into the problem of multiple event - get trigger, and for developer they just have to place - the callback inside the right hook - */ - if (isPrivate) { - log(("isPrivate and fire the " + ON_LOGIN_FN_NAME$1)); - ee.$call(ON_LOGIN_FN_NAME$1)(namespace); - } else { - ee.$call(ON_READY_FN_NAME$1)(namespace, ctnLeft); - // The namespaceEventListener will count this for here - // and this count will only count the public namespace - // it will always be 1 for now - log("isPublic onReady hook executed", ctnLeft); - if (ctnLeft === 0) { - ee.$off(ON_READY_FN_NAME$1); - } - } - // add listener only after the open is called - ee.$only( - createEvt$1(namespace, EMIT_REPLY_TYPE$1), - /** - * actually send the payload to server - * @param {string} resolverName - * @param {array} args NEED TO CHECK HOW WE PASS THIS! - */ - function wsMainOnEvtHandler(resolverName, args) { - var payload = createQueryStr$1(resolverName, args); - log('ws.onopen.send', resolverName, args, payload); - - ws.send(payload); - } - ); - }; - - // reply - // If we change it to the event callback style - // then the payload will just be the payload and fucks up the extractWsPayload call @TODO - ws.onmessage = function onMessageCallback(payload) { - - log("client.ws.onmessage raw payload", payload.data); - - // console.log(`on.message`, typeof payload, payload) - try { - // log(`ws.onmessage raw payload`, payload) - // @TODO the payload actually contain quite a few things - is that changed? - // type: message, data: data_send_from_server - var json = extractWsPayload$1(payload.data); - var resolverName = json.resolverName; - var type = json.type; - - log('Respond from server', type, json); - - switch (type) { - case EMIT_REPLY_TYPE$1: - var e1 = createEvt$1(namespace, resolverName, ON_MESSAGE_FN_NAME$1); - var r = ee.$call(e1)(json); - - log("EMIT_REPLY_TYPE", e1, r); - break - case ACKNOWLEDGE_REPLY_TYPE: - var e2 = createEvt$1(namespace, resolverName, ON_RESULT_FN_NAME$1); - var x2 = ee.$call(e2)(json); - - log("ACKNOWLEDGE_REPLY_TYPE", e2, x2); - break - case ERROR_KEY$1: - // this is handled error and we won't throw it - // we need to extract the error from json - log("ERROR_KEY"); - errorTypeHandler(ee, namespace, resolverName, json); - break - // @TODO there should be an error type instead of roll into the other two types? TBC - default: - // if this happen then we should throw it and halt the operation all together - log('Unhandled event!', json); - errorTypeHandler(ee, namespace, resolverName, json); - // let error = {error: {'message': 'Unhandled event!', type}}; - // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [error]) - } - } catch(e) { - log("client.ws.onmessage error", e); - errorTypeHandler(ee, namespace, false, e); - } - }; - // when the server close the connection - ws.onclose = function onCloseCallback() { - log('client.ws.onclose callback'); - // @TODO what to do with this - // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) - }; - // add a onerror event handler here - ws.onerror = function onErrorCallback(err) { - // trigger a global error event - log("client.ws.onerror", err); - handleNamespaceOnError(ee, namespace, err); - }; - - // we don't bind the logut here and just return the ws - return ws - } - - // take out from the bind-framework-to-jsonql - - /** - * This is the hard of establishing the connection and binding to the jsonql events - * @param {*} nspMap - * @param {*} ee event emitter - * @param {function} log function to show internal - * @return {void} - */ - function connectEventListener(nspMap, ee, log) { - log("[2] setup the CONNECT_EVENT_NAME"); - // this is a automatic trigger from within the framework - ee.$only(CONNECT_EVENT_NAME$1, function connectEventNameHandler($config, $ee) { - log("[3] CONNECT_EVENT_NAME", $ee); - - return createNsp($config, nspMap) - .then(function (nsps) { return namespaceEventListener(bindSocketEventHandler, nsps); }) - .then(function (listenerFn) { return listenerFn($config, nspMap, $ee); }) - }); - - // log(`[3] after setup the CONNECT_EVENT_NAME`) - } - - // share method to create the wsClientResolver - - /** - * Create the framework <---> jsonql client binding - * @param {object} WebSocketClass the different WebSocket module - * @param {string} [type=browser] we need different setup for browser or node - * @return {function} the wsClientResolver - */ - function setupConnectClient(WebSocketClass, type) { - if ( type === void 0 ) type = 'browser'; - - /** - * wsClientResolver - * @param {object} opts configuration - * @param {object} nspMap from the contract - * @param {object} ee instance of the eventEmitter - * @return {object} passing the same 3 input out with additional in the opts - */ - return function createClientBindingAction(opts, nspMap, ee) { - var log = opts.log; - - log("There is problem here with passing the opts", opts); - // this will put two callable methods into the opts - opts[NSP_CLIENT] = setupWebsocketClientFn(WebSocketClass, type); - // we don't need this one unless enableAuth === true - if (opts[ENABLE_AUTH_PROP_KEY$1] === true) { - opts[NSP_AUTH_CLIENT] = setupWebsocketClientFn(WebSocketClass, type, true); - } - // debug - log("[1] bindWebsocketToJsonql", ee.$name, nspMap); - // @2020-03-20 @NOTE - - connectEventListener(nspMap, ee, log); - - // next we need to setup the login event handler - // But the same design (see above) when we received a login event - // from the http-client or the standalone login call - // we received a token here --> update the opts then trigger - // the CONNECT_EVENT_NAME again - loginEventListener(opts, nspMap, ee); - - log("just before returing the values for the next operation from createClientBindingAction"); - - // we just return what comes in - return { opts: opts, nspMap: nspMap, ee: ee } - } - } - - // this will be the news style interface that will pass to the jsonql-ws-client - - var setupSocketClientListener = setupConnectClient(ws$1); - - // this is the module entry point for ES6 for client - - // export back the function and that's it - function wsBrowserClient(config, constProps) { - if ( config === void 0 ) config = {}; - if ( constProps === void 0 ) constProps = {}; - - return wsClientCore( - setupSocketClientListener, - wsClientCheckMap, - Object.assign({}, wsClientConstProps, constProps) - )(config) - } - - // just export interface for browser - - return wsBrowserClient; - -}))); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("fs"),require("path")):"function"==typeof define&&define.amd?define(["fs","path"],e):(t=t||self).jsonqlWsClient=e(t.fs,t.path)}(this,(function(t,e){"use strict";t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var r=Array.isArray,n="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},o="object"==typeof n&&n&&n.Object===Object&&n,i="object"==typeof self&&self&&self.Object===Object&&self,u=o||i||Function("return this")(),a=u.Symbol,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=a?a.toStringTag:void 0;var p=Object.prototype.toString;var h=a?a.toStringTag:void 0;function g(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function v(t,e){return function(r){return t(e(r))}}var d=v(Object.getPrototypeOf,Object);function y(t){return null!=t&&"object"==typeof t}var _=Function.prototype,b=Object.prototype,m=_.toString,w=b.hasOwnProperty,j=m.call(Object);function E(t){if(!y(t)||"[object Object]"!=g(t))return!1;var e=d(t);if(null===e)return!0;var r=w.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&m.call(r)==j}function S(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&k(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var V=function(t){return r(t)?t:[t]},G=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},H=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Q=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},K=function(t){return G("string"==typeof t?t:JSON.stringify(t))},X=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Z=function(){return!1},tt=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,V(t))}),Reflect.apply(t,null,r))}};function et(t,e){return t===e||t!=t&&e!=e}function rt(t,e){for(var r=t.length;r--;)if(et(t[r][0],e))return r;return-1}var nt=Array.prototype.splice;function ot(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ot.prototype.set=function(t,e){var r=this.__data__,n=rt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ut(t){if(!it(t))return!1;var e=g(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var at,ct=u["__core-js_shared__"],st=(at=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var ft=Function.prototype.toString;function lt(t){if(null!=t){try{return ft.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var pt=/^\[object .+?Constructor\]$/,ht=Function.prototype,gt=Object.prototype,vt=ht.toString,dt=gt.hasOwnProperty,yt=RegExp("^"+vt.call(dt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _t(t){return!(!it(t)||(e=t,st&&st in e))&&(ut(t)?yt:pt).test(lt(t));var e}function bt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return _t(r)?r:void 0}var mt=bt(u,"Map"),wt=bt(Object,"create");var jt=Object.prototype.hasOwnProperty;var Et=Object.prototype.hasOwnProperty;function St(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Ht(t){return null!=t&&Gt(t.length)&&!ut(t)}var Qt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Qt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Kt&&Kt.exports===Qt?u.Buffer:void 0,Zt=(Xt?Xt.isBuffer:void 0)||function(){return!1},te={};te["[object Float32Array]"]=te["[object Float64Array]"]=te["[object Int8Array]"]=te["[object Int16Array]"]=te["[object Int32Array]"]=te["[object Uint8Array]"]=te["[object Uint8ClampedArray]"]=te["[object Uint16Array]"]=te["[object Uint32Array]"]=!0,te["[object Arguments]"]=te["[object Array]"]=te["[object ArrayBuffer]"]=te["[object Boolean]"]=te["[object DataView]"]=te["[object Date]"]=te["[object Error]"]=te["[object Function]"]=te["[object Map]"]=te["[object Number]"]=te["[object Object]"]=te["[object RegExp]"]=te["[object Set]"]=te["[object String]"]=te["[object WeakMap]"]=!1;var ee,re="object"==typeof exports&&exports&&!exports.nodeType&&exports,ne=re&&"object"==typeof module&&module&&!module.nodeType&&module,oe=ne&&ne.exports===re&&o.process,ie=function(){try{var t=ne&&ne.require&&ne.require("util").types;return t||oe&&oe.binding&&oe.binding("util")}catch(t){}}(),ue=ie&&ie.isTypedArray,ae=ue?(ee=ue,function(t){return ee(t)}):function(t){return y(t)&&Gt(t.length)&&!!te[g(t)]};function ce(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var se=Object.prototype.hasOwnProperty;function fe(t,e,r){var n=t[e];se.call(t,e)&&et(n,r)&&(void 0!==r||e in t)||Pt(t,e,r)}var le=/^(?:0|[1-9]\d*)$/;function pe(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&le.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Se);function Te(t,e){return Ae(function(t,e,r){return e=Ee(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Ee(n.length-e,0),u=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Re.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!it(r))return!1;var n=typeof e;return!!("number"==n?Ht(r)&&pe(e,r.length):"string"==n&&e in r)&&et(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},cr=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},sr=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ur(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ar(r,t)})).length},fr=function(t,e){if(void 0===e&&(e=null),E(t)){if(!e)return!0;if(ar(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=cr(t))?!sr({arg:r},e):!ur(t)(r))})).length)})).length}return!1},lr=function(t,e){var r,n,o,i,u;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,u=[o],Array.isArray(i.keys)&&i.keys.length&&u.push(i.keys),!Reflect.apply(fr,null,u);case"array"===t:return!ar(e.arg);case!1!==(r=cr(t)):return!sr(e,r);default:return!ur(t)(e.arg)}},pr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},hr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ar(e))throw new qe("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ar(t))throw console.info(t),new qe("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,u=e[r]||{type:o,name:"_"+r};return{arg:i?pr(t,u):t,index:r,param:u,optional:i}}));default:throw new Fe("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!tr(e)&&!(r.type.length>r.type.filter((function(e){return lr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return lr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},gr=v(Object.keys,Object),vr=Object.prototype.hasOwnProperty;function dr(t){return Ht(t)?ge(t):function(t){if(!qt(t))return gr(t);var e=[];for(var r in Object(t))vr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function yr(t,e){return t&&$t(t,e,dr)}function _r(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new At;++ea))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new _r:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var u=i.getMaxStore(t),a=-1;if(u>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var u=Array.from(i.get(t)),a=u.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!$n.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],u=Reflect.apply(this.addToStore,this,i),a=u[0],c=u[1];return this.normalStore=a,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),u=i[0],a=i[1];return this.lazyStore=u,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Mn.set(this,t)},r.normalStore.get=function(){return Mn.get(this)},r.lazyStore.set=function(t){Ln.set(this,t)},r.lazyStore.get=function(){return Ln.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=[],this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE ALL SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){var r=Un(e);if(Nn(r))return!1===t.__isPatternRegisterd(r)&&(t.__pattern__.push(r),t.__pattern__.length);throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')}))},e.prototype.$releaseEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){t.logger("($releaseEvent)",e);var r=Un(e);if(Nn(r)&&t.__isPatternRegisterd(r)){var n=t;return t.__getToReleaseQueue(r).map((function(t,e){return Reflect.apply(n.$trigger,n,t),e})).reduce((function(t,e){return++e}),0)}throw t.logger("$releaseEvent throw error ==========================>",t.__pattern__,r),new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')})).reduce((function(t,e){return t+e}),0)},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];switch(!0){case!0===this.__suspend_state__:return this.__addToQueueStore(t,e);case!0==!!this.__pattern__.length:return this.__pattern__.filter((function(e){return e.test(t)})).length?this.__addToQueueStore(t,e):(this.logger("($queue) "+t+" NOT added to $queueStore",this.__pattern__),!1);default:return this.logger("($queue) get called NOTHING added"),!1}},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__getToReleaseQueue=function(t){var e=this,r=this.$queues.filter((function(e){return t.test(e[0])})).map((function(r){return e.logger("[release] execute "+r[0]+" matches "+t,r),e.queueStore.delete(r),r}));return r.length>0&&(this.__pattern__=this.__pattern__.filter((function(e){return e.toString()!==t.toString()}))),r},e.prototype.__addToQueueStore=function(t,e){return this.logger("($queue) "+t+" added to $queueStore",e),this.queueStore.add([t].concat(e)),!0},e.prototype.__isPatternRegisterd=function(t){return!!this.__pattern__.filter((function(e){return e.toString()===t.toString()})).length},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=[],this.logger("(release) was called with "+e+(r.length?' for "'+r.join(",")+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.logger("(release queue)",n),n.forEach((function(e){t.logger("[release] execute "+e[0],e),Reflect.apply(t.$trigger,t,e)})),this.queueStore.clear(),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Bn)))),qn=function(t){var e=new RegExp("^(http|https)://","i"),r=t.match(e);if(r&&r.length){var n="https"===r[1].toLowerCase()?"wss":"ws";return t.replace(e,n+"://")}return t},Fn=function(t,e){V(e).forEach((function(e){t.$off(Q(e,"emit_reply"))}))};function Yn(t,e,r){H(t,"error")?r(t.error):H(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Jn(t,e,r,n,o){void 0===n&&(n=[]);var i=Q(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,V(n)]),new Promise((function(n,i){var u=Q(e,r,"onResult");t.$on(u,(function(t){o("got the first result",t),Yn(t,n,i)}))}))}var Wn=function(t,e,r,n,o,i){return xe(t,"send",Z,(function(){return i("running call getter method"),function(){for(var t=[],u=arguments.length;u--;)t[u]=arguments[u];return On(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Jn(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(Q(r,n,"onError"),[new qe(n,t)])}))}}))};function Vn(t,e,r,n,o){return function(){for(var i=[],u=arguments.length;u--;)i[u]=arguments[u];return On(i,n.params,!0).then((function(n){return Jn(t,e,r,n,o)})).catch(Je)}}var Gn=function(t,e,r,n,o,i){return[ke(t,"myNamespace",r),e,r,n,o,i]},Hn=function(t,e,r,n,o,i){return[xe(t,"onResult",(function(t){X(t)&&e.$on(Q(r,n,"onResult"),(function(o){Yn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Qn=function(t,e,r,n,o,i){return[xe(t,"onMessage",(function(t){if(X(t)){e.$only(Q(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Yn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Kn=function(t,e,r,n,o,i){return[xe(t,"onError",(function(t){X(t)&&e.$only(Q(r,n,"onError"),t)})),e,r,n,o,i]};function Xn(t,e,r,n,o,i){var u=[Gn,Hn,Qn,Kn,Wn];return Reflect.apply(tt,null,u)(n,o,t,e,r,i)}function Zn(t,e,r){var n=t.log,o={};for(var i in r){var u=r[i];for(var a in u){var c=u[a];o=ke(o,a,Xn(i,a,c,Vn(e,i,a,c,n),e,n))}}return[o,t,e,r]}function to(t,e,r){return[xe(t,"onReady",(function(t){X(t)&&r.$only("onReady",t)})),e,r]}function eo(t,e,r,n){return[xe(t,"onError",(function(t){if(X(t))for(var e in n)r.$on(Q(e,"onError"),t)})),e,r]}var ro=function(t,e,r){return[ke(t,e.loginHandlerName,(function(t){if(t&&Sn(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new qe(e.loginHandlerName,"Unexpected token "+t)})),e,r]},no=function(t,e,r){return[ke(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},oo=function(t,e,r){return[xe(t,"onLogin",(function(t){X(t)&&r.$only("onLogin",t)})),e,r]};function io(t,e,r){return tt(ro,no,oo)(t,e,r)}function uo(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=ke(t,"connected",!1,!0),e,r]}function ao(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function co(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function so(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function fo(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),ke(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}var lo=[],po=[],ho="undefined"!=typeof Uint8Array?Uint8Array:Array,go=!1;function vo(){go=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+lo[o>>12&63]+lo[o>>6&63]+lo[63&o]);return i.join("")}function _o(t){var e;go||vo();for(var r=t.length,n=r%3,o="",i=[],u=0,a=r-n;ua?a:u+16383));return 1===n?(e=t[r-1],o+=lo[e>>2],o+=lo[e<<4&63],o+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],o+=lo[e>>10],o+=lo[e>>4&63],o+=lo[e<<2&63],o+="="),i.push(o),i.join("")}function bo(t,e,r,n,o){var i,u,a=8*o-n-1,c=(1<>1,f=-7,l=r?o-1:0,p=r?-1:1,h=t[e+l];for(l+=p,i=h&(1<<-f)-1,h>>=-f,f+=a;f>0;i=256*i+t[e+l],l+=p,f-=8);for(u=i&(1<<-f)-1,i>>=-f,f+=n;f>0;u=256*u+t[e+l],l+=p,f-=8);if(0===i)i=1-s;else{if(i===c)return u?NaN:1/0*(h?-1:1);u+=Math.pow(2,n),i-=s}return(h?-1:1)*u*Math.pow(2,i-n)}function mo(t,e,r,n,o,i){var u,a,c,s=8*i-o-1,f=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,g=n?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,u=f):(u=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-u))<1&&(u--,c*=2),(e+=u+l>=1?p/c:p*Math.pow(2,1-l))*c>=2&&(u++,c/=2),u+l>=f?(a=0,u=f):u+l>=1?(a=(e*c-1)*Math.pow(2,o),u+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,o),u=0));o>=8;t[r+h]=255&a,h+=g,a/=256,o-=8);for(u=u<0;t[r+h]=255&u,h+=g,u/=256,s-=8);t[r+h-g]|=128*v}var wo={}.toString,jo=Array.isArray||function(t){return"[object Array]"==wo.call(t)};function Eo(){return Oo.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function So(t,e){if(Eo()=Eo())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Eo().toString(16)+" bytes");return 0|t}function ko(t){return!(null==t||!t._isBuffer)}function $o(t,e){if(ko(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ui(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ai(t).length;default:if(n)return ui(t).length;e=(""+e).toLowerCase(),n=!0}}function No(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Vo(this,e,r);case"utf8":case"utf-8":return Yo(this,e,r);case"ascii":return Jo(this,e,r);case"latin1":case"binary":return Wo(this,e,r);case"base64":return Fo(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Go(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Co(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function zo(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=Oo.from(e,n)),ko(e))return 0===e.length?-1:Uo(t,e,r,n,o);if("number"==typeof e)return e&=255,Oo.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Uo(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function Uo(t,e,r,n,o){var i,u=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;u=2,a/=2,c/=2,r/=2}function s(t,e){return 1===u?t[e]:t.readUInt16BE(e*u)}if(o){var f=-1;for(i=r;ia&&(r=a-c),i=r;i>=0;i--){for(var l=!0,p=0;po&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;u>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function Fo(t,e,r){return 0===e&&r===t.length?_o(t):_o(t.slice(e,r))}function Yo(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o239?4:s>223?3:s>191?2:1;if(o+l<=r)switch(l){case 1:s<128&&(f=s);break;case 2:128==(192&(i=t[o+1]))&&(c=(31&s)<<6|63&i)>127&&(f=c);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(c=(15&s)<<12|(63&i)<<6|63&u)>2047&&(c<55296||c>57343)&&(f=c);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(c=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&c<1114112&&(f=c)}null===f?(f=65533,l=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),o+=l}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},Oo.prototype.compare=function(t,e,r,n,o){if(!ko(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(r>>>=0)-(e>>>=0),a=Math.min(i,u),c=this.slice(n,o),s=t.slice(e,r),f=0;fo)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Mo(this,t,e,r);case"utf8":case"utf-8":return Lo(this,t,e,r);case"ascii":return Bo(this,t,e,r);case"latin1":case"binary":return Io(this,t,e,r);case"base64":return Do(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return qo(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Oo.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Jo(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function Qo(t,e,r,n,o,i){if(!ko(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function Ko(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o>>8*(n?o:1-o)}function Xo(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o>>8*(n?o:3-o)&255}function Zo(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function ti(t,e,r,n,o){return o||Zo(t,0,r,4),mo(t,e,r,n,23,4),r+4}function ei(t,e,r,n,o){return o||Zo(t,0,r,8),mo(t,e,r,n,52,8),r+8}Oo.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(o*=256);)n+=this[t+--e]*o;return n},Oo.prototype.readUInt8=function(t,e){return e||Ho(t,1,this.length),this[t]},Oo.prototype.readUInt16LE=function(t,e){return e||Ho(t,2,this.length),this[t]|this[t+1]<<8},Oo.prototype.readUInt16BE=function(t,e){return e||Ho(t,2,this.length),this[t]<<8|this[t+1]},Oo.prototype.readUInt32LE=function(t,e){return e||Ho(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Oo.prototype.readUInt32BE=function(t,e){return e||Ho(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Oo.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Ho(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},Oo.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Ho(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},Oo.prototype.readInt8=function(t,e){return e||Ho(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Oo.prototype.readInt16LE=function(t,e){e||Ho(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Oo.prototype.readInt16BE=function(t,e){e||Ho(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Oo.prototype.readInt32LE=function(t,e){return e||Ho(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Oo.prototype.readInt32BE=function(t,e){return e||Ho(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Oo.prototype.readFloatLE=function(t,e){return e||Ho(t,4,this.length),bo(this,t,!0,23,4)},Oo.prototype.readFloatBE=function(t,e){return e||Ho(t,4,this.length),bo(this,t,!1,23,4)},Oo.prototype.readDoubleLE=function(t,e){return e||Ho(t,8,this.length),bo(this,t,!0,52,8)},Oo.prototype.readDoubleBE=function(t,e){return e||Ho(t,8,this.length),bo(this,t,!1,52,8)},Oo.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Qo(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i=0&&(i*=256);)this[e+o]=t/i&255;return e+r},Oo.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,1,255,0),Oo.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Oo.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,65535,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ko(this,t,e,!0),e+2},Oo.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,65535,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ko(this,t,e,!1),e+2},Oo.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,4294967295,0),Oo.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Xo(this,t,e,!0),e+4},Oo.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,4294967295,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Xo(this,t,e,!1),e+4},Oo.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Qo(this,t,e,r,o-1,-o)}var i=0,u=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},Oo.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Qo(this,t,e,r,o-1,-o)}var i=r-1,u=1,a=0;for(this[e+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/u>>0)-a&255;return e+r},Oo.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,1,127,-128),Oo.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Oo.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,32767,-32768),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ko(this,t,e,!0),e+2},Oo.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,32767,-32768),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ko(this,t,e,!1),e+2},Oo.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,2147483647,-2147483648),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Xo(this,t,e,!0),e+4},Oo.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Xo(this,t,e,!1),e+4},Oo.prototype.writeFloatLE=function(t,e,r){return ti(this,t,e,!0,r)},Oo.prototype.writeFloatBE=function(t,e,r){return ti(this,t,e,!1,r)},Oo.prototype.writeDoubleLE=function(t,e,r){return ei(this,t,e,!0,r)},Oo.prototype.writeDoubleBE=function(t,e,r){return ei(this,t,e,!1,r)},Oo.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else if(i<1e3||!Oo.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function ai(t){return function(t){var e,r,n,o,i,u;go||vo();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,u=new ho(3*a/4-i),n=i>0?a-4:a;var c=0;for(e=0,r=0;e>16&255,u[c++]=o>>8&255,u[c++]=255&o;return 2===i?(o=po[t.charCodeAt(e)]<<2|po[t.charCodeAt(e+1)]>>4,u[c++]=255&o):1===i&&(o=po[t.charCodeAt(e)]<<10|po[t.charCodeAt(e+1)]<<4|po[t.charCodeAt(e+2)]>>2,u[c++]=o>>8&255,u[c++]=255&o),u}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace(oi,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ci(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function si(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function fi(t,e,r){var n=function(t,e,r){var n=[uo,ao,co,so,fo];return Reflect.apply(tt,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),ke(n,"isLogin",!1,!0)}var li={};li.standalone=An(!1,["boolean"]),li.debugOn=An(!1,["boolean"]),li.loginHandlerName=An("login",["string"]),li.logoutHandlerName=An("logout",["string"]),li.disconnectHandlerName=An("disconnect",["string"]),li.switchUserHandlerName=An("switch-user",["string"]),li.hostname=An(!1,["string"]),li.namespace=An("jsonql",["string"]),li.wsOptions=An({},["object"]),li.contract=An({},["object"],((ri={}).checker=function(t){return!!function(t){return E(t)&&(H(t,"query")||H(t,"mutation")||H(t,"socket"))}(t)&&t},ri)),li.enableAuth=An(!1,["boolean"]),li.token=An(!1,["string"]),li.csrf=An("X-CSRF-Token",["string"]),li.suspendOnStart=An(!1,["boolean"]);var pi={};pi.serverType=An(null,["string"],((ni={}).alias="socketClientType",ni));var hi=Object.assign(li,pi),gi={};function vi(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new qe(t)}}()),t.wssPath=qn([t.hostname,t.namespace].join("/"),t.serverType),t.log=Pn(t),t.eventEmitter=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Dn(t.log)}(t),t}))}function di(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Qe(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function yi(t){return function(e){return void 0===e&&(e={}),vi(e).then(di).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Zn,to,eo];return t.enableAuth&&n.push(io),n.push(fi),Reflect.apply(tt,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function _i(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),function(n){return void 0===n&&(n={}),function(t,e,r){var n=Object.assign(hi,e),o=Object.assign(gi,r);return Tn(t,n,o)}(n,e,r).then(yi(t))}}gi.useJwt=!0,gi.log=null,gi.eventEmitter=null,gi.nspClient=null,gi.nspAuthClient=null,gi.wssPath="",gi.publicNamespace="public",gi.privateNamespace="private";var bi=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(Q(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),Fn(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function mi(t,e){return function(r,n,o){var i=r.log,u=n.namespaces,a=function(t){return t.length>1&&t[0]}(u),c=u.length-1;return u.map((function(n){var s=a===n;if(i(n," --\x3e "+(s?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",s,n);var f=[n,e[n],o,s,r,--c];Reflect.apply(t,null,f)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(Q(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(Q(t,r,"onError"),[i]),e.$call(Q(t,r,"onResult"),[{error:i}])}))}(n,o,r);return s&&(i("Has private and add logoutEvtHandler"),bi(e,u,o,r)),s}))}}function wi(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,u=t?[r,t].join("/"):n;return i("createNspClient with URL --\x3e ",u),o(u,e)}var ji,Ei,Si,Oi,Ai,Ti,Ri,Pi,xi;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}An("HS256",["string"]),An(!1,["boolean","number","string"],((ji={}).alias="exp",ji.optional=!0,ji)),An(!1,["boolean","number","string"],((Ei={}).alias="nbf",Ei.optional=!0,Ei)),An(!1,["boolean","string"],((Si={}).alias="iss",Si.optional=!0,Si)),An(!1,["boolean","string"],((Oi={}).alias="sub",Oi.optional=!0,Oi)),An(!1,["boolean","string"],((Ai={}).alias="iss",Ai.optional=!0,Ai)),An(!1,["boolean"],((Ti={}).optional=!0,Ti)),An(!1,["boolean","string"],((Ri={}).optional=!0,Ri)),An(!1,["boolean","string"],((Pi={}).optional=!0,Pi)),An(!1,["boolean"],((xi={}).optional=!0,xi));function ki(t,e){var r,n;void 0===e&&(e=!1);var o=t.wsOptions||{},i=t.headers||{};return e&&(i=Object.assign(i,((r={}).Authorization="Bearer "+e,r))),Object.assign({},o,((n={}).headers=i,n))}function $i(t,e,r){switch(void 0===e&&(e={}),void 0===r&&(r=!1),e.tokenDeliverLocation||"url"){case"url":return{url:r?t+"?token="+r:t,opts:ki(e,!1)};case"header":default:return{url:t,opts:ki(e,r)}}}var Ni="object"==typeof n&&n&&n.Object===Object&&n,Ci="object"==typeof self&&self&&self.Object===Object&&self,zi=Ni||Ci||Function("return this")(),Ui=zi.Symbol;var Mi=Array.isArray,Li=Object.prototype,Bi=Li.hasOwnProperty,Ii=Li.toString,Di=Ui?Ui.toStringTag:void 0;var qi=Object.prototype.toString;var Fi=Ui?Ui.toStringTag:void 0;function Yi(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Fi&&Fi in Object(t)?function(t){var e=Bi.call(t,Di),r=t[Di];try{t[Di]=void 0;var n=!0}catch(t){}var o=Ii.call(t);return n&&(e?t[Di]=r:delete t[Di]),o}(t):function(t){return qi.call(t)}(t)}function Ji(t){return null!=t&&"object"==typeof t}var Wi=Ui?Ui.prototype:void 0,Vi=Wi?Wi.toString:void 0;function Gi(t){if("string"==typeof t)return t;if(Mi(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&Ki(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function pu(t){return function(t){return"number"==typeof t||Ji(t)&&"[object Number]"==Yi(t)}(t)&&t!=+t}function hu(t){return"string"==typeof t||!Mi(t)&&Ji(t)&&"[object String]"==Yi(t)}var gu=function(t){return!hu(t)&&!pu(parseFloat(t))},vu=function(t){return""!==lu(t)&&hu(t)},du=function(t){return null!=t&&"boolean"==typeof t},yu=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==lu(t)&&(!1===e||!0===e&&null!==t)},_u=function(t,e){return void 0===e&&(e=""),!!Mi(t)&&(""===e||""===lu(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return gu;case"string":return vu;case"boolean":return du;default:return yu}}(e)(t)})).length>0))};var bu=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object),mu=Function.prototype,wu=Object.prototype,ju=mu.toString,Eu=wu.hasOwnProperty,Su=ju.call(Object);function Ou(t){if(!Ji(t)||"[object Object]"!=Yi(t))return!1;var e=bu(t);if(null===e)return!0;var r=Eu.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&ju.call(r)==Su}var Au=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Tu=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function Ru(t,e){return t===e||t!=t&&e!=e}function Pu(t,e){for(var r=t.length;r--;)if(Ru(t[r][0],e))return r;return-1}var xu=Array.prototype.splice;function ku(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ku.prototype.set=function(t,e){var r=this.__data__,n=Pu(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function Nu(t){if(!$u(t))return!1;var e=Yi(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Cu=zi["__core-js_shared__"],zu=function(){var t=/[^.]+$/.exec(Cu&&Cu.keys&&Cu.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Uu=Function.prototype.toString;var Mu=/^\[object .+?Constructor\]$/,Lu=Function.prototype,Bu=Object.prototype,Iu=Lu.toString,Du=Bu.hasOwnProperty,qu=RegExp("^"+Iu.call(Du).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Fu(t){return!(!$u(t)||function(t){return!!zu&&zu in t}(t))&&(Nu(t)?qu:Mu).test(function(t){if(null!=t){try{return Uu.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function Yu(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Fu(r)?r:void 0}var Ju=Yu(zi,"Map"),Wu=Yu(Object,"create");var Vu=Object.prototype.hasOwnProperty;var Gu=Object.prototype.hasOwnProperty;function Hu(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function ba(t){return null!=t&&_a(t.length)&&!Nu(t)}var ma="object"==typeof exports&&exports&&!exports.nodeType&&exports,wa=ma&&"object"==typeof module&&module&&!module.nodeType&&module,ja=wa&&wa.exports===ma?zi.Buffer:void 0,Ea=(ja?ja.isBuffer:void 0)||function(){return!1},Sa={};Sa["[object Float32Array]"]=Sa["[object Float64Array]"]=Sa["[object Int8Array]"]=Sa["[object Int16Array]"]=Sa["[object Int32Array]"]=Sa["[object Uint8Array]"]=Sa["[object Uint8ClampedArray]"]=Sa["[object Uint16Array]"]=Sa["[object Uint32Array]"]=!0,Sa["[object Arguments]"]=Sa["[object Array]"]=Sa["[object ArrayBuffer]"]=Sa["[object Boolean]"]=Sa["[object DataView]"]=Sa["[object Date]"]=Sa["[object Error]"]=Sa["[object Function]"]=Sa["[object Map]"]=Sa["[object Number]"]=Sa["[object Object]"]=Sa["[object RegExp]"]=Sa["[object Set]"]=Sa["[object String]"]=Sa["[object WeakMap]"]=!1;var Oa="object"==typeof exports&&exports&&!exports.nodeType&&exports,Aa=Oa&&"object"==typeof module&&module&&!module.nodeType&&module,Ta=Aa&&Aa.exports===Oa&&Ni.process,Ra=function(){try{var t=Aa&&Aa.require&&Aa.require("util").types;return t||Ta&&Ta.binding&&Ta.binding("util")}catch(t){}}(),Pa=Ra&&Ra.isTypedArray,xa=Pa?function(t){return function(e){return t(e)}}(Pa):function(t){return Ji(t)&&_a(t.length)&&!!Sa[Yi(t)]};function ka(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var $a=Object.prototype.hasOwnProperty;function Na(t,e,r){var n=t[e];$a.call(t,e)&&Ru(n,r)&&(void 0!==r||e in t)||ta(t,e,r)}var Ca=/^(?:0|[1-9]\d*)$/;function za(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Ca.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Va);function Qa(t,e){return Ha(function(t,e,r){return e=Wa(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Wa(n.length-e,0),u=Array(i);++o1?r[o-1]:void 0,u=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&function(t,e,r){if(!$u(r))return!1;var n=typeof e;return!!("number"==n?ba(r)&&za(e,r.length):"string"==n&&e in r)&&Ru(r[e],t)}(r[0],r[1],u)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=We(),o=[t].concat(e);return o.push(n),He("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var jc=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(cc,null,o),u=n.data||n;t.$trigger(i,[u])};function Ec(t,e,r,n,o,i){var u=o.log;return n&&(u("Private namespace",t," binding to the DISCONNECT ws.terminate"),wc(r,e)),e.onopen=function(){u("client.ws.onopen listened --\x3e",t),n?(u("isPrivate and fire the onLogin"),r.$call("onLogin")(t)):(r.$call("onReady")(t,i),u("isPublic onReady hook executed",i),0===i&&r.$off("onReady")),r.$only(cc(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(hc(t,e,r))}(t,r);u("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){u("client.ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=lc);try{var r,n=sc(t);if(!1!==(r=vc(n)))return e("_data",r),{data:sc(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Tu("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,i=n.type;switch(u("Respond from server",i,n),i){case"emit_reply":var a=cc(t,o,"onMessage"),c=r.$call(a)(n);u("EMIT_REPLY_TYPE",a,c);break;case"emit_acknowledge":var s=cc(t,o,"onResult"),f=r.$call(s)(n);u("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":u("ERROR_KEY"),jc(r,t,o,n);break;default:u("Unhandled event!",n),jc(r,t,o,n)}}catch(e){u("client.ws.onmessage error",e),jc(r,t,!1,e)}},e.onclose=function(){u("client.ws.onclose callback")},e.onerror=function(e){u("client.ws.onerror",e),function(t,e,r){t.$trigger(Q(e,"onError"),[r])}(r,t,e)},e}var Sc,Oc,Ac=(Sc=ic,void 0===Oc&&(Oc="browser"),function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=bc(Sc,Oc),!0===t.enableAuth&&(t.nspAuthClient=bc(Sc,Oc,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),mc(e,t).then((function(t){return mi(Ec,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),Fn(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}});return function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),_i(Ac,nc,Object.assign({},rc,e))(t)}})); //# sourceMappingURL=jsonql-ws-client.umd.js.map diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map index 139e6b2d5f46a4a9cfec0131a31be35592ebeb05..1dde4399b48d106a9f804348318c4f4e03f997d4 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-ws-client.umd.js","sources":["../../../ws-client-core/node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../../../ws-client-core/node_modules/lodash-es/_objectToString.js","../../../ws-client-core/node_modules/lodash-es/_overArg.js","../../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../../ws-client-core/node_modules/lodash-es/_arrayMap.js","../../../ws-client-core/node_modules/lodash-es/_baseSlice.js","../../../ws-client-core/node_modules/lodash-es/_baseFindIndex.js","../../../ws-client-core/node_modules/lodash-es/_baseIsNaN.js","../../../ws-client-core/node_modules/lodash-es/_strictIndexOf.js","../../../ws-client-core/node_modules/lodash-es/_asciiToArray.js","../../../ws-client-core/node_modules/lodash-es/_hasUnicode.js","../../../ws-client-core/node_modules/lodash-es/_unicodeToArray.js","../../../ws-client-core/node_modules/jsonql-utils/src/generic.js","../../../ws-client-core/node_modules/lodash-es/_listCacheClear.js","../../../ws-client-core/node_modules/lodash-es/eq.js","../../../ws-client-core/node_modules/lodash-es/_stackDelete.js","../../../ws-client-core/node_modules/lodash-es/_stackGet.js","../../../ws-client-core/node_modules/lodash-es/_stackHas.js","../../../ws-client-core/node_modules/lodash-es/isObject.js","../../../ws-client-core/node_modules/lodash-es/_toSource.js","../../../ws-client-core/node_modules/lodash-es/_getValue.js","../../../ws-client-core/node_modules/lodash-es/_hashDelete.js","../../../ws-client-core/node_modules/lodash-es/_isKeyable.js","../../../ws-client-core/node_modules/lodash-es/_createBaseFor.js","../../../ws-client-core/node_modules/lodash-es/_copyArray.js","../../../ws-client-core/node_modules/lodash-es/_isPrototype.js","../../../ws-client-core/node_modules/lodash-es/isLength.js","../../../ws-client-core/node_modules/lodash-es/stubFalse.js","../../../ws-client-core/node_modules/lodash-es/_baseUnary.js","../../../ws-client-core/node_modules/lodash-es/_safeGet.js","../../../ws-client-core/node_modules/lodash-es/_baseTimes.js","../../../ws-client-core/node_modules/lodash-es/_isIndex.js","../../../ws-client-core/node_modules/lodash-es/_nativeKeysIn.js","../../../ws-client-core/node_modules/lodash-es/identity.js","../../../ws-client-core/node_modules/lodash-es/_apply.js","../../../ws-client-core/node_modules/lodash-es/constant.js","../../../ws-client-core/node_modules/lodash-es/_shortOut.js","../../../ws-client-core/node_modules/jsonql-errors/src/enum-error.js","../../../ws-client-core/node_modules/jsonql-errors/src/type-error.js","../../../ws-client-core/node_modules/jsonql-errors/src/checker-error.js","../../../ws-client-core/node_modules/jsonql-errors/src/validation-error.js","../../../ws-client-core/node_modules/jsonql-utils/src/contract.js","../../../ws-client-core/node_modules/jsonql-utils/src/timestamp.js","../../../ws-client-core/node_modules/jsonql-utils/src/params-api.js","../../../ws-client-core/node_modules/jsonql-utils/src/namespace.js","../../../ws-client-core/node_modules/jsonql-utils/src/socket.js","../../../ws-client-core/src/callers/intercom-methods.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/number.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/string.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/boolean.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/any.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/constants.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/combine.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/array.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/object.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/validator.js","../../../ws-client-core/node_modules/lodash-es/_setCacheAdd.js","../../../ws-client-core/node_modules/lodash-es/_setCacheHas.js","../../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../../ws-client-core/node_modules/lodash-es/_cacheHas.js","../../../ws-client-core/node_modules/lodash-es/_mapToArray.js","../../../ws-client-core/node_modules/lodash-es/_setToArray.js","../../../ws-client-core/node_modules/lodash-es/_arrayPush.js","../../../ws-client-core/node_modules/lodash-es/_arrayFilter.js","../../../ws-client-core/node_modules/lodash-es/stubArray.js","../../../ws-client-core/node_modules/lodash-es/_matchesStrictComparable.js","../../../ws-client-core/node_modules/lodash-es/_baseHasIn.js","../../../ws-client-core/node_modules/lodash-es/_baseProperty.js","../../../ws-client-core/node_modules/lodash-es/negate.js","../../../ws-client-core/node_modules/lodash-es/_baseFindKey.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/is-in-array.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/options/run-validation.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/options/check-options-async.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/options/construct-config.js","../../../ws-client-core/node_modules/jsonql-params-validator/src/options/index.js","../../../ws-client-core/node_modules/jsonql-params-validator/index.js","../../../ws-client-core/src/utils/get-log-fn.js","../../../ws-client-core/node_modules/@to1source/event/src/constants.js","../../../ws-client-core/node_modules/@to1source/event/src/utils.js","../../../ws-client-core/node_modules/@to1source/event/src/store.js","../../../ws-client-core/node_modules/@to1source/event/src/base.js","../../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../../ws-client-core/node_modules/@to1source/event/src/store-service.js","../../../ws-client-core/node_modules/@to1source/event/src/event-service.js","../../../ws-client-core/node_modules/@to1source/event/index.js","../../../ws-client-core/src/utils/get-event-emitter.js","../../../ws-client-core/src/utils/helpers.js","../../../ws-client-core/src/options/constants.js","../../../ws-client-core/src/callers/respond-handler.js","../../../ws-client-core/src/callers/action-call.js","../../../ws-client-core/src/callers/setup-send-method.js","../../../ws-client-core/src/callers/setup-resolver.js","../../../ws-client-core/src/callers/generator-methods.js","../../../ws-client-core/src/callers/global-listener.js","../../../ws-client-core/src/callers/setup-auth-methods.js","../../../ws-client-core/src/callers/setup-intercom.js","../../../ws-client-core/src/callers/setup-final-step.js","../../../ws-client-core/src/callers/callers-generator.js","../../../ws-client-core/src/options/index.js","../../../ws-client-core/src/api.js","../../../ws-client-core/src/listener/trigger-namespaces-on-error.js","../../../ws-client-core/src/listener/event-listeners.js","../../../ws-client-core/src/listener/namespace-event-listener.js","../../../ws-client-core/src/create-nsp-client.js","../../../ws-client-core/node_modules/@jsonql/security/src/client/jwt-decode/invalid-character-error.js","../../../ws-client-core/node_modules/@jsonql/security/src/client/jwt-decode/atob.js","../../../ws-client-core/node_modules/@jsonql/security/src/socket/token-header-opts.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/isArray.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_overArg.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-utils/src/chain-promises.js","../node_modules/jsonql-utils/src/timestamp.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/socket.js","../src/core/setup-connect-client/setup-websocket-client-fn.js","../src/core/setup-socket-listeners/login-event-listener.js","../src/core/create-nsp.js","../src/core/setup-socket-listeners/disconnect-event-listener.js","../src/core/setup-socket-listeners/bind-socket-event-handler.js","../src/core/setup-socket-listeners/connect-event-listener.js","../src/core/setup-connect-client/setup-connect-client.js","../src/core/setup-socket-client-listener.js","../src/browser-ws-client.js","../index.js"],"sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError)\n }\n }\n\n static get name() {\n return 'JsonqlEnumError'\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlTypeError.name\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError)\n }\n }\n\n static get name() {\n return 'JsonqlTypeError'\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args)\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError)\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError'\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","// split the contract into the node side and the generic side\nimport { isObjectHasKey } from './generic'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n SOCKET_NAME,\n QUERY_ARG_NAME,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlResolverNotFoundError } from 'jsonql-errors'\n/**\n * Check if the json is a contract file or not\n * @param {object} contract json object\n * @return {boolean} true\n */\nexport function checkIsContract(contract) {\n return isPlainObject(contract)\n && (\n isObjectHasKey(contract, QUERY_NAME)\n || isObjectHasKey(contract, MUTATION_NAME)\n || isObjectHasKey(contract, SOCKET_NAME)\n )\n}\n\n/**\n * Wrapper method that check if it's contract then return the contract or false\n * @param {object} contract the object to check\n * @return {boolean | object} false when it's not\n */\nexport function isContract(contract) {\n return checkIsContract(contract) ? contract : false\n}\n\n/**\n * Ported from jsonql-params-validator but different\n * if we don't find the socket part then return false\n * @param {object} contract the contract object\n * @return {object|boolean} false on failed\n */\nexport function extractSocketPart(contract) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n return contract[SOCKET_NAME]\n }\n return false\n}\n\n/**\n * Extract the args from the payload\n * @param {object} payload to work with\n * @param {string} type of call\n * @return {array} args\n */\nexport function extractArgsFromPayload(payload, type) {\n switch (type) {\n case QUERY_NAME:\n return payload[QUERY_ARG_NAME]\n case MUTATION_NAME:\n return [\n payload[PAYLOAD_PARAM_NAME],\n payload[CONDITION_PARAM_NAME]\n ]\n default:\n throw new JsonqlError(`Unknown ${type} to extract argument from!`)\n }\n}\n\n/**\n * Like what the name said\n * @param {object} contract the contract json\n * @param {string} type query|mutation\n * @param {string} name of the function\n * @return {object} the params part of the contract\n */\nexport function extractParamsFromContract(contract, type, name) {\n try {\n const result = contract[type][name]\n // debug('extractParamsFromContract', result)\n if (!result) {\n // debug(name, type, contract)\n throw new JsonqlResolverNotFoundError(name, type)\n }\n return result\n } catch(e) {\n throw new JsonqlResolverNotFoundError(name, e)\n }\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// take out all the namespace related methods in one place for easy to find\nimport {\n JSONQL_PATH,\n PUBLIC_KEY,\n NSP_GROUP,\n PUBLIC_NAMESPACE\n} from 'jsonql-constants'\nimport { extractSocketPart } from './contract'\nconst SOCKET_NOT_FOUND_ERR = `socket not found in contract!`\nconst SIZE = 'size'\n\n/**\n * create the group using publicNamespace when there is only public\n * @param {object} socket from contract\n * @param {string} publicNamespace\n */\nfunction groupPublicNamespace(socket, publicNamespace) {\n let g = {}\n for (let resolverName in socket) {\n let params = socket[resolverName]\n g[resolverName] = params\n }\n return { size: 1, nspGroup: {[publicNamespace]: g}, publicNamespace}\n}\n\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport function groupByNamespace(contract) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n throw new JsonqlError('groupByNamespace', SOCKET_NOT_FOUND_ERR)\n }\n let prop = {\n [NSP_GROUP]: {},\n [PUBLIC_NAMESPACE]: null,\n [SIZE]: 0 \n }\n\n for (let resolverName in socket) {\n let params = socket[resolverName]\n let { namespace } = params\n if (namespace) {\n if (!prop[NSP_GROUP][namespace]) {\n ++prop[SIZE]\n prop[NSP_GROUP][namespace] = {}\n }\n prop[NSP_GROUP][namespace][resolverName] = params\n // get the public namespace\n if (!prop[PUBLIC_NAMESPACE] && params[PUBLIC_KEY]) {\n prop[PUBLIC_NAMESPACE] = namespace\n }\n }\n }\n \n return prop \n}\n\n/**\n * @NOTE ported from jsonql-ws-client\n * Got to make sure the connection order otherwise\n * it will hang\n * @param {object} nspGroup contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspGroup, publicNamespace) {\n let names = [] // need to make sure the order!\n for (let namespace in nspGroup) {\n if (namespace === publicNamespace) {\n names[1] = namespace\n } else {\n names[0] = namespace\n }\n }\n return names\n}\n\n/**\n * @TODO this might change, what if we want to do room with ws\n * 1. there will only be max two namespace\n * 2. when it's normal we will have the stock path as namespace\n * 3. when enableAuth then we will have two, one is jsonql/public + private\n * @param {object} config options\n * @return {array} of namespace(s)\n */\nexport function getNamespace(config) {\n const base = JSONQL_PATH\n if (config.enableAuth) {\n // the public come first @1.0.1 we use the constants instead of the user supplied value\n // @1.0.4 we use the config value again, because we could control this via the post init\n return [\n [ base , config.privateNamespace ].join('/'),\n [ base , config.publicNamespace ].join('/')\n ]\n }\n return [ base ]\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nexport function getPrivateNamespace(namespaces) {\n return namespaces.length > 1 ? namespaces[0] : false\n}\n\n/**\n * Got a problem with a contract that is public only the groupByNamespace is wrong\n * which is actually not a problem when using a fallback, but to be sure things in order\n * we could combine with the config to group it\n * @param {object} config configuration\n * @return {object} nspInfo object\n */\nexport function getNspInfoByConfig(config) {\n const { contract, enableAuth } = config\n const namespaces = getNamespace(config)\n let nspInfo = enableAuth ? groupByNamespace(contract)\n : groupPublicNamespace(contract.socket, namespaces[0])\n // add the namespaces into it as well\n return Object.assign(nspInfo, { namespaces })\n}\n\n","// There are the socket related methods ported back from \n// ws-server-core and ws-client-core \nimport {\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME,\n TIMESTAMP_PARAM_NAME,\n ERROR_KEY,\n EMIT_REPLY_TYPE,\n EMIT_SEND_TYPE,\n ACKNOWLEDGE_REPLY_TYPE\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlValidationError } from 'jsonql-errors' \nimport isString from 'lodash-es/isString'\nimport isArray from 'lodash-es/isArray'\n\nimport { createDeliverable, formatPayload } from './params-api'\nimport { toJson, isObjectHasKey, nil } from './generic'\nimport { timestamp } from './timestamp'\n\nconst PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'\nconst WS_KEYS = [\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME\n]\n\n/////////////////////////////////////\n// REPLY FROM SERVER //\n/////////////////////////////////////\n\n/**\n * This will be a event emit from the client using the send method \n * But we have to change the server to understand it\n * @param {string} resolverName name of resolver ot call \n * @param {array} args for the resolver\n * @param {boolean} str true then stringify it \n * @return {object} formatted payload\n */\nexport const createSendPayload = (resolverName, args, str = false) => {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n // the different is we add a additonal type in the payload \n const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE})\n return str ? JSON.stringify(result) : result\n }\n throw new JsonqlValidationError(`utils:socket:createSendMsg`, { \n resolverName, \n args, \n message: 'expect resolverName to be string and args to be array!'\n })\n}\n\n/**\n * We need to find the TS field and take it out from the previous payload \n * otherwise it will keep on rolling into the structure which is not what we wanted\n * @param {object} data for inspection\n * @return {object} { data: for the data to use, TS if there is any }\n */\nconst getTsFieldFromData = (data) => {\n let obj = {[TIMESTAMP_PARAM_NAME]: [], data: {}}\n if (data[TIMESTAMP_PARAM_NAME]) {\n const ts = data[TIMESTAMP_PARAM_NAME]\n obj[TIMESTAMP_PARAM_NAME] = Array.isArray(ts) ? ts : [ts]\n delete data[TIMESTAMP_PARAM_NAME]\n } \n obj.data = data\n \n return obj\n}\n\n\n/**\n * The ws doesn't have a acknowledge callback like socket.io\n * so we have to DIY one for ws and other that doesn't have it\n * @param {string} type of reply\n * @param {string} resolverName which is replying\n * @param {*} data payload\n * @param {array} [ts= []] the last received ts, if any \n * @return {string} stringify json\n */\nexport const createWsReply = (type, resolverName, data, ts = []) => {\n const obj = getTsFieldFromData(toJson(data))\n ts = ts.concat(obj[TIMESTAMP_PARAM_NAME])\n if (!ts.length) {\n ts.push(timestamp())\n }\n return JSON.stringify({\n data: {\n [WS_REPLY_TYPE]: type,\n [WS_EVT_NAME]: resolverName,\n [WS_DATA_NAME]: obj.data \n },\n [TIMESTAMP_PARAM_NAME]: ts \n })\n}\n\n// extended function \nexport const createReplyMsg = (resolverName, data, ts = []) => (\n createWsReply(EMIT_REPLY_TYPE, resolverName, data, ts)\n)\n\nexport const createAcknowledgeMsg = (resolverName, data, ts = []) => (\n createWsReply(ACKNOWLEDGE_REPLY_TYPE, resolverName, data, ts)\n)\n\n/**\n * @param {string|object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nexport const isWsReply = payload => {\n const json = isString(payload) ? toJson(payload) : payload\n const { data } = json\n if (data) {\n let result = WS_KEYS.filter(key => isObjectHasKey(data, key))\n return (result.length === WS_KEYS.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {string|object} data received data\n * @param {function} [cb=nil] this is for extracting the TS field or when it's error\n * @return {object} false on failed\n */\nexport const extractWsPayload = (payload, cb = nil) => {\n try {\n const json = toJson(payload)\n // now handle the data\n let _data\n if ((_data = isWsReply(json)) !== false) {\n // note the ts property is on its own \n cb('_data', _data)\n \n return {\n data: toJson(_data[WS_DATA_NAME]),\n resolverName: _data[WS_EVT_NAME],\n type: _data[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError(PAYLOAD_NOT_DECODED_ERR, payload)\n } catch(e) {\n return cb(ERROR_KEY, e)\n }\n}\n","// this will be part of the init client sequence\n// as soon as we create a ws client\n// we listen to the on.connect event \n// then we send a init-ping event back to the server\n// and server issue a csrf token back to use \n// we use this token to create a new client and destroy the old one\nimport {\n INTERCOM_RESOLVER_NAME, \n SOCKET_PING_EVENT_NAME,\n HEADERS_KEY,\n DATA_KEY,\n CSRF_HEADER_KEY\n} from 'jsonql-constants'\nimport { \n createQueryStr, \n extractWsPayload,\n timestamp,\n toJson \n} from 'jsonql-utils/module'\nimport {\n JsonqlError\n} from 'jsonql-errors'\nconst CSRF_HEADER_NOT_EXIST_ERR = 'CSRF header is not in the received payload'\n\n/**\n * Util method \n * @param {string} payload return from server\n * @return {object} the useful bit \n */\nfunction extractSrvPayload(payload) {\n let json = toJson(payload)\n \n if (json && typeof json === 'object') {\n // note this method expect the json.data inside\n return extractWsPayload(json)\n }\n \n throw new JsonqlError('extractSrvPayload', json)\n}\n\n/**\n * call the server to get a csrf token \n * @return {string} formatted payload to send to the server \n */\nfunction createInitPing() {\n const ts = timestamp()\n\n return createQueryStr(INTERCOM_RESOLVER_NAME, [SOCKET_PING_EVENT_NAME, ts])\n}\n\n/**\n * Take the raw on.message result back then decoded it \n * @param {*} payload the raw result from server\n * @return {object} the csrf payload\n */\nfunction extractPingResult(payload) {\n const result = extractSrvPayload(payload)\n \n if (result && result[DATA_KEY] && result[DATA_KEY][CSRF_HEADER_KEY]) {\n return {\n [HEADERS_KEY]: result[DATA_KEY]\n }\n }\n\n throw new JsonqlError('extractPingResult', CSRF_HEADER_NOT_EXIST_ERR)\n}\n\n\n/**\n * Create a generic intercom method\n * @param {string} type the event type \n * @param {array} args if any \n * @return {string} formatted payload to send\n */\nfunction createIntercomPayload(type, ...args) {\n const ts = timestamp()\n let payload = [type].concat(args)\n payload.push(ts)\n return createQueryStr(INTERCOM_RESOLVER_NAME, payload)\n}\n\n\nexport { \n extractSrvPayload,\n createInitPing, \n extractPingResult, \n createIntercomPayload \n}","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nconst ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`\nconst PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`\nconst EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'\nconst UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread'\n\nconst RETURNS_NAME = 'returns'\n\nimport {\n \n DEFAULT_TYPE, // this is a mistake should move back to the validation\n DATA_KEY, \n ERROR_KEY,\n\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n \n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR\n} from 'jsonql-constants'\n\n// group all export in one \nexport {\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR,\n DEFAULT_TYPE,\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n ARRAY_TYPE,\n OBJECT_TYPE,\n STRING_TYPE,\n BOOLEAN_TYPE,\n NUMBER_TYPE,\n KEY_WORD,\n OR_SEPERATOR,\n\n RETURNS_NAME,\n\n DATA_KEY, \n ERROR_KEY \n}","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber\n case STRING_TYPE:\n return checkIsString\n case BOOLEAN_TYPE:\n return checkIsBoolean\n default:\n return checkIsAny\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length\n}\n","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\n// import filter from 'lodash-es/filter'\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (_value !== undefined) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true\n }).length)\n }).length;\n }\n }\n return false\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p\n let _args = [arg]\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return Reflect.apply(checkIsObject, null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\n\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n combineFn,\n notEmpty\n} from './index'\n\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n DATA_KEY, \n ERROR_KEY \n} from './constants'\n\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\nimport JsonqlError from 'jsonql-errors/src/error'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (arg !== undefined) {\n return arg\n }\n return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlValidationError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return []\n }\n if (!checkIsArray(args)) {\n console.info(args)\n throw new JsonqlValidationError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ))\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ))\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ))\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length:\n let ctn = params.length;\n // this happens when we have those array. type\n let _type = [ DEFAULT_TYPE ]\n // we only looking at the first one, this might be a @BUG\n /*\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n } */\n // if we use the params as guide then the rest will get throw out\n // which is not what we want, instead, anything without the param\n // will get a any type and optional flag\n return args.map((arg, i) => {\n let optional = i >= ctn ? true : !!params[i].optional\n let param = params[i] || { type: _type, name: `_${i}` }\n return {\n arg: optional ? getOptionalValue(arg, param) : arg,\n index: i,\n param,\n optional\n }\n })\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n // v1.4.4 this fixed the problem, the root level optional is from the last fn\n if (p.optional === true || p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport isFunction from 'lodash-es/isFunction'\nimport merge from 'lodash-es/merge'\nimport mapValues from 'lodash-es/mapValues'\n\nimport JsonqlEnumError from 'jsonql-errors/src/enum-error'\nimport JsonqlTypeError from 'jsonql-errors/src/type-error'\nimport JsonqlCheckerError from 'jsonql-errors/src/checker-error'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false\n } catch (e) {\n return false\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // log('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n // log(ENUM_KEY, value[ENUM_KEY])\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n // log(CHECKER_KEY, value[CHECKER_KEY])\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","/// this is port back from the client to share across all projects\n\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => runValidation(args1, cb))\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__'\n\n/**\n * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\nimport * as validator from './src/validator'\n// configuration checking\nimport * as jsonqlOptions from './src/options'\n// the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKey from './src/is-object-has-key'\n\nconst isObject = checkIsObject\nconst isAny = checkIsAny\nconst isString = checkIsString\nconst isBoolean = checkIsBoolean\nconst isNumber = checkIsNumber\nconst isArray = checkIsArray\nconst isNotEmpty = notEmpty\n\nconst normalizeArgs = validator.normalizeArgs\nconst validateSync = validator.validateSync\nconst validateAsync = validator.validateAsync\n\nconst JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO\n\nconst createConfig = jsonqlOptions.createConfig\nconst constructConfig = jsonqlOptions.constructConfigFn\n// construct the final output 1.5.2\nconst checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nconst checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\nconst inArray = isInArray\n\n\n// check returns methods \nimport { \n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync \n} from './src/returns'\n\n\n// group the in one \nexport {\n JSONQL_PARAMS_VALIDATOR_INFO,\n \n isObject,\n isAny,\n isString,\n isBoolean,\n isNumber,\n isArray,\n isNotEmpty,\n \n inArray,\n isObjectHasKey,\n\n normalizeArgs,\n validateSync,\n validateAsync,\n\n createConfig,\n constructConfig,\n checkConfig,\n checkConfigAsync,\n\n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync\n}\n\n\n\n\n\n","// move the get logger stuff here\n\n// it does nothing\nconst dummyLogger = () => {}\n\n/**\n * re-use the debugOn prop to control this log method\n * @param {object} opts configuration\n * @return {function} the log function\n */\nconst getLogger = (opts) => {\n const { debugOn } = opts \n if (debugOn) {\n return (...args) => {\n Reflect.apply(console.info, console, ['[jsonql-ws-client-core]', ...args])\n }\n }\n return dummyLogger\n}\n\n/**\n * Make sure there is a log method\n * @param {object} opts configuration\n * @return {object} opts\n */\nconst getLogFn = opts => {\n const { log } = opts // 1.3.9 if we pass a log method here then we use this\n if (!log || typeof log !== 'function') {\n return getLogger(opts)\n }\n opts.log('---> getLogFn user supplied log function <---', opts)\n return log\n}\n\nexport { getLogFn }","// group all the repetitive message here\n\nexport const TAKEN_BY_OTHER_TYPE_ERR = 'You are trying to register an event already been taken by other type:'\n\n// use constants for type\nexport const ON_TYPE = 'on'\nexport const ONLY_TYPE = 'only'\nexport const ONCE_TYPE = 'once'\nexport const ONLY_ONCE_TYPE = 'onlyOnce'\nexport const MAX_CALL_TYPE = 'maxAllowCall'\nexport const NEG_RETURN = -1\n\nexport const AVAILABLE_TYPES = [\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE\n]\n// the type which the callMax can execute on\nexport const ON_MAX_TYPES = [\n ON_TYPE,\n ONLY_TYPE\n]\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n\n/**\n * wrapper to make sure it string\n * @param {*} input whatever\n * @return {string} output\n */\nexport function hashCode2Str(s) {\n return hashCode(s) + ''\n}\n\n/**\n * Just check if a pattern is an RegExp object\n * @param {*} pat whatever\n * @return {boolean} false when its not\n */\nexport function isRegExp(pat) {\n return pat instanceof RegExp\n}\n\n/**\n * check if its string\n * @param {*} arg whatever\n * @return {boolean} false when it's not\n */\nexport function isString(arg) {\n return typeof arg === 'string'\n}\n\n/**\n * check if it's an integer\n * @param {*} num input number\n * @return {boolean}\n */\nexport function isInt(num) {\n if (isString(num)) {\n throw new Error(`Wrong type, we want number!`)\n }\n return !isNaN(parseInt(num))\n}\n\n/**\n * Find from the array by matching the pattern\n * @param {*} pattern a string or RegExp object\n * @return {object} regex object or false when we can not id the input\n */\nexport function getRegex(pattern) {\n switch (true) {\n case isRegExp(pattern) === true:\n return pattern\n case isString(pattern) === true:\n return new RegExp(pattern)\n default:\n return false\n }\n}\n\n\n/**\n * in array\n * @param {array} arr to search\n * @param {*} prop to search\n */\n export const inArray = (arr, prop) => !!arr.filter(v => prop === v).length\n","// Create two WeakMap store as a private keys\nexport const NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap()\nexport const NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap()\n","// setup a base class to put all the don't know where to put methods \nimport { hashCode2Str, isString } from './utils'\nimport { AVAILABLE_TYPES } from './constants'\n\nexport default class BaseClass {\n\n constructor() {}\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n // for id if the instance is this class\n get $name() {\n return 'to1source-event'\n }\n\n // take this down in the next release\n get is() {\n return this.$name\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (!isString(e)) {\n this.logger('(validateEvt)', e)\n\n throw new Error(`Event name must be string type! we got ${typeof e}`)\n }\n })\n\n return true\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n\n return true\n }\n }\n throw new Error(`callback required to be function type! we got ${typeof callback}`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n this.validateEvt(type)\n \n return !!AVAILABLE_TYPES.filter(t => type === t).length\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run) callback:', callback, 'payload:', payload, 'context:', ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n\n return this.$done // return it here first \n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n\n return hashCode2Str(fn.toString())\n }\n} ","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n // @1.2.2 this become an array so we can hold different events\n this.__pattern__ = []\n // key value pair store to store the queued calls\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE ALL SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {array.} patterns the pattern search matches the event name\n * @return {array} if the pattern return is registered or not\n */\n $suspendEvent(...patterns) {\n return patterns.map(pattern => {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n // check if it's already added \n if (this.__isPatternRegisterd(regex) === false) {\n this.__pattern__.push(regex)\n\n return this.__pattern__.length\n }\n return false\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n }\n\n /**\n * This is pair with $suspnedEvent to release part of the event queue by the pattern (eventName)\n * @param {array.<*>} patterns a eventName of partial eventName to create a RegExp\n * @return {number} should be the number of queue got released\n */\n $releaseEvent(...patterns) {\n return patterns.map(pattern => {\n this.logger(`($releaseEvent)`, pattern)\n const regex = getRegex(pattern)\n if (isRegExp(regex) && this.__isPatternRegisterd(regex)) {\n const self = this\n\n return this.__getToReleaseQueue(regex)\n .map((args, i) => {\n \n Reflect.apply(self.$trigger, self, args)\n\n return i \n }).reduce((a, b) => ++b, 0)\n }\n\n this.logger('$releaseEvent throw error ==========================>', this.__pattern__, regex)\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n .reduce((x, y) => x + y, 0)\n }\n\n /**\n * queuing call up when it's in suspend mode,\n * it's currently suspending then add to store then the $trigger will do nothing\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n switch (true) {\n case this.__suspend_state__ === true: // this will take priority over the pattern\n \n return this.__addToQueueStore(evt, args)\n case !!this.__pattern__.length === true: \n // check the pattern and decide if we want to suspend it or not\n if (!!this.__pattern__.filter(p => p.test(evt)).length) {\n \n return this.__addToQueueStore(evt, args)\n }\n this.logger(`($queue) ${evt} NOT added to $queueStore`, this.__pattern__)\n \n return false \n default:\n this.logger('($queue) get called NOTHING added')\n return false\n } \n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n\n /**\n * The reason is before we call $trigger we need to remove the pattern from queue\n * otherwise, it will never get release\n * @param {*} pattern to find the queue \n * @return {array} queue to get execute \n */\n __getToReleaseQueue(regex) {\n // first get the list of events in the queue store that match this pattern\n const list = this.$queues\n // first index is the eventName\n .filter(content => regex.test(content[0]))\n .map(content => {\n this.logger(`[release] execute ${content[0]} matches ${regex}`, content)\n // we just remove it\n this.queueStore.delete(content)\n \n return content\n })\n if (list.length > 0) {\n // we need to remove this event from the pattern queue array \n this.__pattern__ = this.__pattern__.filter(p => p.toString() !== regex.toString()) \n }\n\n return list \n }\n\n /**\n * Wrapper method with a logger \n * @param {*} evt \n * @param {*} args \n * @return {boolean}\n */\n __addToQueueStore(evt, args) {\n this.logger(`($queue) ${evt} added to $queueStore`, args)\n\n // @TODO should we check if this already added? \n // what if that is a multiple call like $on\n this.queueStore.add([evt].concat(args))\n\n return true\n }\n\n /**\n * check if certain pattern already registered in the queue\n * @param {*} pattern\n * @return {boolean} \n */\n __isPatternRegisterd(pattern) {\n // this is a bit of a hack to compare two regex Object \n return !!this.__pattern__.filter(p => (\n p.toString() === pattern.toString()\n )).length \n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue, this is a wholesale release ALL\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = []\n \n this.logger(`(release) was called with ${size}${pattern.length ? ' for \"' + pattern.join(',') + '\"': ''} item${size > 1 ? 's' : ''}`)\n \n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.logger('(release queue)', queue)\n\n queue.forEach(args => {\n this.logger(`[release] execute ${args[0]}`, args)\n\n Reflect.apply(this.$trigger, this, args)\n })\n\n this.queueStore.clear()\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport {\n NEG_RETURN,\n ON_MAX_TYPES\n} from './constants'\nimport { isInt, inArray } from './utils'\n\nimport SuspendClass from './suspend'\n\nexport default class StoreService extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger\n }\n this.keep = config.keep\n // for the $done setter\n this.result = config.keep ? [] : null\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n // this is the new throw away map\n this.maxCountStore = new Map()\n }\n\n /**\n * We need this to pre-check the store, otherwise\n * the execution will be unable to determine the number of calls\n * @param {string} evtName event name\n * @return {number} the count of this store\n */\n getMaxStore(evtName) {\n return this.maxCountStore.get(evtName) || NEG_RETURN\n }\n\n /**\n * This is one stop shop to check and munipulate the maxStore\n * @param {*} evtName\n * @param {*} [max=null]\n * @return {number} when return -1 means removed\n */\n checkMaxStore(evtName, max = null) {\n this.logger(`===========================================`)\n this.logger('checkMaxStore start', evtName, max)\n // init the store\n if (max !== null && isInt(max)) {\n // because this is the setup phrase we just return the max value\n this.maxCountStore.set(evtName, max)\n this.logger(`Setup max store for ${evtName} with ${max}`)\n return max\n }\n if (max === null) {\n // first check if this exist in the maxStore\n let value = this.getMaxStore(evtName)\n\n this.logger('getMaxStore value', value)\n\n if (value !== NEG_RETURN) {\n if (value > 0) {\n --value\n }\n if (value > 0) {\n this.maxCountStore.set(evtName, value) // just update the value\n } else {\n this.maxCountStore.delete(evtName) // just remove it\n this.logger(`remove ${evtName} from maxStore`)\n return NEG_RETURN\n }\n }\n return value\n }\n throw new Error(`Expect max to be an integer, but we got ${typeof max} ${max}`)\n }\n\n /**\n * Wrap several get filter ops together to return the callback we are looking for\n * @param {string} evtName to search for\n * @return {array} empty array when not found\n */\n searchMapEvt(evtName) {\n const evts = this.$get(evtName, true) // return in full\n const search = evts.filter(result => {\n const [ ,,,type ] = result\n\n return inArray(ON_MAX_TYPES, type)\n })\n\n return search.length ? search : []\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName] // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger(`(takeFromStore) has \"${evt}\"`, content)\n store.delete(evt)\n\n return content\n }\n\n return false\n }\n throw new Error(`\"${storeName}\" is not supported!`)\n }\n\n /**\n * This was part of the $get. We take it out\n * so we could use a regex to remove more than one event\n * @param {object} store the store to return from\n * @param {string} evt event name\n * @param {boolean} full return just the callback or everything\n * @return {array|boolean} false when not found\n */\n findFromStore(evt, store, full = false) {\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l\n }\n let [, callback,] = l\n\n return callback\n })\n }\n return false\n }\n\n /**\n * Similar to the findFromStore, but remove\n * @param {string} evt event name\n * @param {object} store the store to remove from\n * @return {boolean} false when not found\n */\n removeFromStore(evt, store) {\n if (store.has(evt)) {\n this.logger('($off)', evt)\n\n store.delete(evt)\n\n return true\n }\n return false\n }\n\n /**\n * Take out from addToStore for reuse\n * @param {object} store the store to use\n * @param {string} evt event name\n * @return {object} the set within the store\n */\n getStoreSet(store, evt) {\n let fnSet\n if (store.has(evt)) {\n this.logger(`(addToStore) \"${evt}\" existed`)\n fnSet = store.get(evt)\n } else {\n this.logger(`(addToStore) create new Set for \"${evt}\"`)\n // this is new\n fnSet = new Set()\n }\n return fnSet\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n const fnSet = this.getStoreSet(store, evt)\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger(`(addToStore) insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(li => {\n let [hash,] = li\n return hash === args[0]\n }).length\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list\n return type !== t\n }).length\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n\n this.logger('(checkTypeInLazyStore)', store)\n\n if (store) {\n\n return !!Array\n .from(store)\n .filter(li => {\n let [,,t] = li\n return t !== type\n }).length\n }\n\n return false\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger(`(addToNormalStore) try to add \"${type}\" --> \"${evt}\" to normal store`)\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n\n this.logger('(addToNormalStore)', `\"${type}\" --> \"${evt}\" can add to normal store`)\n\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store\n\n return size\n }\n\n return false\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store\n this.logger(`(addToLazyStore) size: ${size}`)\n\n return size\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg]\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n\n}\n","// The top level\nimport {\n ON_TYPE,\n ONLY_TYPE,\n ONCE_TYPE,\n ONLY_ONCE_TYPE,\n MAX_CALL_TYPE,\n ON_MAX_TYPES,\n TAKEN_BY_OTHER_TYPE_ERR,\n NEG_RETURN\n} from './constants'\nimport { isInt, inArray } from './utils'\nimport StoreService from './store-service'\n// export\nexport default class EventService extends StoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on'\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger(`($on) \"${evt}\" is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger(`($on) ${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content\n if (t && t !== type) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($on)`, `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n\n this.logger(`($on) return size ${size}`)\n return size\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n // let nStore = this.normalStore\n if (lazyStoreContent === false) {\n this.logger(`($once) \"${evt}\" is not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, ONCE_TYPE, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger('($once)', `call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n\n if (!nStore.has(evt)) {\n this.logger(`($only) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger(`($only) \"${evt}\" found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( li => {\n const [ payload, ctx, t ] = li\n if (t && t !== ONLY_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($only) call run \"${evt}\"`)\n this.run(callback, payload, context || ctx)\n })\n }\n\n return added\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD added in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n\n let added = false\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce) \"${evt}\" add to normalStore`)\n\n added = this.addToNormalStore(evt, ONLY_ONCE_TYPE, callback, context)\n }\n\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== ONLY_ONCE_TYPE) {\n throw new Error(`${TAKEN_BY_OTHER_TYPE_ERR} ${t}`)\n }\n this.logger(`($onlyOnce) call run \"${evt}\"`)\n\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added\n }\n\n /**\n * change the way how it suppose to work, instead of create another new store\n * We perform this check on the trigger end, so we set the number max\n * whenever we call the callback, we increment a value in the store\n * once it reaches that number we remove that event from the store,\n * also this will not get add to the lazy store,\n * which means the event must register before we can fire it\n * therefore we don't have to deal with the backward check\n * @param {string} evtName the event to get pre-registered\n * @param {number} max pass the max amount of callback can add to this event\n * @param {*} [ctx=null] the context the callback execute in\n * @return {function} the event handler\n */\n $max(evtName, max, ctx = null) {\n this.validateEvt(evtName)\n if (isInt(max) && max > 0) {\n // find this in the normalStore\n const fnSet = this.$get(evtName, true)\n if (fnSet !== false) {\n const evts = this.searchMapEvt(evtName)\n if (evts.length) {\n // should only have one anyway\n const [,,,type] = evts[0]\n // now init the max store\n const value = this.checkMaxStore(evtName, max)\n const _self = this\n /**\n * construct the callback\n * @param {array<*>} args\n * @return {number} \n */\n return function executeMaxCall(...args) {\n const ctn = _self.getMaxStore(evtName)\n let value = NEG_RETURN\n if (ctn > 0) {\n const fn = _self.$call(evtName, type, ctx)\n Reflect.apply(fn, _self, args)\n\n value = _self.checkMaxStore(evtName)\n if (value === NEG_RETURN) {\n _self.$off(evtName)\n return NEG_RETURN\n }\n }\n return value\n }\n }\n }\n // change in 1.1.1 because we might just call it without knowing if it's register or not\n this.logger(`The ${evtName} is not registered, can not execute non-existing event at the moment`)\n return NEG_RETURN\n }\n throw new Error(`Expect max to be an integer and greater than zero! But we got [${typeof max}]${max} instead`)\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {*}\n */\n $replace(evt, callback, context = null, type = ON_TYPE) {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n\n this.logger(`($replace)`, evt, callback)\n\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0\n // first check the normal store\n let nStore = this.normalStore\n this.logger('($trigger) normalStore', nStore)\n if (nStore.has(evt)) {\n this.logger(`($trigger) \"${evt}\" found`)\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n if (added) {\n this.logger(`($trigger) Currently suspended \"${evt}\" added to queue, nothing executed. Exit now.`)\n return false // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length\n let hasOnce = false\n // let hasOnly = false\n for (let i=0; i < ctn; ++i) {\n ++found\n // this.logger('found', found)\n let [ _, callback, ctx, _type ] = nSet[i]\n this.logger(`($trigger) call run for ${type}:${evt}`)\n\n this.run(callback, payload, context || ctx)\n\n if (_type === 'once' || _type === 'onlyOnce') {\n hasOnce = true\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter aroun\n * @NOTE breaking change: v1.9.1 it return an function to accept the params as spread\n * @param {string} evt event name\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, type = false, context = null) {\n const ctx = this\n\n return function executeCall(...args) {\n let _args = [evt, args, context, type]\n\n return Reflect.apply(ctx.$trigger, ctx, _args)\n }\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n // @TODO we will allow a regex pattern to mass remove event\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n\n return !!stores\n .filter(store => store.has(evt))\n .map(store => this.removeFromStore(evt, store))\n .length\n }\n\n /**\n * return all the listener bind to that event name\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n // @TODO should we allow the same Regex to search for all?\n this.validateEvt(evt)\n let store = this.normalStore\n return this.findFromStore(evt, store, full)\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done) set value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n this.logger('($done) get result:', this.result)\n if (this.keep) {\n return this.result[this.result.length - 1]\n }\n return this.result\n }\n\n /**\n * Take a look inside the stores\n * @param {number|null} idx of the store, null means all\n * @return {void}\n */\n $debug(idx = null) {\n let names = ['lazyStore', 'normalStore']\n let stores = [this.lazyStore, this.normalStore]\n if (stores[idx]) {\n this.logger(names[idx], stores[idx])\n } else {\n stores.map((store, i) => {\n this.logger(names[i], store)\n })\n }\n }\n}\n","// default\nimport To1sourceEvent from './src/event-service'\n\nexport default To1sourceEvent\n","// this will generate a event emitter and will be use everywhere\nimport EventEmitterClass from '@to1source/event'\n// create a clone version so we know which one we actually is using\nclass JsonqlWsEvt extends EventEmitterClass {\n\n constructor(logger) {\n if (typeof logger !== 'function') {\n throw new Error(`Just die here the logger is not a function!`)\n }\n logger(`---> Create a new EventEmitter <---`)\n // this ee will always come with the logger\n // because we should take the ee from the configuration\n super({ logger })\n }\n\n get name() {\n return'jsonql-ws-client-core'\n }\n}\n\n/**\n * getting the event emitter\n * @param {object} opts configuration\n * @return {object} the event emitter instance\n */\nconst getEventEmitter = opts => {\n const { log, eventEmitter } = opts\n \n if (eventEmitter) {\n log(`eventEmitter is:`, eventEmitter.name)\n return eventEmitter\n }\n \n return new JsonqlWsEvt( opts.log )\n}\n\nexport { \n getEventEmitter, \n EventEmitterClass // for other module to build from \n}\n","// group all the small functions here\nimport { EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/src/generic'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\n\n/**\n * WebSocket is strict about the path, therefore we need to make sure before it goes in\n * @param {string} url input url\n * @return {string} url with correct path name\n */\nexport const fixWss = url => {\n const pattern = new RegExp('^(http|https)\\:\\/\\/', 'i')\n const result = url.match(pattern)\n if (result && result.length) {\n const target = result[1].toLowerCase()\n const replacement = target === 'https' ? 'wss' : 'ws'\n \n return url.replace(pattern, replacement + '://')\n }\n\n return url \n}\n\n\n/**\n * get a stock host name from browser\n */\nexport const getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n throw new JsonqlValidationError(e)\n }\n}\n\n/**\n * Unbind the event, this should only get call when it's disconnected\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nexport const clearMainEmitEvt = (ee, namespace) => {\n let nsps = toArray(namespace)\n nsps.forEach(n => {\n ee.$off(createEvt(n, EMIT_REPLY_TYPE))\n })\n}\n\n\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME\nconst WS = JS_WS_NAME\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!'\n\nconst MISSING_PROP_ERR = 'Missing property in contract!'\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!'\n\nconst EMIT_EVT = EMIT_REPLY_TYPE\n\nconst NAMESPACE_KEY = 'namespaceMap'\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!'\n\nconst NOT_ALLOW_OP = 'This operation is not allow!'\n\nconst MY_NAMESPACE = 'myNamespace'\n\nconst CB_FN_NAME = 'on'\n// this is a socket only (for now) feature so we just put it here \nconst DISCONNECTED_ERROR_MSG = `You have disconnected from the socket server, please reconnect.`\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME,\n DISCONNECTED_ERROR_MSG\n}\n","// breaking it up further to share between methods\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { UNKNOWN_RESULT } from '../options/constants'\nimport { isObjectHasKey } from '../utils'\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver NOT from promise\n * @param {function} rejecter NOT from promise\n * @return {void} nothing\n */\nexport function respondHandler(data, resolver, rejecter) {\n if (isObjectHasKey(data, ERROR_KEY)) {\n // debugFn('-- rejecter called --', data[ERROR_KEY])\n rejecter(data[ERROR_KEY])\n } else if (isObjectHasKey(data, DATA_KEY)) {\n // debugFn('-- resolver called --', data[DATA_KEY])\n // @NOTE we change from calling it directly to use reflect \n // this could have another problem later when the return data is no in an array structure\n Reflect.apply(resolver, null, [...data[DATA_KEY]])\n } else {\n // debugFn('-- UNKNOWN_RESULT --', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n","// the actual trigger call method\nimport { ON_RESULT_FN_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from '../utils'\nimport { respondHandler } from './respond-handler'\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {array} args arguments\n * @param {function} log function \n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, args = [], log) {\n // reply event \n const outEventName = createEvt(namespace, EMIT_REPLY_TYPE)\n\n log(`actionCall: ${outEventName} --> ${resolverName}`, args)\n // This is the out going call \n ee.$trigger(outEventName, [resolverName, toArray(args)])\n \n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n const inEventName = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n // this cause the onResult got the result back first \n // and it should be the promise resolve first\n // @TODO we need to rewrote the respondHandler to change the problem stated above \n ee.$on(\n inEventName,\n function actionCallResultHandler(result) {\n log(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// setting up the send method \nimport { JsonqlValidationError } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n SEND_MSG_FN_NAME\n} from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { objDefineProps, createEvt, toArray, nil } from '../utils'\nimport { actionCall } from './action-call'\n\n/** \n * pairing with the server vesrion SEND_MSG_FN_NAME\n * last of the chain so only return the resolver (fn)\n * This is now change to a getter / setter method \n * and call like this: resolver.send(...args)\n * @param {function} fn the resolver function \n * @param {object} ee event emitter instance \n * @param {string} namespace the namespace it belongs to \n * @param {string} resolverName name of the resolver \n * @param {object} params from contract \n * @param {function} log a logger function\n * @return {function} return the resolver itself \n */ \nexport const setupSendMethod = (fn, ee, namespace, resolverName, params, log) => (\n objDefineProps(\n fn, \n SEND_MSG_FN_NAME, \n nil, \n function sendHandler() {\n log(`running call getter method`)\n // let _log = (...args) => Reflect.apply(console.info, console, ['[SEND]'].concat(args))\n /** \n * This will follow the same pattern like the resolver \n * @param {array} args list of unknown argument follow the resolver \n * @return {promise} resolve the result \n */\n return function sendCallback(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => {\n // @TODO check the result \n // because the validation could failed with the list of fail properties \n log('execute send', namespace, resolverName, _args)\n return actionCall(ee, namespace, resolverName, _args, log)\n })\n .catch(err => {\n // @TODO it shouldn't be just a validation error \n // it could be server return error, so we need to check \n // what error we got back here first \n log('send error', err)\n // @TODO it might not an validation error need the finalCatch here\n ee.$call(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n [new JsonqlValidationError(resolverName, err)]\n )\n })\n } \n })\n)\n","// break up the original setup resolver method here\n// import { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ON_ERROR_FN_NAME,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME\n} from 'jsonql-constants'\nimport { finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\n// local\nimport { \n chainFns, \n objDefineProps, \n injectToFn, \n createEvt, \n isFunc \n} from '../utils'\nimport { actionCall } from './action-call'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { respondHandler } from './respond-handler'\nimport { setupSendMethod } from './setup-send-method'\n\n\n/**\n * moved back from generator-methods \n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @param {function} log pass the log function\n * @return {function} resolver\n */\nfunction createResolver(ee, namespace, resolverName, params, log) {\n // note we pass the new withResult=true option\n return function resolver(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, _args, log))\n .catch(finalCatch)\n }\n}\n\n/**\n * The first one in the chain, just setup a namespace prop\n * the rest are passing through\n * @param {function} fn the resolver function\n * @param {object} ee the event emitter\n * @param {string} resolverName what it said\n * @param {object} params for resolver from contract\n * @param {function} log the logger function\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, log) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * onResult handler\n */\nconst setupOnResult = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_RESULT_FN_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_FN_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * we do need to add the send prop back because it's the only way to deal with\n * bi-directional data stream\n */\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_MESSAGE_FN_NAME, function(messageCallback) {\n // we expect this to be a function\n if (isFunc(messageCallback)) {\n // did that add to the callback\n let onMessageCallback = (args) => {\n log(`onMessageCallback`, args)\n respondHandler(\n args, \n messageCallback, \n (error) => {\n log(`Catch error: \"${resolverName}\"`, error)\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n error\n )\n })\n }\n // register the handler for this message event\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME),\n onMessageCallback\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * ON_ERROR_FN_NAME handler\n */\nconst setupOnError = (fn, ee, namespace, resolverName, params, log) => [\n objDefineProps(fn, ON_ERROR_FN_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_FN_NAME),\n resolverErrorHandler\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n log\n]\n\n/**\n * Add extra property / listeners to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @param {function} log function\n * @return {function} resolver\n */ \nfunction setupResolver(namespace, resolverName, params, fn, ee, log) {\n let fns = [\n setupNamespace,\n setupOnResult,\n setupOnMessage,\n setupOnError,\n setupSendMethod\n ]\n const executor = Reflect.apply(chainFns, null, fns)\n // get the executor\n return executor(fn, ee, namespace, resolverName, params, log)\n}\n\nexport { \n createResolver, \n setupResolver \n}","// put all the resolver related methods here to make it more clear\n\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\n\nimport { createResolver, setupResolver } from './setup-resolver'\nimport { injectToFn } from '../utils'\n\n/**\n * step one get the clientmap with the namespace\n * @param {object} opts configuration\n * @param {object} ee EventEmitter\n * @param {object} nspGroup resolvers index by their namespace\n * @return {promise} resolve the clientmapped, and start the chain\n */\nexport function generateResolvers(opts, ee, nspGroup) {\n const { log } = opts\n let client= {}\n \n for (let namespace in nspGroup) {\n let list = nspGroup[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, log)\n // this should set as a getter therefore can not be overwrite by accident\n client = injectToFn(\n client,\n resolverName,\n setupResolver(namespace, resolverName, params, fn, ee, log)\n )\n }\n }\n // resolve the clientto start the chain\n // chain the result to allow the chain processing\n return [ client, opts, ee, nspGroup ]\n}\n\n","// move from generator-methods \n// they are global event listeners \nimport {\n createEvt,\n objDefineProps,\n isFunc\n} from '../utils'\nimport {\n ON_ERROR_FN_NAME,\n ON_READY_FN_NAME\n} from 'jsonql-constants'\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} client client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ]\n */\nexport function setupOnReadyListener(client, opts, ee) {\n return [\n objDefineProps(\n client,\n ON_READY_FN_NAME,\n function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n // @2020-03-19 only allow ONE onReady callback otherwise\n // it will get fire multiple times which is not what we want\n ee.$only(ON_READY_FN_NAME, onReadyCallback)\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} clientthe client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @param {object} nspGroup namespace keys\n * @return {array} [obj, opts, ee]\n */\nexport function setupNamespaceErrorListener(client, opts, ee, nspGroup) {\n return [\n objDefineProps(\n client,\n ON_ERROR_FN_NAME,\n function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_FN_NAME can add multiple listners\n for (let namespace in nspGroup) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ON_ERROR_FN_NAME), namespaceErrorHandler)\n }\n }\n }\n ),\n opts,\n ee\n ]\n}\n\n","// take out from the resolver-methods\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ON_LOGIN_FN_NAME\n} from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString, objDefineProps, isFunc } from '../utils'\n\n\n/**\n * @UPDATE it might be better if we decoup the two http-client only emit a login event\n * Here should catch it and reload the ws client @TBC\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLoginHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\n opts.log(`Received ${LOGIN_EVENT_NAME} with ${token}`)\n // @TODO add the interceptor hook\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n // should trigger a global error instead @TODO\n throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`)\n }),\n opts,\n ee\n]\n\n\n/**\n * break out from createAuthMethods to allow chaining call - final in chain\n * @param {object} obj the main client object\n * @param {object} opts configuration\n * @param {object} ee event emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nconst setupLogoutHandler = (obj, opts, ee) => [\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n }),\n opts,\n ee\n]\n\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * Plus this will check if it's the private namespace that fired the event\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee] what comes in what goes out\n */\nconst setupOnLoginhandler = (obj, opts, ee) => [\n objDefineProps(obj, ON_LOGIN_FN_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n // Should this be a $onlyOnce listener after the logout \n // we add it back? \n ee.$only(ON_LOGIN_FN_NAME, onLoginCallback)\n }\n }),\n opts,\n ee\n]\n\n// @TODO future feature setup switch user\n\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} opts configuration\n * @param {object} ee Event Emitter\n * @return {array} [ obj, opts, ee ] what comes in what goes out\n */\nexport function setupAuthMethods(obj, opts, ee) {\n return chainFns(\n setupLoginHandler,\n setupLogoutHandler,\n setupOnLoginhandler\n )(obj, opts, ee)\n}\n","// this is a new method that will create several\n// intercom method also reverse listen to the server\n// such as disconnect (server issue disconnect)\nimport { injectToFn, chainFns } from '../utils'\nimport { \n CONNECT_EVENT_NAME,\n CONNECTED_EVENT_NAME,\n DISCONNECT_EVENT_NAME,\n CONNECTED_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * Set up the CONNECTED_PROP_KEY to the client\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectPropKey(client, opts, ee) {\n const { log } = opts \n log('[1] setupConnectPropKey')\n // we just inject a helloWorld method here\n // set up the init state of the connect\n client = injectToFn(client, CONNECTED_PROP_KEY , false, true)\n return [ client, opts, ee ]\n}\n\n\n/**\n * setup listener to the connect event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectEvtListener(client, opts, ee) {\n // @TODO do what at this point?\n const { log } = opts \n\n log(`[2] setupConnectEvtListener`)\n\n ee.$on(CONNECT_EVENT_NAME, function(...args) {\n log(`setupConnectEvtListener pass and do nothing at the moment`, args)\n })\n \n return [client, opts, ee]\n}\n\n/**\n * setup listener to the connected event \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupConnectedEvtListener(client, opts, ee) {\n const { log } = opts \n\n log(`[3] setupConnectedEvtListener`)\n\n ee.$on(CONNECTED_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = true\n // new action to take release the holded event queue \n const ctn = ee.$release()\n\n log(`CONNECTED_EVENT_NAME`, true, 'queue count', ctn)\n\n return {[CONNECTED_PROP_KEY]: true}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * Listen to the disconnect event and set the property to the client \n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n */\nfunction setupDisconnectListener(client, opts, ee) {\n const { log } = opts \n\n log(`[4] setupDisconnectListener`)\n\n ee.$on(DISCONNECT_EVENT_NAME, function() {\n client[CONNECTED_PROP_KEY] = false\n log(`CONNECTED_EVENT_NAME`, false)\n\n return {[CONNECTED_PROP_KEY]: false}\n })\n\n return [client, opts, ee]\n}\n\n/**\n * disconnect action\n * @param {*} client \n * @param {*} opts \n * @param {*} ee \n * @return {object} this is the final step to return the client\n */\nfunction setupDisconectAction(client, opts, ee) {\n const { disconnectHandlerName, log } = opts\n log(`[5] setupDisconectAction`)\n\n return injectToFn(\n client,\n disconnectHandlerName,\n function disconnectHandler(...args) {\n ee.$trigger(DISCONNECT_EVENT_NAME, args)\n }\n )\n}\n\n/**\n * this is the new method that setup the intercom handler\n * also this serve as the final call in the then chain to\n * output the client\n * @param {object} client the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nexport function setupInterCom(client, opts, ee) {\n const fns = [\n setupConnectPropKey,\n setupConnectEvtListener,\n setupConnectedEvtListener,\n setupDisconnectListener,\n setupDisconectAction\n ]\n\n const executor = Reflect.apply(chainFns, null, fns)\n return executor(client, opts, ee)\n}\n","// The final step of the setup before it returns the client\nimport { setupInterCom } from './setup-intercom'\nimport { CONNECT_EVENT_NAME, SUSPEND_EVENT_PROP_KEY } from 'jsonql-constants'\n\n/**\n * The final step to return the client\n * @param {object} obj the client\n * @param {object} opts configuration\n * @param {object} ee the event emitter\n * @return {object} client\n */\nfunction setupFinalStep(obj, opts, ee) {\n \n let client = setupInterCom(obj, opts, ee)\n // opts.log(`---> The final step to return the ws-client <---`)\n // add some debug functions\n client.verifyEventEmitter = () => ee.is\n // we add back the two things into the client\n // then when we do integration, we run it in reverse,\n // create the ws client first then the host client\n client.eventEmitter = opts.eventEmitter\n client.log = opts.log\n\n // now at this point, we are going to call the connect event\n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // just passing back the entire opts object\n // also we can release the queue here \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n opts.$releaseNamespace()\n }\n\n return client\n}\n\n\nexport { setupFinalStep }\n","// resolvers generator\n// we change the interface to return promise from v1.0.3\n// this way we make sure the obj return is correct and timely\nimport { NSP_GROUP } from 'jsonql-constants'\nimport { chainFns } from '../utils'\n\nimport { generateResolvers } from './generator-methods'\nimport {\n setupOnReadyListener,\n setupNamespaceErrorListener\n} from './global-listener'\n\nimport { setupAuthMethods } from './setup-auth-methods'\n\nimport { setupFinalStep } from './setup-final-step'\n\n/**\n * This is the starting point of binding callable method to the \n * ws, and we have to determine which is actually active \n * if enableAuth but we don't have a token, when the connection \n * to ws establish we only release the public related event \n * and the private one remain hold until the LOGIN_EVENT get trigger\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport function callersGenerator(opts, nspMap, ee) {\n \n\n let fns = [\n generateResolvers,\n setupOnReadyListener,\n setupNamespaceErrorListener\n ]\n if (opts.enableAuth) {\n // there is a problem here, when this is a public namespace\n // it should not have a login logout event attach to it\n fns.push(setupAuthMethods)\n }\n // we will always get back the [ obj, opts, ee ]\n // then we only return the obj (wsClient)\n // This has move outside of here, into the main method\n // the reason is we could switch around the sequence much easier\n fns.push(setupFinalStep)\n // stupid reaon!!!\n const executer = Reflect.apply(chainFns, null, fns)\n // run it\n return executer(opts, ee, nspMap[NSP_GROUP])\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n","// the top level API\n// The goal is to create a generic method that will able to handle\n// any kind of clients\n// import { injectToFn } from 'jsonql-utils'\nimport { callersGenerator } from './callers'\nimport {\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams\n} from './options'\n\n\n/**\n * 0.5.0 we break up the wsClientCore in two parts one without the config check\n * @param {function} setupSocketClientListener just make sure what it said it does\n * @return {function} to actually generate the client\n */\nexport function wsClientCoreAction(setupSocketClientListener) {\n /**\n * This is a breaking change, to continue the onion skin design\n * @param {object} config the already checked config\n * @return {promise} resolve the client\n */\n return function createClientAction(config = {}) {\n\n return postCheckInjectOpts(config)\n .then(createRequiredParams)\n .then(\n ({opts, nspMap, ee}) => setupSocketClientListener(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => callersGenerator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`[jsonql-ws-core-client init error]`, err)\n })\n }\n}\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientListerner this is the one method export by various clients\n * @param {object} [configCheckMap={}] we should do all the checking in the core instead of the client\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {function} accept a config then return the wsClient instance with all the available API\n */\nexport function wsClientCore(socketClientListener, configCheckMap = {}, constProps = {}) {\n // we need to inject property to this client later\n return (config = {}) => checkConfiguration(config, configCheckMap, constProps)\n .then(\n wsClientCoreAction(socketClientListener)\n )\n}\n","// this use by client-event-handler\nimport { ON_ERROR_FN_NAME } from 'jsonql-constants'\nimport { createEvt } from '../utils'\n\n/**\n * trigger errors on all the namespace onError handler\n * @param {object} ee Event Emitter\n * @param {array} namespaces nsps string\n * @param {string} message optional\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message) {\n namespaces.forEach( namespace => {\n ee.$trigger(\n createEvt(namespace, ON_ERROR_FN_NAME), \n [{ message, namespace }]\n )\n })\n}\n\n/**\n * Handle the onerror callback \n * @param {object} ee event emitter \n * @param {string} namespace which namespace has error \n * @param {*} err error object\n * @return {void} \n */\nexport const handleNamespaceOnError = (ee, namespace, err) => {\n ee.$trigger(createEvt(namespace, ON_ERROR_FN_NAME), [err])\n}","// NOT IN USE AT THE MOMENT JUST KEEP IT HERE FOR THE TIME BEING \nimport {\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_FN_NAME,\n ON_RESULT_FN_NAME,\n DISCONNECT_EVENT_NAME\n // SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\nimport { EMIT_EVT, DISCONNECTED_ERROR_MSG } from '../options/constants'\nimport { createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\n\n/**\n * A Event Listerner placeholder when it's not connect to any nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notConnectedListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function disconnectedEvtCallback(resolverName, args) {\n log(`[disconnectedListerner] hijack the ws call`, namespace, resolverName, args)\n // Now we suspend all the calls but note the existing one won't be affected \n // we need to update the methods to move everything across \n const error = {\n message: DISCONNECTED_ERROR_MSG\n }\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n\n/**\n * The disconnect event Listerner, now we log the client out from everything\n * @TODO now we are another problem they disconnect, how to reconnect\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const disconnectListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n ee.$on(\n DISCONNECT_EVENT_NAME, \n function disconnectEvtCallback() {\n triggerNamespacesOnError(ee, namespaces, DISCONNECT_EVENT_NAME)\n namespaces.forEach( namespace => { \n log(`disconnect from ${namespace}`)\n\n clearMainEmitEvt(ee, namespace)\n nsps[namespace] = null \n disconnectedListerner(namespace, ee, opts)\n })\n }\n )\n}\n\n/**\n * A Event Listerner placeholder when it's not connect to the private nsp\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nexport const notLoginListener = (namespace, ee, opts) => {\n const { log } = opts \n\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginListernerCallback(resolverName, args) {\n log('[notLoginListerner] hijack the ws call', namespace, resolverName, args)\n const error = { message: NOT_LOGIN_ERR_MSG }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ON_ERROR_FN_NAME), [ error ])\n // also trigger the result Listerner, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [{ error }])\n }\n )\n}\n\n/**\n * Only when there is a private namespace then we bind to this event\n * @param {object} nsps the available nsp(s)\n * @param {array} namespaces available namespace \n * @param {object} ee eventEmitter \n * @param {object} opts configuration\n * @return {void}\n */\nexport const logoutEvtListener = (nsps, namespaces, ee, opts) => {\n const { log } = opts \n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(\n LOGOUT_EVENT_NAME, \n function logoutEvtCallback() {\n const privateNamespace = getPrivateNamespace(namespaces)\n log(`${LOGOUT_EVENT_NAME} event triggered`)\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError Listerner\n triggerNamespacesOnError(ee, [privateNamespace], LOGOUT_EVENT_NAME)\n // rebind all of the Listerner to the fake one\n log(`logout from ${privateNamespace}`)\n\n clearMainEmitEvt(ee, privateNamespace)\n // we need to issue one more call to the server before we disconnect\n // now this is a catch 22, here we are not suppose to do anything platform specific\n // so that should fire before trigger this event\n // clear out the nsp\n nsps[privateNamespace] = null \n // add a NOT LOGIN error if call\n notLoginWsListerner(privateNamespace, ee, opts)\n }\n )\n}\n\n","// This is share between different clients so we export it\n// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\n\n/*\nInside the map call but we take it out for now and until the WebSocket version is fully working\nimport { SOCKET_IO } from '../options/constants'\n // @TODO need to double check this\n if (opts.serverType === SOCKET_IO) {\n let { nspGroup } = nspMap\n args.push(nspGroup[namespace])\n }\n*/\nimport { getPrivateNamespace } from 'jsonql-utils/src/namespace'\nimport { logoutEvtListener, notLoginListener } from './event-listeners'\n\n/**\n * centralize all the comm in one place\n * @param {function} bindSocketEventHandler binding the ee to ws --> this is the core bit\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function namespaceEventListener(bindSocketEventListener, nsps) {\n /**\n * BREAKING CHANGE instead of one flat structure\n * we return a function to accept the two\n * @param {object} opts configuration\n * @param {object} nspMap this is not in the opts\n * @param {object} ee Event Emitter instance\n * @return {array} although we return something but this is the last step and nothing to do further\n */\n return (opts, nspMap, ee) => {\n // since all these params already in the opts\n const { log } = opts\n const { namespaces } = nspMap\n // @1.1.3 add isPrivate prop to id which namespace is the private nsp\n // then we can use this prop to determine if we need to fire the ON_LOGIN_PROP_NAME event\n const privateNamespace = getPrivateNamespace(namespaces)\n // The total number of namespaces (which is 2 at the moment) minus the private namespace number\n let ctn = namespaces.length - 1 \n // @NOTE we need to somehow id if this namespace already been connected \n // and the event been released before \n return namespaces.map(namespace => {\n let isPrivate = privateNamespace === namespace\n log(namespace, ` --> ${isPrivate ? 'private': 'public'} nsp --> `, nsps[namespace] !== false)\n if (nsps[namespace]) {\n log('[call bindWsHandler]', isPrivate, namespace)\n // we need to add one more property here to tell the bindSocketEventListener \n // how many times it should call the onReady \n let args = [namespace, nsps[namespace], ee, isPrivate, opts, --ctn]\n // Finally we binding everything together\n Reflect.apply(bindSocketEventListener, null, args)\n \n } else {\n log(`binding notLoginWsHandler to ${namespace}`)\n // a dummy placeholder\n // @TODO but it should be a not connect handler\n // when it's not login (or fail) this should be handle differently\n notLoginListener(namespace, ee, opts)\n }\n if (isPrivate) {\n log(`Has private and add logoutEvtHandler`)\n logoutEvtListener(nsps, namespaces, ee, opts)\n }\n // just return something its not going to get use anywhere\n return isPrivate\n })\n }\n}\n","/*\nThis two client is the final one that gets call \nall it does is to create the url that connect to \nand actually trigger the connection and return the socket \ntherefore they are as generic as it can be\n*/\n\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspClient(namespace, opts) {\n const { hostname, wssPath, nspClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n log(`createNspClient with URL --> `, url)\n\n return nspClient(url, opts)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nfunction createNspAuthClient(namespace, opts) {\n const { hostname, wssPath, token, nspAuthClient, log } = opts\n const url = namespace ? [hostname, namespace].join('/') : wssPath\n \n log(`createNspAuthClient with URL -->`, url)\n\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n // now we need to get an extra options for framework specific method, which is not great\n // instead we just pass the entrie opts to the authClient \n\n return nspAuthClient(url, opts, token)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// same with the invalid-token-error \n\n/*\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\n*/\n\nclass InvalidCharacterError extends Error {\n\n constructor(message) {\n this.message = message \n }\n\n get name() {\n return 'InvalidCharacterError'\n }\n}\n\nexport { InvalidCharacterError }","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\nimport { InvalidCharacterError } from './invalid-character-error'\n\n/**\n * Polyfill the non ASCII code \n * @param {*} input\n * @return {*} usable output \n */\nfunction atob(input) {\n var str = String(input).replace(/=+$/, '')\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n for (\n // initialize result and counters\n let bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\n// polyfill the window object\ntry {\n typeof window !== 'undefined' && window.atob && window.atob.bind(window) || atob\n} catch(e) {}\n\nexport { atob }\n\n\n","// this method is re-use in several clients \n// therefore it's better to share here \nimport { \n TOKEN_PARAM_NAME, \n AUTH_HEADER,\n TOKEN_DELIVER_LOCATION_PROP_KEY, \n TOKEN_IN_URL,\n TOKEN_IN_HEADER,\n WS_OPT_PROP_KEY,\n HEADERS_KEY,\n BEARER,\n COOKIE_PROP_KEY\n} from 'jsonql-constants'\n// move back to jsonql-constants later\n\n/**\n * extract the new options for authorization\n * @param {*} opts configuration\n * @return {string} the header option\n */\nexport function extractConfig(opts) {\n // we don't really need to do any validation here \n // because the opts should be clean before calling here\n return opts[TOKEN_DELIVER_LOCATION_PROP_KEY] || TOKEN_IN_URL\n}\n\n/**\n * When running the CSRF token, and have a Auth token \n * the csrf is missing so we need to take that into account as well\n * @param {object} config configuration\n * @param {string} token auth token \n * @return {object} constructed the full options to pass to the WS object \n */\nfunction prepareHeaderOpts(config, token = false) {\n const wsOptions = config[WS_OPT_PROP_KEY] || {}\n let headers = config[HEADERS_KEY] || {}\n if (token) {\n headers = Object.assign(headers, {\n [AUTH_HEADER]: `${BEARER} ${token}`\n })\n }\n // we might have to use the merge here\n return Object.assign({}, wsOptions, {[HEADERS_KEY]: headers})\n}\n\n/**\n * prepare the url and options to the WebSocket\n * @param {*} url \n * @param {*} config \n * @param {*} [token = false] \n * @return {object} with url and opts key \n */\nexport function prepareConnectConfig(url, config = {}, token = false) {\n const tokenOpt = extractConfig(config)\n\n switch (tokenOpt) {\n case TOKEN_IN_URL:\n return {\n url: token ? `${url}?${TOKEN_PARAM_NAME}=${token}` : url,\n opts: prepareHeaderOpts(config, false)\n }\n case TOKEN_IN_HEADER:\n default: \n return {\n url,\n opts: prepareHeaderOpts(config, token)\n }\n }\n}\n\n/**\n * Extract the cookie part from the header\n * @param {object} headers\n * @return {*} false when failed to find or object contain the break down cookie content \n */\nfunction getCookie(headers) {\n if (headers[COOKIE_PROP_KEY]) {\n const parts = headers[COOKIE_PROP_KEY].split(';')\n \n return parts.map(part => {\n let values = part.split('=')\n return {[values[0]]: values[1]}\n }).reduce((a, b) => Object.assign(a, b), {})\n }\n\n return false \n}\n\n/**\n * When we use the browser WebSocket object we need to set the header via cookie \n * And the server will see it like this \"cookie: 'X-CSRF-Token=MDUBgJIGVWEjvjYjGMnMN'\"\n * Therefore, we need a different way to extract the csrf / authorisation headers \n * @param {object} headers the server received the headers \n * @param {string} target the target header we are looking for\n * @param {boolean} term just don't want to run into an infinite loop \n * @return {*} the value of the target headers or false when failed to find \n */\nexport function extractHeaderValue(headers, target, term = false) {\n if (headers[target]) {\n\n return headers[target]\n } else if (headers[target.toLowerCase()]) {\n \n return headers[target.toLowerCase()]\n }\n if (term) { // if we still couldn't find anything then just exit here\n\n return false\n }\n\n const cookies = getCookie(headers) \n if (cookies) {\n // call myself again\n return extractHeaderValue(cookies, target, true)\n }\n\n return false\n}\n\n\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\n\nimport isNaN from 'lodash-es/isNaN'\nimport isString from 'lodash-es/isString'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a chck if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport trim from 'lodash-es/trim'\nimport isString from 'lodash-es/isString'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false\n}\n\nexport default checkIsString\n","// check for boolean\n\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return value !== null && value !== undefined && typeof value === 'boolean'\n}\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport trim from 'lodash-es/trim'\n\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (value !== undefined && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && value !== null)) {\n return true;\n }\n }\n return false;\n}\n\nexport default checkIsAny\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber\n case STRING_TYPE:\n return checkIsString\n case BOOLEAN_TYPE:\n return checkIsBoolean\n default:\n return checkIsAny\n }\n}\n\nexport default combineFn\n","// validate array type\n\nimport isArray from 'lodash-es/isArray'\nimport trim from 'lodash-es/trim'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length\n}\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError)\n }\n }\n\n static get name() {\n return 'JsonqlValidationError'\n }\n}\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","// create function to construct the config entry so we don't need to keep building object\n\nimport isFunction from 'lodash-es/isFunction'\nimport isString from 'lodash-es/isString'\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants'\n\nimport { checkIsArray } from '../array'\n// import checkIsBoolean from '../boolean'\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n }\n if (optional === true) {\n base[OPTIONAL_KEY] = true\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias\n }\n return base\n}\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__'\n\n/**\n * construct the actual end user method, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfigAsync = function(validateSync) {\n /**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n/**\n * copy of above but it's sync, rename with prefix get since 1.5.2\n * @param {function} validateSync validation method\n * @return {function} for performaning the actual valdiation\n */\nconst getCheckConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n getCheckConfigAsync,\n getCheckConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\nimport * as validator from './src/validator'\n// configuration checking\nimport * as jsonqlOptions from './src/options'\n// the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKey from './src/is-object-has-key'\n\nconst isObject = checkIsObject\nconst isAny = checkIsAny\nconst isString = checkIsString\nconst isBoolean = checkIsBoolean\nconst isNumber = checkIsNumber\nconst isArray = checkIsArray\nconst isNotEmpty = notEmpty\n\nconst normalizeArgs = validator.normalizeArgs\nconst validateSync = validator.validateSync\nconst validateAsync = validator.validateAsync\n\nconst JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO\n\nconst createConfig = jsonqlOptions.createConfig\nconst constructConfig = jsonqlOptions.constructConfigFn\n// construct the final output 1.5.2\nconst checkConfigAsync = jsonqlOptions.getCheckConfigAsync(validator.validateSync)\nconst checkConfig = jsonqlOptions.getCheckConfig(validator.validateSync)\n\nconst inArray = isInArray\n\n\n// check returns methods \nimport { \n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync \n} from './src/returns'\n\n\n// group the in one \nexport {\n JSONQL_PARAMS_VALIDATOR_INFO,\n \n isObject,\n isAny,\n isString,\n isBoolean,\n isNumber,\n isArray,\n isNotEmpty,\n \n inArray,\n isObjectHasKey,\n\n normalizeArgs,\n validateSync,\n validateAsync,\n\n createConfig,\n constructConfig,\n checkConfig,\n checkConfigAsync,\n\n checkReturns, \n checkReturnsAsync, \n checkResolverReturns, \n checkResolverReturnsAsync\n}\n\n\n\n\n\n","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport trim from 'lodash-es/trim'\n\n/**\n * DIY in Array\n * @param {array} arr to check from\n * @param {*} value to check against\n * @return {boolean} true on found\n */\nexport const inArray = (arr, value) => !!arr.filter(a => a === value).length\n\n// quick and dirty to turn non array to array\nexport const toArray = (arg) => isArray(arg) ? arg : [arg]\n\n/**\n * parse string to json or just return the original value if error happened\n * @param {*} n input\n * @param {boolean} [t=true] or throw\n * @return {*} json object on success\n */\nexport const parseJson = function(n, t=true) {\n try {\n return JSON.parse(n)\n } catch(e) {\n if (t) {\n return n\n }\n throw new Error(e)\n }\n}\n\n/**\n * @param {object} obj for search\n * @param {string} key target\n * @return {boolean} true on success\n */\nexport const isObjectHasKey = function(obj, key) {\n try {\n const keys = Object.keys(obj)\n return inArray(keys, key)\n } catch(e) {\n // @BUG when the obj is not an OBJECT we got some weird output\n return false\n }\n}\n\n/**\n * create a event name\n * @param {string[]} args\n * @return {string} event name for use\n */\nexport const createEvt = (...args) => args.join('_')\n\n/**\n * simple util method to get the value\n * @param {string} name of the key\n * @param {object} obj to take value from\n * @return {*} the object value id by name or undefined\n */\nexport const getConfigValue = (name, obj) => (\n obj && isPlainObject(obj) ? ( (name in obj) ? obj[name] : undefined ) : undefined\n)\n\n/**\n * small util to make sure the return value is valid JSON object\n * @param {*} n input\n * @return {object} correct JSON object\n */\nexport const toJson = n => {\n if (typeof n === 'string') {\n return parseJson(n)\n }\n return parseJson(JSON.stringify(n))\n}\n\n/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nexport const isNotEmpty = function(param) {\n return param !== undefined && param !== false && param !== null && trim(param) !== ''\n}\n\n/**\n * Simple check if the prop is function\n * @param {*} prop input\n * @return {boolean} true on success\n */\nexport const isFunc = prop => {\n if (typeof prop === 'function') {\n return true;\n }\n console.error(`Expect to be Function type! Got ${typeof prop}`)\n}\n\n/**\n * Shorthand method for Object.assign \n * @param {array} args \n * @return {object} merge together object by key \n */\nexport const assign = (...args) => Reflect.apply(Object.assign, Object, args)\n \n/** \n * generic placeholder function\n * @return {boolean} false \n */\nexport const nil = () => false\n\n/**\n * generic turn config into immutatble \n */\nexport const freeze = config => Object.freeze(config)","// break it out on its own because\n// it's building from the lodash-es from scratch\n// according to this discussion https://github.com/lodash/lodash/issues/3298\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport merge from 'lodash-es/merge'\n\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @param {boolean} asObject if true then merge the result object\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport function chainPromises(promises, asObject = false) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult)\n ))\n ))\n ), Promise.resolve(\n asObject === false ? [] : (isPlainObject(asObject) ? asObject : {})\n ))\n}\n\n\n/**\n * This one return a different result from the chainPromises\n * it will be the same like chainFns that take one promise resolve as the next fn parameter\n * @param {function} initPromise a function that accept param and resolve result\n * @param {array} promises array of function pass that resolve promises\n * @return {promise} resolve the processed result\n */\nexport function chainProcessPromises(initPromise, ...promises) {\n return (...args) => (\n promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResult => (\n currentTask(chainResult)\n )\n )\n ), Reflect.apply(initPromise, null, args))\n )\n}\n","/**\n * @param {boolean} sec return in second or not\n * @return {number} timestamp\n */\nexport const timestamp = (sec = false) => {\n let time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time\n}\n","// ported from jsonql-params-validator\n// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\n\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isString from 'lodash-es/isString'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\nimport { timestamp } from './timestamp'\nimport { parseJson } from './generic'\n\n/**\n * check if the payload has a timestamp field, then append a new timestamp to it\n * @param {object} payload from the com\n * @return {array} timestamp field with an array value\n */\nexport const handleTimestamp = payload => {\n let ts = payload[TIMESTAMP_PARAM_NAME]\n if (!isArray(ts)) {\n ts = [ts]\n }\n ts.push( timestamp() )\n\n return ts\n}\n\n/**\n * make sure it's an object (it was call formatPayload but it doesn't make sense)\n * @param {*} payload the object comes in could be string based\n * @return {object} the transformed payload\n */\nexport const toPayload = payload => isString(payload) ? parseJson(payload) : payload\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nexport const formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * extract the resolver name from the payload \n * @param {object} payload\n * @return {string} resolver name \n */\nexport function getResolverFromPayload(payload) {\n const keys = Object.keys(payload)\n return keys.filter(key => key !== TIMESTAMP_PARAM_NAME)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName name of the resolver\n * @param {*} payload what is sending \n * @param {object} extra additonal property we want to merge into the deliverable\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload, extra = {}) {\n return Object.assign({\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }, extra)\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n if (jsonp === true) {\n return payload\n }\n return createDeliverable(resolverName, payload)\n }\n throw new JsonqlValidationError('utils:params-api:createQuery', { \n message: `expect resolverName to be string and args to be array!`,\n resolverName, \n args \n })\n}\n\n/**\n * string version of the createQuery\n * @return {string}\n */\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload\n }\n if (isString(resolverName)) {\n return createDeliverable(resolverName, _payload)\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n/**\n * string version of createMutation\n * @return {string}\n */\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Extract the parts from payload and format for use\n * @param {string} resolverName name of fn\n * @param {object} payload the incoming json\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * Share function so no repeat\n * @param {object} payload the payload from client\n * @param {function} processor the last get result method\n * @return {*} result processed result\n */\nfunction processPayload(payload, processor) {\n const p = toPayload(payload)\n const resolverName = getResolverFromPayload(p)\n return Reflect.apply(processor, null, [resolverName, p])\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const result = processPayload(payload, getQueryFromArgs)\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && isPlainObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME],\n [TIMESTAMP_PARAM_NAME]: handleTimestamp(payload)\n }\n }\n }\n return false\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const result = processPayload(payload, getMutationFromArgs)\n\n if (result !== false) {\n return result\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// There are the socket related methods ported back from \n// ws-server-core and ws-client-core \nimport {\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME,\n TIMESTAMP_PARAM_NAME,\n ERROR_KEY,\n EMIT_REPLY_TYPE,\n EMIT_SEND_TYPE,\n ACKNOWLEDGE_REPLY_TYPE\n} from 'jsonql-constants'\nimport { JsonqlError, JsonqlValidationError } from 'jsonql-errors' \nimport isString from 'lodash-es/isString'\nimport isArray from 'lodash-es/isArray'\n\nimport { createDeliverable, formatPayload } from './params-api'\nimport { toJson, isObjectHasKey, nil } from './generic'\nimport { timestamp } from './timestamp'\n\nconst PAYLOAD_NOT_DECODED_ERR = 'payload can not decoded'\nconst WS_KEYS = [\n WS_REPLY_TYPE,\n WS_EVT_NAME,\n WS_DATA_NAME\n]\n\n/////////////////////////////////////\n// REPLY FROM SERVER //\n/////////////////////////////////////\n\n/**\n * This will be a event emit from the client using the send method \n * But we have to change the server to understand it\n * @param {string} resolverName name of resolver ot call \n * @param {array} args for the resolver\n * @param {boolean} str true then stringify it \n * @return {object} formatted payload\n */\nexport const createSendPayload = (resolverName, args, str = false) => {\n if (isString(resolverName) && isArray(args)) {\n let payload = formatPayload(args)\n // the different is we add a additonal type in the payload \n const result = createDeliverable(resolverName, payload, {type: EMIT_SEND_TYPE})\n return str ? JSON.stringify(result) : result\n }\n throw new JsonqlValidationError(`utils:socket:createSendMsg`, { \n resolverName, \n args, \n message: 'expect resolverName to be string and args to be array!'\n })\n}\n\n/**\n * We need to find the TS field and take it out from the previous payload \n * otherwise it will keep on rolling into the structure which is not what we wanted\n * @param {object} data for inspection\n * @return {object} { data: for the data to use, TS if there is any }\n */\nconst getTsFieldFromData = (data) => {\n let obj = {[TIMESTAMP_PARAM_NAME]: [], data: {}}\n if (data[TIMESTAMP_PARAM_NAME]) {\n const ts = data[TIMESTAMP_PARAM_NAME]\n obj[TIMESTAMP_PARAM_NAME] = Array.isArray(ts) ? ts : [ts]\n delete data[TIMESTAMP_PARAM_NAME]\n } \n obj.data = data\n \n return obj\n}\n\n\n/**\n * The ws doesn't have a acknowledge callback like socket.io\n * so we have to DIY one for ws and other that doesn't have it\n * @param {string} type of reply\n * @param {string} resolverName which is replying\n * @param {*} data payload\n * @param {array} [ts= []] the last received ts, if any \n * @return {string} stringify json\n */\nexport const createWsReply = (type, resolverName, data, ts = []) => {\n const obj = getTsFieldFromData(toJson(data))\n ts = ts.concat(obj[TIMESTAMP_PARAM_NAME])\n if (!ts.length) {\n ts.push(timestamp())\n }\n return JSON.stringify({\n data: {\n [WS_REPLY_TYPE]: type,\n [WS_EVT_NAME]: resolverName,\n [WS_DATA_NAME]: obj.data \n },\n [TIMESTAMP_PARAM_NAME]: ts \n })\n}\n\n// extended function \nexport const createReplyMsg = (resolverName, data, ts = []) => (\n createWsReply(EMIT_REPLY_TYPE, resolverName, data, ts)\n)\n\nexport const createAcknowledgeMsg = (resolverName, data, ts = []) => (\n createWsReply(ACKNOWLEDGE_REPLY_TYPE, resolverName, data, ts)\n)\n\n/**\n * @param {string|object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nexport const isWsReply = payload => {\n const json = isString(payload) ? toJson(payload) : payload\n const { data } = json\n if (data) {\n let result = WS_KEYS.filter(key => isObjectHasKey(data, key))\n return (result.length === WS_KEYS.length) ? data : false\n }\n return false\n}\n\n/**\n * @param {string|object} data received data\n * @param {function} [cb=nil] this is for extracting the TS field or when it's error\n * @return {object} false on failed\n */\nexport const extractWsPayload = (payload, cb = nil) => {\n try {\n const json = toJson(payload)\n // now handle the data\n let _data\n if ((_data = isWsReply(json)) !== false) {\n // note the ts property is on its own \n cb('_data', _data)\n \n return {\n data: toJson(_data[WS_DATA_NAME]),\n resolverName: _data[WS_EVT_NAME],\n type: _data[WS_REPLY_TYPE]\n }\n }\n throw new JsonqlError(PAYLOAD_NOT_DECODED_ERR, payload)\n } catch(e) {\n return cb(ERROR_KEY, e)\n }\n}\n","// pass the different type of ws to generate the client\n// this is where the framework specific code get injected\nimport cookies from 'js-cookie'\nimport { disconnect } from '../disconnect'\nimport {\n createInitPing, \n extractPingResult,\n prepareConnectConfig,\n fixWss\n} from '../modules'\n\n/**\n * \n * @param {*} WebSocketClass \n * @param {*} url \n * @param {*} type \n * @param {*} options \n */\nfunction createWs(WebSocketClass, type, url, options) {\n if (type === 'browser') {\n const { headers } = options \n if (headers) {\n for (let key in headers) {\n if (!cookies.get(key)) {\n cookies.set(key, headers[key])\n }\n }\n }\n }\n let wsUrl = fixWss(url)\n return type === 'node' ? new WebSocketClass(wsUrl, options) : new WebSocketClass(wsUrl) \n}\n\n/**\n * Group the ping and get respond create new client in one\n * @param {object} ws \n * @param {object} WebSocket \n * @param {string} url\n * @param {function} resolver \n * @param {function} rejecter \n * @param {boolean} auth client or not\n * @return {promise} resolve the confirm client\n */\nfunction initPingAction(ws, WebSocketClass, type, url, wsOptions, resolver, rejecter) {\n\n // @TODO how to we id this client can issue a CSRF\n // by origin? \n ws.onopen = function onOpenCallback() {\n ws.send(createInitPing())\n }\n\n ws.onmessage = function onMessageCallback(payload) {\n try {\n const header = extractPingResult(payload.data)\n // delay or not show no different but just on the safe side\n setTimeout(() => { \n disconnect(ws)\n }, 50)\n const newWs = createWs(WebSocketClass, type, url, Object.assign(wsOptions, header)) \n \n resolver(newWs) \n \n } catch(e) {\n rejecter(e)\n }\n }\n\n ws.onerror = function onErrorCallback(err) {\n rejecter(err)\n }\n}\n\n/**\n * less duplicated code the better \n * @param {object} WebSocket \n * @param {string} type we need to change the way how it deliver header for different platform\n * @param {string} url formatted url\n * @param {object} options or not\n * @return {promise} resolve the actual verified client\n */\nfunction asyncConnect(WebSocketClass, type, url, options) {\n \n return new Promise((resolver, rejecter) => { \n const unconfirmClient = createWs(WebSocketClass, type, url, options)\n \n return initPingAction(unconfirmClient, WebSocketClass, type, url, options, resolver, rejecter)\n })\n}\n\n/**\n * The bug was in the wsOptions where ws don't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @NOTE here we only return a method to create the client, it might not get call \n * @param {object} WebSocket the client or node version of ws\n * @param {string} [type = 'browser'] we need to tell if this is browser or node \n * @param {boolean} [auth = false] if it's auth then 3 param or just one\n * @return {function} the client method to connect to the ws socket server\n */\nfunction setupWebsocketClientFn(WebSocketClass, type = 'browser', auth = false) {\n if (auth === false) {\n /**\n * Create a non-protected client\n * @param {string} uri already constructed url \n * @param {object} config from the ws-client-core this will be wsOptions taken out from opts \n * @return {promise} resolve to the confirmed client\n */\n return function createWsClient(uri, config) {\n // const { log } = config\n const { url, opts } = prepareConnectConfig(uri, config, false)\n\n return asyncConnect(WebSocketClass, type, url, opts)\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} uri start with ws:// @TODO check this?\n * @param {object} config this is the full configuration because we need something from it\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClient(uri, config, token) {\n // const { log } = config\n const { url, opts } = prepareConnectConfig(uri, config, token)\n\n return asyncConnect(WebSocketClass, type, url, opts)\n }\n}\n\nexport { setupWebsocketClientFn }","// @BUG when call disconnected\n// this keep causing an \"Disconnect call failed TypeError: Cannot read property 'readyState' of null\"\n// I think that is because it's not login then it can not be disconnect\n// how do we track this state globally\nimport { \n LOGIN_EVENT_NAME, \n CONNECT_EVENT_NAME \n} from 'jsonql-constants'\nimport { clearMainEmitEvt } from '../modules'\n\n/**\n * when we received a login event \n * from the http-client or the standalone login call \n * we received a token here --> update the opts then trigger \n * the CONNECT_EVENT_NAME again\n * @param {object} opts configurations\n * @param {object} nspMap contain all the required info\n * @param {object} ee event emitter\n * @return {void}\n */\nexport function loginEventListener(opts, nspMap, ee) {\n const { log } = opts\n const { namespaces } = nspMap\n\n log(`[4] loginEventHandler`)\n\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandlerCallback(tokenFromLoginAction) {\n\n log('createClient LOGIN_EVENT_NAME $only handler')\n // @NOTE this is wrong because whenever start it will connect the to the public \n // but when login it should just start binding the private event\n clearMainEmitEvt(ee, namespaces)\n // reload the nsp and rebind all the events\n opts.token = tokenFromLoginAction \n ee.$trigger(CONNECT_EVENT_NAME, [opts, ee]) // don't need to pass the nspMap \n })\n}\n","// actually binding the event client to the socket client\nimport {\n createNspClient,\n createNspAuthClient\n} from './modules'\nimport {\n chainPromises \n} from 'jsonql-utils/src/chain-promises'\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @NOTE when we enable the standalone method this sequence will not change \n * only call and reload\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {promise} resolve the nsps namespace with namespace as key\n */\nconst createNsp = function(opts, nspMap, token = null) {\n // we leave the token param out because it could get call by another method\n token = token || opts.token \n let { publicNamespace, namespaces } = nspMap\n const { log } = opts \n log(`createNspAction`, 'publicNamespace', publicNamespace, 'namespaces', namespaces)\n \n // reverse the namespaces because it got stuck for some reason\n // const reverseNamespaces = namespaces.reverse()\n if (opts.enableAuth) {\n return chainPromises(\n namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token\n log('create createNspAuthClient at run time')\n return createNspAuthClient(namespace, opts)\n }\n return Promise.resolve(false)\n }\n return createNspClient(namespace, opts)\n })\n )\n .then(results => \n results.map((result, i) => \n ({ [namespaces[i]]: result }))\n .reduce((a, b) => Object.assign(a, b), {})\n )\n }\n \n return createNspClient(false, opts)\n .then(nsp => ({[publicNamespace]: nsp}))\n}\n\nexport { createNsp }\n","// taken out from the bind-socket-event-handler \nimport { DISCONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { createIntercomPayload } from '../modules'\n\n/**\n * This is the actual logout (terminate socket connection) handler \n * There is another one that is handle what should do when this happen \n * @param {object} ee eventEmitter\n * @param {object} ws the WebSocket instance\n * @return {void}\n */\nexport function disconnectEventListener(ee, ws) {\n // listen to the LOGOUT_EVENT_NAME when this is a private nsp\n ee.$on(DISCONNECT_EVENT_NAME, function closeEvtHandler() {\n try {\n // @TODO we need find a way to get the userdata\n ws.send(createIntercomPayload(LOGOUT_EVENT_NAME))\n log('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}","// the WebSocket main handler\nimport {\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_KEY,\n ON_MESSAGE_FN_NAME,\n ON_RESULT_FN_NAME,\n ON_READY_FN_NAME,\n ON_LOGIN_FN_NAME,\n ON_ERROR_FN_NAME\n} from 'jsonql-constants'\nimport {\n createQueryStr,\n createEvt,\n extractWsPayload\n} from 'jsonql-utils/module'\nimport {\n handleNamespaceOnError\n} from '../modules'\nimport { \n disconnectEventListener\n} from './disconnect-event-listener'\n\n/**\n * in some edge case we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n * @return {undefined} nothing return\n */\nexport const errorTypeHandler = (ee, namespace, resolverName, json) => {\n let evt = [namespace]\n if (resolverName) {\n evt.push(resolverName)\n }\n evt.push(ON_ERROR_FN_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the event to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @param {boolean} isPrivate to id if this namespace is private or not\n * @param {object} opts configuration\n * @param {number} ctnLeft in the namespaceEventListener count down how many namespace left to call \n * @return {object} promise resolve after the onopen event\n */\nexport function bindSocketEventHandler(namespace, ws, ee, isPrivate, opts, ctnLeft) {\n const { log } = opts\n // setup the logut event listener \n // this will hear the event and actually call the ws.terminate\n if (isPrivate) {\n log('Private namespace', namespace, ' binding to the DISCONNECT ws.terminate')\n disconnectEventListener(ee, ws)\n }\n // log(`log test, isPrivate:`, isPrivate)\n // connection open\n ws.onopen = function onOpenCallback() {\n\n log('client.ws.onopen listened -->', namespace)\n /*\n This is the change from before about the hooks \n now only the public namespace will get trigger the onReady \n and the private one will get the onLogin \n this way, we won't get into the problem of multiple event \n get trigger, and for developer they just have to place \n the callback inside the right hook\n */\n if (isPrivate) {\n log(`isPrivate and fire the ${ON_LOGIN_FN_NAME}`)\n ee.$call(ON_LOGIN_FN_NAME)(namespace)\n } else {\n ee.$call(ON_READY_FN_NAME)(namespace, ctnLeft)\n // The namespaceEventListener will count this for here\n // and this count will only count the public namespace \n // it will always be 1 for now\n log(`isPublic onReady hook executed`, ctnLeft)\n if (ctnLeft === 0) {\n ee.$off(ON_READY_FN_NAME)\n }\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n /**\n * actually send the payload to server\n * @param {string} resolverName\n * @param {array} args NEED TO CHECK HOW WE PASS THIS!\n */\n function wsMainOnEvtHandler(resolverName, args) {\n const payload = createQueryStr(resolverName, args)\n log('ws.onopen.send', resolverName, args, payload)\n\n ws.send(payload)\n }\n )\n }\n\n // reply\n // If we change it to the event callback style\n // then the payload will just be the payload and fucks up the extractWsPayload call @TODO\n ws.onmessage = function onMessageCallback(payload) {\n\n log(`client.ws.onmessage raw payload`, payload.data)\n \n // console.log(`on.message`, typeof payload, payload)\n try {\n // log(`ws.onmessage raw payload`, payload)\n // @TODO the payload actually contain quite a few things - is that changed?\n // type: message, data: data_send_from_server\n const json = extractWsPayload(payload.data)\n const { resolverName, type } = json\n\n log('Respond from server', type, json)\n\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, ON_MESSAGE_FN_NAME)\n let r = ee.$call(e1)(json)\n \n log(`EMIT_REPLY_TYPE`, e1, r)\n break\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, ON_RESULT_FN_NAME)\n let x2 = ee.$call(e2)(json)\n\n log(`ACKNOWLEDGE_REPLY_TYPE`, e2, x2)\n break\n case ERROR_KEY:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n log(`ERROR_KEY`)\n errorTypeHandler(ee, namespace, resolverName, json)\n break\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n log('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_FN_NAME), [error])\n }\n } catch(e) {\n log(`client.ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n log('client.ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // add a onerror event handler here\n ws.onerror = function onErrorCallback(err) {\n // trigger a global error event\n log(`client.ws.onerror`, err)\n handleNamespaceOnError(ee, namespace, err)\n }\n \n // we don't bind the logut here and just return the ws \n return ws \n}\n","// take out from the bind-framework-to-jsonql \nimport { CONNECT_EVENT_NAME } from 'jsonql-constants'\nimport { createNsp } from '../create-nsp'\nimport { namespaceEventListener } from '../modules'\nimport { bindSocketEventHandler } from './bind-socket-event-handler'\n\n/**\n * This is the hard of establishing the connection and binding to the jsonql events \n * @param {*} nspMap \n * @param {*} ee event emitter\n * @param {function} log function to show internal \n * @return {void}\n */\nexport function connectEventListener(nspMap, ee, log) {\n log(`[2] setup the CONNECT_EVENT_NAME`)\n // this is a automatic trigger from within the framework\n ee.$only(CONNECT_EVENT_NAME, function connectEventNameHandler($config, $ee) {\n log(`[3] CONNECT_EVENT_NAME`, $ee)\n\n return createNsp($config, nspMap)\n .then(nsps => namespaceEventListener(bindSocketEventHandler, nsps))\n .then(listenerFn => listenerFn($config, nspMap, $ee))\n })\n\n // log(`[3] after setup the CONNECT_EVENT_NAME`)\n}","// share method to create the wsClientResolver\nimport { \n NSP_CLIENT, \n NSP_AUTH_CLIENT,\n ENABLE_AUTH_PROP_KEY\n} from 'jsonql-constants'\nimport { \n setupWebsocketClientFn \n} from './setup-websocket-client-fn'\nimport { \n loginEventListener, \n connectEventListener \n} from '../setup-socket-listeners'\n\n/**\n * Create the framework <---> jsonql client binding\n * @param {object} WebSocketClass the different WebSocket module\n * @param {string} [type=browser] we need different setup for browser or node\n * @return {function} the wsClientResolver\n */\nfunction setupConnectClient(WebSocketClass, type = 'browser') {\n /**\n * wsClientResolver\n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\n return function createClientBindingAction(opts, nspMap, ee) {\n const { log } = opts\n\n log(`There is problem here with passing the opts`, opts)\n // this will put two callable methods into the opts \n opts[NSP_CLIENT] = setupWebsocketClientFn(WebSocketClass, type)\n // we don't need this one unless enableAuth === true \n if (opts[ENABLE_AUTH_PROP_KEY] === true) {\n opts[NSP_AUTH_CLIENT] = setupWebsocketClientFn(WebSocketClass, type, true)\n } \n // debug \n log(`[1] bindWebsocketToJsonql`, ee.$name, nspMap)\n // @2020-03-20 @NOTE \n \n connectEventListener(nspMap, ee, log)\n \n // next we need to setup the login event handler\n // But the same design (see above) when we received a login event \n // from the http-client or the standalone login call \n // we received a token here --> update the opts then trigger \n // the CONNECT_EVENT_NAME again\n loginEventListener(opts, nspMap, ee)\n\n log(`just before returing the values for the next operation from createClientBindingAction`)\n\n // we just return what comes in\n return { opts, nspMap, ee }\n }\n}\n\nexport { setupConnectClient }","// this will be the news style interface that will pass to the jsonql-ws-client\n// then return a function for accepting an opts to generate the final\n// client api\nimport ws from './ws'\nimport { setupConnectClient } from './setup-connect-client'\n\nconst setupSocketClientListener = setupConnectClient(ws)\n\n/**\n * We export it as a default and use the file name to id the function \n * but it just way too confusing, therefore we change it to a name export \n * @param {object} opts configuration\n * @param {object} nspMap from the contract\n * @param {object} ee instance of the eventEmitter\n * @return {object} passing the same 3 input out with additional in the opts\n */\nexport {\n setupSocketClientListener\n} \n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { \n wsClientCore\n} from './core/modules' \nimport { \n wsClientCheckMap,\n wsClientConstProps\n} from './options'\nimport { \n setupSocketClientListener \n} from './core/setup-socket-client-listener'\n\n// export back the function and that's it\nexport default function wsBrowserClient(config = {}, constProps = {}) {\n return wsClientCore(\n setupSocketClientListener, \n wsClientCheckMap, \n Object.assign({}, wsClientConstProps, constProps)\n )(config)\n}\n","// just export interface for browser\nimport wsBrowserClient from './src/browser-ws-client'\n\nexport default wsBrowserClient"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;ECAA;;;;;;;;;;;;;;ECAA;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-ws-client.umd.js","sources":["../../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../../ws-client-core/src/options/index.js"],"sourcesContent":["/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n // @1.2.2 this become an array so we can hold different events\n this.__pattern__ = []\n // key value pair store to store the queued calls\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE ALL SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {array.} patterns the pattern search matches the event name\n * @return {array} if the pattern return is registered or not\n */\n $suspendEvent(...patterns) {\n return patterns.map(pattern => {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n // check if it's already added \n if (this.__isPatternRegisterd(regex) === false) {\n this.__pattern__.push(regex)\n\n return this.__pattern__.length\n }\n return false\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n }\n\n /**\n * This is pair with $suspnedEvent to release part of the event queue by the pattern (eventName)\n * @param {array.<*>} patterns a eventName of partial eventName to create a RegExp\n * @return {number} should be the number of queue got released\n */\n $releaseEvent(...patterns) {\n return patterns.map(pattern => {\n this.logger(`($releaseEvent)`, pattern)\n const regex = getRegex(pattern)\n if (isRegExp(regex) && this.__isPatternRegisterd(regex)) {\n const self = this\n\n return this.__getToReleaseQueue(regex)\n .map((args, i) => {\n \n Reflect.apply(self.$trigger, self, args)\n\n return i \n }).reduce((a, b) => ++b, 0)\n }\n\n this.logger('$releaseEvent throw error ==========================>', this.__pattern__, regex)\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n .reduce((x, y) => x + y, 0)\n }\n\n /**\n * queuing call up when it's in suspend mode,\n * it's currently suspending then add to store then the $trigger will do nothing\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n switch (true) {\n case this.__suspend_state__ === true: // this will take priority over the pattern\n \n return this.__addToQueueStore(evt, args)\n case !!this.__pattern__.length === true: \n // check the pattern and decide if we want to suspend it or not\n if (!!this.__pattern__.filter(p => p.test(evt)).length) {\n \n return this.__addToQueueStore(evt, args)\n }\n this.logger(`($queue) ${evt} NOT added to $queueStore`, this.__pattern__)\n \n return false \n default:\n this.logger('($queue) get called NOTHING added')\n return false\n } \n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n\n /**\n * The reason is before we call $trigger we need to remove the pattern from queue\n * otherwise, it will never get release\n * @param {*} pattern to find the queue \n * @return {array} queue to get execute \n */\n __getToReleaseQueue(regex) {\n // first get the list of events in the queue store that match this pattern\n const list = this.$queues\n // first index is the eventName\n .filter(content => regex.test(content[0]))\n .map(content => {\n this.logger(`[release] execute ${content[0]} matches ${regex}`, content)\n // we just remove it\n this.queueStore.delete(content)\n \n return content\n })\n if (list.length > 0) {\n // we need to remove this event from the pattern queue array \n this.__pattern__ = this.__pattern__.filter(p => p.toString() !== regex.toString()) \n }\n\n return list \n }\n\n /**\n * Wrapper method with a logger \n * @param {*} evt \n * @param {*} args \n * @return {boolean}\n */\n __addToQueueStore(evt, args) {\n this.logger(`($queue) ${evt} added to $queueStore`, args)\n\n // @TODO should we check if this already added? \n // what if that is a multiple call like $on\n this.queueStore.add([evt].concat(args))\n\n return true\n }\n\n /**\n * check if certain pattern already registered in the queue\n * @param {*} pattern\n * @return {boolean} \n */\n __isPatternRegisterd(pattern) {\n // this is a bit of a hack to compare two regex Object \n return !!this.__pattern__.filter(p => (\n p.toString() === pattern.toString()\n )).length \n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue, this is a wholesale release ALL\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = []\n \n this.logger(`(release) was called with ${size}${pattern.length ? ' for \"' + pattern.join(',') + '\"': ''} item${size > 1 ? 's' : ''}`)\n \n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.logger('(release queue)', queue)\n\n queue.forEach(args => {\n this.logger(`[release] execute ${args[0]}`, args)\n\n Reflect.apply(this.$trigger, this, args)\n })\n\n this.queueStore.clear()\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n"],"names":["SetCache","Object","wsCoreConstProps"],"mappings":"4gCAAA,89vBCAAA,8tWCAAC,q3uCCAAC"} \ No newline at end of file diff --git a/packages/@jsonql/ws/node-module.js b/packages/@jsonql/ws/node-module.js index 21e4b1400f8a0d0617bab7923d3e5d420042ea53..d3ec48b02aa66884a3ccec0fe0c4f13ec6a88645 100644 --- a/packages/@jsonql/ws/node-module.js +++ b/packages/@jsonql/ws/node-module.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof r&&r&&r.Object===Object&&r,o="object"==typeof self&&self&&self.Object===Object&&self,i=n||o||Function("return this")(),u=i.Symbol;var a=Array.isArray,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=u?u.toStringTag:void 0;var p=Object.prototype.toString;var h=u?u.toStringTag:void 0;function v(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function g(t){return null!=t&&"object"==typeof t}var d=u?u.prototype:void 0,y=d?d.toString:void 0;function _(t){if("string"==typeof t)return t;if(a(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&w(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function q(t){return function(t){return"number"==typeof t||g(t)&&"[object Number]"==v(t)}(t)&&t!=+t}function M(t){return"string"==typeof t||!a(t)&&g(t)&&"[object String]"==v(t)}var F=function(t){return!M(t)&&!q(parseFloat(t))},L=function(t){return""!==R(t)&&M(t)},D=function(t){return null!=t&&"boolean"==typeof t},U=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==R(t)&&(!1===e||!0===e&&null!==t)},J=function(t,e){return void 0===e&&(e=""),!!a(t)&&(""===e||""===R(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return F;case"string":return L;case"boolean":return D;default:return U}}(e)(t)})).length>0))};var I,B,W=(I=Object.getPrototypeOf,B=Object,function(t){return I(B(t))}),V=Function.prototype,G=Object.prototype,H=V.toString,Q=G.hasOwnProperty,Y=H.call(Object);function K(t){if(!g(t)||"[object Object]"!=v(t))return!1;var e=W(t);if(null===e)return!0;var r=Q.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&H.call(r)==Y}var X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function tt(t,e){return t===e||t!=t&&e!=e}function et(t,e){for(var r=t.length;r--;)if(tt(t[r][0],e))return r;return-1}var rt=Array.prototype.splice;function nt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},nt.prototype.set=function(t,e){var r=this.__data__,n=et(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function it(t){if(!ot(t))return!1;var e=v(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ut,at=i["__core-js_shared__"],ct=(ut=/[^.]+$/.exec(at&&at.keys&&at.keys.IE_PROTO||""))?"Symbol(src)_1."+ut:"";var st=Function.prototype.toString;var ft=/^\[object .+?Constructor\]$/,lt=Function.prototype,pt=Object.prototype,ht=lt.toString,vt=pt.hasOwnProperty,gt=RegExp("^"+ht.call(vt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function dt(t){return!(!ot(t)||function(t){return!!ct&&ct in t}(t))&&(it(t)?gt:ft).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function yt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return dt(r)?r:void 0}var _t=yt(i,"Map"),bt=yt(Object,"create");var mt=Object.prototype.hasOwnProperty;var wt=Object.prototype.hasOwnProperty;function jt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Gt(t){return null!=t&&Vt(t.length)&&!it(t)}var Ht="object"==typeof exports&&exports&&!exports.nodeType&&exports,Qt=Ht&&"object"==typeof module&&module&&!module.nodeType&&module,Yt=Qt&&Qt.exports===Ht?i.Buffer:void 0,Kt=(Yt?Yt.isBuffer:void 0)||function(){return!1},Xt={};Xt["[object Float32Array]"]=Xt["[object Float64Array]"]=Xt["[object Int8Array]"]=Xt["[object Int16Array]"]=Xt["[object Int32Array]"]=Xt["[object Uint8Array]"]=Xt["[object Uint8ClampedArray]"]=Xt["[object Uint16Array]"]=Xt["[object Uint32Array]"]=!0,Xt["[object Arguments]"]=Xt["[object Array]"]=Xt["[object ArrayBuffer]"]=Xt["[object Boolean]"]=Xt["[object DataView]"]=Xt["[object Date]"]=Xt["[object Error]"]=Xt["[object Function]"]=Xt["[object Map]"]=Xt["[object Number]"]=Xt["[object Object]"]=Xt["[object RegExp]"]=Xt["[object Set]"]=Xt["[object String]"]=Xt["[object WeakMap]"]=!1;var Zt="object"==typeof exports&&exports&&!exports.nodeType&&exports,te=Zt&&"object"==typeof module&&module&&!module.nodeType&&module,ee=te&&te.exports===Zt&&n.process,re=function(){try{var t=te&&te.require&&te.require("util").types;return t||ee&&ee.binding&&ee.binding("util")}catch(t){}}(),ne=re&&re.isTypedArray,oe=ne?function(t){return function(e){return t(e)}}(ne):function(t){return g(t)&&Vt(t.length)&&!!Xt[v(t)]};function ie(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ue=Object.prototype.hasOwnProperty;function ae(t,e,r){var n=t[e];ue.call(t,e)&&tt(n,r)&&(void 0!==r||e in t)||xt(t,e,r)}var ce=/^(?:0|[1-9]\d*)$/;function se(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&ce.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(we);function Se(t,e){return Oe(function(t,e,r){return e=me(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=me(n.length-e,0),u=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Ee.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!ot(r))return!1;var n=typeof e;return!!("number"==n?Gt(r)&&se(e,r.length):"string"==n&&e in r)&&tt(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&ar(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Or=function(t){return Pe(t)?t:[t]},Sr=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Er=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},$r=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},xr=function(t){return Sr("string"==typeof t?t:JSON.stringify(t))},kr=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Ar=function(){return!1},Tr=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,Or(t))}),Reflect.apply(t,null,r))}};function Nr(t,e){return t===e||t!=t&&e!=e}function Cr(t,e){for(var r=t.length;r--;)if(Nr(t[r][0],e))return r;return-1}var Pr=Array.prototype.splice;function zr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},zr.prototype.set=function(t,e){var r=this.__data__,n=Cr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function qr(t){if(!Rr(t))return!1;var e=Be(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Mr=qe["__core-js_shared__"],Fr=function(){var t=/[^.]+$/.exec(Mr&&Mr.keys&&Mr.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Lr=Function.prototype.toString;function Dr(t){if(null!=t){try{return Lr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Ur=/^\[object .+?Constructor\]$/,Jr=Function.prototype,Ir=Object.prototype,Br=Jr.toString,Wr=Ir.hasOwnProperty,Vr=RegExp("^"+Br.call(Wr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gr(t){return!(!Rr(t)||function(t){return!!Fr&&Fr in t}(t))&&(qr(t)?Vr:Ur).test(Dr(t))}function Hr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Gr(r)?r:void 0}var Qr=Hr(qe,"Map"),Yr=Hr(Object,"create");var Kr=Object.prototype.hasOwnProperty;var Xr=Object.prototype.hasOwnProperty;function Zr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Sn(t){return null!=t&&On(t.length)&&!qr(t)}var En="object"==typeof exports&&exports&&!exports.nodeType&&exports,$n=En&&"object"==typeof module&&module&&!module.nodeType&&module,xn=$n&&$n.exports===En?qe.Buffer:void 0,kn=(xn?xn.isBuffer:void 0)||function(){return!1},An={};An["[object Float32Array]"]=An["[object Float64Array]"]=An["[object Int8Array]"]=An["[object Int16Array]"]=An["[object Int32Array]"]=An["[object Uint8Array]"]=An["[object Uint8ClampedArray]"]=An["[object Uint16Array]"]=An["[object Uint32Array]"]=!0,An["[object Arguments]"]=An["[object Array]"]=An["[object ArrayBuffer]"]=An["[object Boolean]"]=An["[object DataView]"]=An["[object Date]"]=An["[object Error]"]=An["[object Function]"]=An["[object Map]"]=An["[object Number]"]=An["[object Object]"]=An["[object RegExp]"]=An["[object Set]"]=An["[object String]"]=An["[object WeakMap]"]=!1;var Tn="object"==typeof exports&&exports&&!exports.nodeType&&exports,Nn=Tn&&"object"==typeof module&&module&&!module.nodeType&&module,Cn=Nn&&Nn.exports===Tn&&ze.process,Pn=function(){try{var t=Nn&&Nn.require&&Nn.require("util").types;return t||Cn&&Cn.binding&&Cn.binding("util")}catch(t){}}(),zn=Pn&&Pn.isTypedArray,Rn=zn?function(t){return function(e){return t(e)}}(zn):function(t){return Ge(t)&&On(t.length)&&!!An[Be(t)]};function qn(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var Mn=Object.prototype.hasOwnProperty;function Fn(t,e,r){var n=t[e];Mn.call(t,e)&&Nr(n,r)&&(void 0!==r||e in t)||on(t,e,r)}var Ln=/^(?:0|[1-9]\d*)$/;function Dn(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Ln.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Xn);function eo(t,e){return to(function(t,e,r){return e=Kn(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Kn(n.length-e,0),u=Array(i);++o1?r[o-1]:void 0,u=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&function(t,e,r){if(!Rr(r))return!1;var n=typeof e;return!!("number"==n?Sn(r)&&Dn(e,r.length):"string"==n&&e in r)&&Nr(r[e],t)}(r[0],r[1],u)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0))},qo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},Mo=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!zo(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Ro(r,t)})).length},Fo=function(t,e){if(void 0===e&&(e=null),Ze(t)){if(!e)return!0;if(Ro(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=qo(t))?!Mo({arg:r},e):!zo(t)(r))})).length)})).length}return!1},Lo=function(t,e){var r,n,o,i,u;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,u=[o],Array.isArray(i.keys)&&i.keys.length&&u.push(i.keys),!Reflect.apply(Fo,null,u);case"array"===t:return!Ro(e.arg);case!1!==(r=qo(t)):return!Mo(e,r);default:return!zo(t)(e.arg)}},Do=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Uo=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Ro(e))throw new go("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Ro(t))throw console.info(t),new go("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,u=e[r]||{type:o,name:"_"+r};return{arg:i?Do(t,u):t,index:r,param:u,optional:i}}));default:throw new yo("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!ko(e)&&!(r.type.length>r.type.filter((function(e){return Lo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Lo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Jo=We(Object.keys,Object),Io=Object.prototype.hasOwnProperty;function Bo(t){return Sn(t)?Jn(t):function(t){if(!yn(t))return Jo(t);var e=[];for(var r in Object(t))Io.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function Wo(t,e){return t&&an(t,e,Bo)}function Vo(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new en;++ea))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new Vo:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var u=i.getMaxStore(t),a=-1;if(u>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var u=Array.from(i.get(t)),a=u.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!au.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],u=Reflect.apply(this.addToStore,this,i),a=u[0],c=u[1];return this.normalStore=a,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),u=i[0],a=i[1];return this.lazyStore=u,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){pu.set(this,t)},r.normalStore.get=function(){return pu.get(this)},r.lazyStore.set=function(t){hu.set(this,t)},r.lazyStore.get=function(){return hu.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=[],this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE ALL SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){var r=lu(e);if(cu(r))return!1===t.__isPatternRegisterd(r)&&(t.__pattern__.push(r),t.__pattern__.length);throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')}))},e.prototype.$releaseEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){t.logger("($releaseEvent)",e);var r=lu(e);if(cu(r)&&t.__isPatternRegisterd(r)){var n=t;return t.__getToReleaseQueue(r).map((function(t,e){return Reflect.apply(n.$trigger,n,t),e})).reduce((function(t,e){return++e}),0)}throw t.logger("$releaseEvent throw error ==========================>",t.__pattern__,r),new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')})).reduce((function(t,e){return t+e}),0)},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];switch(!0){case!0===this.__suspend_state__:return this.__addToQueueStore(t,e);case!0==!!this.__pattern__.length:return this.__pattern__.filter((function(e){return e.test(t)})).length?this.__addToQueueStore(t,e):(this.logger("($queue) "+t+" NOT added to $queueStore",this.__pattern__),!1);default:return this.logger("($queue) get called NOTHING added"),!1}},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__getToReleaseQueue=function(t){var e=this,r=this.$queues.filter((function(e){return t.test(e[0])})).map((function(r){return e.logger("[release] execute "+r[0]+" matches "+t,r),e.queueStore.delete(r),r}));return r.length>0&&(this.__pattern__=this.__pattern__.filter((function(e){return e.toString()!==t.toString()}))),r},e.prototype.__addToQueueStore=function(t,e){return this.logger("($queue) "+t+" added to $queueStore",e),this.queueStore.add([t].concat(e)),!0},e.prototype.__isPatternRegisterd=function(t){return!!this.__pattern__.filter((function(e){return e.toString()===t.toString()})).length},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=[],this.logger("(release) was called with "+e+(r.length?' for "'+r.join(",")+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.logger("(release queue)",n),n.forEach((function(e){t.logger("[release] execute "+e[0],e),Reflect.apply(t.$trigger,t,e)})),this.queueStore.clear(),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(vu))),yu=function(t){function e(e){if("function"!=typeof e)throw new Error("Just die here the logger is not a function!");e("---\x3e Create a new EventEmitter <---"),t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client-core"},Object.defineProperties(e.prototype,r),e}(du),_u=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new yu(t.log)},bu=function(t){var e=new RegExp("^(http|https)://","i"),r=t.match(e);if(r&&r.length){var n="https"===r[1].toLowerCase()?"wss":"ws";return t.replace(e,n+"://")}return t},mu=function(t,e){Or(e).forEach((function(e){t.$off($r(e,"emit_reply"))}))};function wu(t,e,r){Er(t,"error")?r(t.error):Er(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function ju(t,e,r,n,o){void 0===n&&(n=[]);var i=$r(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,Or(n)]),new Promise((function(n,i){var u=$r(e,r,"onResult");t.$on(u,(function(t){o("got the first result",t),wu(t,n,i)}))}))}var Ou=function(t,e,r,n,o,i){return no(t,"send",Ar,(function(){return i("running call getter method"),function(){for(var t=[],u=arguments.length;u--;)t[u]=arguments[u];return Zi(t,o.params,!0).then((function(t){return i("execute send",r,n,t),ju(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call($r(r,n,"onError"),[new go(n,t)])}))}}))};function Su(t,e,r,n,o){return function(){for(var i=[],u=arguments.length;u--;)i[u]=arguments[u];return Zi(i,n.params,!0).then((function(n){return ju(t,e,r,n,o)})).catch(bo)}}var Eu=function(t,e,r,n,o,i){return[oo(t,"myNamespace",r),e,r,n,o,i]},$u=function(t,e,r,n,o,i){return[no(t,"onResult",(function(t){kr(t)&&e.$on($r(r,n,"onResult"),(function(o){wu(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger($r(r,n,"onError"),t)}))}))})),e,r,n,o,i]},xu=function(t,e,r,n,o,i){return[no(t,"onMessage",(function(t){if(kr(t)){e.$only($r(r,n,"onMessage"),(function(o){i("onMessageCallback",o),wu(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger($r(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},ku=function(t,e,r,n,o,i){return[no(t,"onError",(function(t){kr(t)&&e.$only($r(r,n,"onError"),t)})),e,r,n,o,i]};function Au(t,e,r,n,o,i){var u=[Eu,$u,xu,ku,Ou];return Reflect.apply(Tr,null,u)(n,o,t,e,r,i)}function Tu(t,e,r){var n=t.log,o={};for(var i in r){var u=r[i];for(var a in u){var c=u[a];o=oo(o,a,Au(i,a,c,Su(e,i,a,c,n),e,n))}}return[o,t,e,r]}function Nu(t,e,r){return[no(t,"onReady",(function(t){kr(t)&&r.$only("onReady",t)})),e,r]}function Cu(t,e,r,n){return[no(t,"onError",(function(t){if(kr(t))for(var e in n)r.$on($r(e,"onError"),t)})),e,r]}var Pu,zu,Ru=function(t,e,r){return[oo(t,e.loginHandlerName,(function(t){if(t&&Xi(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new go(e.loginHandlerName,"Unexpected token "+t)})),e,r]},qu=function(t,e,r){return[oo(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},Mu=function(t,e,r){return[no(t,"onLogin",(function(t){kr(t)&&r.$only("onLogin",t)})),e,r]};function Fu(t,e,r){return Tr(Ru,qu,Mu)(t,e,r)}function Lu(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=oo(t,"connected",!1,!0),e,r]}function Du(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function Uu(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function Ju(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function Iu(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),oo(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function Bu(t,e,r){var n=function(t,e,r){var n=[Lu,Du,Uu,Ju,Iu];return Reflect.apply(Tr,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var Wu={};Wu.standalone=tu(!1,["boolean"]),Wu.debugOn=tu(!1,["boolean"]),Wu.loginHandlerName=tu("login",["string"]),Wu.logoutHandlerName=tu("logout",["string"]),Wu.disconnectHandlerName=tu("disconnect",["string"]),Wu.switchUserHandlerName=tu("switch-user",["string"]),Wu.hostname=tu(!1,["string"]),Wu.namespace=tu("jsonql",["string"]),Wu.wsOptions=tu({},["object"]),Wu.contract=tu({},["object"],((Pu={}).checker=function(t){return!!function(t){return Ze(t)&&(Er(t,"query")||Er(t,"mutation")||Er(t,"socket"))}(t)&&t},Pu)),Wu.enableAuth=tu(!1,["boolean"]),Wu.token=tu(!1,["string"]),Wu.csrf=tu("X-CSRF-Token",["string"]),Wu.suspendOnStart=tu(!1,["boolean"]);var Vu={};Vu.serverType=tu(null,["string"],((zu={}).alias="socketClientType",zu));var Gu=Object.assign(Wu,Vu),Hu={};function Qu(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new go(t)}}()),t.wssPath=bu([t.hostname,t.namespace].join("/"),t.serverType),t.log=ou(t),t.eventEmitter=_u(t),t}))}function Yu(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?So(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function Ku(t){return function(e){return void 0===e&&(e={}),Qu(e).then(Yu).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Tu,Nu,Cu];return t.enableAuth&&n.push(Fu),n.push(Bu),Reflect.apply(Tr,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}Hu.useJwt=!0,Hu.log=null,Hu.eventEmitter=null,Hu.nspClient=null,Hu.nspAuthClient=null,Hu.wssPath="",Hu.publicNamespace="public",Hu.privateNamespace="private";var Xu=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger($r(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),mu(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function Zu(t,e){return function(r,n,o){var i=r.log,u=n.namespaces,a=function(t){return t.length>1&&t[0]}(u),c=u.length-1;return u.map((function(n){var s=a===n;if(i(n," --\x3e "+(s?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",s,n);var f=[n,e[n],o,s,r,--c];Reflect.apply(t,null,f)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only($r(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call($r(t,r,"onError"),[i]),e.$call($r(t,r,"onResult"),[{error:i}])}))}(n,o,r);return s&&(i("Has private and add logoutEvtHandler"),Xu(e,u,o,r)),s}))}}function ta(t,e,r,n){var o=function(t,e,r){void 0===r&&(r=!1);var n=Object.assign({},Gu,t),o=Object.assign({},Hu,e);return function(t){return eu(t,n,o).then((function(t){return r?Qu(t):t}))}}(r,n);return function(r){return void 0===r&&(r={}),o(r).then((function(e){return t(e)})).then((function(t){var r=Ku(e)(opts);return t.socket=r,t}))}}function ea(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,u=t?[r,t].join("/"):n;return i("createNspClient with URL --\x3e ",u),o(u,e)}var ra,na,oa,ia,ua,aa,ca,sa,fa;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}tu("HS256",["string"]),tu(!1,["boolean","number","string"],((ra={}).alias="exp",ra.optional=!0,ra)),tu(!1,["boolean","number","string"],((na={}).alias="nbf",na.optional=!0,na)),tu(!1,["boolean","string"],((oa={}).alias="iss",oa.optional=!0,oa)),tu(!1,["boolean","string"],((ia={}).alias="sub",ia.optional=!0,ia)),tu(!1,["boolean","string"],((ua={}).alias="iss",ua.optional=!0,ua)),tu(!1,["boolean"],((aa={}).optional=!0,aa)),tu(!1,["boolean","string"],((ca={}).optional=!0,ca)),tu(!1,["boolean","string"],((sa={}).optional=!0,sa)),tu(!1,["boolean"],((fa={}).optional=!0,fa));function la(t,e){var r,n;void 0===e&&(e=!1);var o=t.wsOptions||{},i=t.headers||{};return e&&(i=Object.assign(i,((r={}).Authorization="Bearer "+e,r))),Object.assign({},o,((n={}).headers=i,n))}function pa(t,e,r){switch(void 0===e&&(e={}),void 0===r&&(r=!1),function(t){return t.tokenDeliverLocation||"url"}(e)){case"url":return{url:r?t+"?token="+r:t,opts:la(e,!1)};case"header":default:return{url:t,opts:la(e,r)}}}var ha=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t,e){var r;r=function(){function t(){for(var t=arguments,e=0,r={};e0;)e[r]=arguments[r+1];var n=mo(),o=[t].concat(e);return o.push(n),Oo("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Aa=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(ga,null,o),u=n.data||n;t.$trigger(i,[u])};function Ta(t,e,r,n,o,i){var u=o.log;return n&&(u("Private namespace",t," binding to the DISCONNECT ws.terminate"),ka(r,e)),e.onopen=function(){u("client.ws.onopen listened --\x3e",t),n?(u("isPrivate and fire the onLogin"),r.$call("onLogin")(t)):(r.$call("onReady")(t,i),u("isPublic onReady hook executed",i),0===i&&r.$off("onReady")),r.$only(ga(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(ma(t,e,r))}(t,r);u("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){u("client.ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=_a);try{var r,n=da(t);if(!1!==(r=ja(n)))return e("_data",r),{data:da(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Z("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,i=n.type;switch(u("Respond from server",i,n),i){case"emit_reply":var a=ga(t,o,"onMessage"),c=r.$call(a)(n);u("EMIT_REPLY_TYPE",a,c);break;case"emit_acknowledge":var s=ga(t,o,"onResult"),f=r.$call(s)(n);u("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":u("ERROR_KEY"),Aa(r,t,o,n);break;default:u("Unhandled event!",n),Aa(r,t,o,n)}}catch(e){u("client.ws.onmessage error",e),Aa(r,t,!1,e)}},e.onclose=function(){u("client.ws.onclose callback")},e.onerror=function(e){u("client.ws.onerror",e),function(t,e,r){t.$trigger($r(e,"onError"),[r])}(r,t,e)},e}var Na,Ca,Pa=function(t){return function(e,r,n){var o=Object.assign({},n,Ne),i=Object.assign({},r,Ce);return ta(e,t,i,o)}}((Na=e,void 0===(Ca="node")&&(Ca="browser"),function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=$a(Na,Ca),!0===t.enableAuth&&(t.nspAuthClient=$a(Na,Ca,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),xa(e,t).then((function(t){return Zu(Ta,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),mu(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}}));exports.EventEmitterClass=du,exports.checkSocketClientType=function(t){return ru(t,Vu)},exports.createCombineWsClient=Pa,exports.getEventEmitter=_u; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("fs"),require("path");var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof r&&r&&r.Object===Object&&r,o="object"==typeof self&&self&&self.Object===Object&&self,i=n||o||Function("return this")(),u=i.Symbol;var a=Array.isArray,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=u?u.toStringTag:void 0;var p=Object.prototype.toString;var h=u?u.toStringTag:void 0;function g(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function v(t){return null!=t&&"object"==typeof t}var d=u?u.prototype:void 0,y=d?d.toString:void 0;function _(t){if("string"==typeof t)return t;if(a(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&w(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function U(t){return function(t){return"number"==typeof t||v(t)&&"[object Number]"==g(t)}(t)&&t!=+t}function L(t){return"string"==typeof t||!a(t)&&v(t)&&"[object String]"==g(t)}var M=function(t){return!L(t)&&!U(parseFloat(t))},B=function(t){return""!==z(t)&&L(t)},I=function(t){return null!=t&&"boolean"==typeof t},D=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==z(t)&&(!1===e||!0===e&&null!==t)},q=function(t,e){return void 0===e&&(e=""),!!a(t)&&(""===e||""===z(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return M;case"string":return B;case"boolean":return I;default:return D}}(e)(t)})).length>0))};var F,Y,J=(F=Object.getPrototypeOf,Y=Object,function(t){return F(Y(t))}),V=Function.prototype,W=Object.prototype,G=V.toString,H=W.hasOwnProperty,Q=G.call(Object);function K(t){if(!v(t)||"[object Object]"!=g(t))return!1;var e=J(t);if(null===e)return!0;var r=H.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&G.call(r)==Q}var X=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Z=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function tt(t,e){return t===e||t!=t&&e!=e}function et(t,e){for(var r=t.length;r--;)if(tt(t[r][0],e))return r;return-1}var rt=Array.prototype.splice;function nt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},nt.prototype.set=function(t,e){var r=this.__data__,n=et(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function it(t){if(!ot(t))return!1;var e=g(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ut,at=i["__core-js_shared__"],ct=(ut=/[^.]+$/.exec(at&&at.keys&&at.keys.IE_PROTO||""))?"Symbol(src)_1."+ut:"";var st=Function.prototype.toString;var ft=/^\[object .+?Constructor\]$/,lt=Function.prototype,pt=Object.prototype,ht=lt.toString,gt=pt.hasOwnProperty,vt=RegExp("^"+ht.call(gt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function dt(t){return!(!ot(t)||function(t){return!!ct&&ct in t}(t))&&(it(t)?vt:ft).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function yt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return dt(r)?r:void 0}var _t=yt(i,"Map"),bt=yt(Object,"create");var mt=Object.prototype.hasOwnProperty;var wt=Object.prototype.hasOwnProperty;function jt(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Wt(t){return null!=t&&Vt(t.length)&&!it(t)}var Gt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ht=Gt&&"object"==typeof module&&module&&!module.nodeType&&module,Qt=Ht&&Ht.exports===Gt?i.Buffer:void 0,Kt=(Qt?Qt.isBuffer:void 0)||function(){return!1},Xt={};Xt["[object Float32Array]"]=Xt["[object Float64Array]"]=Xt["[object Int8Array]"]=Xt["[object Int16Array]"]=Xt["[object Int32Array]"]=Xt["[object Uint8Array]"]=Xt["[object Uint8ClampedArray]"]=Xt["[object Uint16Array]"]=Xt["[object Uint32Array]"]=!0,Xt["[object Arguments]"]=Xt["[object Array]"]=Xt["[object ArrayBuffer]"]=Xt["[object Boolean]"]=Xt["[object DataView]"]=Xt["[object Date]"]=Xt["[object Error]"]=Xt["[object Function]"]=Xt["[object Map]"]=Xt["[object Number]"]=Xt["[object Object]"]=Xt["[object RegExp]"]=Xt["[object Set]"]=Xt["[object String]"]=Xt["[object WeakMap]"]=!1;var Zt="object"==typeof exports&&exports&&!exports.nodeType&&exports,te=Zt&&"object"==typeof module&&module&&!module.nodeType&&module,ee=te&&te.exports===Zt&&n.process,re=function(){try{var t=te&&te.require&&te.require("util").types;return t||ee&&ee.binding&&ee.binding("util")}catch(t){}}(),ne=re&&re.isTypedArray,oe=ne?function(t){return function(e){return t(e)}}(ne):function(t){return v(t)&&Vt(t.length)&&!!Xt[g(t)]};function ie(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ue=Object.prototype.hasOwnProperty;function ae(t,e,r){var n=t[e];ue.call(t,e)&&tt(n,r)&&(void 0!==r||e in t)||Tt(t,e,r)}var ce=/^(?:0|[1-9]\d*)$/;function se(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&ce.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(we);function Se(t,e){return Ee(function(t,e,r){return e=me(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=me(n.length-e,0),u=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Oe.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!ot(r))return!1;var n=typeof e;return!!("number"==n?Wt(r)&&se(e,r.length):"string"==n&&e in r)&&tt(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&ar(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Er=function(t){return Ne(t)?t:[t]},Sr=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Or=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Ar=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Tr=function(t){return Sr("string"==typeof t?t:JSON.stringify(t))},Rr=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Pr=function(){return!1},xr=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,Er(t))}),Reflect.apply(t,null,r))}};function kr(t,e){return t===e||t!=t&&e!=e}function $r(t,e){for(var r=t.length;r--;)if(kr(t[r][0],e))return r;return-1}var Nr=Array.prototype.splice;function Cr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},Cr.prototype.set=function(t,e){var r=this.__data__,n=$r(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function Ur(t){if(!zr(t))return!1;var e=Ye(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Lr=Ue["__core-js_shared__"],Mr=function(){var t=/[^.]+$/.exec(Lr&&Lr.keys&&Lr.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Br=Function.prototype.toString;function Ir(t){if(null!=t){try{return Br.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Dr=/^\[object .+?Constructor\]$/,qr=Function.prototype,Fr=Object.prototype,Yr=qr.toString,Jr=Fr.hasOwnProperty,Vr=RegExp("^"+Yr.call(Jr).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Wr(t){return!(!zr(t)||function(t){return!!Mr&&Mr in t}(t))&&(Ur(t)?Vr:Dr).test(Ir(t))}function Gr(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Wr(r)?r:void 0}var Hr=Gr(Ue,"Map"),Qr=Gr(Object,"create");var Kr=Object.prototype.hasOwnProperty;var Xr=Object.prototype.hasOwnProperty;function Zr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Sn(t){return null!=t&&En(t.length)&&!Ur(t)}var On="object"==typeof exports&&exports&&!exports.nodeType&&exports,An=On&&"object"==typeof module&&module&&!module.nodeType&&module,Tn=An&&An.exports===On?Ue.Buffer:void 0,Rn=(Tn?Tn.isBuffer:void 0)||function(){return!1},Pn={};Pn["[object Float32Array]"]=Pn["[object Float64Array]"]=Pn["[object Int8Array]"]=Pn["[object Int16Array]"]=Pn["[object Int32Array]"]=Pn["[object Uint8Array]"]=Pn["[object Uint8ClampedArray]"]=Pn["[object Uint16Array]"]=Pn["[object Uint32Array]"]=!0,Pn["[object Arguments]"]=Pn["[object Array]"]=Pn["[object ArrayBuffer]"]=Pn["[object Boolean]"]=Pn["[object DataView]"]=Pn["[object Date]"]=Pn["[object Error]"]=Pn["[object Function]"]=Pn["[object Map]"]=Pn["[object Number]"]=Pn["[object Object]"]=Pn["[object RegExp]"]=Pn["[object Set]"]=Pn["[object String]"]=Pn["[object WeakMap]"]=!1;var xn="object"==typeof exports&&exports&&!exports.nodeType&&exports,kn=xn&&"object"==typeof module&&module&&!module.nodeType&&module,$n=kn&&kn.exports===xn&&Ce.process,Nn=function(){try{var t=kn&&kn.require&&kn.require("util").types;return t||$n&&$n.binding&&$n.binding("util")}catch(t){}}(),Cn=Nn&&Nn.isTypedArray,zn=Cn?function(t){return function(e){return t(e)}}(Cn):function(t){return We(t)&&En(t.length)&&!!Pn[Ye(t)]};function Un(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var Ln=Object.prototype.hasOwnProperty;function Mn(t,e,r){var n=t[e];Ln.call(t,e)&&kr(n,r)&&(void 0!==r||e in t)||on(t,e,r)}var Bn=/^(?:0|[1-9]\d*)$/;function In(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Bn.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Xn);function eo(t,e){return to(function(t,e,r){return e=Kn(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Kn(n.length-e,0),u=Array(i);++o1?r[o-1]:void 0,u=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&function(t,e,r){if(!zr(r))return!1;var n=typeof e;return!!("number"==n?Sn(r)&&In(e,r.length):"string"==n&&e in r)&&kr(r[e],t)}(r[0],r[1],u)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0))},Uo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},Lo=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Co(e)(t)})).length)})).length:e.length>e.filter((function(t){return!zo(r,t)})).length},Mo=function(t,e){if(void 0===e&&(e=null),Ze(t)){if(!e)return!0;if(zo(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=Uo(t))?!Lo({arg:r},e):!Co(t)(r))})).length)})).length}return!1},Bo=function(t,e){var r,n,o,i,u;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,u=[o],Array.isArray(i.keys)&&i.keys.length&&u.push(i.keys),!Reflect.apply(Mo,null,u);case"array"===t:return!zo(e.arg);case!1!==(r=Uo(t)):return!Lo(e,r);default:return!Co(t)(e.arg)}},Io=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},Do=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!zo(e))throw new vo("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!zo(t))throw console.info(t),new vo("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,u=e[r]||{type:o,name:"_"+r};return{arg:i?Io(t,u):t,index:r,param:u,optional:i}}));default:throw new yo("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Ro(e)&&!(r.type.length>r.type.filter((function(e){return Bo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Bo(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},qo=Je(Object.keys,Object),Fo=Object.prototype.hasOwnProperty;function Yo(t){return Sn(t)?qn(t):function(t){if(!yn(t))return qo(t);var e=[];for(var r in Object(t))Fo.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function Jo(t,e){return t&&an(t,e,Yo)}function Vo(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new en;++ea))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new Vo:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var u=i.getMaxStore(t),a=-1;if(u>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var u=Array.from(i.get(t)),a=u.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!au.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],u=Reflect.apply(this.addToStore,this,i),a=u[0],c=u[1];return this.normalStore=a,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),u=i[0],a=i[1];return this.lazyStore=u,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){pu.set(this,t)},r.normalStore.get=function(){return pu.get(this)},r.lazyStore.set=function(t){hu.set(this,t)},r.lazyStore.get=function(){return hu.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=[],this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE ALL SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){var r=lu(e);if(cu(r))return!1===t.__isPatternRegisterd(r)&&(t.__pattern__.push(r),t.__pattern__.length);throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')}))},e.prototype.$releaseEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){t.logger("($releaseEvent)",e);var r=lu(e);if(cu(r)&&t.__isPatternRegisterd(r)){var n=t;return t.__getToReleaseQueue(r).map((function(t,e){return Reflect.apply(n.$trigger,n,t),e})).reduce((function(t,e){return++e}),0)}throw t.logger("$releaseEvent throw error ==========================>",t.__pattern__,r),new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')})).reduce((function(t,e){return t+e}),0)},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];switch(!0){case!0===this.__suspend_state__:return this.__addToQueueStore(t,e);case!0==!!this.__pattern__.length:return this.__pattern__.filter((function(e){return e.test(t)})).length?this.__addToQueueStore(t,e):(this.logger("($queue) "+t+" NOT added to $queueStore",this.__pattern__),!1);default:return this.logger("($queue) get called NOTHING added"),!1}},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__getToReleaseQueue=function(t){var e=this,r=this.$queues.filter((function(e){return t.test(e[0])})).map((function(r){return e.logger("[release] execute "+r[0]+" matches "+t,r),e.queueStore.delete(r),r}));return r.length>0&&(this.__pattern__=this.__pattern__.filter((function(e){return e.toString()!==t.toString()}))),r},e.prototype.__addToQueueStore=function(t,e){return this.logger("($queue) "+t+" added to $queueStore",e),this.queueStore.add([t].concat(e)),!0},e.prototype.__isPatternRegisterd=function(t){return!!this.__pattern__.filter((function(e){return e.toString()===t.toString()})).length},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=[],this.logger("(release) was called with "+e+(r.length?' for "'+r.join(",")+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.logger("(release queue)",n),n.forEach((function(e){t.logger("[release] execute "+e[0],e),Reflect.apply(t.$trigger,t,e)})),this.queueStore.clear(),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(gu))),yu=function(t){function e(e){if("function"!=typeof e)throw new Error("Just die here the logger is not a function!");e("---\x3e Create a new EventEmitter <---"),t.call(this,{logger:e})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client-core"},Object.defineProperties(e.prototype,r),e}(du),_u=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new yu(t.log)},bu=function(t){var e=new RegExp("^(http|https)://","i"),r=t.match(e);if(r&&r.length){var n="https"===r[1].toLowerCase()?"wss":"ws";return t.replace(e,n+"://")}return t},mu=function(t,e){Er(e).forEach((function(e){t.$off(Ar(e,"emit_reply"))}))};function wu(t,e,r){Or(t,"error")?r(t.error):Or(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function ju(t,e,r,n,o){void 0===n&&(n=[]);var i=Ar(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,Er(n)]),new Promise((function(n,i){var u=Ar(e,r,"onResult");t.$on(u,(function(t){o("got the first result",t),wu(t,n,i)}))}))}var Eu=function(t,e,r,n,o,i){return no(t,"send",Pr,(function(){return i("running call getter method"),function(){for(var t=[],u=arguments.length;u--;)t[u]=arguments[u];return Zi(t,o.params,!0).then((function(t){return i("execute send",r,n,t),ju(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(Ar(r,n,"onError"),[new vo(n,t)])}))}}))};function Su(t,e,r,n,o){return function(){for(var i=[],u=arguments.length;u--;)i[u]=arguments[u];return Zi(i,n.params,!0).then((function(n){return ju(t,e,r,n,o)})).catch(bo)}}var Ou=function(t,e,r,n,o,i){return[oo(t,"myNamespace",r),e,r,n,o,i]},Au=function(t,e,r,n,o,i){return[no(t,"onResult",(function(t){Rr(t)&&e.$on(Ar(r,n,"onResult"),(function(o){wu(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Ar(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Tu=function(t,e,r,n,o,i){return[no(t,"onMessage",(function(t){if(Rr(t)){e.$only(Ar(r,n,"onMessage"),(function(o){i("onMessageCallback",o),wu(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Ar(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Ru=function(t,e,r,n,o,i){return[no(t,"onError",(function(t){Rr(t)&&e.$only(Ar(r,n,"onError"),t)})),e,r,n,o,i]};function Pu(t,e,r,n,o,i){var u=[Ou,Au,Tu,Ru,Eu];return Reflect.apply(xr,null,u)(n,o,t,e,r,i)}function xu(t,e,r){var n=t.log,o={};for(var i in r){var u=r[i];for(var a in u){var c=u[a];o=oo(o,a,Pu(i,a,c,Su(e,i,a,c,n),e,n))}}return[o,t,e,r]}function ku(t,e,r){return[no(t,"onReady",(function(t){Rr(t)&&r.$only("onReady",t)})),e,r]}function $u(t,e,r,n){return[no(t,"onError",(function(t){if(Rr(t))for(var e in n)r.$on(Ar(e,"onError"),t)})),e,r]}var Nu=function(t,e,r){return[oo(t,e.loginHandlerName,(function(t){if(t&&Xi(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new vo(e.loginHandlerName,"Unexpected token "+t)})),e,r]},Cu=function(t,e,r){return[oo(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},zu=function(t,e,r){return[no(t,"onLogin",(function(t){Rr(t)&&r.$only("onLogin",t)})),e,r]};function Uu(t,e,r){return xr(Nu,Cu,zu)(t,e,r)}function Lu(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=oo(t,"connected",!1,!0),e,r]}function Mu(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function Bu(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function Iu(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function Du(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),oo(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}var qu=[],Fu=[],Yu="undefined"!=typeof Uint8Array?Uint8Array:Array,Ju=!1;function Vu(){Ju=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+qu[o>>12&63]+qu[o>>6&63]+qu[63&o]);return i.join("")}function Gu(t){var e;Ju||Vu();for(var r=t.length,n=r%3,o="",i=[],u=0,a=r-n;ua?a:u+16383));return 1===n?(e=t[r-1],o+=qu[e>>2],o+=qu[e<<4&63],o+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],o+=qu[e>>10],o+=qu[e>>4&63],o+=qu[e<<2&63],o+="="),i.push(o),i.join("")}function Hu(t,e,r,n,o){var i,u,a=8*o-n-1,c=(1<>1,f=-7,l=r?o-1:0,p=r?-1:1,h=t[e+l];for(l+=p,i=h&(1<<-f)-1,h>>=-f,f+=a;f>0;i=256*i+t[e+l],l+=p,f-=8);for(u=i&(1<<-f)-1,i>>=-f,f+=n;f>0;u=256*u+t[e+l],l+=p,f-=8);if(0===i)i=1-s;else{if(i===c)return u?NaN:1/0*(h?-1:1);u+=Math.pow(2,n),i-=s}return(h?-1:1)*u*Math.pow(2,i-n)}function Qu(t,e,r,n,o,i){var u,a,c,s=8*i-o-1,f=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,g=n?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,u=f):(u=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-u))<1&&(u--,c*=2),(e+=u+l>=1?p/c:p*Math.pow(2,1-l))*c>=2&&(u++,c/=2),u+l>=f?(a=0,u=f):u+l>=1?(a=(e*c-1)*Math.pow(2,o),u+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,o),u=0));o>=8;t[r+h]=255&a,h+=g,a/=256,o-=8);for(u=u<0;t[r+h]=255&u,h+=g,u/=256,s-=8);t[r+h-g]|=128*v}var Ku={}.toString,Xu=Array.isArray||function(t){return"[object Array]"==Ku.call(t)};function Zu(){return ea.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ta(t,e){if(Zu()=Zu())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Zu().toString(16)+" bytes");return 0|t}function aa(t){return!(null==t||!t._isBuffer)}function ca(t,e){if(aa(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Ua(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return La(t).length;default:if(n)return Ua(t).length;e=(""+e).toLowerCase(),n=!0}}function sa(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Ea(this,e,r);case"utf8":case"utf-8":return ma(this,e,r);case"ascii":return wa(this,e,r);case"latin1":case"binary":return ja(this,e,r);case"base64":return ba(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Sa(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function fa(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function la(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=ea.from(e,n)),aa(e))return 0===e.length?-1:pa(t,e,r,n,o);if("number"==typeof e)return e&=255,ea.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):pa(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function pa(t,e,r,n,o){var i,u=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;u=2,a/=2,c/=2,r/=2}function s(t,e){return 1===u?t[e]:t.readUInt16BE(e*u)}if(o){var f=-1;for(i=r;ia&&(r=a-c),i=r;i>=0;i--){for(var l=!0,p=0;po&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;u>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function ba(t,e,r){return 0===e&&r===t.length?Gu(t):Gu(t.slice(e,r))}function ma(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o239?4:s>223?3:s>191?2:1;if(o+l<=r)switch(l){case 1:s<128&&(f=s);break;case 2:128==(192&(i=t[o+1]))&&(c=(31&s)<<6|63&i)>127&&(f=c);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(c=(15&s)<<12|(63&i)<<6|63&u)>2047&&(c<55296||c>57343)&&(f=c);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(c=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&c<1114112&&(f=c)}null===f?(f=65533,l=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),o+=l}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},ea.prototype.compare=function(t,e,r,n,o){if(!aa(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(r>>>=0)-(e>>>=0),a=Math.min(i,u),c=this.slice(n,o),s=t.slice(e,r),f=0;fo)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return ha(this,t,e,r);case"utf8":case"utf-8":return ga(this,t,e,r);case"ascii":return va(this,t,e,r);case"latin1":case"binary":return da(this,t,e,r);case"base64":return ya(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _a(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},ea.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function wa(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function Aa(t,e,r,n,o,i){if(!aa(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function Ta(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o>>8*(n?o:1-o)}function Ra(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o>>8*(n?o:3-o)&255}function Pa(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function xa(t,e,r,n,o){return o||Pa(t,0,r,4),Qu(t,e,r,n,23,4),r+4}function ka(t,e,r,n,o){return o||Pa(t,0,r,8),Qu(t,e,r,n,52,8),r+8}ea.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(o*=256);)n+=this[t+--e]*o;return n},ea.prototype.readUInt8=function(t,e){return e||Oa(t,1,this.length),this[t]},ea.prototype.readUInt16LE=function(t,e){return e||Oa(t,2,this.length),this[t]|this[t+1]<<8},ea.prototype.readUInt16BE=function(t,e){return e||Oa(t,2,this.length),this[t]<<8|this[t+1]},ea.prototype.readUInt32LE=function(t,e){return e||Oa(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},ea.prototype.readUInt32BE=function(t,e){return e||Oa(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},ea.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Oa(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},ea.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Oa(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},ea.prototype.readInt8=function(t,e){return e||Oa(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},ea.prototype.readInt16LE=function(t,e){e||Oa(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},ea.prototype.readInt16BE=function(t,e){e||Oa(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},ea.prototype.readInt32LE=function(t,e){return e||Oa(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},ea.prototype.readInt32BE=function(t,e){return e||Oa(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},ea.prototype.readFloatLE=function(t,e){return e||Oa(t,4,this.length),Hu(this,t,!0,23,4)},ea.prototype.readFloatBE=function(t,e){return e||Oa(t,4,this.length),Hu(this,t,!1,23,4)},ea.prototype.readDoubleLE=function(t,e){return e||Oa(t,8,this.length),Hu(this,t,!0,52,8)},ea.prototype.readDoubleBE=function(t,e){return e||Oa(t,8,this.length),Hu(this,t,!1,52,8)},ea.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Aa(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i=0&&(i*=256);)this[e+o]=t/i&255;return e+r},ea.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,1,255,0),ea.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},ea.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,2,65535,0),ea.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ta(this,t,e,!0),e+2},ea.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,2,65535,0),ea.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ta(this,t,e,!1),e+2},ea.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,4,4294967295,0),ea.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Ra(this,t,e,!0),e+4},ea.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,4,4294967295,0),ea.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Ra(this,t,e,!1),e+4},ea.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Aa(this,t,e,r,o-1,-o)}var i=0,u=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},ea.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Aa(this,t,e,r,o-1,-o)}var i=r-1,u=1,a=0;for(this[e+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/u>>0)-a&255;return e+r},ea.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,1,127,-128),ea.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},ea.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,2,32767,-32768),ea.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ta(this,t,e,!0),e+2},ea.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,2,32767,-32768),ea.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ta(this,t,e,!1),e+2},ea.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,4,2147483647,-2147483648),ea.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Ra(this,t,e,!0),e+4},ea.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Aa(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),ea.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Ra(this,t,e,!1),e+4},ea.prototype.writeFloatLE=function(t,e,r){return xa(this,t,e,!0,r)},ea.prototype.writeFloatBE=function(t,e,r){return xa(this,t,e,!1,r)},ea.prototype.writeDoubleLE=function(t,e,r){return ka(this,t,e,!0,r)},ea.prototype.writeDoubleBE=function(t,e,r){return ka(this,t,e,!1,r)},ea.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else if(i<1e3||!ea.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function La(t){return function(t){var e,r,n,o,i,u;Ju||Vu();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,u=new Yu(3*a/4-i),n=i>0?a-4:a;var c=0;for(e=0,r=0;e>16&255,u[c++]=o>>8&255,u[c++]=255&o;return 2===i?(o=Fu[t.charCodeAt(e)]<<2|Fu[t.charCodeAt(e+1)]>>4,u[c++]=255&o):1===i&&(o=Fu[t.charCodeAt(e)]<<10|Fu[t.charCodeAt(e+1)]<<4|Fu[t.charCodeAt(e+2)]>>2,u[c++]=o>>8&255,u[c++]=255&o),u}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace(Ca,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Ma(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function Ba(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function Ia(t,e,r){var n=function(t,e,r){var n=[Lu,Mu,Bu,Iu,Du];return Reflect.apply(xr,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),oo(n,"isLogin",!1,!0)}var Da={};Da.standalone=tu(!1,["boolean"]),Da.debugOn=tu(!1,["boolean"]),Da.loginHandlerName=tu("login",["string"]),Da.logoutHandlerName=tu("logout",["string"]),Da.disconnectHandlerName=tu("disconnect",["string"]),Da.switchUserHandlerName=tu("switch-user",["string"]),Da.hostname=tu(!1,["string"]),Da.namespace=tu("jsonql",["string"]),Da.wsOptions=tu({},["object"]),Da.contract=tu({},["object"],(($a={}).checker=function(t){return!!function(t){return Ze(t)&&(Or(t,"query")||Or(t,"mutation")||Or(t,"socket"))}(t)&&t},$a)),Da.enableAuth=tu(!1,["boolean"]),Da.token=tu(!1,["string"]),Da.csrf=tu("X-CSRF-Token",["string"]),Da.suspendOnStart=tu(!1,["boolean"]);var qa={};qa.serverType=tu(null,["string"],((Na={}).alias="socketClientType",Na));var Fa=Object.assign(Da,qa),Ya={};function Ja(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new vo(t)}}()),t.wssPath=bu([t.hostname,t.namespace].join("/"),t.serverType),t.log=ou(t),t.eventEmitter=_u(t),t}))}function Va(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?So(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function Wa(t){return function(e){return void 0===e&&(e={}),Ja(e).then(Va).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[xu,ku,$u];return t.enableAuth&&n.push(Uu),n.push(Ia),Reflect.apply(xr,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}Ya.useJwt=!0,Ya.log=null,Ya.eventEmitter=null,Ya.nspClient=null,Ya.nspAuthClient=null,Ya.wssPath="",Ya.publicNamespace="public",Ya.privateNamespace="private";var Ga=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(Ar(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),mu(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function Ha(t,e){return function(r,n,o){var i=r.log,u=n.namespaces,a=function(t){return t.length>1&&t[0]}(u),c=u.length-1;return u.map((function(n){var s=a===n;if(i(n," --\x3e "+(s?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",s,n);var f=[n,e[n],o,s,r,--c];Reflect.apply(t,null,f)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(Ar(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(Ar(t,r,"onError"),[i]),e.$call(Ar(t,r,"onResult"),[{error:i}])}))}(n,o,r);return s&&(i("Has private and add logoutEvtHandler"),Ga(e,u,o,r)),s}))}}function Qa(t,e,r,n){var o=function(t,e,r){void 0===r&&(r=!1);var n=Object.assign({},Fa,t),o=Object.assign({},Ya,e);return function(t){return eu(t,n,o).then((function(t){return r?Ja(t):t}))}}(r,n);return function(r){return void 0===r&&(r={}),o(r).then((function(e){return t(e)})).then((function(t){var r=Wa(e)(opts);return t.socket=r,t}))}}function Ka(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,u=t?[r,t].join("/"):n;return i("createNspClient with URL --\x3e ",u),o(u,e)}var Xa,Za,tc,ec,rc,nc,oc,ic,uc;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}tu("HS256",["string"]),tu(!1,["boolean","number","string"],((Xa={}).alias="exp",Xa.optional=!0,Xa)),tu(!1,["boolean","number","string"],((Za={}).alias="nbf",Za.optional=!0,Za)),tu(!1,["boolean","string"],((tc={}).alias="iss",tc.optional=!0,tc)),tu(!1,["boolean","string"],((ec={}).alias="sub",ec.optional=!0,ec)),tu(!1,["boolean","string"],((rc={}).alias="iss",rc.optional=!0,rc)),tu(!1,["boolean"],((nc={}).optional=!0,nc)),tu(!1,["boolean","string"],((oc={}).optional=!0,oc)),tu(!1,["boolean","string"],((ic={}).optional=!0,ic)),tu(!1,["boolean"],((uc={}).optional=!0,uc));function ac(t,e){var r,n;void 0===e&&(e=!1);var o=t.wsOptions||{},i=t.headers||{};return e&&(i=Object.assign(i,((r={}).Authorization="Bearer "+e,r))),Object.assign({},o,((n={}).headers=i,n))}function cc(t,e,r){switch(void 0===e&&(e={}),void 0===r&&(r=!1),function(t){return t.tokenDeliverLocation||"url"}(e)){case"url":return{url:r?t+"?token="+r:t,opts:ac(e,!1)};case"header":default:return{url:t,opts:ac(e,r)}}}var sc=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t,e){var r;r=function(){function t(){for(var t=arguments,e=0,r={};e0;)e[r]=arguments[r+1];var n=mo(),o=[t].concat(e);return o.push(n),Eo("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Oc=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(lc,null,o),u=n.data||n;t.$trigger(i,[u])};function Ac(t,e,r,n,o,i){var u=o.log;return n&&(u("Private namespace",t," binding to the DISCONNECT ws.terminate"),Sc(r,e)),e.onopen=function(){u("client.ws.onopen listened --\x3e",t),n?(u("isPrivate and fire the onLogin"),r.$call("onLogin")(t)):(r.$call("onReady")(t,i),u("isPublic onReady hook executed",i),0===i&&r.$off("onReady")),r.$only(lc(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(dc(t,e,r))}(t,r);u("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){u("client.ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=gc);try{var r,n=pc(t);if(!1!==(r=_c(n)))return e("_data",r),{data:pc(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Z("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,i=n.type;switch(u("Respond from server",i,n),i){case"emit_reply":var a=lc(t,o,"onMessage"),c=r.$call(a)(n);u("EMIT_REPLY_TYPE",a,c);break;case"emit_acknowledge":var s=lc(t,o,"onResult"),f=r.$call(s)(n);u("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":u("ERROR_KEY"),Oc(r,t,o,n);break;default:u("Unhandled event!",n),Oc(r,t,o,n)}}catch(e){u("client.ws.onmessage error",e),Oc(r,t,!1,e)}},e.onclose=function(){u("client.ws.onclose callback")},e.onerror=function(e){u("client.ws.onerror",e),function(t,e,r){t.$trigger(Ar(e,"onError"),[r])}(r,t,e)},e}var Tc,Rc,Pc=function(t){return function(e,r,n){var o=Object.assign({},n,ke),i=Object.assign({},r,$e);return Qa(e,t,i,o)}}((Tc=e,void 0===(Rc="node")&&(Rc="browser"),function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=jc(Tc,Rc),!0===t.enableAuth&&(t.nspAuthClient=jc(Tc,Rc,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),Ec(e,t).then((function(t){return Ha(Ac,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),mu(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}}));exports.EventEmitterClass=du,exports.checkSocketClientType=function(t){return ru(t,qa)},exports.createCombineWsClient=Pc,exports.getEventEmitter=_u; //# sourceMappingURL=node-module.js.map diff --git a/packages/@jsonql/ws/node-module.js.map b/packages/@jsonql/ws/node-module.js.map index 788cdc3a729029a946c59bcb1d68ada9f3bd92e1..5fd9c91bd3a3c589fc1ff37fecedaa8db95d470d 100644 --- a/packages/@jsonql/ws/node-module.js.map +++ b/packages/@jsonql/ws/node-module.js.map @@ -1 +1 @@ -{"version":3,"file":"node-module.js","sources":["../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/src/options/index.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n"],"names":["SetCache","wsCoreConstProps"],"mappings":"+3tCAAAA,u76BCAAC"} \ No newline at end of file +{"version":3,"file":"node-module.js","sources":["../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/src/options/index.js"],"sourcesContent":["/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n"],"names":["SetCache","wsCoreConstProps"],"mappings":"65tCAAAA,wqlDCAAC"} \ No newline at end of file diff --git a/packages/@jsonql/ws/node-ws-client.js b/packages/@jsonql/ws/node-ws-client.js index eceab5e3c8778e3d39f1b56d1b0f18194c28cfb1..26eca4ab49b6350fcb203a4b321f5d8c4898cc0b 100644 --- a/packages/@jsonql/ws/node-ws-client.js +++ b/packages/@jsonql/ws/node-ws-client.js @@ -1,2 +1,2 @@ -"use strict";var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r=Array.isArray,n="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},o="object"==typeof n&&n&&n.Object===Object&&n,i="object"==typeof self&&self&&self.Object===Object&&self,a=o||i||Function("return this")(),u=a.Symbol,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=u?u.toStringTag:void 0;var p=Object.prototype.toString;var h=u?u.toStringTag:void 0;function v(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function g(t,e){return function(r){return t(e(r))}}var d=g(Object.getPrototypeOf,Object);function y(t){return null!=t&&"object"==typeof t}var _=Function.prototype,b=Object.prototype,m=_.toString,w=b.hasOwnProperty,j=m.call(Object);function O(t){if(!y(t)||"[object Object]"!=v(t))return!1;var e=d(t);if(null===e)return!0;var r=w.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&m.call(r)==j}function S(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&N(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var G=function(t){return r(t)?t:[t]},H=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},Q=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Y=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},K=function(t){return H("string"==typeof t?t:JSON.stringify(t))},X=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Z=function(){return!1},tt=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,G(t))}),Reflect.apply(t,null,r))}};function et(t,e){return t===e||t!=t&&e!=e}function rt(t,e){for(var r=t.length;r--;)if(et(t[r][0],e))return r;return-1}var nt=Array.prototype.splice;function ot(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ot.prototype.set=function(t,e){var r=this.__data__,n=rt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function at(t){if(!it(t))return!1;var e=v(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var ut,ct=a["__core-js_shared__"],st=(ut=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+ut:"";var ft=Function.prototype.toString;function lt(t){if(null!=t){try{return ft.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var pt=/^\[object .+?Constructor\]$/,ht=Function.prototype,vt=Object.prototype,gt=ht.toString,dt=vt.hasOwnProperty,yt=RegExp("^"+gt.call(dt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _t(t){return!(!it(t)||(e=t,st&&st in e))&&(at(t)?yt:pt).test(lt(t));var e}function bt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return _t(r)?r:void 0}var mt=bt(a,"Map"),wt=bt(Object,"create");var jt=Object.prototype.hasOwnProperty;var Ot=Object.prototype.hasOwnProperty;function St(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Qt(t){return null!=t&&Ht(t.length)&&!at(t)}var Yt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Yt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Kt&&Kt.exports===Yt?a.Buffer:void 0,Zt=(Xt?Xt.isBuffer:void 0)||function(){return!1},te={};te["[object Float32Array]"]=te["[object Float64Array]"]=te["[object Int8Array]"]=te["[object Int16Array]"]=te["[object Int32Array]"]=te["[object Uint8Array]"]=te["[object Uint8ClampedArray]"]=te["[object Uint16Array]"]=te["[object Uint32Array]"]=!0,te["[object Arguments]"]=te["[object Array]"]=te["[object ArrayBuffer]"]=te["[object Boolean]"]=te["[object DataView]"]=te["[object Date]"]=te["[object Error]"]=te["[object Function]"]=te["[object Map]"]=te["[object Number]"]=te["[object Object]"]=te["[object RegExp]"]=te["[object Set]"]=te["[object String]"]=te["[object WeakMap]"]=!1;var ee,re="object"==typeof exports&&exports&&!exports.nodeType&&exports,ne=re&&"object"==typeof module&&module&&!module.nodeType&&module,oe=ne&&ne.exports===re&&o.process,ie=function(){try{var t=ne&&ne.require&&ne.require("util").types;return t||oe&&oe.binding&&oe.binding("util")}catch(t){}}(),ae=ie&&ie.isTypedArray,ue=ae?(ee=ae,function(t){return ee(t)}):function(t){return y(t)&&Ht(t.length)&&!!te[v(t)]};function ce(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var se=Object.prototype.hasOwnProperty;function fe(t,e,r){var n=t[e];se.call(t,e)&&et(n,r)&&(void 0!==r||e in t)||At(t,e,r)}var le=/^(?:0|[1-9]\d*)$/;function pe(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&le.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Se);function xe(t,e){return $e(function(t,e,r){return e=Oe(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Oe(n.length-e,0),a=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=ke.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!it(r))return!1;var n=typeof e;return!!("number"==n?Qt(r)&&pe(e,r.length):"string"==n&&e in r)&&et(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},cr=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},sr=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ar(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ur(r,t)})).length},fr=function(t,e){if(void 0===e&&(e=null),O(t)){if(!e)return!0;if(ur(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=cr(t))?!sr({arg:r},e):!ar(t)(r))})).length)})).length}return!1},lr=function(t,e){var r,n,o,i,a;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(fr,null,a);case"array"===t:return!ur(e.arg);case!1!==(r=cr(t)):return!sr(e,r);default:return!ar(t)(e.arg)}},pr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},hr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ur(e))throw new Je("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ur(t))throw console.info(t),new Je("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,a=e[r]||{type:o,name:"_"+r};return{arg:i?pr(t,a):t,index:r,param:a,optional:i}}));default:throw new Ie("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!tr(e)&&!(r.type.length>r.type.filter((function(e){return lr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return lr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},vr=g(Object.keys,Object),gr=Object.prototype.hasOwnProperty;function dr(t){return Qt(t)?ve(t):function(t){if(!Jt(t))return vr(t);var e=[];for(var r in Object(t))gr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function yr(t,e){return t&&Pt(t,e,dr)}function _r(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new $t;++eu))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new _r:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var a=i.getMaxStore(t),u=-1;if(a>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(u=i.checkMaxStore(t)))return i.$off(t),-1}return u}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var a=Array.from(i.get(t)),u=a.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!Pn.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,this.logger("(addToLazyStore) size: "+u),u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Mn.set(this,t)},r.normalStore.get=function(){return Mn.get(this)},r.lazyStore.set=function(t){Fn.set(this,t)},r.lazyStore.get=function(){return Fn.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=[],this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE ALL SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){var r=qn(e);if(Cn(r))return!1===t.__isPatternRegisterd(r)&&(t.__pattern__.push(r),t.__pattern__.length);throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')}))},e.prototype.$releaseEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){t.logger("($releaseEvent)",e);var r=qn(e);if(Cn(r)&&t.__isPatternRegisterd(r)){var n=t;return t.__getToReleaseQueue(r).map((function(t,e){return Reflect.apply(n.$trigger,n,t),e})).reduce((function(t,e){return++e}),0)}throw t.logger("$releaseEvent throw error ==========================>",t.__pattern__,r),new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')})).reduce((function(t,e){return t+e}),0)},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];switch(!0){case!0===this.__suspend_state__:return this.__addToQueueStore(t,e);case!0==!!this.__pattern__.length:return this.__pattern__.filter((function(e){return e.test(t)})).length?this.__addToQueueStore(t,e):(this.logger("($queue) "+t+" NOT added to $queueStore",this.__pattern__),!1);default:return this.logger("($queue) get called NOTHING added"),!1}},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__getToReleaseQueue=function(t){var e=this,r=this.$queues.filter((function(e){return t.test(e[0])})).map((function(r){return e.logger("[release] execute "+r[0]+" matches "+t,r),e.queueStore.delete(r),r}));return r.length>0&&(this.__pattern__=this.__pattern__.filter((function(e){return e.toString()!==t.toString()}))),r},e.prototype.__addToQueueStore=function(t,e){return this.logger("($queue) "+t+" added to $queueStore",e),this.queueStore.add([t].concat(e)),!0},e.prototype.__isPatternRegisterd=function(t){return!!this.__pattern__.filter((function(e){return e.toString()===t.toString()})).length},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=[],this.logger("(release) was called with "+e+(r.length?' for "'+r.join(",")+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.logger("(release queue)",n),n.forEach((function(e){t.logger("[release] execute "+e[0],e),Reflect.apply(t.$trigger,t,e)})),this.queueStore.clear(),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Ln)))),Jn=function(t){var e=new RegExp("^(http|https)://","i"),r=t.match(e);if(r&&r.length){var n="https"===r[1].toLowerCase()?"wss":"ws";return t.replace(e,n+"://")}return t},In=function(t,e){G(e).forEach((function(e){t.$off(Y(e,"emit_reply"))}))};function Bn(t,e,r){Q(t,"error")?r(t.error):Q(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Vn(t,e,r,n,o){void 0===n&&(n=[]);var i=Y(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,G(n)]),new Promise((function(n,i){var a=Y(e,r,"onResult");t.$on(a,(function(t){o("got the first result",t),Bn(t,n,i)}))}))}var Wn=function(t,e,r,n,o,i){return Te(t,"send",Z,(function(){return i("running call getter method"),function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return En(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Vn(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(Y(r,n,"onError"),[new Je(n,t)])}))}}))};function Gn(t,e,r,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return En(i,n.params,!0).then((function(n){return Vn(t,e,r,n,o)})).catch(Ve)}}var Hn=function(t,e,r,n,o,i){return[Ne(t,"myNamespace",r),e,r,n,o,i]},Qn=function(t,e,r,n,o,i){return[Te(t,"onResult",(function(t){X(t)&&e.$on(Y(r,n,"onResult"),(function(o){Bn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Y(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Yn=function(t,e,r,n,o,i){return[Te(t,"onMessage",(function(t){if(X(t)){e.$only(Y(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Bn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Y(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Kn=function(t,e,r,n,o,i){return[Te(t,"onError",(function(t){X(t)&&e.$only(Y(r,n,"onError"),t)})),e,r,n,o,i]};function Xn(t,e,r,n,o,i){var a=[Hn,Qn,Yn,Kn,Wn];return Reflect.apply(tt,null,a)(n,o,t,e,r,i)}function Zn(t,e,r){var n=t.log,o={};for(var i in r){var a=r[i];for(var u in a){var c=a[u];o=Ne(o,u,Xn(i,u,c,Gn(e,i,u,c,n),e,n))}}return[o,t,e,r]}function to(t,e,r){return[Te(t,"onReady",(function(t){X(t)&&r.$only("onReady",t)})),e,r]}function eo(t,e,r,n){return[Te(t,"onError",(function(t){if(X(t))for(var e in n)r.$on(Y(e,"onError"),t)})),e,r]}var ro,no,oo=function(t,e,r){return[Ne(t,e.loginHandlerName,(function(t){if(t&&Sn(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new Je(e.loginHandlerName,"Unexpected token "+t)})),e,r]},io=function(t,e,r){return[Ne(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},ao=function(t,e,r){return[Te(t,"onLogin",(function(t){X(t)&&r.$only("onLogin",t)})),e,r]};function uo(t,e,r){return tt(oo,io,ao)(t,e,r)}function co(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=Ne(t,"connected",!1,!0),e,r]}function so(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function fo(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function lo(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function po(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),Ne(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}function ho(t,e,r){var n=function(t,e,r){var n=[co,so,fo,lo,po];return Reflect.apply(tt,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),n}var vo={};vo.standalone=$n(!1,["boolean"]),vo.debugOn=$n(!1,["boolean"]),vo.loginHandlerName=$n("login",["string"]),vo.logoutHandlerName=$n("logout",["string"]),vo.disconnectHandlerName=$n("disconnect",["string"]),vo.switchUserHandlerName=$n("switch-user",["string"]),vo.hostname=$n(!1,["string"]),vo.namespace=$n("jsonql",["string"]),vo.wsOptions=$n({},["object"]),vo.contract=$n({},["object"],((ro={}).checker=function(t){return!!function(t){return O(t)&&(Q(t,"query")||Q(t,"mutation")||Q(t,"socket"))}(t)&&t},ro)),vo.enableAuth=$n(!1,["boolean"]),vo.token=$n(!1,["string"]),vo.csrf=$n("X-CSRF-Token",["string"]),vo.suspendOnStart=$n(!1,["boolean"]);var go={};go.serverType=$n(null,["string"],((no={}).alias="socketClientType",no));var yo=Object.assign(vo,go),_o={};function bo(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new Je(t)}}()),t.wssPath=Jn([t.hostname,t.namespace].join("/"),t.serverType),t.log=An(t),t.eventEmitter=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Un(t.log)}(t),t}))}function mo(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Ye(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function wo(t){return function(e){return void 0===e&&(e={}),bo(e).then(mo).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Zn,to,eo];return t.enableAuth&&n.push(uo),n.push(ho),Reflect.apply(tt,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function jo(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),function(n){return void 0===n&&(n={}),function(t,e,r){var n=Object.assign(yo,e),o=Object.assign(_o,r);return xn(t,n,o)}(n,e,r).then(wo(t))}}_o.useJwt=!0,_o.log=null,_o.eventEmitter=null,_o.nspClient=null,_o.nspAuthClient=null,_o.wssPath="",_o.publicNamespace="public",_o.privateNamespace="private";var Oo=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(Y(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),In(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function So(t,e){return function(r,n,o){var i=r.log,a=n.namespaces,u=function(t){return t.length>1&&t[0]}(a),c=a.length-1;return a.map((function(n){var s=u===n;if(i(n," --\x3e "+(s?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",s,n);var f=[n,e[n],o,s,r,--c];Reflect.apply(t,null,f)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(Y(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(Y(t,r,"onError"),[i]),e.$call(Y(t,r,"onResult"),[{error:i}])}))}(n,o,r);return s&&(i("Has private and add logoutEvtHandler"),Oo(e,a,o,r)),s}))}}function Eo(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,a=t?[r,t].join("/"):n;return i("createNspClient with URL --\x3e ",a),o(a,e)}var $o,xo,ko,Ao,To,No,Po,Co,zo;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}$n("HS256",["string"]),$n(!1,["boolean","number","string"],(($o={}).alias="exp",$o.optional=!0,$o)),$n(!1,["boolean","number","string"],((xo={}).alias="nbf",xo.optional=!0,xo)),$n(!1,["boolean","string"],((ko={}).alias="iss",ko.optional=!0,ko)),$n(!1,["boolean","string"],((Ao={}).alias="sub",Ao.optional=!0,Ao)),$n(!1,["boolean","string"],((To={}).alias="iss",To.optional=!0,To)),$n(!1,["boolean"],((No={}).optional=!0,No)),$n(!1,["boolean","string"],((Po={}).optional=!0,Po)),$n(!1,["boolean","string"],((Co={}).optional=!0,Co)),$n(!1,["boolean"],((zo={}).optional=!0,zo));function Ro(t,e){var r,n;void 0===e&&(e=!1);var o=t.wsOptions||{},i=t.headers||{};return e&&(i=Object.assign(i,((r={}).Authorization="Bearer "+e,r))),Object.assign({},o,((n={}).headers=i,n))}function qo(t,e,r){switch(void 0===e&&(e={}),void 0===r&&(r=!1),e.tokenDeliverLocation||"url"){case"url":return{url:r?t+"?token="+r:t,opts:Ro(e,!1)};case"header":default:return{url:t,opts:Ro(e,r)}}}var Mo="object"==typeof n&&n&&n.Object===Object&&n,Fo="object"==typeof self&&self&&self.Object===Object&&self,Lo=Mo||Fo||Function("return this")(),Do=Lo.Symbol;var Uo=Array.isArray,Jo=Object.prototype,Io=Jo.hasOwnProperty,Bo=Jo.toString,Vo=Do?Do.toStringTag:void 0;var Wo=Object.prototype.toString;var Go=Do?Do.toStringTag:void 0;function Ho(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Go&&Go in Object(t)?function(t){var e=Io.call(t,Vo),r=t[Vo];try{t[Vo]=void 0;var n=!0}catch(t){}var o=Bo.call(t);return n&&(e?t[Vo]=r:delete t[Vo]),o}(t):function(t){return Wo.call(t)}(t)}function Qo(t){return null!=t&&"object"==typeof t}var Yo=Do?Do.prototype:void 0,Ko=Yo?Yo.toString:void 0;function Xo(t){if("string"==typeof t)return t;if(Uo(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&ei(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function di(t){return function(t){return"number"==typeof t||Qo(t)&&"[object Number]"==Ho(t)}(t)&&t!=+t}function yi(t){return"string"==typeof t||!Uo(t)&&Qo(t)&&"[object String]"==Ho(t)}var _i=function(t){return!yi(t)&&!di(parseFloat(t))},bi=function(t){return""!==gi(t)&&yi(t)},mi=function(t){return null!=t&&"boolean"==typeof t},wi=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==gi(t)&&(!1===e||!0===e&&null!==t)},ji=function(t,e){return void 0===e&&(e=""),!!Uo(t)&&(""===e||""===gi(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return _i;case"string":return bi;case"boolean":return mi;default:return wi}}(e)(t)})).length>0))};var Oi=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object),Si=Function.prototype,Ei=Object.prototype,$i=Si.toString,xi=Ei.hasOwnProperty,ki=$i.call(Object);function Ai(t){if(!Qo(t)||"[object Object]"!=Ho(t))return!1;var e=Oi(t);if(null===e)return!0;var r=xi.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&$i.call(r)==ki}var Ti=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Ni=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function Pi(t,e){return t===e||t!=t&&e!=e}function Ci(t,e){for(var r=t.length;r--;)if(Pi(t[r][0],e))return r;return-1}var zi=Array.prototype.splice;function Ri(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},Ri.prototype.set=function(t,e){var r=this.__data__,n=Ci(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function Mi(t){if(!qi(t))return!1;var e=Ho(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Fi=Lo["__core-js_shared__"],Li=function(){var t=/[^.]+$/.exec(Fi&&Fi.keys&&Fi.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Di=Function.prototype.toString;var Ui=/^\[object .+?Constructor\]$/,Ji=Function.prototype,Ii=Object.prototype,Bi=Ji.toString,Vi=Ii.hasOwnProperty,Wi=RegExp("^"+Bi.call(Vi).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gi(t){return!(!qi(t)||function(t){return!!Li&&Li in t}(t))&&(Mi(t)?Wi:Ui).test(function(t){if(null!=t){try{return Di.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function Hi(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Gi(r)?r:void 0}var Qi=Hi(Lo,"Map"),Yi=Hi(Object,"create");var Ki=Object.prototype.hasOwnProperty;var Xi=Object.prototype.hasOwnProperty;function Zi(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Oa(t){return null!=t&&ja(t.length)&&!Mi(t)}var Sa="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ea=Sa&&"object"==typeof module&&module&&!module.nodeType&&module,$a=Ea&&Ea.exports===Sa?Lo.Buffer:void 0,xa=($a?$a.isBuffer:void 0)||function(){return!1},ka={};ka["[object Float32Array]"]=ka["[object Float64Array]"]=ka["[object Int8Array]"]=ka["[object Int16Array]"]=ka["[object Int32Array]"]=ka["[object Uint8Array]"]=ka["[object Uint8ClampedArray]"]=ka["[object Uint16Array]"]=ka["[object Uint32Array]"]=!0,ka["[object Arguments]"]=ka["[object Array]"]=ka["[object ArrayBuffer]"]=ka["[object Boolean]"]=ka["[object DataView]"]=ka["[object Date]"]=ka["[object Error]"]=ka["[object Function]"]=ka["[object Map]"]=ka["[object Number]"]=ka["[object Object]"]=ka["[object RegExp]"]=ka["[object Set]"]=ka["[object String]"]=ka["[object WeakMap]"]=!1;var Aa="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ta=Aa&&"object"==typeof module&&module&&!module.nodeType&&module,Na=Ta&&Ta.exports===Aa&&Mo.process,Pa=function(){try{var t=Ta&&Ta.require&&Ta.require("util").types;return t||Na&&Na.binding&&Na.binding("util")}catch(t){}}(),Ca=Pa&&Pa.isTypedArray,za=Ca?function(t){return function(e){return t(e)}}(Ca):function(t){return Qo(t)&&ja(t.length)&&!!ka[Ho(t)]};function Ra(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var qa=Object.prototype.hasOwnProperty;function Ma(t,e,r){var n=t[e];qa.call(t,e)&&Pi(n,r)&&(void 0!==r||e in t)||oa(t,e,r)}var Fa=/^(?:0|[1-9]\d*)$/;function La(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Fa.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Ka);function tu(t,e){return Za(function(t,e,r){return e=Ya(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Ya(n.length-e,0),a=Array(i);++o1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,r){if(!qi(r))return!1;var n=typeof e;return!!("number"==n?Oa(r)&&La(e,r.length):"string"==n&&e in r)&&Pi(r[e],t)}(r[0],r[1],a)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=We(),o=[t].concat(e);return o.push(n),Qe("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Su=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(fu,null,o),a=n.data||n;t.$trigger(i,[a])};function Eu(t,e,r,n,o,i){var a=o.log;return n&&(a("Private namespace",t," binding to the DISCONNECT ws.terminate"),Ou(r,e)),e.onopen=function(){a("client.ws.onopen listened --\x3e",t),n?(a("isPrivate and fire the onLogin"),r.$call("onLogin")(t)):(r.$call("onReady")(t,i),a("isPublic onReady hook executed",i),0===i&&r.$off("onReady")),r.$only(fu(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(gu(t,e,r))}(t,r);a("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){a("client.ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=hu);try{var r,n=lu(t);if(!1!==(r=yu(n)))return e("_data",r),{data:lu(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Ni("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,i=n.type;switch(a("Respond from server",i,n),i){case"emit_reply":var u=fu(t,o,"onMessage"),c=r.$call(u)(n);a("EMIT_REPLY_TYPE",u,c);break;case"emit_acknowledge":var s=fu(t,o,"onResult"),f=r.$call(s)(n);a("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":a("ERROR_KEY"),Su(r,t,o,n);break;default:a("Unhandled event!",n),Su(r,t,o,n)}}catch(e){a("client.ws.onmessage error",e),Su(r,t,!1,e)}},e.onclose=function(){a("client.ws.onclose callback")},e.onerror=function(e){a("client.ws.onerror",e),function(t,e,r){t.$trigger(Y(e,"onError"),[r])}(r,t,e)},e}var $u,xu,ku=($u=e,void 0===(xu="node")&&(xu="browser"),function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=wu($u,xu),!0===t.enableAuth&&(t.nspAuthClient=wu($u,xu,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),ju(e,t).then((function(t){return So(Eu,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),In(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}});module.exports=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),jo(ku,uu,Object.assign({},au,e))(t)}; +"use strict";require("fs"),require("path");var t,e=(t=require("ws"))&&"object"==typeof t&&"default"in t?t.default:t,r=Array.isArray,n="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},o="object"==typeof n&&n&&n.Object===Object&&n,i="object"==typeof self&&self&&self.Object===Object&&self,u=o||i||Function("return this")(),a=u.Symbol,c=Object.prototype,s=c.hasOwnProperty,f=c.toString,l=a?a.toStringTag:void 0;var p=Object.prototype.toString;var h=a?a.toStringTag:void 0;function g(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=s.call(t,l),r=t[l];try{t[l]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(e?t[l]=r:delete t[l]),o}(t):function(t){return p.call(t)}(t)}function v(t,e){return function(r){return t(e(r))}}var d=v(Object.getPrototypeOf,Object);function y(t){return null!=t&&"object"==typeof t}var _=Function.prototype,b=Object.prototype,m=_.toString,w=b.hasOwnProperty,j=m.call(Object);function E(t){if(!y(t)||"[object Object]"!=g(t))return!1;var e=d(t);if(null===e)return!0;var r=w.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&m.call(r)==j}function S(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&k(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var W=function(t){return r(t)?t:[t]},G=function(t,e){void 0===e&&(e=!0);try{return JSON.parse(t)}catch(r){if(e)return t;throw new Error(r)}},H=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Q=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},K=function(t){return G("string"==typeof t?t:JSON.stringify(t))},X=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},Z=function(){return!1},tt=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,W(t))}),Reflect.apply(t,null,r))}};function et(t,e){return t===e||t!=t&&e!=e}function rt(t,e){for(var r=t.length;r--;)if(et(t[r][0],e))return r;return-1}var nt=Array.prototype.splice;function ot(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ot.prototype.set=function(t,e){var r=this.__data__,n=rt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function ut(t){if(!it(t))return!1;var e=g(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var at,ct=u["__core-js_shared__"],st=(at=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var ft=Function.prototype.toString;function lt(t){if(null!=t){try{return ft.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var pt=/^\[object .+?Constructor\]$/,ht=Function.prototype,gt=Object.prototype,vt=ht.toString,dt=gt.hasOwnProperty,yt=RegExp("^"+vt.call(dt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _t(t){return!(!it(t)||(e=t,st&&st in e))&&(ut(t)?yt:pt).test(lt(t));var e}function bt(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return _t(r)?r:void 0}var mt=bt(u,"Map"),wt=bt(Object,"create");var jt=Object.prototype.hasOwnProperty;var Et=Object.prototype.hasOwnProperty;function St(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function Ht(t){return null!=t&&Gt(t.length)&&!ut(t)}var Qt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Kt=Qt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Kt&&Kt.exports===Qt?u.Buffer:void 0,Zt=(Xt?Xt.isBuffer:void 0)||function(){return!1},te={};te["[object Float32Array]"]=te["[object Float64Array]"]=te["[object Int8Array]"]=te["[object Int16Array]"]=te["[object Int32Array]"]=te["[object Uint8Array]"]=te["[object Uint8ClampedArray]"]=te["[object Uint16Array]"]=te["[object Uint32Array]"]=!0,te["[object Arguments]"]=te["[object Array]"]=te["[object ArrayBuffer]"]=te["[object Boolean]"]=te["[object DataView]"]=te["[object Date]"]=te["[object Error]"]=te["[object Function]"]=te["[object Map]"]=te["[object Number]"]=te["[object Object]"]=te["[object RegExp]"]=te["[object Set]"]=te["[object String]"]=te["[object WeakMap]"]=!1;var ee,re="object"==typeof exports&&exports&&!exports.nodeType&&exports,ne=re&&"object"==typeof module&&module&&!module.nodeType&&module,oe=ne&&ne.exports===re&&o.process,ie=function(){try{var t=ne&&ne.require&&ne.require("util").types;return t||oe&&oe.binding&&oe.binding("util")}catch(t){}}(),ue=ie&&ie.isTypedArray,ae=ue?(ee=ue,function(t){return ee(t)}):function(t){return y(t)&&Gt(t.length)&&!!te[g(t)]};function ce(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var se=Object.prototype.hasOwnProperty;function fe(t,e,r){var n=t[e];se.call(t,e)&&et(n,r)&&(void 0!==r||e in t)||Pt(t,e,r)}var le=/^(?:0|[1-9]\d*)$/;function pe(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&le.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Se);function Te(t,e){return Ae(function(t,e,r){return e=Ee(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Ee(n.length-e,0),u=Array(i);++o1?e[n-1]:void 0,i=n>2?e[2]:void 0;for(o=Re.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,e,r){if(!it(r))return!1;var n=typeof e;return!!("number"==n?Ht(r)&&pe(e,r.length):"string"==n&&e in r)&&et(r[e],t)}(e[0],e[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},cr=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},sr=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!ur(e)(t)})).length)})).length:e.length>e.filter((function(t){return!ar(r,t)})).length},fr=function(t,e){if(void 0===e&&(e=null),E(t)){if(!e)return!0;if(ar(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return void 0===r||(!1!==(e=cr(t))?!sr({arg:r},e):!ur(t)(r))})).length)})).length}return!1},lr=function(t,e){var r,n,o,i,u;switch(!0){case"object"===t:return o=(n=e).arg,i=n.param,u=[o],Array.isArray(i.keys)&&i.keys.length&&u.push(i.keys),!Reflect.apply(fr,null,u);case"array"===t:return!ar(e.arg);case!1!==(r=cr(t)):return!sr(e,r);default:return!ur(t)(e.arg)}},pr=function(t,e){return void 0!==t?t:!0===e.optional&&void 0!==e.defaultvalue?e.defaultvalue:null},hr=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!ar(e))throw new qe("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!ar(t))throw console.info(t),new qe("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:var n=e.length,o=["any"];return t.map((function(t,r){var i=r>=n||!!e[r].optional,u=e[r]||{type:o,name:"_"+r};return{arg:i?pr(t,u):t,index:r,param:u,optional:i}}));default:throw new Fe("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!tr(e)&&!(r.type.length>r.type.filter((function(e){return lr(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return lr(e,t)})).length)}));return r?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},gr=v(Object.keys,Object),vr=Object.prototype.hasOwnProperty;function dr(t){return Ht(t)?ge(t):function(t){if(!qt(t))return gr(t);var e=[];for(var r in Object(t))vr.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function yr(t,e){return t&&$t(t,e,dr)}function _r(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new At;++ea))return!1;var s=i.get(t);if(s&&i.get(e))return s==e;var f=-1,l=!0,p=2&r?new _r:void 0;for(i.set(t,e),i.set(e,t);++f0){if(!1!==this.$get(t,!0)){var n=this.searchMapEvt(t);if(n.length){var o=n[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var u=i.getMaxStore(t),a=-1;if(u>0){var c=i.$call(t,o,r);if(Reflect.apply(c,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,n))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var u=Array.from(i.get(t)),a=u.length,c=!1,s=0;s0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!$n.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var n=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',n),r.delete(t),n}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||o.add(r)}else this.checkContentExist(r,o)||(this.logger("(addToStore) insert new",r),o.add(r));else o.add(r);return t.set(e,o),[t,o.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var o=this.hashFnToKey(r),i=[this.normalStore,t,o,r,n,e],u=Reflect.apply(this.addToStore,this,i),a=u[0],c=u[1];return this.normalStore=a,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),u=i[0],a=i[1];return this.lazyStore=u,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){Ln.set(this,t)},r.normalStore.get=function(){return Ln.get(this)},r.lazyStore.set=function(t){Mn.set(this,t)},r.lazyStore.get=function(){return Mn.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=[],this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE ALL SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){var r=Un(e);if(Nn(r))return!1===t.__isPatternRegisterd(r)&&(t.__pattern__.push(r),t.__pattern__.length);throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')}))},e.prototype.$releaseEvent=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.map((function(e){t.logger("($releaseEvent)",e);var r=Un(e);if(Nn(r)&&t.__isPatternRegisterd(r)){var n=t;return t.__getToReleaseQueue(r).map((function(t,e){return Reflect.apply(n.$trigger,n,t),e})).reduce((function(t,e){return++e}),0)}throw t.logger("$releaseEvent throw error ==========================>",t.__pattern__,r),new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof r+'" instead')})).reduce((function(t,e){return t+e}),0)},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];switch(!0){case!0===this.__suspend_state__:return this.__addToQueueStore(t,e);case!0==!!this.__pattern__.length:return this.__pattern__.filter((function(e){return e.test(t)})).length?this.__addToQueueStore(t,e):(this.logger("($queue) "+t+" NOT added to $queueStore",this.__pattern__),!1);default:return this.logger("($queue) get called NOTHING added"),!1}},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__getToReleaseQueue=function(t){var e=this,r=this.$queues.filter((function(e){return t.test(e[0])})).map((function(r){return e.logger("[release] execute "+r[0]+" matches "+t,r),e.queueStore.delete(r),r}));return r.length>0&&(this.__pattern__=this.__pattern__.filter((function(e){return e.toString()!==t.toString()}))),r},e.prototype.__addToQueueStore=function(t,e){return this.logger("($queue) "+t+" added to $queueStore",e),this.queueStore.add([t].concat(e)),!0},e.prototype.__isPatternRegisterd=function(t){return!!this.__pattern__.filter((function(e){return e.toString()===t.toString()})).length},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=[],this.logger("(release) was called with "+e+(r.length?' for "'+r.join(",")+'"':"")+" item"+(e>1?"s":"")),e>0){var n=Array.from(this.queueStore);this.logger("(release queue)",n),n.forEach((function(e){t.logger("[release] execute "+e[0],e),Reflect.apply(t.$trigger,t,e)})),this.queueStore.clear(),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(Bn)))),qn=function(t){var e=new RegExp("^(http|https)://","i"),r=t.match(e);if(r&&r.length){var n="https"===r[1].toLowerCase()?"wss":"ws";return t.replace(e,n+"://")}return t},Fn=function(t,e){W(e).forEach((function(e){t.$off(Q(e,"emit_reply"))}))};function Yn(t,e,r){H(t,"error")?r(t.error):H(t,"data")?Reflect.apply(e,null,[].concat(t.data)):r({message:"UKNNOWN RESULT!",error:t})}function Jn(t,e,r,n,o){void 0===n&&(n=[]);var i=Q(e,"emit_reply");return o("actionCall: "+i+" --\x3e "+r,n),t.$trigger(i,[r,W(n)]),new Promise((function(n,i){var u=Q(e,r,"onResult");t.$on(u,(function(t){o("got the first result",t),Yn(t,n,i)}))}))}var Vn=function(t,e,r,n,o,i){return xe(t,"send",Z,(function(){return i("running call getter method"),function(){for(var t=[],u=arguments.length;u--;)t[u]=arguments[u];return On(t,o.params,!0).then((function(t){return i("execute send",r,n,t),Jn(e,r,n,t,i)})).catch((function(t){i("send error",t),e.$call(Q(r,n,"onError"),[new qe(n,t)])}))}}))};function Wn(t,e,r,n,o){return function(){for(var i=[],u=arguments.length;u--;)i[u]=arguments[u];return On(i,n.params,!0).then((function(n){return Jn(t,e,r,n,o)})).catch(Je)}}var Gn=function(t,e,r,n,o,i){return[ke(t,"myNamespace",r),e,r,n,o,i]},Hn=function(t,e,r,n,o,i){return[xe(t,"onResult",(function(t){X(t)&&e.$on(Q(r,n,"onResult"),(function(o){Yn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))})),e,r,n,o,i]},Qn=function(t,e,r,n,o,i){return[xe(t,"onMessage",(function(t){if(X(t)){e.$only(Q(r,n,"onMessage"),(function(o){i("onMessageCallback",o),Yn(o,t,(function(t){i('Catch error: "'+n+'"',t),e.$trigger(Q(r,n,"onError"),t)}))}))}})),e,r,n,o,i]},Kn=function(t,e,r,n,o,i){return[xe(t,"onError",(function(t){X(t)&&e.$only(Q(r,n,"onError"),t)})),e,r,n,o,i]};function Xn(t,e,r,n,o,i){var u=[Gn,Hn,Qn,Kn,Vn];return Reflect.apply(tt,null,u)(n,o,t,e,r,i)}function Zn(t,e,r){var n=t.log,o={};for(var i in r){var u=r[i];for(var a in u){var c=u[a];o=ke(o,a,Xn(i,a,c,Wn(e,i,a,c,n),e,n))}}return[o,t,e,r]}function to(t,e,r){return[xe(t,"onReady",(function(t){X(t)&&r.$only("onReady",t)})),e,r]}function eo(t,e,r,n){return[xe(t,"onError",(function(t){if(X(t))for(var e in n)r.$on(Q(e,"onError"),t)})),e,r]}var ro=function(t,e,r){return[ke(t,e.loginHandlerName,(function(t){if(t&&Sn(t))return e.log("Received __login__ with "+t),r.$trigger("__login__",[t]);throw new qe(e.loginHandlerName,"Unexpected token "+t)})),e,r]},no=function(t,e,r){return[ke(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__logout__",t)})),e,r]},oo=function(t,e,r){return[xe(t,"onLogin",(function(t){X(t)&&r.$only("onLogin",t)})),e,r]};function io(t,e,r){return tt(ro,no,oo)(t,e,r)}function uo(t,e,r){return(0,e.log)("[1] setupConnectPropKey"),[t=ke(t,"connected",!1,!0),e,r]}function ao(t,e,r){var n=e.log;return n("[2] setupConnectEvtListener"),r.$on("__connect__",(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];n("setupConnectEvtListener pass and do nothing at the moment",t)})),[t,e,r]}function co(t,e,r){var n=e.log;return n("[3] setupConnectedEvtListener"),r.$on("__connected__",(function(){var e;t.connected=!0;var o=r.$release();return n("CONNECTED_EVENT_NAME",!0,"queue count",o),(e={}).connected=!0,e})),[t,e,r]}function so(t,e,r){var n=e.log;return n("[4] setupDisconnectListener"),r.$on("__disconnect__",(function(){var e;return t.connected=!1,n("CONNECTED_EVENT_NAME",!1),(e={}).connected=!1,e})),[t,e,r]}function fo(t,e,r){var n=e.disconnectHandlerName;return(0,e.log)("[5] setupDisconectAction"),ke(t,n,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger("__disconnect__",t)}))}var lo=[],po=[],ho="undefined"!=typeof Uint8Array?Uint8Array:Array,go=!1;function vo(){go=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+lo[o>>12&63]+lo[o>>6&63]+lo[63&o]);return i.join("")}function _o(t){var e;go||vo();for(var r=t.length,n=r%3,o="",i=[],u=0,a=r-n;ua?a:u+16383));return 1===n?(e=t[r-1],o+=lo[e>>2],o+=lo[e<<4&63],o+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],o+=lo[e>>10],o+=lo[e>>4&63],o+=lo[e<<2&63],o+="="),i.push(o),i.join("")}function bo(t,e,r,n,o){var i,u,a=8*o-n-1,c=(1<>1,f=-7,l=r?o-1:0,p=r?-1:1,h=t[e+l];for(l+=p,i=h&(1<<-f)-1,h>>=-f,f+=a;f>0;i=256*i+t[e+l],l+=p,f-=8);for(u=i&(1<<-f)-1,i>>=-f,f+=n;f>0;u=256*u+t[e+l],l+=p,f-=8);if(0===i)i=1-s;else{if(i===c)return u?NaN:1/0*(h?-1:1);u+=Math.pow(2,n),i-=s}return(h?-1:1)*u*Math.pow(2,i-n)}function mo(t,e,r,n,o,i){var u,a,c,s=8*i-o-1,f=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,g=n?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,u=f):(u=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-u))<1&&(u--,c*=2),(e+=u+l>=1?p/c:p*Math.pow(2,1-l))*c>=2&&(u++,c/=2),u+l>=f?(a=0,u=f):u+l>=1?(a=(e*c-1)*Math.pow(2,o),u+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,o),u=0));o>=8;t[r+h]=255&a,h+=g,a/=256,o-=8);for(u=u<0;t[r+h]=255&u,h+=g,u/=256,s-=8);t[r+h-g]|=128*v}var wo={}.toString,jo=Array.isArray||function(t){return"[object Array]"==wo.call(t)};function Eo(){return Oo.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function So(t,e){if(Eo()=Eo())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Eo().toString(16)+" bytes");return 0|t}function ko(t){return!(null==t||!t._isBuffer)}function $o(t,e){if(ko(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ui(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ai(t).length;default:if(n)return ui(t).length;e=(""+e).toLowerCase(),n=!0}}function No(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Wo(this,e,r);case"utf8":case"utf-8":return Yo(this,e,r);case"ascii":return Jo(this,e,r);case"latin1":case"binary":return Vo(this,e,r);case"base64":return Fo(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Go(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Co(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function zo(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=Oo.from(e,n)),ko(e))return 0===e.length?-1:Uo(t,e,r,n,o);if("number"==typeof e)return e&=255,Oo.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Uo(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function Uo(t,e,r,n,o){var i,u=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;u=2,a/=2,c/=2,r/=2}function s(t,e){return 1===u?t[e]:t.readUInt16BE(e*u)}if(o){var f=-1;for(i=r;ia&&(r=a-c),i=r;i>=0;i--){for(var l=!0,p=0;po&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;u>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function Fo(t,e,r){return 0===e&&r===t.length?_o(t):_o(t.slice(e,r))}function Yo(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o239?4:s>223?3:s>191?2:1;if(o+l<=r)switch(l){case 1:s<128&&(f=s);break;case 2:128==(192&(i=t[o+1]))&&(c=(31&s)<<6|63&i)>127&&(f=c);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(c=(15&s)<<12|(63&i)<<6|63&u)>2047&&(c<55296||c>57343)&&(f=c);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(c=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&c<1114112&&(f=c)}null===f?(f=65533,l=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),o+=l}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},Oo.prototype.compare=function(t,e,r,n,o){if(!ko(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(r>>>=0)-(e>>>=0),a=Math.min(i,u),c=this.slice(n,o),s=t.slice(e,r),f=0;fo)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Lo(this,t,e,r);case"utf8":case"utf-8":return Mo(this,t,e,r);case"ascii":return Bo(this,t,e,r);case"latin1":case"binary":return Io(this,t,e,r);case"base64":return Do(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return qo(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Oo.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Jo(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function Qo(t,e,r,n,o,i){if(!ko(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function Ko(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o>>8*(n?o:1-o)}function Xo(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o>>8*(n?o:3-o)&255}function Zo(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function ti(t,e,r,n,o){return o||Zo(t,0,r,4),mo(t,e,r,n,23,4),r+4}function ei(t,e,r,n,o){return o||Zo(t,0,r,8),mo(t,e,r,n,52,8),r+8}Oo.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(o*=256);)n+=this[t+--e]*o;return n},Oo.prototype.readUInt8=function(t,e){return e||Ho(t,1,this.length),this[t]},Oo.prototype.readUInt16LE=function(t,e){return e||Ho(t,2,this.length),this[t]|this[t+1]<<8},Oo.prototype.readUInt16BE=function(t,e){return e||Ho(t,2,this.length),this[t]<<8|this[t+1]},Oo.prototype.readUInt32LE=function(t,e){return e||Ho(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Oo.prototype.readUInt32BE=function(t,e){return e||Ho(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Oo.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Ho(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},Oo.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Ho(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},Oo.prototype.readInt8=function(t,e){return e||Ho(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Oo.prototype.readInt16LE=function(t,e){e||Ho(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Oo.prototype.readInt16BE=function(t,e){e||Ho(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Oo.prototype.readInt32LE=function(t,e){return e||Ho(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Oo.prototype.readInt32BE=function(t,e){return e||Ho(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Oo.prototype.readFloatLE=function(t,e){return e||Ho(t,4,this.length),bo(this,t,!0,23,4)},Oo.prototype.readFloatBE=function(t,e){return e||Ho(t,4,this.length),bo(this,t,!1,23,4)},Oo.prototype.readDoubleLE=function(t,e){return e||Ho(t,8,this.length),bo(this,t,!0,52,8)},Oo.prototype.readDoubleBE=function(t,e){return e||Ho(t,8,this.length),bo(this,t,!1,52,8)},Oo.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Qo(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i=0&&(i*=256);)this[e+o]=t/i&255;return e+r},Oo.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,1,255,0),Oo.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Oo.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,65535,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ko(this,t,e,!0),e+2},Oo.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,65535,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ko(this,t,e,!1),e+2},Oo.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,4294967295,0),Oo.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Xo(this,t,e,!0),e+4},Oo.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,4294967295,0),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Xo(this,t,e,!1),e+4},Oo.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Qo(this,t,e,r,o-1,-o)}var i=0,u=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},Oo.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);Qo(this,t,e,r,o-1,-o)}var i=r-1,u=1,a=0;for(this[e+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/u>>0)-a&255;return e+r},Oo.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,1,127,-128),Oo.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Oo.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,32767,-32768),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Ko(this,t,e,!0),e+2},Oo.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,2,32767,-32768),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Ko(this,t,e,!1),e+2},Oo.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,2147483647,-2147483648),Oo.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Xo(this,t,e,!0),e+4},Oo.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Qo(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Oo.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Xo(this,t,e,!1),e+4},Oo.prototype.writeFloatLE=function(t,e,r){return ti(this,t,e,!0,r)},Oo.prototype.writeFloatBE=function(t,e,r){return ti(this,t,e,!1,r)},Oo.prototype.writeDoubleLE=function(t,e,r){return ei(this,t,e,!0,r)},Oo.prototype.writeDoubleBE=function(t,e,r){return ei(this,t,e,!1,r)},Oo.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else if(i<1e3||!Oo.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function ai(t){return function(t){var e,r,n,o,i,u;go||vo();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,u=new ho(3*a/4-i),n=i>0?a-4:a;var c=0;for(e=0,r=0;e>16&255,u[c++]=o>>8&255,u[c++]=255&o;return 2===i?(o=po[t.charCodeAt(e)]<<2|po[t.charCodeAt(e+1)]>>4,u[c++]=255&o):1===i&&(o=po[t.charCodeAt(e)]<<10|po[t.charCodeAt(e+1)]<<4|po[t.charCodeAt(e+2)]>>2,u[c++]=o>>8&255,u[c++]=255&o),u}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace(oi,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ci(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function si(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function fi(t,e,r){var n=function(t,e,r){var n=[uo,ao,co,so,fo];return Reflect.apply(tt,null,n)(t,e,r)}(t,e,r);return n.verifyEventEmitter=function(){return r.is},n.eventEmitter=e.eventEmitter,n.log=e.log,r.$trigger("__connect__",[e,r]),!0===e.suspendOnStart&&e.$releaseNamespace(),ke(n,"isLogin",!1,!0)}var li={};li.standalone=An(!1,["boolean"]),li.debugOn=An(!1,["boolean"]),li.loginHandlerName=An("login",["string"]),li.logoutHandlerName=An("logout",["string"]),li.disconnectHandlerName=An("disconnect",["string"]),li.switchUserHandlerName=An("switch-user",["string"]),li.hostname=An(!1,["string"]),li.namespace=An("jsonql",["string"]),li.wsOptions=An({},["object"]),li.contract=An({},["object"],((ri={}).checker=function(t){return!!function(t){return E(t)&&(H(t,"query")||H(t,"mutation")||H(t,"socket"))}(t)&&t},ri)),li.enableAuth=An(!1,["boolean"]),li.token=An(!1,["string"]),li.csrf=An("X-CSRF-Token",["string"]),li.suspendOnStart=An(!1,["boolean"]);var pi={};pi.serverType=An(null,["string"],((ni={}).alias="socketClientType",ni));var hi=Object.assign(li,pi),gi={};function vi(t){return Promise.resolve(t).then((function(t){return t.hostname||(t.hostname=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new qe(t)}}()),t.wssPath=qn([t.hostname,t.namespace].join("/"),t.serverType),t.log=Pn(t),t.eventEmitter=function(t){var e=t.log,r=t.eventEmitter;return r?(e("eventEmitter is:",r.name),r):new Dn(t.log)}(t),t}))}function di(t){var e=function(t){var e=t.contract,r=t.enableAuth,n=function(t){var e="jsonql";return t.enableAuth?[[e,t.privateNamespace].join("/"),[e,t.publicNamespace].join("/")]:[e]}(t),o=r?Qe(e):function(t,e){var r,n={};for(var o in t){var i=t[o];n[o]=i}return{size:1,nspGroup:(r={},r[e]=n,r),publicNamespace:e}}(e.socket,n[0]);return Object.assign(o,{namespaces:n})}(t),r=t.eventEmitter,n=t.log,o=e.namespaces;return n("namespaces",o),!0===t.suspendOnStart&&(t.$suspendNamepsace=function(){return o.forEach((function(t){return r.$suspendEvent(t)}))},t.$releaseNamespace=function(){return r.$release()},t.$suspendNamepsace()),{opts:t,nspMap:e,ee:r}}function yi(t){return function(e){return void 0===e&&(e={}),vi(e).then(di).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return function(t,e,r){var n=[Zn,to,eo];return t.enableAuth&&n.push(io),n.push(fi),Reflect.apply(tt,null,n)(t,r,e.nspGroup)}(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("[jsonql-ws-core-client init error]",t)}))}}function _i(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),function(n){return void 0===n&&(n={}),function(t,e,r){var n=Object.assign(hi,e),o=Object.assign(gi,r);return Tn(t,n,o)}(n,e,r).then(yi(t))}}gi.useJwt=!0,gi.log=null,gi.eventEmitter=null,gi.nspClient=null,gi.nspAuthClient=null,gi.wssPath="",gi.publicNamespace="public",gi.privateNamespace="private";var bi=function(t,e,r,n){var o=n.log;r.$on("__logout__",(function(){var i=getPrivateNamespace(e);o("__logout__ event triggered"),function(t,e,r){e.forEach((function(e){t.$trigger(Q(e,"onError"),[{message:r,namespace:e}])}))}(r,[i],"__logout__"),o("logout from "+i),Fn(r,i),t[i]=null,notLoginWsListerner(i,r,n)}))};function mi(t,e){return function(r,n,o){var i=r.log,u=n.namespaces,a=function(t){return t.length>1&&t[0]}(u),c=u.length-1;return u.map((function(n){var s=a===n;if(i(n," --\x3e "+(s?"private":"public")+" nsp --\x3e ",!1!==e[n]),e[n]){i("[call bindWsHandler]",s,n);var f=[n,e[n],o,s,r,--c];Reflect.apply(t,null,f)}else i("binding notLoginWsHandler to "+n),function(t,e,r){var n=r.log;e.$only(Q(t,"emit_reply"),(function(r,o){n("[notLoginListerner] hijack the ws call",t,r,o);var i={message:"NOT LOGIN"};e.$call(Q(t,r,"onError"),[i]),e.$call(Q(t,r,"onResult"),[{error:i}])}))}(n,o,r);return s&&(i("Has private and add logoutEvtHandler"),bi(e,u,o,r)),s}))}}function wi(t,e){var r=e.hostname,n=e.wssPath,o=e.nspClient,i=e.log,u=t?[r,t].join("/"):n;return i("createNspClient with URL --\x3e ",u),o(u,e)}var ji,Ei,Si,Oi,Ai,Ti,Ri,Pi,xi;Error;try{"undefined"!=typeof window&&window.atob&&window.atob.bind(window)}catch(t){}An("HS256",["string"]),An(!1,["boolean","number","string"],((ji={}).alias="exp",ji.optional=!0,ji)),An(!1,["boolean","number","string"],((Ei={}).alias="nbf",Ei.optional=!0,Ei)),An(!1,["boolean","string"],((Si={}).alias="iss",Si.optional=!0,Si)),An(!1,["boolean","string"],((Oi={}).alias="sub",Oi.optional=!0,Oi)),An(!1,["boolean","string"],((Ai={}).alias="iss",Ai.optional=!0,Ai)),An(!1,["boolean"],((Ti={}).optional=!0,Ti)),An(!1,["boolean","string"],((Ri={}).optional=!0,Ri)),An(!1,["boolean","string"],((Pi={}).optional=!0,Pi)),An(!1,["boolean"],((xi={}).optional=!0,xi));function ki(t,e){var r,n;void 0===e&&(e=!1);var o=t.wsOptions||{},i=t.headers||{};return e&&(i=Object.assign(i,((r={}).Authorization="Bearer "+e,r))),Object.assign({},o,((n={}).headers=i,n))}function $i(t,e,r){switch(void 0===e&&(e={}),void 0===r&&(r=!1),e.tokenDeliverLocation||"url"){case"url":return{url:r?t+"?token="+r:t,opts:ki(e,!1)};case"header":default:return{url:t,opts:ki(e,r)}}}var Ni="object"==typeof n&&n&&n.Object===Object&&n,Ci="object"==typeof self&&self&&self.Object===Object&&self,zi=Ni||Ci||Function("return this")(),Ui=zi.Symbol;var Li=Array.isArray,Mi=Object.prototype,Bi=Mi.hasOwnProperty,Ii=Mi.toString,Di=Ui?Ui.toStringTag:void 0;var qi=Object.prototype.toString;var Fi=Ui?Ui.toStringTag:void 0;function Yi(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":Fi&&Fi in Object(t)?function(t){var e=Bi.call(t,Di),r=t[Di];try{t[Di]=void 0;var n=!0}catch(t){}var o=Ii.call(t);return n&&(e?t[Di]=r:delete t[Di]),o}(t):function(t){return qi.call(t)}(t)}function Ji(t){return null!=t&&"object"==typeof t}var Vi=Ui?Ui.prototype:void 0,Wi=Vi?Vi.toString:void 0;function Gi(t){if("string"==typeof t)return t;if(Li(t))return function(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n-1;);return r}(o,i),function(t,e){for(var r=t.length;r--&&Ki(e,t[r],0)>-1;);return r}(o,i)+1).join("")}function pu(t){return function(t){return"number"==typeof t||Ji(t)&&"[object Number]"==Yi(t)}(t)&&t!=+t}function hu(t){return"string"==typeof t||!Li(t)&&Ji(t)&&"[object String]"==Yi(t)}var gu=function(t){return!hu(t)&&!pu(parseFloat(t))},vu=function(t){return""!==lu(t)&&hu(t)},du=function(t){return null!=t&&"boolean"==typeof t},yu=function(t,e){return void 0===e&&(e=!0),void 0!==t&&""!==t&&""!==lu(t)&&(!1===e||!0===e&&null!==t)},_u=function(t,e){return void 0===e&&(e=""),!!Li(t)&&(""===e||""===lu(e)||!(t.filter((function(t){return!function(t){switch(t){case"number":return gu;case"string":return vu;case"boolean":return du;default:return yu}}(e)(t)})).length>0))};var bu=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object),mu=Function.prototype,wu=Object.prototype,ju=mu.toString,Eu=wu.hasOwnProperty,Su=ju.call(Object);function Ou(t){if(!Ji(t)||"[object Object]"!=Yi(t))return!1;var e=bu(t);if(null===e)return!0;var r=Eu.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&ju.call(r)==Su}var Au=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(Error),Tu=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(Error);function Ru(t,e){return t===e||t!=t&&e!=e}function Pu(t,e){for(var r=t.length;r--;)if(Ru(t[r][0],e))return r;return-1}var xu=Array.prototype.splice;function ku(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ku.prototype.set=function(t,e){var r=this.__data__,n=Pu(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};function Nu(t){if(!$u(t))return!1;var e=Yi(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var Cu=zi["__core-js_shared__"],zu=function(){var t=/[^.]+$/.exec(Cu&&Cu.keys&&Cu.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();var Uu=Function.prototype.toString;var Lu=/^\[object .+?Constructor\]$/,Mu=Function.prototype,Bu=Object.prototype,Iu=Mu.toString,Du=Bu.hasOwnProperty,qu=RegExp("^"+Iu.call(Du).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Fu(t){return!(!$u(t)||function(t){return!!zu&&zu in t}(t))&&(Nu(t)?qu:Lu).test(function(t){if(null!=t){try{return Uu.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function Yu(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return Fu(r)?r:void 0}var Ju=Yu(zi,"Map"),Vu=Yu(Object,"create");var Wu=Object.prototype.hasOwnProperty;var Gu=Object.prototype.hasOwnProperty;function Hu(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=9007199254740991}function ba(t){return null!=t&&_a(t.length)&&!Nu(t)}var ma="object"==typeof exports&&exports&&!exports.nodeType&&exports,wa=ma&&"object"==typeof module&&module&&!module.nodeType&&module,ja=wa&&wa.exports===ma?zi.Buffer:void 0,Ea=(ja?ja.isBuffer:void 0)||function(){return!1},Sa={};Sa["[object Float32Array]"]=Sa["[object Float64Array]"]=Sa["[object Int8Array]"]=Sa["[object Int16Array]"]=Sa["[object Int32Array]"]=Sa["[object Uint8Array]"]=Sa["[object Uint8ClampedArray]"]=Sa["[object Uint16Array]"]=Sa["[object Uint32Array]"]=!0,Sa["[object Arguments]"]=Sa["[object Array]"]=Sa["[object ArrayBuffer]"]=Sa["[object Boolean]"]=Sa["[object DataView]"]=Sa["[object Date]"]=Sa["[object Error]"]=Sa["[object Function]"]=Sa["[object Map]"]=Sa["[object Number]"]=Sa["[object Object]"]=Sa["[object RegExp]"]=Sa["[object Set]"]=Sa["[object String]"]=Sa["[object WeakMap]"]=!1;var Oa="object"==typeof exports&&exports&&!exports.nodeType&&exports,Aa=Oa&&"object"==typeof module&&module&&!module.nodeType&&module,Ta=Aa&&Aa.exports===Oa&&Ni.process,Ra=function(){try{var t=Aa&&Aa.require&&Aa.require("util").types;return t||Ta&&Ta.binding&&Ta.binding("util")}catch(t){}}(),Pa=Ra&&Ra.isTypedArray,xa=Pa?function(t){return function(e){return t(e)}}(Pa):function(t){return Ji(t)&&_a(t.length)&&!!Sa[Yi(t)]};function ka(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var $a=Object.prototype.hasOwnProperty;function Na(t,e,r){var n=t[e];$a.call(t,e)&&Ru(n,r)&&(void 0!==r||e in t)||ta(t,e,r)}var Ca=/^(?:0|[1-9]\d*)$/;function za(t,e){var r=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==r||"symbol"!=r&&Ca.test(t))&&t>-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Wa);function Qa(t,e){return Ha(function(t,e,r){return e=Va(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,i=Va(n.length-e,0),u=Array(i);++o1?r[o-1]:void 0,u=o>2?r[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&function(t,e,r){if(!$u(r))return!1;var n=typeof e;return!!("number"==n?ba(r)&&za(e,r.length):"string"==n&&e in r)&&Ru(r[e],t)}(r[0],r[1],u)&&(i=o<3?void 0:i,o=1),e=Object(e);++n0;)e[r]=arguments[r+1];var n=Ve(),o=[t].concat(e);return o.push(n),He("__intercom__",o)}(LOGOUT_EVENT_NAME)),log("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var mc=function(t,e,r,n){var o=[e];r&&o.push(r),o.push("onError");var i=Reflect.apply(uc,null,o),u=n.data||n;t.$trigger(i,[u])};function wc(t,e,r,n,o,i){var u=o.log;return n&&(u("Private namespace",t," binding to the DISCONNECT ws.terminate"),bc(r,e)),e.onopen=function(){u("client.ws.onopen listened --\x3e",t),n?(u("isPrivate and fire the onLogin"),r.$call("onLogin")(t)):(r.$call("onReady")(t,i),u("isPublic onReady hook executed",i),0===i&&r.$off("onReady")),r.$only(uc(t,"emit_reply"),(function(t,r){var n=function(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(lc(t,e,r))}(t,r);u("ws.onopen.send",t,r,n),e.send(n)}))},e.onmessage=function(e){u("client.ws.onmessage raw payload",e.data);try{var n=function(t,e){void 0===e&&(e=sc);try{var r,n=ac(t);if(!1!==(r=hc(n)))return e("_data",r),{data:ac(r.__data__),resolverName:r.__event__,type:r.__reply__};throw new Tu("payload can not decoded",t)}catch(t){return e("error",t)}}(e.data),o=n.resolverName,i=n.type;switch(u("Respond from server",i,n),i){case"emit_reply":var a=uc(t,o,"onMessage"),c=r.$call(a)(n);u("EMIT_REPLY_TYPE",a,c);break;case"emit_acknowledge":var s=uc(t,o,"onResult"),f=r.$call(s)(n);u("ACKNOWLEDGE_REPLY_TYPE",s,f);break;case"error":u("ERROR_KEY"),mc(r,t,o,n);break;default:u("Unhandled event!",n),mc(r,t,o,n)}}catch(e){u("client.ws.onmessage error",e),mc(r,t,!1,e)}},e.onclose=function(){u("client.ws.onclose callback")},e.onerror=function(e){u("client.ws.onerror",e),function(t,e,r){t.$trigger(Q(e,"onError"),[r])}(r,t,e)},e}var jc,Ec,Sc=(jc=e,void 0===(Ec="node")&&(Ec="browser"),function(t,e,r){var n=t.log;return n("There is problem here with passing the opts",t),t.nspClient=yc(jc,Ec),!0===t.enableAuth&&(t.nspAuthClient=yc(jc,Ec,!0)),n("[1] bindWebsocketToJsonql",r.$name,e),function(t,e,r){r("[2] setup the CONNECT_EVENT_NAME"),e.$only("__connect__",(function(e,n){return r("[3] CONNECT_EVENT_NAME",n),_c(e,t).then((function(t){return mi(wc,t)})).then((function(r){return r(e,t,n)}))}))}(e,r,n),function(t,e,r){var n=t.log,o=e.namespaces;n("[4] loginEventHandler"),r.$only("__login__",(function(e){n("createClient LOGIN_EVENT_NAME $only handler"),Fn(r,o),t.token=e,r.$trigger("__connect__",[t,r])}))}(t,e,r),n("just before returing the values for the next operation from createClientBindingAction"),{opts:t,nspMap:e,ee:r}});module.exports=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),_i(Sc,nc,Object.assign({},rc,e))(t)}; //# sourceMappingURL=node-ws-client.js.map diff --git a/packages/@jsonql/ws/node-ws-client.js.map b/packages/@jsonql/ws/node-ws-client.js.map index a668a7e7c1f755f75ba2666006d0cf48a7f38f69..3b022415df13689a3765d3327258eeff7e709872 100644 --- a/packages/@jsonql/ws/node-ws-client.js.map +++ b/packages/@jsonql/ws/node-ws-client.js.map @@ -1 +1 @@ -{"version":3,"file":"node-ws-client.js","sources":["../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../ws-client-core/src/options/index.js"],"sourcesContent":["/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n // @1.2.2 this become an array so we can hold different events\n this.__pattern__ = []\n // key value pair store to store the queued calls\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE ALL SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {array.} patterns the pattern search matches the event name\n * @return {array} if the pattern return is registered or not\n */\n $suspendEvent(...patterns) {\n return patterns.map(pattern => {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n // check if it's already added \n if (this.__isPatternRegisterd(regex) === false) {\n this.__pattern__.push(regex)\n\n return this.__pattern__.length\n }\n return false\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n }\n\n /**\n * This is pair with $suspnedEvent to release part of the event queue by the pattern (eventName)\n * @param {array.<*>} patterns a eventName of partial eventName to create a RegExp\n * @return {number} should be the number of queue got released\n */\n $releaseEvent(...patterns) {\n return patterns.map(pattern => {\n this.logger(`($releaseEvent)`, pattern)\n const regex = getRegex(pattern)\n if (isRegExp(regex) && this.__isPatternRegisterd(regex)) {\n const self = this\n\n return this.__getToReleaseQueue(regex)\n .map((args, i) => {\n \n Reflect.apply(self.$trigger, self, args)\n\n return i \n }).reduce((a, b) => ++b, 0)\n }\n\n this.logger('$releaseEvent throw error ==========================>', this.__pattern__, regex)\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n .reduce((x, y) => x + y, 0)\n }\n\n /**\n * queuing call up when it's in suspend mode,\n * it's currently suspending then add to store then the $trigger will do nothing\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n switch (true) {\n case this.__suspend_state__ === true: // this will take priority over the pattern\n \n return this.__addToQueueStore(evt, args)\n case !!this.__pattern__.length === true: \n // check the pattern and decide if we want to suspend it or not\n if (!!this.__pattern__.filter(p => p.test(evt)).length) {\n \n return this.__addToQueueStore(evt, args)\n }\n this.logger(`($queue) ${evt} NOT added to $queueStore`, this.__pattern__)\n \n return false \n default:\n this.logger('($queue) get called NOTHING added')\n return false\n } \n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n\n /**\n * The reason is before we call $trigger we need to remove the pattern from queue\n * otherwise, it will never get release\n * @param {*} pattern to find the queue \n * @return {array} queue to get execute \n */\n __getToReleaseQueue(regex) {\n // first get the list of events in the queue store that match this pattern\n const list = this.$queues\n // first index is the eventName\n .filter(content => regex.test(content[0]))\n .map(content => {\n this.logger(`[release] execute ${content[0]} matches ${regex}`, content)\n // we just remove it\n this.queueStore.delete(content)\n \n return content\n })\n if (list.length > 0) {\n // we need to remove this event from the pattern queue array \n this.__pattern__ = this.__pattern__.filter(p => p.toString() !== regex.toString()) \n }\n\n return list \n }\n\n /**\n * Wrapper method with a logger \n * @param {*} evt \n * @param {*} args \n * @return {boolean}\n */\n __addToQueueStore(evt, args) {\n this.logger(`($queue) ${evt} added to $queueStore`, args)\n\n // @TODO should we check if this already added? \n // what if that is a multiple call like $on\n this.queueStore.add([evt].concat(args))\n\n return true\n }\n\n /**\n * check if certain pattern already registered in the queue\n * @param {*} pattern\n * @return {boolean} \n */\n __isPatternRegisterd(pattern) {\n // this is a bit of a hack to compare two regex Object \n return !!this.__pattern__.filter(p => (\n p.toString() === pattern.toString()\n )).length \n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue, this is a wholesale release ALL\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = []\n \n this.logger(`(release) was called with ${size}${pattern.length ? ' for \"' + pattern.join(',') + '\"': ''} item${size > 1 ? 's' : ''}`)\n \n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.logger('(release queue)', queue)\n\n queue.forEach(args => {\n this.logger(`[release] execute ${args[0]}`, args)\n\n Reflect.apply(this.$trigger, this, args)\n })\n\n this.queueStore.clear()\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n"],"names":["SetCache","Object","wsCoreConstProps"],"mappings":"6xBAAA,89vBCAAA,8tWCAAC,ookBCAAC"} \ No newline at end of file +{"version":3,"file":"node-ws-client.js","sources":["../../ws-client-core/node_modules/lodash-es/isObjectLike.js","../../ws-client-core/node_modules/lodash-es/_arraySome.js","../../ws-client-core/node_modules/@to1source/event/src/suspend.js","../../ws-client-core/src/options/index.js"],"sourcesContent":["/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n/*\nwe use a different way to do the same watch thing now\nthis.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n})\n*/\nimport { getRegex, isRegExp } from './utils'\n\nimport BaseClass from './base'\n\nexport default class SuspendClass extends BaseClass {\n\n constructor() {\n super()\n // suspend, release and queue\n this.__suspend_state__ = null\n // to do this proper we don't use a new prop to hold the event name pattern\n // @1.2.2 this become an array so we can hold different events\n this.__pattern__ = []\n // key value pair store to store the queued calls\n this.queueStore = new Set()\n }\n\n /**\n * start suspend\n * @return {void}\n */\n $suspend() {\n this.logger(`---> SUSPEND ALL OPS <---`)\n this.__suspend__(true)\n }\n\n /**\n * release the queue\n * @return {void}\n */\n $release() {\n this.logger(`---> RELEASE ALL SUSPENDED QUEUE <---`)\n this.__suspend__(false)\n }\n\n /**\n * suspend event by pattern\n * @param {array.} patterns the pattern search matches the event name\n * @return {array} if the pattern return is registered or not\n */\n $suspendEvent(...patterns) {\n return patterns.map(pattern => {\n const regex = getRegex(pattern)\n if (isRegExp(regex)) {\n // check if it's already added \n if (this.__isPatternRegisterd(regex) === false) {\n this.__pattern__.push(regex)\n\n return this.__pattern__.length\n }\n return false\n }\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n }\n\n /**\n * This is pair with $suspnedEvent to release part of the event queue by the pattern (eventName)\n * @param {array.<*>} patterns a eventName of partial eventName to create a RegExp\n * @return {number} should be the number of queue got released\n */\n $releaseEvent(...patterns) {\n return patterns.map(pattern => {\n this.logger(`($releaseEvent)`, pattern)\n const regex = getRegex(pattern)\n if (isRegExp(regex) && this.__isPatternRegisterd(regex)) {\n const self = this\n\n return this.__getToReleaseQueue(regex)\n .map((args, i) => {\n \n Reflect.apply(self.$trigger, self, args)\n\n return i \n }).reduce((a, b) => ++b, 0)\n }\n\n this.logger('$releaseEvent throw error ==========================>', this.__pattern__, regex)\n throw new Error(`We expect a pattern variable to be string or RegExp, but we got \"${typeof regex}\" instead`)\n })\n .reduce((x, y) => x + y, 0)\n }\n\n /**\n * queuing call up when it's in suspend mode,\n * it's currently suspending then add to store then the $trigger will do nothing\n * @param {string} evt the event name\n * @param {*} args unknown number of arguments\n * @return {boolean} true when added or false when it's not\n */\n $queue(evt, ...args) {\n switch (true) {\n case this.__suspend_state__ === true: // this will take priority over the pattern\n \n return this.__addToQueueStore(evt, args)\n case !!this.__pattern__.length === true: \n // check the pattern and decide if we want to suspend it or not\n if (!!this.__pattern__.filter(p => p.test(evt)).length) {\n \n return this.__addToQueueStore(evt, args)\n }\n this.logger(`($queue) ${evt} NOT added to $queueStore`, this.__pattern__)\n \n return false \n default:\n this.logger('($queue) get called NOTHING added')\n return false\n } \n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n\n /**\n * The reason is before we call $trigger we need to remove the pattern from queue\n * otherwise, it will never get release\n * @param {*} pattern to find the queue \n * @return {array} queue to get execute \n */\n __getToReleaseQueue(regex) {\n // first get the list of events in the queue store that match this pattern\n const list = this.$queues\n // first index is the eventName\n .filter(content => regex.test(content[0]))\n .map(content => {\n this.logger(`[release] execute ${content[0]} matches ${regex}`, content)\n // we just remove it\n this.queueStore.delete(content)\n \n return content\n })\n if (list.length > 0) {\n // we need to remove this event from the pattern queue array \n this.__pattern__ = this.__pattern__.filter(p => p.toString() !== regex.toString()) \n }\n\n return list \n }\n\n /**\n * Wrapper method with a logger \n * @param {*} evt \n * @param {*} args \n * @return {boolean}\n */\n __addToQueueStore(evt, args) {\n this.logger(`($queue) ${evt} added to $queueStore`, args)\n\n // @TODO should we check if this already added? \n // what if that is a multiple call like $on\n this.queueStore.add([evt].concat(args))\n\n return true\n }\n\n /**\n * check if certain pattern already registered in the queue\n * @param {*} pattern\n * @return {boolean} \n */\n __isPatternRegisterd(pattern) {\n // this is a bit of a hack to compare two regex Object \n return !!this.__pattern__.filter(p => (\n p.toString() === pattern.toString()\n )).length \n }\n\n /**\n * to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n __suspend__(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend_state__\n this.__suspend_state__ = value\n this.logger(`($suspend) Change from \"${lastValue}\" --> \"${value}\"`)\n if (lastValue === true && value === false) {\n this.__release__()\n }\n } else {\n throw new Error(`$suspend only accept Boolean value! we got ${typeof value}`)\n }\n }\n\n /**\n * Release the queue, this is a wholesale release ALL\n * @return {int} size if any\n */\n __release__() {\n let size = this.queueStore.size\n let pattern = this.__pattern__\n this.__pattern__ = []\n \n this.logger(`(release) was called with ${size}${pattern.length ? ' for \"' + pattern.join(',') + '\"': ''} item${size > 1 ? 's' : ''}`)\n \n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.logger('(release queue)', queue)\n\n queue.forEach(args => {\n this.logger(`[release] execute ${args[0]}`, args)\n\n Reflect.apply(this.$trigger, this, args)\n })\n\n this.queueStore.clear()\n this.logger(`Release size ${this.queueStore.size}`)\n }\n\n return size\n }\n}\n","// create options\nimport {\n checkConfigAsync,\n checkConfig\n} from 'jsonql-params-validator'\nimport {\n wsCoreCheckMap,\n wsCoreConstProps,\n socketCheckMap\n} from './defaults'\nimport {\n fixWss,\n getHostName,\n getEventEmitter,\n getNspInfoByConfig,\n getLogFn\n} from '../utils'\n\nimport {\n SUSPEND_EVENT_PROP_KEY\n} from 'jsonql-constants'\n\n/**\n * We need this to find the socket server type\n * @param {*} config\n * @return {string} the name of the socket server if any\n */\nfunction checkSocketClientType(config) {\n return checkConfig(config, socketCheckMap)\n}\n\n/**\n * Create a combine checkConfig for the creating the combine client\n * @param {*} configCheckMap\n * @param {*} constProps\n * @param {boolean} [withInject=false] if we need to run the postCheckInjectOpts \n * @return {function} takes the user input config then resolve the configuration\n */\nfunction createCombineConfigCheck(configCheckMap, constProps, withInject = false) {\n const combineCheckMap = Object.assign({}, wsCoreCheckMap, configCheckMap)\n const combineConstProps = Object.assign({}, wsCoreConstProps, constProps)\n\n return function runCheckConfigAsync(config) { \n return checkConfigAsync(config, combineCheckMap, combineConstProps)\n .then(opts => withInject ? postCheckInjectOpts(opts) : opts)\n }\n}\n\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config user supply config\n * @param {object} defaultOptions for checking\n * @param {object} constProps user supply const props\n * @return {promise} resolve to the checked opitons\n */\nfunction checkConfiguration(config, defaultOptions, constProps) {\n const defaultCheckMap= Object.assign(wsCoreCheckMap, defaultOptions)\n const wsConstProps = Object.assign(wsCoreConstProps, constProps)\n\n return checkConfigAsync(config, defaultCheckMap, wsConstProps)\n}\n\n/**\n * Taking the `then` part from the method below\n * @param {object} opts\n * @return {promise} opts all done\n */\nfunction postCheckInjectOpts(opts) {\n \n return Promise.resolve(opts)\n .then(opts => {\n if (!opts.hostname) {\n opts.hostname = getHostName()\n }\n // @TODO the contract now will supply the namespace information\n // and we need to use that to group the namespace call\n \n opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n // get the log function here\n opts.log = getLogFn(opts)\n\n opts.eventEmitter = getEventEmitter(opts)\n \n return opts\n })\n}\n\n/**\n * Don't want to make things confusing\n * Breaking up the opts process in one place\n * then generate the necessary parameter in another step\n * @2020-3-20 here we suspend operation by it's namespace first\n * Then in the framework part, after the connection establish we release\n * the queue\n * @param {object} opts checked --> merge --> injected\n * @return {object} {opts, nspMap, ee}\n */\nfunction createRequiredParams(opts) {\n const nspMap = getNspInfoByConfig(opts)\n const ee = opts.eventEmitter\n // @TODO here we are going to add suspend event to the namespace related methods\n const { log } = opts \n const { namespaces } = nspMap\n log(`namespaces`, namespaces)\n // next we loop the namespace and suspend all the events prefix with namespace \n if (opts[SUSPEND_EVENT_PROP_KEY] === true) {\n // we create this as a function then we can call it again \n opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace))\n // then we create a new method to releas the queue \n // we prefix it with the $ to notify this is not a jsonql part methods\n opts.$releaseNamespace = () => ee.$release()\n // now run it \n opts.$suspendNamepsace()\n }\n \n return { opts, nspMap, ee }\n}\n\nexport {\n // properties\n wsCoreCheckMap,\n wsCoreConstProps,\n // functions\n checkConfiguration,\n postCheckInjectOpts,\n createRequiredParams,\n // this will just get export for integration\n checkSocketClientType,\n createCombineConfigCheck\n}\n"],"names":["SetCache","Object","wsCoreConstProps"],"mappings":"2zBAAA,89vBCAAA,8tWCAAC,q3uCCAAC"} \ No newline at end of file diff --git a/packages/@jsonql/ws/package.json b/packages/@jsonql/ws/package.json index 365f26fa9037c5e4364716784ea9888486eb00db..f7c5349d34f859aa0919b4a37942ad1e5371852e 100644 --- a/packages/@jsonql/ws/package.json +++ b/packages/@jsonql/ws/package.json @@ -34,7 +34,8 @@ "test:on": "DEBUG=jsonql-ws* ava ./tests/on-event.test.js", "test:chain": "DEBUG=jsonql-ws-* ava ./tests/ws-client-chain.test.js", "test:int": "DEBUG=jsonql-ws* ava ./tests/integration.test.js", - "test:reg": "ava ./tests/regex.test.js" + "test:reg": "ava ./tests/regex.test.js", + "test:login": "DEBUG=jsonql-ws-* ava ./tests/ws-client-login.test.js" }, "keywords": [ "jsonql", @@ -50,7 +51,7 @@ "homepage": "jsonql.org", "dependencies": { "js-cookie": "^2.2.1", - "jsonql-constants": "^2.1.1", + "jsonql-constants": "^2.1.2", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.3", "jsonql-utils": "^1.2.7", diff --git a/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js b/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js index b0cc416c341a5698484614c20be098de5eec8ef7..4c517587c3cab6fe60821c8757325a4dfb73889f 100644 --- a/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js +++ b/packages/@jsonql/ws/src/core/setup-socket-listeners/connect-event-listener.js @@ -15,7 +15,7 @@ export function connectEventListener(nspMap, ee, log) { log(`[2] setup the CONNECT_EVENT_NAME`) // this is a automatic trigger from within the framework ee.$only(CONNECT_EVENT_NAME, function connectEventNameHandler($config, $ee) { - log(`[3] CONNECT_EVENT_NAME`, $ee) + log(`[3] CONNECT_EVENT_NAME`, $config) return createNsp($config, nspMap) .then(nsps => namespaceEventListener(bindSocketEventHandler, nsps)) diff --git a/packages/@jsonql/ws/tests/ws-client-login.test.js b/packages/@jsonql/ws/tests/ws-client-login.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7bb30bca61c36c8bf7dd633721281292a3547e06 --- /dev/null +++ b/packages/@jsonql/ws/tests/ws-client-login.test.js @@ -0,0 +1,71 @@ +// need to test the way how it suppose to connect to public interface first +// then we trigger a login and have the and ONLY the onLogin trigger next +// then we need to try to logout and then log back in again to see what +// is the effect of the logout + +const test = require('ava') +const EventClass = require('@to1source/event') +const modulePath = process.env.JSONQL_DEBUG ? '../node-module' : '../node-ws-client' +const wsClient = require(modulePath) + +const serverSetup = require('./fixtures/server-setup') + +const { join } = require('path') +const fsx = require('fs-extra') + +const genToken = require('./fixtures/token') + +const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') +const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) +const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) + +const _debug = require('debug')('jsonql-ws-client:test:ws-auth') +const colors = require('colors/safe') + +const debug = (str, ...args) => { + Reflect.apply(_debug, null, [colors.black.bgBrightMagenta(str+'')].concat(args)) +} + +const localDebug = (str, ...args) => { + Reflect.apply(debug, null, [ colors.black.bgBrightGreen(str+'') ].concat(args) ) +} + +const payload = {name: 'Joel'} +const token = genToken(payload) +const port = 8006 + +test.before(async t => { + + const { app } = await serverSetup({ + contract, + contractDir, + resolverDir: join(__dirname, 'fixtures', 'resolvers'), + serverType: 'ws', + enableAuth: true, + keysDir: join(__dirname, 'fixtures', 'keys') + }) + t.context.server = app.listen(port) + + t.context.client = await wsClient({ + token, + hostname: `ws://localhost:${port}`, + contract: publicContract, + enableAuth: true + }, { log: debug }) // debug + + t.context.evt = new EventClass() +}) + +test.after(t => { + t.context.server.close() +}) + + +test.serial.cb(`Should have a onReady event fired`, t => { + const client = t.context.client + client.onReady(namespace => { + localDebug('isLogin?', client.isLogin, namespace) + t.is('jsonql/public', namespace) + t.end() + }) +}) \ No newline at end of file diff --git a/packages/constants/README.md b/packages/constants/README.md index b79d5addacb15779a56ede1fb52e2df0df9f3a60..c77de1d0cbd87274e6775fcd22c2a0226decfef1 100755 --- a/packages/constants/README.md +++ b/packages/constants/README.md @@ -180,6 +180,7 @@ Please consult the detail break down below. - ENABLE_CACHE_RESOLVER_PROP_KEY - TOKEN_DELIVER_LOCATION_PROP_KEY - COOKIE_PROP_KEY +- IS_READY_PROP_KEY - IS_LOGIN_PROP_KEY ### SOCKET diff --git a/packages/constants/browser.js b/packages/constants/browser.js index 9b193de41691d228c98203f2598aaa3e56e198ef..5461d7eb9c8ec0eaa9df6b7a14e53b7eb66e194e 100644 --- a/packages/constants/browser.js +++ b/packages/constants/browser.js @@ -181,6 +181,7 @@ var jsonqlConstants = { "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "TOKEN_DELIVER_LOCATION_PROP_KEY": "tokenDeliverLocation", "COOKIE_PROP_KEY": "cookie", + "IS_READY_PROP_KEY": "isReady", "IS_LOGIN_PROP_KEY": "isLogin", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", diff --git a/packages/constants/constants.json b/packages/constants/constants.json index d8ebefd513d5fa7fdc07c674c4dec1ba1ddb46f3..31b318d4f8aaeab7ad0b5492342bdce1983b9550 100644 --- a/packages/constants/constants.json +++ b/packages/constants/constants.json @@ -181,6 +181,7 @@ "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "TOKEN_DELIVER_LOCATION_PROP_KEY": "tokenDeliverLocation", "COOKIE_PROP_KEY": "cookie", + "IS_READY_PROP_KEY": "isReady", "IS_LOGIN_PROP_KEY": "isLogin", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", diff --git a/packages/constants/index.js b/packages/constants/index.js index bbadbf78a9205f0b4e7d9e17efecd9acb58b84ca..79b8c289c5e1547fd83906ba0f83485e99574933 100644 --- a/packages/constants/index.js +++ b/packages/constants/index.js @@ -262,7 +262,8 @@ export const ENABLE_CACHE_RESOLVER_PROP_KEY = 'enableCacheResolver' export const TOKEN_DELIVER_LOCATION_PROP_KEY = 'tokenDeliverLocation' export const COOKIE_PROP_KEY = 'cookie' - +// for tracking the login and connect state for socket client +export const IS_READY_PROP_KEY = 'isReady' export const IS_LOGIN_PROP_KEY = 'isLogin' /* socket.js */ // the constants file is gettig too large diff --git a/packages/constants/main.js b/packages/constants/main.js index a1d9f4ae58bd6df89a54b78d9481a7219ce41d53..6fad87770712c57b7b52f46b5034e1b48f1bbc58 100644 --- a/packages/constants/main.js +++ b/packages/constants/main.js @@ -181,6 +181,7 @@ module.exports = { "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "TOKEN_DELIVER_LOCATION_PROP_KEY": "tokenDeliverLocation", "COOKIE_PROP_KEY": "cookie", + "IS_READY_PROP_KEY": "isReady", "IS_LOGIN_PROP_KEY": "isLogin", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", diff --git a/packages/constants/package.json b/packages/constants/package.json index 46a194636b5550b2127a18e34f5bd5614ae0f500..23190969cf41005d8097f46aac40bf70372977d7 100755 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-constants", - "version": "2.1.2", + "version": "2.1.3", "description": "All the share constants for jsonql modules", "main": "main.js", "module": "index.js", diff --git a/packages/constants/prop.js b/packages/constants/prop.js index e8c798e947be04fbcf98794f813781dbde87b78a..645e5eb1eedc00980a630fc296066554a9964fdb 100644 --- a/packages/constants/prop.js +++ b/packages/constants/prop.js @@ -117,5 +117,6 @@ export const ENABLE_CACHE_RESOLVER_PROP_KEY = 'enableCacheResolver' export const TOKEN_DELIVER_LOCATION_PROP_KEY = 'tokenDeliverLocation' export const COOKIE_PROP_KEY = 'cookie' - +// for tracking the login and connect state for socket client +export const IS_READY_PROP_KEY = 'isReady' export const IS_LOGIN_PROP_KEY = 'isLogin' \ No newline at end of file diff --git a/packages/ws-client-core/package.json b/packages/ws-client-core/package.json index 90f2ef0dc0c6f30253aec9efa076496e9c74ebfa..d3297f58a9b86d1d16a460da5ea8b6220de94f10 100644 --- a/packages/ws-client-core/package.json +++ b/packages/ws-client-core/package.json @@ -58,7 +58,7 @@ "dependencies": { "@jsonql/security": "^1.0.1", "@to1source/event": "^1.3.0", - "jsonql-constants": "^2.1.1", + "jsonql-constants": "^2.1.2", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.3", "jsonql-utils": "^1.2.7" diff --git a/packages/ws-client-core/src/auth/index.js b/packages/ws-client-core/src/auth/index.js index 1fb7ddf255031beb98146460cae08cd50b04d270..1608f5246e1178885b30423d8474e47831f78991 100644 --- a/packages/ws-client-core/src/auth/index.js +++ b/packages/ws-client-core/src/auth/index.js @@ -1,2 +1,6 @@ // when this is running standalone mode then we need to -// provide the extra methods for it to store and retrieve the userdata \ No newline at end of file +// provide the extra methods for it to store and retrieve the userdata + +import { setupAuthMethods } from './setup-auth-methods' + +export { setupAuthMethods } \ No newline at end of file diff --git a/packages/ws-client-core/src/callers/setup-auth-methods.js b/packages/ws-client-core/src/auth/setup-auth-methods.js similarity index 45% rename from packages/ws-client-core/src/callers/setup-auth-methods.js rename to packages/ws-client-core/src/auth/setup-auth-methods.js index 04d367476f81c1e73463bc8be4a8d38e466b291c..e88e3bdcc39bbe4330458146b34637251af2367c 100644 --- a/packages/ws-client-core/src/callers/setup-auth-methods.js +++ b/packages/ws-client-core/src/auth/setup-auth-methods.js @@ -2,36 +2,68 @@ import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, - ON_LOGIN_FN_NAME + ON_LOGIN_FN_NAME, + SOCKET_AUTH_NAME } from 'jsonql-constants' -import { JsonqlValidationError } from 'jsonql-errors' +import { JsonqlValidationError, finalCatch } from 'jsonql-errors' import { injectToFn, chainFns, isString, objDefineProps, isFunc } from '../utils' - +import { validateAsync } from 'jsonql-params-validator' /** * @UPDATE it might be better if we decoup the two http-client only emit a login event * Here should catch it and reload the ws client @TBC * break out from createAuthMethods to allow chaining call + * @TODO when this is using the standalone mode then this will have to be disable + * or delegated to the login method from the contract * @param {object} obj the main client object * @param {object} opts configuration * @param {object} ee event emitter * @return {array} [ obj, opts, ee ] what comes in what goes out */ const setupLoginHandler = (obj, opts, ee) => [ - injectToFn(obj, opts.loginHandlerName, function loginHandler(token) { - if (token && isString(token)) { - opts.log(`Received ${LOGIN_EVENT_NAME} with ${token}`) - // @TODO add the interceptor hook - return ee.$trigger(LOGIN_EVENT_NAME, [token]) + injectToFn( + obj, + opts.loginHandlerName, + function loginHandler(token) { + if (token && isString(token)) { + opts.log(`Received ${LOGIN_EVENT_NAME} with ${token}`) + // @TODO add the interceptor hook + return ee.$trigger(LOGIN_EVENT_NAME, [token]) + } + // should trigger a global error instead @TODO + throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`) } - // should trigger a global error instead @TODO - throw new JsonqlValidationError(opts.loginHandlerName, `Unexpected token ${token}`) - }), + ), opts, ee ] +/** + * Switch to this one when standalone mode is enable + * @param {*} obj + * @param {*} opts + * @param {*} ee + */ +const setupStandaloneLoginHandler = (obj, opts, ee) => { + /* + we don't actually have this because the public contract not included it + so we need to figure out a different way to include the auth method + that get expose to the public before we can continue with this standalone mode + const { contract, loginHandlerName } = opts + const params = contract[SOCKET_AUTH_NAME][loginHandlerName] + */ + return [ + injectToFn( + obj, + loginHandlerName, + function standaloneLoginHandler(...args) { + } + ), + opts, + ee + ] +} /** * break out from createAuthMethods to allow chaining call - final in chain * @param {object} obj the main client object @@ -40,9 +72,13 @@ const setupLoginHandler = (obj, opts, ee) => [ * @return {array} [ obj, opts, ee ] what comes in what goes out */ const setupLogoutHandler = (obj, opts, ee) => [ - injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) { - ee.$trigger(LOGOUT_EVENT_NAME, args) - }), + injectToFn( + obj, + opts.logoutHandlerName, + function logoutHandler(...args) { + ee.$trigger(LOGOUT_EVENT_NAME, args) + } + ), opts, ee ] @@ -55,15 +91,19 @@ const setupLogoutHandler = (obj, opts, ee) => [ * @param {object} ee Event Emitter * @return {array} [ obj, opts, ee] what comes in what goes out */ -const setupOnLoginhandler = (obj, opts, ee) => [ - objDefineProps(obj, ON_LOGIN_FN_NAME, function onLoginCallbackHandler(onLoginCallback) { - if (isFunc(onLoginCallback)) { - // only one callback can registered with it, TBC - // Should this be a $onlyOnce listener after the logout - // we add it back? - ee.$only(ON_LOGIN_FN_NAME, onLoginCallback) +const setupOnLoginListener = (obj, opts, ee) => [ + objDefineProps( + obj, + ON_LOGIN_FN_NAME, + function onLoginCallbackHandler(onLoginCallback) { + if (isFunc(onLoginCallback)) { + // only one callback can registered with it, TBC + // Should this be a $onlyOnce listener after the logout + // we add it back? + ee.$only(ON_LOGIN_FN_NAME, onLoginCallback) + } } - }), + ), opts, ee ] @@ -80,8 +120,8 @@ const setupOnLoginhandler = (obj, opts, ee) => [ */ export function setupAuthMethods(obj, opts, ee) { return chainFns( - setupLoginHandler, + setupLoginHandler, // @TODO need a switch here setupLogoutHandler, - setupOnLoginhandler + setupOnLoginListener )(obj, opts, ee) } diff --git a/packages/ws-client-core/src/callers/callers-generator.js b/packages/ws-client-core/src/callers/callers-generator.js index 641d83acbdf43b75949def6ed2b02461e3063337..4649bd5540211b7cf100b559e8b1e3a9452e0899 100644 --- a/packages/ws-client-core/src/callers/callers-generator.js +++ b/packages/ws-client-core/src/callers/callers-generator.js @@ -8,9 +8,9 @@ import { generateResolvers } from './generator-methods' import { setupOnReadyListener, setupNamespaceErrorListener -} from './global-listener' +} from '../listener/global-listeners' -import { setupAuthMethods } from './setup-auth-methods' +import { setupAuthMethods } from '../auth' import { setupFinalStep } from './setup-final-step' @@ -28,7 +28,6 @@ import { setupFinalStep } from './setup-final-step' */ export function callersGenerator(opts, nspMap, ee) { - let fns = [ generateResolvers, setupOnReadyListener, diff --git a/packages/ws-client-core/src/callers/setup-final-step.js b/packages/ws-client-core/src/callers/setup-final-step.js index 778aa05161efaaa451a07f9ddc868f7503466206..fa1ccc25d87483b6bd5e33c59433e34e73ab88a4 100644 --- a/packages/ws-client-core/src/callers/setup-final-step.js +++ b/packages/ws-client-core/src/callers/setup-final-step.js @@ -1,6 +1,12 @@ // The final step of the setup before it returns the client +import { + CONNECT_EVENT_NAME, + SUSPEND_EVENT_PROP_KEY, + IS_LOGIN_PROP_KEY +} from 'jsonql-constants' + import { setupInterCom } from './setup-intercom' -import { CONNECT_EVENT_NAME, SUSPEND_EVENT_PROP_KEY } from 'jsonql-constants' + import { injectToFn } from 'jsonql-utils' /** @@ -30,7 +36,7 @@ function setupFinalStep(obj, opts, ee) { } // just inject one more property to the client - return injectToFn(client, 'isLogin', false, true) + return injectToFn(client, IS_LOGIN_PROP_KEY, false, true) } diff --git a/packages/ws-client-core/src/callers/global-listener.js b/packages/ws-client-core/src/listener/global-listeners.js similarity index 100% rename from packages/ws-client-core/src/callers/global-listener.js rename to packages/ws-client-core/src/listener/global-listeners.js diff --git a/packages/ws-client-core/src/options/index.js b/packages/ws-client-core/src/options/index.js index f18316b1a00bc527b65a459ccac0350b1d09c912..e453ec7626c8221d9af0df3b318cece34b9bcc0a 100644 --- a/packages/ws-client-core/src/options/index.js +++ b/packages/ws-client-core/src/options/index.js @@ -17,7 +17,9 @@ import { } from '../utils' import { - SUSPEND_EVENT_PROP_KEY + SUSPEND_EVENT_PROP_KEY, + ON_RESULT_FN_NAME, + ON_LOGIN_FN_NAME } from 'jsonql-constants' /** @@ -101,15 +103,35 @@ function createRequiredParams(opts) { const ee = opts.eventEmitter // @TODO here we are going to add suspend event to the namespace related methods const { log } = opts - const { namespaces } = nspMap + const { namespaces, publicNamespace } = nspMap log(`namespaces`, namespaces) // next we loop the namespace and suspend all the events prefix with namespace if (opts[SUSPEND_EVENT_PROP_KEY] === true) { + // ON_READY_FN_NAME + // ON_LOGIN_FN_NAME + // we create this as a function then we can call it again - opts.$suspendNamepsace = () => namespaces.forEach(namespace => ee.$suspendEvent(namespace)) + // @TODO we need to add the onReady and the onLogin in the suspend list as well + opts.$suspendNamepsace = () => { + let eventNames = [ON_RESULT_FN_NAME, ...namespaces] + if (opts.enableAuth) { + eventNames.push(ON_LOGIN_FN_NAME) + } + // [ON_READY_FN_NAME, ON_LOGIN_FN_NAME, ...namespaces] + Reflect.apply(ee.$suspendEvent, ee, eventNames) + } // then we create a new method to releas the queue // we prefix it with the $ to notify this is not a jsonql part methods - opts.$releaseNamespace = () => ee.$release() + opts.$releaseNamespace = () => { + ee.$releaseEvent(ON_RESULT_FN_NAME, publicNamespace) + } + + if (opts.enableAuth) { + opts.$releasePrivateNamespace = () => { + ee.$releaseEvent(ON_LOGIN_FN_NAME, namespaces[1]) + } + } + // now run it opts.$suspendNamepsace() }