From fe8e802cbd8dae56961b33a92b92a2443d1fd23a Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 14:12:48 +0800 Subject: [PATCH 1/8] adding empty api for future development --- packages/@jsonql/client/ng/README.md | 4 ++++ packages/@jsonql/client/package.json | 4 ++-- packages/@jsonql/client/preact/index.js | 1 + packages/@jsonql/client/riot/index.js | 1 + 4 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 packages/@jsonql/client/ng/README.md create mode 100644 packages/@jsonql/client/preact/index.js create mode 100644 packages/@jsonql/client/riot/index.js diff --git a/packages/@jsonql/client/ng/README.md b/packages/@jsonql/client/ng/README.md new file mode 100644 index 00000000..e3dfb1e3 --- /dev/null +++ b/packages/@jsonql/client/ng/README.md @@ -0,0 +1,4 @@ +# jsonql for Angular API + +Since Angular comes with it's own library, we need to figure out a different way +to build an Angular port without the original jsonql-client diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index 08a8b07a..79ce0dfe 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -46,7 +46,7 @@ "license": "MIT", "dependencies": { "flyio": "^0.6.14", - "jsonql-client": "^1.4.12" + "jsonql-client": "^1.5.1" }, "optionalDependencies": { "@jsonql/ws": "^0.8.5" @@ -62,7 +62,7 @@ "nyc": "^14.1.1", "promise-polyfill": "8.1.3", "qunit": "^2.9.3", - "rollup": "^1.27.8", + "rollup": "^1.27.9", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-analyzer": "^3.2.2", "rollup-plugin-async": "^1.2.0", diff --git a/packages/@jsonql/client/preact/index.js b/packages/@jsonql/client/preact/index.js new file mode 100644 index 00000000..504a5f2b --- /dev/null +++ b/packages/@jsonql/client/preact/index.js @@ -0,0 +1 @@ +// for preact.js api diff --git a/packages/@jsonql/client/riot/index.js b/packages/@jsonql/client/riot/index.js new file mode 100644 index 00000000..cd0db6d5 --- /dev/null +++ b/packages/@jsonql/client/riot/index.js @@ -0,0 +1 @@ +// for riot.js api -- Gitee From b589ca8a9ae6fe15b255b9dfd52807f56db6357f Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 14:34:50 +0800 Subject: [PATCH 2/8] add new build jsonqlStores --- .../client/dist/jsonql-client-ws.debug.js | 8397 ++++++++++------- .../client/dist/jsonql-client-ws.debug.js.map | 2 +- .../@jsonql/client/dist/jsonql-client-ws.js | 2 +- .../client/dist/jsonql-client-ws.js.map | 2 +- packages/http-client/package.json | 1 + packages/http-client/rollup.config.js | 5 +- 6 files changed, 4776 insertions(+), 3633 deletions(-) diff --git a/packages/@jsonql/client/dist/jsonql-client-ws.debug.js b/packages/@jsonql/client/dist/jsonql-client-ws.debug.js index 46fd15d3..c2c263df 100644 --- a/packages/@jsonql/client/dist/jsonql-client-ws.debug.js +++ b/packages/@jsonql/client/dist/jsonql-client-ws.debug.js @@ -27,6 +27,9 @@ var QUERY_NAME = 'query'; var MUTATION_NAME = 'mutation'; var SOCKET_NAME = 'socket'; + // for calling the mutation + var PAYLOAD_PARAM_NAME = 'payload'; // @TODO shortern them + var CONDITION_PARAM_NAME = 'condition'; var QUERY_ARG_NAME = 'args'; var TIMESTAMP_PARAM_NAME = 'TS'; // new jsonp @@ -52,9 +55,9 @@ var BEARER = 'Bearer'; // for client use @TODO need to clean this up some of them are not in use - var CREDENTIAL_STORAGE_KEY = 'credential'; - var CLIENT_STORAGE_KEY = 'storageKey'; - var CLIENT_AUTH_KEY = 'authKey'; + var CREDENTIAL_STORAGE_KEY = 'jsonqlcredential'; + var CLIENT_STORAGE_KEY = 'jsonqlstore'; + var CLIENT_AUTH_KEY = 'jsonqlauthkey'; // contract key var CONTRACT_KEY_NAME = 'X-JSONQL-CV-KEY'; var SHOW_CONTRACT_DESC_PARAM = {desc: 'y'}; @@ -72,43 +75,7 @@ var NO_ERROR_MSG = 'No message'; var NO_STATUS_CODE = -1; - var LOGIN_EVENT_NAME = '__login__'; - var LOGOUT_EVENT_NAME = '__logout__'; - - // for ws servers - var WS_REPLY_TYPE = '__reply__'; - var WS_EVT_NAME = '__event__'; - var WS_DATA_NAME = '__data__'; - var EMIT_REPLY_TYPE = 'emit'; - var ACKNOWLEDGE_REPLY_TYPE = 'acknowledge'; - var ERROR_TYPE = 'error'; - - var NSP_SET = 'nspSet'; - var PUBLIC_NAMESPACE = 'publicNamespace'; - - var JS_WS_SOCKET_IO_NAME = 'socket.io'; - var JS_WS_NAME = 'ws'; - - // for ws client - var ON_MESSAGE_PROP_NAME$1 = 'onMessage'; - var ON_RESULT_PROP_NAME$1 = 'onResult'; - var ON_ERROR_PROP_NAME$1 = 'onError'; - var ON_READY_PROP_NAME = 'onReady'; - var ON_LOGIN_PROP_NAME = 'onLogin'; // new @1.8.6 - - var SEND_MSG_PROP_NAME = 'send'; - // breaking change from 1.8.8 the above name was the name below - // the names are using in the new resolver.on getter interface - var MESSAGE_PROP_NAME = 'message'; - var RESULT_PROP_NAME = 'result'; - var ERROR_PROP_NAME = 'error'; - var READY_PROP_NAME$1 = 'ready'; - var LOGIN_PROP_NAME = 'login'; // new @1.8.6 - var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; var HSA_ALGO = 'HS256'; - var TOKEN_PARAM_NAME = 'token'; - var IO_ROUNDTRIP_LOGIN = 'roundtip'; - var IO_HANDSHAKE_LOGIN = 'handshake'; /** * This is a custom error to throw when server throw a 406 @@ -664,25 +631,29 @@ } /** - * Checks if `value` is `null`. + * 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 `null`, else `false`. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * - * _.isNull(null); + * _.isArray([1, 2, 3]); * // => true * - * _.isNull(void 0); + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); * // => false */ - function isNull(value) { - return value === null; - } + var isArray = Array.isArray; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : @@ -700,51 +671,6 @@ /** Built-in value references. */ var Symbol = root.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(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 = Array.isArray; - /** Used for built-in method references. */ var objectProto = Object.prototype; @@ -832,6 +758,23 @@ : 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". @@ -861,96 +804,359 @@ } /** `Object#toString` result references. */ - var symbolTag = '[object Symbol]'; + 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 classified as a `Symbol` primitive or 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 4.0.0 + * @since 0.8.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * - * _.isSymbol(Symbol.iterator); - * // => true + * function Foo() { + * this.a = 1; + * } * - * _.isSymbol('abc'); + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + 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; } - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0; + // bunch of generic helpers - /** 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. + * DIY in Array + * @param {array} arr to check from + * @param {*} value to check against + * @return {boolean} true on found */ - 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; - } + 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]; }; /** - * 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`. + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success */ - 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; + var isObjectHasKey$1 = 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; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + }; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; + // 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$1(contract, QUERY_NAME) + || isObjectHasKey$1(contract, MUTATION_NAME) + || isObjectHasKey$1(contract, SOCKET_NAME) + ) } /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. + * 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; + } + + /** + * 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) + } + + // take only the module part which is what we use here + /** + * @param {object} jsonqlInstance the init instance of jsonql client + * @param {object} contract the static contract + * @return {object} contract may be from server + */ + var getContractFromConfig = function(jsonqlInstance, contract) { + if ( contract === void 0 ) contract = {}; + + if (isContract(contract)) { + return Promise.resolve(contract) + } + return jsonqlInstance.getContract() + }; + // wrapper method to make sure it's a string + var hashCode$1 = function (str) { return hashCode(str) + ''; }; + var USERDATA_TABLE = 'userdata'; + var CLS_LOCAL_STORE_NAME = 'localStore'; + var CLS_SESS_STORE_NAME = 'sessionStore'; + var CLS_CONTRACT_NAME = 'contract'; + var CLS_PROFILE_IDX = 'prof_idx'; + var ZERO_IDX = 0; + + /** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + + InvalidCharacterError.prototype = new Error(); + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + function polyfill (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, buffer, idx = 0, output = ''; + // 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 += 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; + } + + + var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + + function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + })); + } + + var base64_url_decode = function(str) { + var output = str.replace(/-/g, "+").replace(/_/g, "/"); + switch (output.length % 4) { + case 0: + break; + case 2: + output += "=="; + break; + case 3: + output += "="; + break; + default: + throw "Illegal base64url string!"; + } + + try{ + return b64DecodeUnicode(output); + } catch (err) { + return atob(output); + } + }; + + function InvalidTokenError(message) { + this.message = message; + } + + InvalidTokenError.prototype = new Error(); + InvalidTokenError.prototype.name = 'InvalidTokenError'; + + var lib = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } + + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } + }; + + var InvalidTokenError_1 = InvalidTokenError; + lib.InvalidTokenError = InvalidTokenError_1; + + /** + * 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. @@ -1219,52 +1425,93 @@ return castSlice(strSymbols, start, end).join(''); } + /** `Object#toString` result references. */ + var stringTag = '[object String]'; + /** - * Checks if `value` is `undefined`. + * 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 `undefined`, else `false`. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * - * _.isUndefined(void 0); + * _.isString('abc'); * // => true * - * _.isUndefined(null); + * _.isString(1); * // => false */ - function isUndefined(value) { - return value === undefined; + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } - /** `Object#toString` result references. */ - var boolTag = '[object Boolean]'; - + // validate string type /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false + * @param {string} value expected value + * @return {boolean} true if OK */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + var checkIsString = function(value) { + return (trim(value) !== '') ? isString(value) : false; + }; + + // when the user is login with the jwt + + var timestamp = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + /** + * We only check the nbf and exp + * @param {object} token for checking + * @return {object} token on success + */ + function validate(token) { + var start = token.iat || timestamp(true); + // we only check the exp for the time being + if (token.exp) { + if (start >= token.exp) { + var expired = new Date(token.exp).toISOString(); + throw new JsonqlError(("Token has expired on " + expired), token) + } + } + return token; + } + + /** + * The browser client version it has far fewer options and it doesn't verify it + * because it couldn't this is the job for the server + * @TODO we need to add some extra proessing here to check for the exp field + * @param {string} token to decrypted + * @return {object} decrypted object + */ + function jwtDecode(token) { + if (checkIsString(token)) { + var t = lib(token); + return validate(t) + } + throw new JsonqlError('Token must be a string!') } + /** + * 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 = '[object Number]'; @@ -1334,131 +1581,179 @@ return isNumber(value) && value != +value; } - /** `Object#toString` result references. */ - var stringTag = '[object String]'; + // 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) ) + }; + + // check for boolean /** - * 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 + * @param {boolean} value expected + * @return {boolean} true if OK */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } + var checkIsBoolean = function(value) { + return value !== null && value !== undefined && typeof value === 'boolean' + }; + + // validate any thing only check if there is something /** - * 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. + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } + var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); + if (value !== undefined && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && value !== null)) { + return true; + } + } + return false; + }; - /** `Object#toString` result references. */ - var objectTag = '[object Object]'; + // Good practice rule - No magic number - /** Used for built-in method references. */ - var funcProto = Function.prototype, - objectProto$2 = Object.prototype; + 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!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$1 = DEFAULT_TYPE; + var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; + var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; + var TYPE_KEY$1 = TYPE_KEY; + var OPTIONAL_KEY$1 = OPTIONAL_KEY; + var ENUM_KEY$1 = ENUM_KEY; + var ARGS_KEY$1 = ARGS_KEY; + var CHECKER_KEY$1 = CHECKER_KEY; + var ALIAS_KEY$1 = ALIAS_KEY; - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + var ARRAY_TYPE$1 = ARRAY_TYPE; + var OBJECT_TYPE$1 = OBJECT_TYPE; + var STRING_TYPE$1 = STRING_TYPE; + var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; + var NUMBER_TYPE$1 = NUMBER_TYPE; + var KEY_WORD$1 = KEY_WORD; + var OR_SEPERATOR$1 = OR_SEPERATOR; - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + + // primitive types /** - * 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 + * 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 */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; + var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; } - var Ctor = hasOwnProperty$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } + }; + + // validate array type /** - * 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. + * @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 */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; + 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 result; - } + return false; + }; /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ + var isArrayLike = 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) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + 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; + }; + + /** + * 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; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. @@ -1671,7 +1966,7 @@ /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', - boolTag$1 = '[object Boolean]', + boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', @@ -1703,7 +1998,7 @@ typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag$1] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = @@ -1960,7 +2255,7 @@ * _.isArrayLike(_.noop); * // => false */ - function isArrayLike(value) { + function isArrayLike$1(value) { return value != null && isLength(value.length) && !isFunction(value); } @@ -1993,7 +2288,7 @@ * // => ['0', '1'] */ function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); } /** @@ -2860,7 +3155,7 @@ COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ - var boolTag$2 = '[object Boolean]', + var boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', errorTag$1 = '[object Error]', mapTag$1 = '[object Map]', @@ -2911,7 +3206,7 @@ } return true; - case boolTag$2: + case boolTag$1: case dateTag$1: case numberTag$2: // Coerce booleans to `1` or `0` and dates to milliseconds. @@ -3843,263 +4138,515 @@ return property(value); } - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - + // validate object type /** - * 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. + * @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 */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } + var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; - /** - * 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); + 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(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; + } } - } - - /** 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; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + return false; + }; /** - * 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. + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); + 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); } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + // just simple check + return Reflect.apply(checkIsObject, null, _args) + }; - buffer.copy(result); - return result; - } + // 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 /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. + * 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 */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); - return result; - } + 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; + }; /** - * 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. + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } + var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // 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(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } + }; /** - * 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`. + * 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 */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; + var getOptionalValue = function(arg, param) { + if (arg !== undefined) { + return arg; } - return array; - } - - /** Built-in value references. */ - var objectCreate = Object.create; + return (param.optional === true && param.defaultvalue !== undefined ? param.defaultvalue : null) + }; /** - * 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. + * 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 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; - }; - }()); + 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 JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(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$1 ]; + // 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(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 /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } + var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; /** - * 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 + * 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 */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } + 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 ) + }; /** - * 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. + * 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 */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } + var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; + 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([]) + }) + }; - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); /** - * 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. + * 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 assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$a.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; } } /** - * Copies properties of `source` to `object`. + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * * @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`. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } - var index = -1, - length = props.length; + /** Detect free variable `exports`. */ + var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - while (++index < length) { - var key = props[index]; + /** Detect free variable `module`. */ + var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - var newValue = customizer + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + + /** Built-in value references. */ + var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.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; + } + + /** + * 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$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(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; + }; + }()); + + /** + * 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)) + : {}; + } + + /** + * 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$1(value); + } + + /** + * 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$d = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.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$a.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; @@ -4186,7 +4733,7 @@ * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** @@ -4496,7 +5043,7 @@ } var type = typeof index; if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) + ? (isArrayLike$1(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); @@ -4925,835 +5472,415 @@ } /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - - function notEmpty (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a check if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN$1( parseFloat(value) ) + var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; }; - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false; + var isObjectHasKey$2 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) }; - // check for boolean - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return isBoolean(value); - }; + // just not to make my head hurt + var isEmpty = function (value) { return !isNotEmpty(value); }; - // 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 + * 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 */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (!isUndefined(value) && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && !isNull(value))) { - return true; - } + 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$1]; } ); + if (isEqual(aliasMap, {})) { + return config; } - return false; - }; + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } - // Good practice rule - No magic number + /** + * 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$2(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$2(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } + } - 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!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + /** + * 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; - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; + return ( + config[key] === undefined || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) + } - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; + /** + * 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 + ] + } - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + // breaking the whole thing up to see what cause the multiple calls issue - // primitive types + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') /** - * 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 + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; + var toArray$1 = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - // validate array type + /** + * 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 + ); }; /** - * @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 + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; + function validateHandler$1(value, cb) { + var obj; - 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; - }; + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray$1(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array + * 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 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) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] + var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray$1(enumv, value) } - return false; + return true; }; /** - * 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 + * 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 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; + var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; } - // 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 + * 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 */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; + function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] } - 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 (!isUndefined(_value)) { - 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; + var check = validateHandler$1(value, cb); + if (check.length) { + // log('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + // log(ENUM_KEY, value[ENUM_KEY]) + throw new JsonqlEnumError(key) } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + // log(CHECKER_KEY, value[CHECKER_KEY]) + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] } - 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 checkIsObject.apply(null, _args) - }; - - /** - * just a simple util for helping to debug - * @param {array} args arguments - * @return {void} + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values */ - function log() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - try { - if (window && window.console) { - Reflect.apply(console.log, console, args); - } - } catch(e) {} + 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) } - // move the index.js code here that make more sense to find where things are + /// this is port back from the client to share across all projects + // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places + // const debugFn = debug('jsonql-params-validator:check-options-async') /** - * 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 + * Quick transform + * @param {object} config that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (notEmpty(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; + var configToArgs = function (config, appProps) { + return Promise.resolve( + prepareArgsForValidation(config, appProps) + ) }; /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK + * @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 */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // 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) - } - }; + 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); }) + } + + // this is port back from the client to share across all projects /** - * 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 + * @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 */ - var getOptionalValue = function(arg, param) { - if (!isUndefined(arg)) { - return arg; - } - return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null) - }; + function checkOptionsSync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return merge( + runValidation( + prepareArgsForValidation(config, appProps), + cb + ), + constProps + ) + } + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); /** - * 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 + * @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 */ - 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 JsonqlError(PARAMS_NOT_ARRAY_ERR) + 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 (params.length === 0) { - return []; + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - log(1); - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }) - case params[0].variable === true: // using spread syntax - log(2); - 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: - log(3); - 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: - log(4); - var ctn = params.length; - // this happens when we have those array. type - var _type = [ DEFAULT_TYPE$1 ]; - // 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 - log(5); - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + if (isString(alias)) { + base[ALIAS_KEY] = alias; } - }; + return base; + } - // 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; }); }; + // export also create wrapper methods /** - * 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 + * 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 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; + var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; - 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([]) - }) + // 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]) }; /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs + * 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 */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; + var checkConfigAsync = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps= {}; - var isObjectHasKey$1 = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) + return checkOptionsAsync(config, appProps, constantProps, validateSync) + } }; - // just not to make my head hurt - var isEmpty = function (value) { return !notEmpty(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$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } + // copy of above but it's sync + var checkConfig = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps = {}; - /** - * 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 + return checkOptionsSync(config, appProps, constantProps, validateSync) } - } + }; - /** - * 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; + // export + var isString$1 = checkIsString; + var isNumber$1 = checkIsNumber; + var validateAsync$1 = validateAsync; - return ( - isUndefined(config[key]) || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } + var createConfig$1 = createConfig; - /** - * 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 - ] - } + var checkConfigAsync$1 = checkConfigAsync(validateSync); + var checkConfig$1 = checkConfig(validateSync); - // breaking the whole thing up to see what cause the multiple calls issue + var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') + var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), + 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 )) + }; /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output + * @param {boolean} sec return in second or not + * @return {number} timestamp */ - var toArray = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + var timestamp$1 = function (sec) { + if ( sec === void 0 ) sec = false; - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; - /** - * 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; + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; } - /** - * 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(enumv, value) - } - return true; - }; + var assign = make_assign(); + var create = make_create(); + var trim$1 = make_trim(); + var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - /** - * 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$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - log('runValidationAction', key, value); - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - log(ENUM_KEY$1, value[ENUM_KEY$1]); - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - log(CHECKER_KEY$1, value[CHECKER_KEY$1]); - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @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) { - // debugFn('args', args1) - return runValidation(args1, cb) - }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) - } - - // this is port back from the client to share across all projects - - /** - * @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 checkOptionsSync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return merge( - runValidation( - prepareArgsForValidation(config, appProps), - cb - ), - constProps - ) - } - - // create function to construct the config entry so we don't need to keep building object - // 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 - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:index'); - - /** - * 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]) - }; - - /** - * 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 - */ - var checkConfigAsync = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } - }; - - // copy of above but it's sync - var checkConfig = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps = {}; - - return checkOptionsSync(config, appProps, constantProps, validateSync) - } - }; - - // export - var isString$1 = checkIsString; - var isArray$1 = checkIsArray; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - - var checkConfigAsync$1 = checkConfigAsync(validateSync); - var checkConfig$1 = checkConfig(validateSync); - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var assign = make_assign(); - var create = make_create(); - var trim$1 = make_trim(); - var Global = (typeof window !== 'undefined' ? window : commonjsGlobal); - - var util = { - assign: assign, - create: create, - trim: trim$1, - bind: bind, - slice: slice, - each: each, - map: map, - pluck: pluck, - isList: isList, - isFunction: isFunction$1, - isObject: isObject$1, - Global: Global + var util = { + assign: assign, + create: create, + trim: trim$1, + bind: bind, + slice: slice, + each: each, + map: map, + pluck: pluck, + isList: isList, + isFunction: isFunction$1, + isObject: isObject$1, + Global: Global }; function make_assign() { @@ -6214,66 +6341,6 @@ } } - var namespace = 'expire_mixin'; - - var expire = expirePlugin; - - function expirePlugin() { - var expirations = this.createStore(this.storage, null, this._namespacePrefix+namespace); - - return { - set: expire_set, - get: expire_get, - remove: expire_remove, - getExpiration: getExpiration, - removeExpiredKeys: removeExpiredKeys - } - - function expire_set(super_fn, key, val, expiration) { - if (!this.hasNamespace(namespace)) { - expirations.set(key, expiration); - } - return super_fn() - } - - function expire_get(super_fn, key) { - if (!this.hasNamespace(namespace)) { - _checkExpiration.call(this, key); - } - return super_fn() - } - - function expire_remove(super_fn, key) { - if (!this.hasNamespace(namespace)) { - expirations.remove(key); - } - return super_fn() - } - - function getExpiration(_, key) { - return expirations.get(key) - } - - function removeExpiredKeys(_) { - var keys = []; - this.each(function(val, key) { - keys.push(key); - }); - for (var i=0; i true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false + * @param {*} args arguments to send + *@return {object} formatted payload */ - var isArray$2 = Array.isArray; - - var global$1$1 = (typeof global$1 !== "undefined" ? global$1 : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - /** Detect free variable `global` from Node.js. */ - var freeGlobal$1 = typeof global$1$1 == 'object' && global$1$1 && global$1$1.Object === Object && global$1$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; - - /** Used for built-in method references. */ - var objectProto$f = Object.prototype; + var formatPayload = function (args) { + var obj; - /** Used to check objects for own properties. */ - var hasOwnProperty$c = objectProto$f.hasOwnProperty; + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) + ); + }; /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name */ - var nativeObjectToString$2 = objectProto$f.toString; - - /** Built-in value references. */ - var symToStringTag$2 = Symbol$1 ? Symbol$1.toStringTag : undefined; + function getNameFromPayload(payload) { + return Object.keys(payload)[0] + } /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable */ - 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) {} + function createDeliverable(resolverName, payload) { + var obj; - var result = nativeObjectToString$2.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$2] = tag; - } else { - delete value[symToStringTag$2]; - } - } - return result; + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$1() ], obj ) } - /** Used for built-in method references. */ - var objectProto$1$1 = Object.prototype; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. + * @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 */ - var nativeObjectToString$1$1 = objectProto$1$1.toString; + function createQuery(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; - /** - * 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$1$1.call(value); + if (isString(resolverName) && isArray(args)) { + var payload = formatPayload(args); + if (jsonp === true) { + return payload; + } + return createDeliverable(resolverName, payload) + } + throw new JsonqlValidationError$1("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) } - /** `Object#toString` result references. */ - var nullTag$1 = '[object Null]', - undefinedTag$1 = '[object Undefined]'; - - /** Built-in value references. */ - var symToStringTag$1$1 = 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`. + * @param {string} resolverName name of function + * @param {*} payload to send + * @param {object} [condition={}] for what + * @param {boolean} [jsonp = false] add v1.3.0 to koa + * @return {object} formatted argument */ - function baseGetTag$1(value) { - if (value == null) { - return value === undefined ? undefinedTag$1 : nullTag$1; + function createMutation(resolverName, payload, condition, jsonp) { + if ( condition === void 0 ) condition = {}; + if ( jsonp === void 0 ) jsonp = false; + + var _payload = {}; + _payload[PAYLOAD_PARAM_NAME] = payload; + _payload[CONDITION_PARAM_NAME] = condition; + if (jsonp === true) { + return _payload; + } + if (isString(resolverName)) { + return createDeliverable(resolverName, _payload) } - return (symToStringTag$1$1 && symToStringTag$1$1 in Object(value)) - ? getRawTag$1(value) - : objectToString$1(value); + throw new JsonqlValidationError$1("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) } /** - * 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. + * @return {object} _cb as key with timestamp */ - function overArg$1(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } + var cacheBurst = function () { return ({ _cb: timestamp$1() }); }; - /** Built-in value references. */ - var getPrototype$1 = overArg$1(Object.getPrototypeOf, Object); + // break up from node-middleware + + // ported from http-client /** - * 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 + * handle the return data + * @TODO how to handle the return timestamp and calculate the diff? + * @param {object} result return from server + * @return {object} strip the data part out, or if the error is presented */ - function isObjectLike$1(value) { - return value != null && typeof value == 'object'; - } - - /** `Object#toString` result references. */ - var objectTag$4 = '[object Object]'; + var resultHandler = function (result) { return ( + (isObjectHasKey$1(result, DATA_KEY) && !isObjectHasKey$1(result, ERROR_KEY)) ? result[DATA_KEY] : result + ); }; - /** Used for built-in method references. */ - var funcProto$3 = Function.prototype, - objectProto$2$1 = Object.prototype; + // new 1.5.0 - /** Used to resolve the decompiled source of functions. */ - var funcToString$3 = funcProto$3.toString; + // this becomes the base class instead of the HttpCls + var StoreClass = function StoreClass(opts) { + this.opts = opts; + // make it a string + this.instanceKey = hashCode$1(this.opts.hostname); + // pass this store for use later + this.localStore = localStore$1; + this.sessionStore = sessionStore$1; + /* + if (this.opts.debugOn) { // reuse this to clear out the data + this.log('clear all stores') + localStore.clearAll() + sessionStore.clearAll() - /** Used to check objects for own properties. */ - var hasOwnProperty$1$1 = objectProto$2$1.hasOwnProperty; + localStore.set('TEST', Date.now()) + sessionStore.set('TEST', Date.now()) + } + */ + }; - /** Used to infer the `Object` constructor. */ - var objectCtorString$1 = funcToString$3.call(Object); + var prototypeAccessors = { lset: { configurable: true },lget: { configurable: true },sset: { configurable: true },sget: { configurable: true } }; + // store in local storage id by the instanceKey + // values should be an object so with key so we just merge + // into the existing store without going through the keys + StoreClass.prototype.__setMethod = function __setMethod (storeType, values) { + var obj; - /** - * 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 store = this[storeType]; + var data = this.__getMethod(storeType); + var skey = this.opts.storageKey; + var ikey = this.instanceKey; + store.set(skey, ( obj = {}, obj[ikey] = data ? merge({}, data, values) : values, obj )); + }; + // return the data id by the instaceKey + StoreClass.prototype.__getMethod = function __getMethod (storeType) { + var store = this[storeType]; + var data = store.get(this.opts.storageKey); + return data ? data[this.instanceKey] : false + }; + // remove from local store id by instanceKey + StoreClass.prototype.__delMethod = function __delMethod (storeType, key) { + var data = this.__getMethod(storeType); + if (data) { + var store = {}; + for (var k in data) { + if (k !== key) { + store[k] = data[k]; + } + } + this.__setMethod(storeType, store); } - var proto = getPrototype$1(value); - if (proto === null) { - return true; + }; + // clear everything by this instanceKey + StoreClass.prototype.__clearMethod = function __clearMethod (storeKey) { + var skey = this.opts.storageKey; + var store = this[storeKey]; + var data = store.get(skey); + if (data) { + var _store = {}; + for (var k in data) { + if (k !== this.instanceKey) { + _store[k] = data[k]; + } + } + store.set(skey, _store); } - var Ctor = hasOwnProperty$1$1.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$3.call(Ctor) == objectCtorString$1; - } - - /** 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; + }; + // Alias for different store + prototypeAccessors.lset.set = function (values) { + return this.__setMethod(CLS_LOCAL_STORE_NAME, values) + }; - /** `Object#toString` result references. */ - var stringTag$3 = '[object String]'; + prototypeAccessors.lget.get = function () { + return this.__getMethod(CLS_LOCAL_STORE_NAME) + }; - /** - * 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$2(value) { - return typeof value == 'string' || - (!isArray$2(value) && isObjectLike$1(value) && baseGetTag$1(value) == stringTag$3); - } + StoreClass.prototype.ldel = function ldel (key) { + return this.__delMethod(CLS_LOCAL_STORE_NAME, key) + }; - // bunch of generic helpers + StoreClass.prototype.lclear = function lclear () { + return this.__clearMethod(CLS_LOCAL_STORE_NAME) + }; - /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found - */ - var inArray$1 = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + // store in session store id by the instanceKey + prototypeAccessors.sset.set = function (values) { + // this.log('--- sset ---', values) + return this.__setMethod(CLS_SESS_STORE_NAME, values) + }; - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var isObjectHasKey$2 = function(obj, key) { - var keys = Object.keys(obj); - return inArray$1(keys, key) + prototypeAccessors.sget.get = function () { + return this.__getMethod(CLS_SESS_STORE_NAME) }; - /** - * @param {boolean} sec return in second or not - * @return {number} timestamp - */ - var timestamp = function (sec) { - if ( sec === void 0 ) { sec = false; } + StoreClass.prototype.sdel = function sdel (key) { + return this.__delMethod(CLS_SESS_STORE_NAME, key) + }; - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; + StoreClass.prototype.sclear = function sclear () { + return this.__clearMethod(CLS_SESS_STORE_NAME) }; - /** - * @return {object} _cb as key with timestamp - */ - var cacheBurst = function () { return ({ _cb: timestamp() }); }; + Object.defineProperties( StoreClass.prototype, prototypeAccessors ); - // the core stuff to id if it's calling with jsonql - var DATA_KEY$1 = 'data'; - var ERROR_KEY$1 = 'error'; + // base HttpClass - // @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$1 = 'query'; - var MUTATION_NAME$1 = 'mutation'; - var SOCKET_NAME$1 = 'socket'; - // for calling the mutation - var PAYLOAD_PARAM_NAME = 'payload'; - var CONDITION_PARAM_NAME = 'condition'; - var QUERY_ARG_NAME$1 = 'args'; + // extract the one we need + var POST = API_REQUEST_METHODS[0]; + var PUT = API_REQUEST_METHODS[1]; - /** - * some time it's hard to tell where the error is throw from - * because client server throw the same, therefore this util fn - * to add a property to the error object to tell if it's throw - * from client or server - * - */ + var HttpClass = /*@__PURE__*/(function (StoreClass) { + function HttpClass(opts) { + StoreClass.call(this, opts); + // change the way how we init Fly + // flyio now become external depedencies and it makes it easier to switch + // @BUG should we run test to check if we have the windows object? + // this.log(opts) + // this.fly = opts.Fly ? new opts.Fly() : new Fly() + // to a different environment like WeChat mini app + + this.extraHeader = {}; + // @1.2.1 for adding query to the call on the fly + this.extraParams = {}; + // this.log('start up opts', opts); + this.reqInterceptor(); + this.resInterceptor(); + } + + if ( StoreClass ) HttpClass.__proto__ = StoreClass; + HttpClass.prototype = Object.create( StoreClass && StoreClass.prototype ); + HttpClass.prototype.constructor = HttpClass; + + var prototypeAccessors = { headers: { configurable: true } }; + + // set headers for that one call + prototypeAccessors.headers.set = function (header) { + this.extraHeader = header; + }; - var isBrowser = function () { - try { - if (window || document) { - return true; - } - } catch(e) {} - return false; - }; + /** + * Create the reusage request method + * @param {object} payload jsonql payload + * @param {object} options extra options add the request + * @param {object} headers extra headers add to the call + * @return {object} the fly request instance + */ + HttpClass.prototype.request = function request (payload, options, headers) { + var obj; - var isNode = function () { - try { - if (!isBrowser() && global$1$1) { - return true; - } - } catch(e) {} - return false; - }; + if ( options === void 0 ) options = {}; + if ( headers === void 0 ) headers = {}; + this.headers = headers; + var params = merge({}, cacheBurst(), this.extraParams); + // @TODO need to add a jsonp url and payload + if (this.opts.enableJsonp) { + var resolverName = getNameFromPayload(payload); + params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); + payload = payload[resolverName]; + } + // double up the url param and see what happen @TODO remove later + var reqParams = merge({}, { method: POST, params: params }, options); + this.log('request params', reqParams, this.jsonqlEndpoint); + + return this.fly.request(this.jsonqlEndpoint, payload, reqParams) + }; - function whereAmI() { - if (isBrowser()) { - return 'browser' - } - if (isNode()) { - return 'node' - } - return 'unknown' - } + /** + * This will replace the create baseRequest method + * + */ + HttpClass.prototype.reqInterceptor = function reqInterceptor () { + var this$1 = this; - // The base Error of all + this.fly.interceptors.request.use( + function (req) { + var headers = this$1.getHeaders(); + this$1.log('request interceptor call', headers); - var JsonqlBaseError = /*@__PURE__*/(function (Error) { - function JsonqlBaseError() { - var arguments$1 = arguments; + for (var key in headers) { + req.headers[key] = headers[key]; + } + return req; + } + ); + }; - var args = [], len = arguments.length; - while ( len-- ) { args[ len ] = arguments$1[ len ]; } + // @TODO + HttpClass.prototype.processJsonp = function processJsonp (result) { + return resultHandler(result) + }; - Error.apply(this, args); - } + /** + * This will be replacement of the first then call + * + */ + HttpClass.prototype.resInterceptor = function resInterceptor () { + var this$1 = this; - if ( Error ) { JsonqlBaseError.__proto__ = Error; } - JsonqlBaseError.prototype = Object.create( Error && Error.prototype ); - JsonqlBaseError.prototype.constructor = JsonqlBaseError; + var self = this; + var jsonp = self.opts.enableJsonp; + this.fly.interceptors.response.use( + function (res) { + this$1.log('response interceptor call', res); + self.cleanUp(); + // now more processing here + // there is a problem if we throw the result.error here + // the original data is lost, so we need to do what we did before + // deal with that error in the first then instead + var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; + if (jsonp) { + return self.processJsonp(result) + } + return resultHandler(result) + }, + // this get call when it's not 200 + function (err) { + self.cleanUp(); + console.error(err); + throw new JsonqlServerError('Server side error', err) + } + ); + }; - JsonqlBaseError.where = function where () { - return whereAmI() + /** + * Get the headers inject into the call + * @return {object} headers + */ + HttpClass.prototype.getHeaders = function getHeaders () { + if (this.opts.enableAuth) { + return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + } + return merge({}, DEFAULT_HEADER, this.extraHeader) }; - return JsonqlBaseError; - }(Error)); + /** + * Post http call operation to clean up things we need + */ + HttpClass.prototype.cleanUp = function cleanUp () { + this.extraHeader = {}; + this.extraParams = {}; + }; - // custom validation error class - // when validaton failed - var JsonqlValidationError$2 = /*@__PURE__*/(function (JsonqlBaseError) { - function JsonqlValidationError() { - var arguments$1 = arguments; + /** + * GET for contract only + * @return {promise} resolve the contract + */ + HttpClass.prototype.getRemoteContract = function getRemoteContract () { + var this$1 = this; - var args = [], len = arguments.length; - while ( len-- ) { args[ len ] = arguments$1[ len ]; } + if (this.opts.showContractDesc) { + this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + } + return this.request({}, {method: 'GET'}, this.contractHeader) + .then(clientErrorsHandler) + .then(function (result) { + this$1.log('get contract result', result); + // when refresh the window the result is different! + // @TODO need to check the Koa side about why is that + // also it should set a flag if we want the description or not + if (result.cache && result.contract) { + return result.contract; + } + // just the normal result + return result + }) + .catch(function (err) { + console.error('getRemoteContract err', err); + throw new JsonqlServerError('getRemoteContract', err) + }) + }; - JsonqlBaseError.apply(this, args); + /** + * POST to server - query + * @param {object} name of the resolver + * @param {array} args arguments + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.query = function query (name, args) { + if ( args === void 0 ) args = []; - this.message = args[0]; - this.detail = args[1]; + return this.request(createQuery(name, args)) + .then(clientErrorsHandler) + }; - this.className = JsonqlValidationError.name; + /** + * PUT to server - mutation + * @param {string} name of resolver + * @param {object} payload what it said + * @param {object} conditions what it said + * @return {object} promise resolve to the resolver return + */ + HttpClass.prototype.mutation = function mutation (name, payload, conditions) { + if ( payload === void 0 ) payload = {}; + if ( conditions === void 0 ) conditions = {}; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } + return this.request(createMutation(name, payload, conditions), {method: PUT}) + .then(clientErrorsHandler) + }; - if ( JsonqlBaseError ) { JsonqlValidationError.__proto__ = JsonqlBaseError; } - JsonqlValidationError.prototype = Object.create( JsonqlBaseError && JsonqlBaseError.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; + Object.defineProperties( HttpClass.prototype, prototypeAccessors ); - var staticAccessors = { name: { configurable: true } }; + return HttpClass; + }(StoreClass)); - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; + // all the contract related methods will be here - Object.defineProperties( JsonqlValidationError, staticAccessors ); + // export + var ContractClass = /*@__PURE__*/(function (HttpClass) { + function ContractClass(opts) { + HttpClass.call(this, opts); + } - return JsonqlValidationError; - }(JsonqlBaseError)); + if ( HttpClass ) ContractClass.__proto__ = HttpClass; + ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); + ContractClass.prototype.constructor = ContractClass; - // 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$1(contract) - && ( - isObjectHasKey$2(contract, QUERY_NAME$1) - || isObjectHasKey$2(contract, MUTATION_NAME$1) - || isObjectHasKey$2(contract, SOCKET_NAME$1) - ) - } + var prototypeAccessors = { contractHeader: { configurable: true } }; - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; + /** + * return the contract public api + * @return {object} contract + */ + ContractClass.prototype.getContract = function getContract () { + var contract = this.readContract(); + this.log('getContract first call', contract); + return contract ? Promise.resolve(contract) + : this.getRemoteContract().then(this.storeContract.bind(this)) + }; - return ( - ( obj = {}, obj[QUERY_ARG_NAME$1] = args, obj ) - ); - }; + /** + * We are changing the way how to auth to get the contract.json + * Instead of in the url, we will be putting that key value in the header + * @return {object} header + */ + prototypeAccessors.contractHeader.get = function () { + var base = {}; + if (this.opts.contractKey !== false) { + base[this.opts.contractKeyName] = this.opts.contractKey; + } + return base; + }; - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } + /** + * Save the contract to local store + * @param {object} contract to save + * @return {object|boolean} false when its not a contract or contract on OK + */ + ContractClass.prototype.storeContract = function storeContract (contract) { + var obj; - /** - * @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) { - var obj; + // first need to check if the contract is a contract + if (!isContract(contract)) { + throw new JsonqlValidationError$1("Contract is malformed!") + //return false; + } + /* @TODO need to rethink how to expired the contract + let args = [contract] + if (this.opts.contractExpired) { + let expired = parseFloat(this.opts.contractExpired) + if (!isNaN(expired) && expired > 0) { + args.push(expired) + } + } + // calling the setter + this.jsonqlContract = args; + */ + this.lset = ( obj = {}, obj[CLS_CONTRACT_NAME] = contract, obj ); + // return it + this.log('storeContract return result', contract); + return contract; + }; - if ( args === void 0 ) { args = []; } - if ( jsonp === void 0 ) { jsonp = false; } - if (isString$2(resolverName) && isArray$2(args)) { - var payload = formatPayload(args); - if (jsonp === true) { - return payload; + /** + * return the contract from options or localStore + * @return {object|boolean} false on not found + */ + ContractClass.prototype.readContract = function readContract () { + var contract = isContract(this.opts.contract); + if (contract !== false) { + return contract; } - return ( obj = {}, obj[resolverName] = payload, obj ) - } - throw new JsonqlValidationError$2("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } + var data = this.lget; + if (data) { + return data[CLS_CONTRACT_NAME] + } + return false; + }; - /** - * @param {string} resolverName name of function - * @param {*} payload to send - * @param {object} [condition={}] for what - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createMutation(resolverName, payload, condition, jsonp) { - var obj; + Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - if ( condition === void 0 ) { condition = {}; } - if ( jsonp === void 0 ) { jsonp = false; } - var _payload = {}; - _payload[PAYLOAD_PARAM_NAME] = payload; - _payload[CONDITION_PARAM_NAME] = condition; - if (jsonp === true) { - return _payload; - } - if (isString$2(resolverName)) { - return ( obj = {}, obj[resolverName] = _payload, obj ) - } - throw new JsonqlValidationError$2("[createMutation] expect resolverName to be string!", { resolverName: resolverName, payload: payload, condition: condition }) - } + return ContractClass; + }(HttpClass)); - // ported from http-client + // this is the new auth class that integrate with the jsonql-jwt + // export + var AuthClass = /*@__PURE__*/(function (ContractClass) { + function AuthClass(opts) { + ContractClass.call(this, opts); + if (opts.enableAuth) { + this.setDecoder = jwtDecode; + } + } - /** - * handle the return data - * @param {object} result return from server - * @return {object} strip the data part out, or if the error is presented - */ - var resultHandler = function (result) { return ( - (isObjectHasKey$2(result, DATA_KEY$1) && !isObjectHasKey$2(result, ERROR_KEY$1)) ? result[DATA_KEY$1] : result - ); }; + if ( ContractClass ) AuthClass.__proto__ = ContractClass; + AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); + AuthClass.prototype.constructor = AuthClass; - // exportfor ES modules + var prototypeAccessors = { profileIndex: { configurable: true },setDecoder: { configurable: true },saveProfile: { configurable: true },readProfile: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - // alias - var isContract = checkIsContract; + /** + * for overwrite + * @param {string} token stored token + * @return {string} token + */ + AuthClass.prototype.decoder = function decoder (token) { + return token; + }; - // take only the module part which is what we use here - - /** - * @param {object} jsonqlInstance the init instance of jsonql client - * @param {object} contract the static contract - * @return {object} contract may be from server - */ - var getContractFromConfig = function(jsonqlInstance, contract) { - if ( contract === void 0 ) contract = {}; - - if (isContract(contract)) { - return Promise.resolve(contract) - } - return jsonqlInstance.getContract() - }; - - // export some constants as well - // since it's only use here there is no point of adding it to the constants module - // or may be we add it back later - var ENDPOINT_TABLE = 'endpoint'; - var USERDATA_TABLE = 'userdata'; - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + /** + * set the profile index + * @param {number} idx + */ + prototypeAccessors.profileIndex.set = function (idx) { + var obj; - function InvalidCharacterError(message) { - this.message = message; - } + var key = CLS_PROFILE_IDX; + if (isNumber$1(idx)) { + this[key] = idx; + if (this.opts.persistToken) { + this.lset = ( obj = {}, obj[key] = idx, obj ); + } + return; + } + throw new JsonqlValidationError$1('profileIndex', ("Expect idx to be number but got " + (typeof idx))) + }; - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + /** + * get the profile index + * @return {number} idx + */ + prototypeAccessors.profileIndex.get = function () { + var key = CLS_PROFILE_IDX; + if (this.opts.persistToken) { + var data = this.lget; + if (data[key]) { + return data[key] + } + } + return this[key] ? this[key] : ZERO_IDX + }; - function polyfill (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, buffer, idx = 0, output = ''; - // 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 += 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; - } + /** + * Return the token from session store + * @param {number} [idx=false] profile index + * @return {string} token + */ + AuthClass.prototype.rawAuthToken = function rawAuthToken (idx) { + if ( idx === void 0 ) idx = false; + if (idx !== false) { + this.profileIndex = idx; + } + // this should return from the base + return this.jsonqlToken; // see base-cls + }; - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + /** + * Setter to add a decoder when retrieve user token + * @param {function} d a decoder + */ + prototypeAccessors.setDecoder.set = function (d) { + if (typeof d === 'function') { + this.decoder = d; + } + }; - function b64DecodeUnicode(str) { - return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; + /** + * getter to return the session or local store set method + * @param {*} data to save + * @return {object} set method + */ + prototypeAccessors.saveProfile.set = function (data) { + if (this.opts.persistToken) { + // this.log('--- saveProfile lset ---', data) + this.lset = data; + } else { + // this.log('--- saveProfile sset ---', data) + this.sset = data; } - return '%' + code; - })); - } + }; - var base64_url_decode = function(str) { - var output = str.replace(/-/g, "+").replace(/_/g, "/"); - switch (output.length % 4) { - case 0: - break; - case 2: - output += "=="; - break; - case 3: - output += "="; - break; - default: - throw "Illegal base64url string!"; - } + /** + * getter to return the session or local store get method + * @return {object} get method + */ + prototypeAccessors.readProfile.get = function () { + return this.opts.persistToken ? this.lget : this.sget + }; - try{ - return b64DecodeUnicode(output); - } catch (err) { - return atob(output); - } - }; + // these were in the base class before but it should be here + /** + * save token + * @param {string} token to store + * @return {string|boolean} false on failed + */ + prototypeAccessors.jsonqlToken.set = function (token) { + var obj; - function InvalidTokenError(message) { - this.message = message; - } + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + // @TODO also have to make sure the token is not already existed! + var tokens = (data && data[key]) ? data[key] : []; + tokens.push(token); + this.saveProfile = ( obj = {}, obj[key] = tokens, obj ); + // store the userdata + this.jsonqlUserdata = this.decoder(token); + }; - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; + /** + * Jsonql token getter + * 1.5.1 each token associate with the same profileIndex + * @return {string|boolean} false when failed + */ + prototypeAccessors.jsonqlToken.get = function () { + var data = this.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex]); + return data[key][this.profileIndex] + } + return false + }; - var lib = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); - } + /** + * this one will use the sessionStore + * basically we hook this onto the token store and decode it to store here + * we only store one decoded user data at a time, but the token can be multiple + */ + prototypeAccessors.jsonqlUserdata.set = function (userdata) { + var obj; - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); - } - }; + this.sset = ( obj = {}, obj[USERDATA_TABLE] = userdata, obj ); + }; - var InvalidTokenError_1 = InvalidTokenError; - lib.InvalidTokenError = InvalidTokenError_1; + /** + * this one store in the session store + * get login userdata decoded jwt + * 1.5.1 each userdata associate with the same profileIndex + * @return {object|null} + */ + prototypeAccessors.jsonqlUserdata.get = function () { + var data = this.sget; + return data ? data[USERDATA_TABLE] : false + }; - // when the user is login with the jwt + /** + * Construct the auth header + * @return {object} header + */ + AuthClass.prototype.getAuthHeader = function getAuthHeader () { + var obj; - var timestamp$1 = function (sec) { - if ( sec === void 0 ) { sec = false; } + var token = this.jsonqlToken; // only call the getter to get the default one + return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; + }; - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; + /** + * return all the stored token and decode it + * @param {number} [idx=false] profile index + * @return {array|boolean|string} false not found or array + */ + AuthClass.prototype.getProfiles = function getProfiles (idx) { + if ( idx === void 0 ) idx = false; - /** - * We only check the nbf and exp - * @param {object} token for checking - * @return {object} token on success - */ - function validate(token) { - var start = token.iat || timestamp$1(true); - // we only check the exp for the time being - if (token.exp) { - if (start >= token.exp) { - var expired = new Date(token.exp).toISOString(); - throw new JsonqlError(("Token has expired on " + expired), token) + var self = this; // just in case the scope problem + var data = self.readProfile; + var key = CREDENTIAL_STORAGE_KEY; + if (data && data[key]) { + if (idx !== false && isNumber$1(idx)) { + return data[key][idx] || false + } + return data[key].map(self.decoder.bind(self)) } - } - return token; - } + return false + }; - /** - * The browser client version it has far fewer options and it doesn't verify it - * because it couldn't this is the job for the server - * @TODO we need to add some extra proessing here to check for the exp field - * @param {string} token to decrypted - * @return {object} decrypted object - */ - function jwtDecode(token) { - if (isString$1(token)) { - var t = lib(token); - return validate(t) - } - throw new JsonqlError('Token must be a string!') - } + /** + * call after the login + * @param {string} token return from server + * @return {object} decoded token to userdata object + */ + AuthClass.prototype.postLoginAction = function postLoginAction (token) { + this.jsonqlToken = token; + return token + }; - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + /** + * call after the logout @TODO + */ + AuthClass.prototype.postLogoutAction = function postLogoutAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - 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 )) - }; + console.info("postLogoutAction", args); + }; - // base HttpClass + Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - // extract the one we need - var POST = API_REQUEST_METHODS[0]; - var PUT = API_REQUEST_METHODS[1]; + return AuthClass; + }(ContractClass)); - var _log = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + // this the core of the internal storage management - try { - if (window && window.console) { - Reflect.apply(console.log, null, args); - } - } catch(e) {} - }; + // This class will only focus on the storage system + var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { + function JsonqlBaseClient(fly, opts) { + // change at 1.4.10 pass it directly without init it + this.fly = fly; + AuthCls.call(this, opts); + } - var HttpClass = function HttpClass(opts) { - // change the way how we init Fly - // flyio now become external depedencies and it makes it easier to switch - // @BUG should we run test to check if we have the windows object? - _log(opts); - // this.fly = opts.Fly ? new opts.Fly() : new Fly() - // to a different environment like WeChat mini app - this.opts = opts; - this.extraHeader = {}; - // @1.2.1 for adding query to the call on the fly - this.extraParams = {}; - // this.log('start up opts', opts); - this.reqInterceptor(); - this.resInterceptor(); - }; + if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; + JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); + JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - var prototypeAccessors = { headers: { configurable: true } }; + var prototypeAccessors = { jsonqlEndpoint: { configurable: true } }; - // set headers for that one call - prototypeAccessors.headers.set = function (header) { - this.extraHeader = header; - }; + /** + * construct the end point + * @return {string} the end point to call + */ + prototypeAccessors.jsonqlEndpoint.get = function () { + var baseUrl = this.opts.hostname || ''; + return [baseUrl, this.opts.jsonqlPath].join('/') + }; - /** - * Create the reusage request method - * @param {object} payload jsonql payload - * @param {object} options extra options add the request - * @param {object} headers extra headers add to the call - * @return {object} the fly request instance - */ - HttpClass.prototype.request = function request (payload, options, headers) { - var obj; + /** + * simple log + */ + JsonqlBaseClient.prototype.log = function log () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - if ( options === void 0 ) options = {}; - if ( headers === void 0 ) headers = {}; - this.headers = headers; - var params = merge({}, cacheBurst(), this.extraParams); - // @TODO need to add a jsonp url and payload - if (this.opts.enableJsonp) { - var resolverName = getNameFromPayload(payload); - params = merge({}, params, ( obj = {}, obj[JSONP_CALLBACK_NAME] = resolverName, obj )); - payload = payload[resolverName]; - } - return this.fly.request( - this.jsonqlEndpoint, - payload, - merge({}, { method: POST, params: params }, options) - ) - }; + if (this.opts.debugOn === true) { + Reflect.apply(console.info, console, args); + } + }; - /** - * This will replace the create baseRequest method - * - */ - HttpClass.prototype.reqInterceptor = function reqInterceptor () { - var this$1 = this; + Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); - this.fly.interceptors.request.use( - function (req) { - var headers = this$1.getHeaders(); - this$1.log('request interceptor call', headers); + return JsonqlBaseClient; + }(AuthClass)); - for (var key in headers) { - req.headers[key] = headers[key]; - } - return req; + // export interface + + var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); + var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + + // making all the functionality on it's own + // import { WatchClass } from './watch' + + var SuspendClass = function SuspendClass() { + // suspend, release and queue + this.__suspend__ = null; + this.queueStore = new Set(); + /* + this.watch('suspend', function(value, prop, oldValue) { + this.logger(`${prop} set from ${oldValue} to ${value}`) + // it means it set the suspend = true then release it + if (oldValue === true && value === false) { + // we want this happen after the return happens + setTimeout(() => { + this.release() + }, 1) } - ); + return value; // we need to return the value to store it + }) + */ }; - // @TODO - HttpClass.prototype.processJsonp = function processJsonp (result) { - return resultHandler(result) - }; + var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; /** - * This will be replacement of the first then call - * + * setter to set the suspend and check if it's boolean value + * @param {boolean} value to trigger */ - HttpClass.prototype.resInterceptor = function resInterceptor () { + prototypeAccessors$1.$suspend.set = function (value) { var this$1 = this; - var self = this; - var jsonp = self.opts.enableJsonp; - this.fly.interceptors.response.use( - function (res) { - this$1.log('response interceptor call'); - self.cleanUp(); - // now more processing here - // there is a problem if we throw the result.error here - // the original data is lost, so we need to do what we did before - // deal with that error in the first then instead - var result = isString$1(res.data) ? JSON.parse(res.data) : res.data; - if (jsonp) { - return self.processJsonp(result) - } - return resultHandler(result) - }, - // this get call when it's not 200 - function (err) { - self.cleanUp(); - console.error(err); - throw new JsonqlServerError('Server side error', err) + if (typeof value === 'boolean') { + var lastValue = this.__suspend__; + this.__suspend__ = value; + this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); + if (lastValue === true && value === false) { + setTimeout(function () { + this$1.release(); + }, 1); } - ); + } else { + throw new Error("$suspend only accept Boolean value!") + } }; /** - * Get the headers inject into the call - * @return {object} headers + * queuing call up when it's in suspend mode + * @param {any} value + * @return {Boolean} true when added or false when it's not */ - HttpClass.prototype.getHeaders = function getHeaders () { - if (this.opts.enableAuth) { - return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader) + SuspendClass.prototype.$queue = function $queue () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (this.__suspend__ === true) { + this.logger('($queue)', 'added to $queue', args); + // there shouldn't be any duplicate ... + this.queueStore.add(args); } - return merge({}, DEFAULT_HEADER, this.extraHeader) + return this.__suspend__; }; /** - * Post http call operation to clean up things we need + * a getter to get all the store queue + * @return {array} Set turn into Array before return */ - HttpClass.prototype.cleanUp = function cleanUp () { - this.extraHeader = {}; - this.extraParams = {}; + prototypeAccessors$1.$queues.get = function () { + var size = this.queueStore.size; + this.logger('($queues)', ("size: " + size)); + if (size > 0) { + return Array.from(this.queueStore) + } + return [] }; /** - * GET for contract only + * Release the queue + * @return {int} size if any */ - HttpClass.prototype.get = function get () { + SuspendClass.prototype.release = function release () { var this$1 = this; - if (this.opts.showContractDesc) { - this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM); + var size = this.queueStore.size; + this.logger('(release)', ("Release was called " + size)); + if (size > 0) { + var queue = Array.from(this.queueStore); + this.queueStore.clear(); + this.logger('queue', queue); + queue.forEach(function (args) { + this$1.logger(args); + Reflect.apply(this$1.$trigger, this$1, args); + }); + this.logger(("Release size " + (this.queueStore.size))); } - return this.request({}, {method: 'GET'}, this.contractHeader) - .then(clientErrorsHandler) - .then(function (result) { - this$1.log('get contract result', result); - // when refresh the window the result is different! - // @TODO need to check the Koa side about why is that - // also it should set a flag if we want the description or not - if (result.cache && result.contract) { - return result.contract; - } - // just the normal result - return result - }) }; - /** - * POST to server - query - * @param {object} name of the resolver - * @param {array} args arguments - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.query = function query (name, args) { - if ( args === void 0 ) args = []; - - return this.request(createQuery(name, args)) - .then(clientErrorsHandler) - }; - - /** - * PUT to server - mutation - * @param {string} name of resolver - * @param {object} payload what it said - * @param {object} conditions what it said - * @return {object} promise resolve to the resolver return - */ - HttpClass.prototype.mutation = function mutation (name, payload, conditions) { - if ( payload === void 0 ) payload = {}; - if ( conditions === void 0 ) conditions = {}; - - return this.request(createMutation(name, payload, conditions), {method: PUT}) - .then(clientErrorsHandler) - }; + Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - Object.defineProperties( HttpClass.prototype, prototypeAccessors ); + // break up the main file because its getting way too long - // all the contract related methods will be here + var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { + function NbEventServiceBase(config) { + if ( config === void 0 ) config = {}; - // export - var ContractClass = /*@__PURE__*/(function (HttpClass) { - function ContractClass(opts) { - HttpClass.call(this, opts); + 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(); } - if ( HttpClass ) ContractClass.__proto__ = HttpClass; - ContractClass.prototype = Object.create( HttpClass && HttpClass.prototype ); - ContractClass.prototype.constructor = ContractClass; + if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; + NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); + NbEventServiceBase.prototype.constructor = NbEventServiceBase; - var prototypeAccessors = { contractHeader: { configurable: true } }; + var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; /** - * return the contract public api - * @return {object} contract + * validate the event name(s) + * @param {string[]} evt event name + * @return {boolean} true when OK */ - ContractClass.prototype.getContract = function getContract () { - var contracts = this.readContract(); - this.log('getContract first call', contracts); - if (contracts && Array.isArray(contracts)) { - var contract = contracts[ this[ENDPOINT_TABLE + 'Index'] || 0 ]; - if (contract) { - return Promise.resolve(contract) - } - } - return this.get() - .then( this.storeContract.bind(this) ) - }; + NbEventServiceBase.prototype.validateEvt = function validateEvt () { + var this$1 = this; + var evt = [], len = arguments.length; + while ( len-- ) evt[ len ] = arguments[ len ]; - /** - * We are changing the way how to auth to get the contract.json - * Instead of in the url, we will be putting that key value in the header - * @return {object} header - */ - prototypeAccessors.contractHeader.get = function () { - var base = {}; - if (this.opts.contractKey !== false) { - base[this.opts.contractKeyName] = this.opts.contractKey; - } - return base; + evt.forEach(function (e) { + if (typeof e !== 'string') { + this$1.logger('(validateEvt)', e); + throw new Error("event name must be string type!") + } + }); + return true; }; /** - * Save the contract to local store - * @param {object} contract to save - * @return {object|boolean} false when its not a contract or contract on OK + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK */ - ContractClass.prototype.storeContract = function storeContract (contract) { - // first need to check if the contract is a contract - if (!isContract(contract)) { - throw new JsonqlValidationError$1("Contract is malformed!") - //return false; - } - var args = [contract]; - if (this.opts.contractExpired) { - var expired = parseFloat(this.opts.contractExpired); - if (!isNaN(expired) && expired > 0) { - args.push(expired); + NbEventServiceBase.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; } } - // calling the setter - this.jsonqlContract = args; - // return it - this.log('storeContract return result', contract); - return contract; + throw new Error("callback required to be function type!") }; /** - * return the contract from options or localStore - * @return {object} contract + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK */ - ContractClass.prototype.readContract = function readContract () { - var contract = isContract(this.opts.contract); - return contract ? this.opts.contract : localStore$1.get(this.opts.storageKey) + NbEventServiceBase.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; }; - Object.defineProperties( ContractClass.prototype, prototypeAccessors ); - - return ContractClass; - }(HttpClass)); - - // this is the new auth class that integrate with the jsonql-jwt - // export - var AuthClass = /*@__PURE__*/(function (ContractClass) { - function AuthClass(opts) { - ContractClass.call(this, opts); - if (opts.enableAuth && opts.useJwt) { - this.setDecoder = jwtDecode; - } - } - - if ( ContractClass ) AuthClass.__proto__ = ContractClass; - AuthClass.prototype = Object.create( ContractClass && ContractClass.prototype ); - AuthClass.prototype.constructor = AuthClass; - - var prototypeAccessors = { userdata: { configurable: true },rawAuthToken: { configurable: true },setDecoder: { configurable: true } }; - /** - * Getter to get the login userdata - * @return {mixed} userdata + * 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 */ - prototypeAccessors.userdata.get = function () { - return this.jsonqlUserdata; // see base-cls + NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { + this.logger('(run)', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); }; /** - * Return the token from session store - * @return {string} token + * 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 */ - prototypeAccessors.rawAuthToken.get = function () { - // this should return from the base - return this.jsonqlToken; // see base-cls - }; - - /** - * Setter to add a decoder when retrieve user token - * @param {function} d a decoder - */ - prototypeAccessors.setDecoder.set = function (d) { - if (typeof d === 'function') { - this.decoder = d; + NbEventServiceBase.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!")) }; /** - * Setter after login success - * @TODO this move to a new class to handle multiple login - * @param {string} token to store - * @return {*} success store + * 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 */ - AuthClass.prototype.storeToken = function storeToken (token) { - return this.jsonqlToken = token; + NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + 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(); + } + // 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] }; /** - * for overwrite - * @param {string} token stored token - * @return {string} token + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist */ - AuthClass.prototype.decoder = function decoder (token) { - return token; + NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; }; /** - * Construct the auth header - * @return {object} header + * 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 */ - AuthClass.prototype.getAuthHeader = function getAuthHeader () { - var obj; - - var token = this.rawAuthToken; - return token ? ( obj = {}, obj[this.opts.AUTH_HEADER] = (BEARER + " " + token), obj ) : {}; - }; - - Object.defineProperties( AuthClass.prototype, prototypeAccessors ); - - return AuthClass; - }(ContractClass)); - - // this the core of the internal storage management - - // This class will only focus on the storage system - var JsonqlBaseClient = /*@__PURE__*/(function (AuthCls) { - function JsonqlBaseClient(fly, opts) { - // change at 1.4.10 pass it directly without init it - this.fly = fly; - - AuthCls.call(this, opts); - } - - if ( AuthCls ) JsonqlBaseClient.__proto__ = AuthCls; - JsonqlBaseClient.prototype = Object.create( AuthCls && AuthCls.prototype ); - JsonqlBaseClient.prototype.constructor = JsonqlBaseClient; - - var prototypeAccessors = { storeIt: { configurable: true },jsonqlEndpoint: { configurable: true },jsonqlContract: { configurable: true },jsonqlToken: { configurable: true },jsonqlUserdata: { configurable: true } }; - - // @TODO - prototypeAccessors.storeIt.set = function (args) { - // the args MUST contain [0] the key , [1] the content [2] optional expired in - if (isArray$1(args) && args.length >= 2) { - return Reflect.apply(localStore$1.set, localStore$1, args) - } - throw new JsonqlValidationError$1("Expect argument to be array and least 2 items!") - }; - - // this table index key will drive the contract - // also it should not allow to change dynamicly - // because this is how different client can id itself - // OK this could be self manage because when init a new client - // it will add a new endpoint and we will know if they are the same or not - // but the check here - prototypeAccessors.jsonqlEndpoint.set = function (endpoint) { - var urls = localStore$1.get(ENDPOINT_TABLE) || []; - // should check if this url already existed? - if (!inArray$1(urls, endpoint)) { - urls.push(endpoint); - this.storeId = [ENDPOINT_TABLE, urls]; - this[ENDPOINT_TABLE + 'Index'] = urls.length - 1; + NbEventServiceBase.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; }; - // by the time it call the save contract already been checked - prototypeAccessors.jsonqlContract.set = function (args) { - var key = this.opts.storageKey; - var _args = [ key ]; - var contract = args[0]; - var expired = args[1]; - // get the endpoint index - var contracts = localStore$1.get(key) || []; - contracts[ this[ENDPOINT_TABLE + 'Index'] || 0 ] = contract; - _args.push(contracts); - if (expired) { - _args.push(expired); - } - if (this.opts.keepContract) { - this.storeIt = _args; + /** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ + NbEventServiceBase.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 (l) { + var t = l[2]; + return t !== type; + }).length } + return false; }; /** - * save token - * @param {string} token to store - * @return {string|boolean} false on failed + * 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 */ - prototypeAccessors.jsonqlToken.set = function (token) { - var key = CREDENTIAL_STORAGE_KEY; - var tokens = localStorage.get(key) || []; - if (!inArray$1(tokens, token)) { - var index = tokens.length - 1; - tokens[ index ] = token; - this[key + 'Index'] = index; - var args = [key, tokens]; - if (this.opts.tokenExpired) { - var expired = parseFloat(this.opts.tokenExpired); - if (!isNaN(expired) && expired > 0) { - var ts = timestamp(); - args.push( ts + parseFloat(expired) ); - } - } - this.storeIt = args; - // now decode it and store in the userdata - this.jsonqlUserdata = this.decoder(token); - return token; + NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger('(addToNormalStore)', (type + " can add to " + evt + " 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; }; /** - * this one will use the sessionStore - * basically we hook this onto the token store and decode it to store here + * 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 */ - prototypeAccessors.jsonqlUserdata.set = function (userdata) { - var args = [USERDATA_TABLE, userdata]; - if (userdata.exp) { - args.push(userdata.exp); + NbEventServiceBase.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); } - return Reflect.apply(localStore$1.set, localStore$1, args) + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; }; /** - * This also manage the index internally - * There is NO need to store them in an array - * because each instance contain one end point - * @return {string} the end point to call + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured */ - prototypeAccessors.jsonqlEndpoint.get = function () { - var urls = localStore$1.get(ENDPOINT_TABLE); - if (!urls) { - var ref = this.opts; - var hostname = ref.hostname; - var jsonqlPath = ref.jsonqlPath; - var url = [hostname, jsonqlPath].join('/'); - this.jsonqlEndpoint = url; - return url; - } - return urls[this[ENDPOINT_TABLE + 'Index']] + NbEventServiceBase.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; }; /** - * If already stored then return it by the end point index - * or false when there is none - * 1.2.0 start using the keepContract option (replace the useLocalStorage) - * @return {object|boolean} as described above + * setter to store the Set in private + * @param {object} obj a Set */ - prototypeAccessors.jsonqlContract.get = function () { - var key = this.opts.storageKey; - var contracts = localStore$1.get(key) || []; - return contracts[ this[ENDPOINT_TABLE + 'Index'] ] || false + prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); }; /** - * Jsonql token getter - * @return {string|boolean} false when failed + * @return {object} Set object */ - prototypeAccessors.jsonqlToken.get = function () { - var key = CREDENTIAL_STORAGE_KEY; - var tokens = localStorage.get(key); - if (tokens) { - return tokens[ this[key + 'Index'] ] - } - return false; + prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) }; /** - * this one store in the session store - * get login userdata decoded jwt - * @return {object|null} + * setter to store the Set in lazy store + * @param {object} obj a Set */ - prototypeAccessors.jsonqlUserdata.get = function () { - return sessionStore$1.get(USERDATA_TABLE) + prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); }; /** - * simple log + * @return {object} the lazy store Set */ - JsonqlBaseClient.prototype.log = function log () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) + }; - if (this.opts.debugOn === true) { - Reflect.apply(console.info, console, args); - } + /** + * 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 + */ + NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; }; - Object.defineProperties( JsonqlBaseClient.prototype, prototypeAccessors ); + Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - return JsonqlBaseClient; - }(AuthClass)); + return NbEventServiceBase; + }(SuspendClass)); - // export interface + // The top level + // export + var EventService = /*@__PURE__*/(function (NbStoreService) { + function EventService(config) { + if ( config === void 0 ) config = {}; - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - /** - * 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) - } - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors$1 = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors$1.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors$1.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); + NbStoreService.call(this, config); } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors$1 ); - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; + if ( NbStoreService ) EventService.__proto__ = NbStoreService; + EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); + EventService.prototype.constructor = EventService; - 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(); - } + var prototypeAccessors = { $done: { configurable: true } }; - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; + /** + * logger function for overwrite + */ + EventService.prototype.logger = function logger () {}; - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; + ////////////////////////// + // PUBLIC METHODS // + ////////////////////////// /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK + * 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 */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { + EventService.prototype.$on = function $on (evt , callback , context) { var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; + if ( context === void 0 ) context = null; - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") + 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 + " callback 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(("You are trying to register an event already been taken by other type: " + t)) } + this$1.logger("($on)", ("call run on " + evt)); + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); }); - return true; + return size; }; /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK + * 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 */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; + EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('($once)', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, 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 !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) } + this.logger('($once)', ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); } - throw new Error("callback required to be function type!") }; /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK + * 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 */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; + EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; - /** - * 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 - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); + this.validate(evt, callback); + var type = 'only'; + 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 store")); + added = this.addToNormalStore(evt, 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 (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.logger("($only)", ("call run for " + evt)); + this$1.run(callback, payload, context || ctx); + }); + } + return added; }; /** - * Take the content out and remove it from store id by the name + * $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 {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; + EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; - 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; + this.validate(evt, callback); + var type = 'onlyOnce'; + 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 store")); + added = this.addToNormalStore(evt, 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 !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) } - return false; + this.logger("($onlyOnce)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); } - throw new Error((storeName + " is not supported!")) + return added; }; /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use + * This is a shorthand of $off + $on added in V1.5.0 * @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 + * @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 {} */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; - 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(); + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + this.logger("($replace)", evt, callback); + return Reflect.apply(method, this, [evt, callback, context]) } - // 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); + 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)) { + // @1.8.0 to add the suspend queue + var added = this.$queue(evt, payload, context, type); + this.logger('($trigger)', evt, 'found; add to queue: ', added); + if (added === true) { + this.logger('($trigger)', evt, 'not executed. Exit now.'); + return false; // not executed + } + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = 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$1 = ref[3]; + this.logger("($trigger)", ("call run for " + evt)); + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; } } - } else { // add straight to lazy store - fnSet.add(args); + if (hasOnce) { + nStore.delete(evt); + } + return found; } - store.set(evt, fnSet); - return [store, fnSet.size] + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; }; /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; + EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params, context, type]; + return Reflect.apply(this.$trigger, this, 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; + + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + this$1.logger('($off)', evt); + store.delete(evt); } - return false; - }).length; + }); + return found; }; /** - * get the existing type to make sure no mix type add to the same store + * return all the listener from the event * @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 + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found */ - NbEventServiceBase.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; + EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; + return false; }; /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it + * store the return result from the run + * @param {*} value whatever return from callback */ - NbEventServiceBase.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 (l) { - var t = l[2]; - return t !== type; - }).length + prototypeAccessors.$done.set = function (value) { + this.logger('($done)', 'value: ', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; } - 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 + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " 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; + prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger('(get $done)', this.result); + return this.result[this.result.length - 1] } - return false; + return this.result; }; - /** - * 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 - */ - NbEventServiceBase.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; - return size; - }; + Object.defineProperties( EventService.prototype, prototypeAccessors ); - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; + return EventService; + }(NbEventServiceBase)); - /** - * 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); - }; + // default - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; + // this will generate a event emitter and will be use everywhere + // output + function getEventEmitter(debugOn) { + var logger = debugOn ? function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - /** - * 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); - }; + args.unshift('[NBS]'); + console.log.apply(null, args); + }: undefined; + return new EventService({ logger: logger }) + } - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; + /** + * 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 ]; - /** - * 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 - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; + return ( + function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); + 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)) + ); + } + ); + }; - return NbEventServiceBase; - }(SuspendClass)); + /** + * 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; + } - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; + /** + * 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; - NbStoreService.call(this, config); + var check = objHasProp(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; } + /* this will throw error! + 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 + }); - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; + return resolver; + } - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// + // breaking out the inner methods generator in here - /** - * 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; + /** + * generate authorisation specific methods + * @param {object} jsonqlInstance instance of this + * @param {string} name of method + * @param {object} opts configuration + * @param {object} contract to match + * @return {function} for use + */ + var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - 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 + " callback 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 + var params = contract.auth[name].params; + var values = params.map(function (p, i) { return args[i]; }); + var header = args[params.length] || {}; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [name, values, header]); } + ) + .catch(finalCatch) + } + }; - 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(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($on)", ("call run on " + evt)); - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); + /** + * Break up the different type each - create query methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { + var query = {}; + var loop = function ( queryFn ) { + // to keep it clean we use a param to id the auth method + // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; + // generate the query method + query = injectToFn(query, queryFn, function queryFnHandler() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var params = contract.query[queryFn].params; + var _args = params.map(function (param, i) { return args[i]; }); + // debug('query', queryFn, _params); + // @TODO this need to change to a different way to add an extra header + var header = {}; + // @TODO validate against the type + return validateAsync$1(_args, params) + .then(function () { return jsonqlInstance + .query + .apply(jsonqlInstance, [queryFn, _args, header]); } + ) + .catch(finalCatch) }); - 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 type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, 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 !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger('($once)', ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; + for (var queryFn in contract.query) loop( queryFn ); + obj.query = query; + // create an alias to the helloWorld method + obj.helloWorld = query.helloWorld; + return [ obj, jsonqlInstance, ee, config, contract ] + }; - /** - * 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; + /** + * create mutation methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { + var mutation = {}; + // process the mutation, the reason the mutation has a fixed number of parameters + // there is only the payload, and conditions parameters + // plus a header at the end + var loop = function ( mutationFn ) { + mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { + if ( header === void 0 ) header = {}; - this.validate(evt, callback); - var type = 'only'; - 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 store")); - added = this.addToNormalStore(evt, 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 (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.logger("($only)", ("call run for " + evt)); - this$1.run(callback, payload, context || ctx); - }); - } - return added; + var args = [payload, conditions]; + var params = contract.mutation[mutationFn].params; + return validateAsync$1(args, params) + .then(function () { return jsonqlInstance + .mutation + .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } + ) + .catch(finalCatch) + }); }; - /** - * $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; + for (var mutationFn in contract.mutation) loop( mutationFn ); + obj.mutation = mutation; + return [ obj, jsonqlInstance, ee, config, contract ] + }; - this.validate(evt, callback); - var type = 'onlyOnce'; - 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 store")); - added = this.addToNormalStore(evt, type, callback, context); + /** + * create auth methods + * @param {object} obj to hold all the objects + * @param {object} jsonqlInstance jsonql class instance + * @param {object} ee eventEmitter + * @param {object} config configuration + * @param {object} contract json + * @return {object} modified output for next op + */ + var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { + if (config.enableAuth && contract.auth) { + var auth = {}; // v1.3.1 add back the auth prop name in contract + var loginHandlerName = config.loginHandlerName; + var logoutHandlerName = config.logoutHandlerName; + if (contract.auth[loginHandlerName]) { + // changing to the name the config specify + auth[loginHandlerName] = function loginHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance)) + .then(function (token) { + ee.$trigger(LOGIN_NAME, token); + return token; + }) + }; } - 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 !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.logger("($onlyOnce)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); + // @TODO allow to logout one particular profile or all of them + if (contract.auth[logoutHandlerName]) { + auth[logoutHandlerName] = function logoutHandlerFn() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); + return fn.apply(null, args) + .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance)) + .then(function (r) { + ee.$trigger(LOGOUT_NAME, r); + return r; + }) + }; + } else { + auth[logoutHandlerName] = function logoutHandlerFn() { + jsonqlInstance.postLogoutAction(KEY_WORD); + ee.$trigger(LOGOUT_NAME, KEY_WORD); + }; } - return added; - }; + obj.auth = auth; + } - /** - * 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'; + return obj; + }; - 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!")) - }; + /** + * Here just generate the methods calls + * @param {object} jsonqlInstance what it said + * @param {object} ee event emitter + * @param {object} config configuration + * @param {object} contract the map + * @return {object} with mapped methods + */ + function methodsGenerator(jsonqlInstance, ee, config, contract) { + var obj = {}; + var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); + return executor(obj, jsonqlInstance, ee, config, contract) + } - /** - * 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; + // Generate the resolver for developer to use - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - this.logger('($trigger)', evt, 'not executed. Exit now.'); - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = 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$1 = ref[3]; - this.logger("($trigger)", ("call run for " + evt)); - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); + /** + * @param {object} jsonqlInstance jsonql class instance + * @param {object} config options + * @param {object} contract the contract + * @param {object} ee eventEmitter + * @return {object} constructed functions call + */ + var generator = function (jsonqlInstance, config, contract, ee) { + // V1.3.0 - now everything wrap inside this method + var client = methodsGenerator(jsonqlInstance, ee, config, contract); + // create the rest of the methods + if (config.enableAuth) { + /** + * new method to allow retrieve the current login user data + * @TODO allow to pass an id to switch to different userdata + * @return {*} userdata + */ + client.userdata = function () { return jsonqlInstance.jsonqlUserdata; }; + // allow getting the token for valdiate agains the socket + // if it's not require auth there is no point of calling getToken + client.getToken = function (idx) { + if ( idx === void 0 ) idx = false; + + return jsonqlInstance.rawAuthToken(idx); + }; + // switch profile or read back what is the currenct index + client.profileIndex = function (idx) { + if ( idx === void 0 ) idx = false; + + if (idx === false) { + return jsonqlInstance.profileIndex } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; + jsonqlInstance.profileIndex = idx; + }; + // new in 1.5.1 to return different profiles + client.getProfiles = function (idx) { + if ( idx === void 0 ) idx = false; - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; + return jsonqlInstance.getProfiles(idx); + }; + } + // this will pass to the ws-client if needed + // client.eventEmitter = ee; + // this will require a param + if (config.exposeContract) { + // 1.4.0 change from the get (raw) to the getContract cache and raw version + client.getContract = function () { return jsonqlInstance.getContract(); }; + } + // allow developer to access the store api + if (config.exposeStore) { + // @TODO in 1.5.2 + client.tmpSave = function (data) {}; + client.tmpGet = function (key) { + }; + client.tmpDel = function (key) { + }; - var args = [evt, params, context, type]; - return Reflect.apply(this.$trigger, this, args) + client.persistSave = function (data) {}; + client.persistGet = function (key) { + }; + client.persistDel = function (key) { + }; + } + // this is for the ws to use later - but this could be dangerous because it's expose the internal + client.eventEmitter = ee; + client.version = '0.1.0'; + // use this method then we can hook into the debugOn at the same time + client.log = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args)); }; + // output + return client; + }; - /** - * 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; + // all the client configuration options here + var constProps = { + contract: false, + MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? + CONTENT_TYPE: CONTENT_TYPE, + BEARER: BEARER, + AUTH_HEADER: AUTH_HEADER + }; - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - this$1.logger('($off)', evt); - store.delete(evt); - } - }); - return found; - }; + // grab the localhost name and put into the hostname as default + var getHostName = function () { + try { + return [window.location.protocol, window.location.host].join('//') + } catch(e) { + return null + } + }; - /** - * return all the listener from the event - * @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; + var appProps$1 = { - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; + hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname + jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server + + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // add to koa v1.3.0 - this might remove in the future + enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + // enable useJwt by default @TODO replace with something else and remove them later + useJwt: createConfig$1(true, [BOOLEAN_TYPE]), + // when true then store infinity or pass a time in seconds then we check against + // the token date of creation + persistToken: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE]), + // the header + // v1.2.0 we are using this option during the dev + // so it won't save anything to the localstorage and fetch a new contract + // whenever the browser reload + useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage + storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage + authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage + contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, + // 0 never expired, + // > 0 then compare the timestamp with the current one to see if we need to get contract again + // useful during development + keepContract: createConfig$1(true, [BOOLEAN_TYPE]), + exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), + exposeStore: createConfig$1(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn + // @1.2.1 new option for the contract-console to fetch the contract with description + showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), + contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this + contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs + enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO + timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds + returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), + allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), + debugOn: createConfig$1(false, [BOOLEAN_TYPE]) + }; + + // we must ensure the user passing the correct options + + function checkOptionsAsync$1(config) { + var contract = config.contract; + return checkConfigAsync$1(config, appProps$1, constProps) + .then(function (opts) { + opts.contract = contract; + return opts; + }) + } + + // export interface + /** + * 1.5.0 overload the orginal functions to pass over the check + */ + function checkOptionsAsync$2(config) { + return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) + } + + // new module interface for @jsonql/client + + /** + * Check if the contract has socket field and the socket client is suplied + * @param {object} client the http client + * @param {object} contract the json + * @param {object} config the checked configuration + * @param {object} socketClient from the original config + * @return {object} the completed client + */ + function initSocketClient(client, contract, config, socketClient) { + if (isObjectHasKey$1(contract, SOCKET_NAME)) { + if (socketClient) { + // pass the contract here one more time in case the constProps overwritten it + config.contract = contract; + config.eventEmitter = client.eventEmitter; + return socketClient(config) + .then(function (sc) { + client[SOCKET_NAME] = sc; + return client; }) + } else { + throw new JsonqlError("initSocketClient", "socketClient is missing!") + } + } + return client; + } + + /** + * Main interface for jsonql fetch api + * @1.4.8 change this to named export to diff this from the other + * and this is only use with the @jsonql/client to construct the client with ws + * @param {object} Fly the http engine + * @param {object} [config={}] configuration + * @return {object} jsonqlClient + */ + function jsonqlClientModule(fly, config) { + if ( config === void 0 ) config = {}; + + var socketClient = config.socketClient; + var debugOn = config.debugOn; + var ee = getEventEmitter(debugOn); + return checkOptionsAsync$2(config) + .then(function (opts) { return ( + { + opts: opts, + baseClient: new JsonqlBaseClient(fly, opts) + } + ); }) + .then(function (ref) { + var opts = ref.opts; + var baseClient = ref.baseClient; + + return getContractFromConfig(baseClient, opts.contract) + .then(function (contract) { return ( + { + opts: opts, + contract: contract, + client: generator(baseClient, opts, contract, ee) + } + ); } + ); + } + ) + .then(function (ref) { + var opts = ref.opts; + var contract = ref.contract; + var client = ref.client; + + return ( + initSocketClient(client, contract, opts, socketClient) + ); + }) + } + + // this will replace the preConfigCheck in jsonql-koa + + /** + * the rest of the argument will be functions that + * need to add to the process chain, + * finally return a function to accept the config + * @param {object} defaultOptions prepared before hand + * @param {object} constProps prepare before hand + * @param {array} fns arguments see description + * @return {function} to perform the final configuration check + */ + function preConfigCheck(defaultOptions, constProps) { + var fns = [], len = arguments.length - 2; + while ( len-- > 0 ) fns[ len ] = arguments[ len + 2 ]; + + // should have just add the method to the last + var finalFn = function (opt) { return injectToFn(opt, CHECKED_KEY, timestamp$1()); }; + // if there is more than one then chain it otherwise just return the zero idx one + var fn = Reflect.apply(chainFns, null, fns.concat(finalFn)); + // 0.8.8 add a default property empty object + return function (config) { + if ( config === void 0 ) config = {}; + + return fn(config, defaultOptions, constProps); + } + } + + // export the options for the pre-check to use + // just export the function here for use to save repeat coding + + /** + * This will combine the socket client options and merge this one + * then do a pre-check on both at the same time + * @param {object} [extraProps = {}] + * @param {object} [extraConstProps = {}] + * @return {function} to process the developer options + */ + function getPreConfigCheck(extraProps, extraConstProps) { + if ( extraProps === void 0 ) extraProps = {}; + if ( extraConstProps === void 0 ) extraConstProps = {}; + + var aProps = merge({}, appProps$1, extraProps); + var cProps = merge({}, constProps, extraConstProps); + + return preConfigCheck(aProps, cProps, checkConfig$1) + } + + /** + * 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$1 = /*@__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 406; + }; + + 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$1 = /*@__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 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; + }(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$1 = /*@__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 401; + }; + + 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$1 = /*@__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 401; + }; + + 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$1 = /*@__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 500; + }; + + 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$1 = /*@__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 404; + }; + + 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$1 = /*@__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$1 = /*@__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$1 = /*@__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$2 = /*@__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)); + + // the core stuff to id if it's calling with jsonql + var DATA_KEY$1 = 'data'; + var ERROR_KEY$1 = 'error'; + + var JSONQL_PATH$1 = 'jsonql'; + + // export const INDEX = 'index'; use INDEX_KEY instead + var DEFAULT_TYPE$2 = '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$1 = 'query'; + var MUTATION_NAME$1 = 'mutation'; + var SOCKET_NAME$1 = 'socket'; + var QUERY_ARG_NAME$1 = 'args'; + var TIMESTAMP_PARAM_NAME$1 = 'TS'; + // for contract-cli + var KEY_WORD$2 = 'continue'; + + var TYPE_KEY$2 = 'type'; + var OPTIONAL_KEY$2 = 'optional'; + var ENUM_KEY$2 = 'enumv'; // need to change this because enum is a reserved word + var ARGS_KEY$2 = 'args'; + var CHECKER_KEY$2 = 'checker'; + var ALIAS_KEY$2 = 'alias'; + var CHECKED_KEY$1 = '__checked__'; + var LOGIN_NAME$1 = 'login'; + var ISSUER_NAME$1 = LOGIN_NAME$1; // legacy issue need to replace them later + var LOGOUT_NAME$1 = 'logout'; + + var OR_SEPERATOR$2 = '|'; + + var STRING_TYPE$2 = 'string'; + var BOOLEAN_TYPE$2 = 'boolean'; + var ARRAY_TYPE$2 = 'array'; + var OBJECT_TYPE$2 = 'object'; + + var NUMBER_TYPE$2 = 'number'; + var ARRAY_TYPE_LFT$2 = 'array.<'; + var ARRAY_TYPE_RGT$2 = '>'; + + var NO_ERROR_MSG$1 = 'No message'; + var NO_STATUS_CODE$1 = -1; + var LOGIN_EVENT_NAME = '__login__'; + var LOGOUT_EVENT_NAME = '__logout__'; + + // for ws servers + var WS_REPLY_TYPE = '__reply__'; + var WS_EVT_NAME = '__event__'; + var WS_DATA_NAME = '__data__'; + var EMIT_REPLY_TYPE = 'emit'; + var ACKNOWLEDGE_REPLY_TYPE = 'acknowledge'; + var ERROR_TYPE = 'error'; + + var NSP_SET = 'nspSet'; + var PUBLIC_NAMESPACE = 'publicNamespace'; + + var JS_WS_SOCKET_IO_NAME = 'socket.io'; + var JS_WS_NAME = 'ws'; + + // for ws client + var ON_MESSAGE_PROP_NAME$1 = 'onMessage'; + var ON_RESULT_PROP_NAME$1 = 'onResult'; + var ON_ERROR_PROP_NAME$1 = 'onError'; + var ON_READY_PROP_NAME = 'onReady'; + var ON_LOGIN_PROP_NAME = 'onLogin'; // new @1.8.6 + + var SEND_MSG_PROP_NAME = 'send'; + // breaking change from 1.8.8 the above name was the name below + // the names are using in the new resolver.on getter interface + var MESSAGE_PROP_NAME = 'message'; + var RESULT_PROP_NAME = 'result'; + var ERROR_PROP_NAME = 'error'; + var READY_PROP_NAME$1 = 'ready'; + var LOGIN_PROP_NAME = 'login'; // new @1.8.6 + var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; + var TOKEN_PARAM_NAME = 'token'; + var IO_ROUNDTRIP_LOGIN = 'roundtip'; + var IO_HANDSHAKE_LOGIN = 'handshake'; + + /** + * 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)); + + // 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$1 = /*@__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 = { name: { configurable: true } }; + + 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$1(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$2('', e) + } + var msg = e.message || NO_ERROR_MSG$1; + var detail = e.detail || e; + switch (true) { + case e instanceof Jsonql406Error$1: + throw new Jsonql406Error$1(msg, detail) + case e instanceof Jsonql500Error$1: + throw new Jsonql500Error$1(msg, detail) + case e instanceof JsonqlAuthorisationError$1: + throw new JsonqlAuthorisationError$1(msg, detail) + case e instanceof JsonqlContractAuthError$1: + throw new JsonqlContractAuthError$1(msg, detail) + case e instanceof JsonqlResolverAppError$1: + throw new JsonqlResolverAppError$1(msg, detail) + case e instanceof JsonqlResolverNotFoundError$1: + throw new JsonqlResolverNotFoundError$1(msg, detail) + case e instanceof JsonqlEnumError$1: + throw new JsonqlEnumError$1(msg, detail) + case e instanceof JsonqlTypeError$1: + throw new JsonqlTypeError$1(msg, detail) + case e instanceof JsonqlCheckerError$1: + throw new JsonqlCheckerError$1(msg, detail) + case e instanceof JsonqlValidationError$2: + throw new JsonqlValidationError$2(msg, detail) + case e instanceof JsonqlServerError$1: + throw new JsonqlServerError$1(msg, detail) + default: + throw new JsonqlError$2(msg, detail) + } + } + + // constants + + var SOCKET_IO = JS_WS_SOCKET_IO_NAME; + + var MISSING_PROP_ERR = 'Missing property in contract!'; + + var EMIT_EVT = EMIT_REPLY_TYPE; + + var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; + + var MY_NAMESPACE = 'myNamespace'; + + var CB_FN_NAME = 'on'; + + // 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$2 = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + + // quick and dirty to turn non array to array + var toArray$2 = function (arg) { return isArray(arg) ? arg : [arg]; }; + + /** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ + var isObjectHasKey$3 = function(obj, key) { + try { + var keys = Object.keys(obj); + return inArray$2(keys, key) + } catch(e) { + // @BUG when the obj is not an OBJECT we got some weird output + return false; + /* + console.info('obj', obj) + console.error(e) + throw new Error(e) + */ + } + }; + + /** + * 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('_'); + }; + + /** + * @param {boolean} sec return in second or not + * @return {number} timestamp + */ + var timestamp$2 = function (sec) { + if ( sec === void 0 ) sec = false; + + var time = Date.now(); + return sec ? Math.floor( time / 1000 ) : time; + }; + + /** + * 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!"); + }; + + /** + * 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$1 = 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$2(value)) + ); }, Reflect.apply(mainFn, null, args)) + ); + } + ); + }; + + // break it out on its own because + + + /** + * This one return a different result from the chainPromises + * it will be the same like chainFns that take one promise resolve as the next fn parameter + * @param {function} initPromise a function that accept param and resolve result + * @param {array} promises array of function pass that resolve promises + * @return {promise} resolve the processed result + */ + function chainProcessPromises(initPromise) { + var promises = [], len = arguments.length - 1; + while ( len-- > 0 ) promises[ len ] = arguments[ len + 1 ]; + + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return ( + promises.reduce(function (promiseChain, currentTask) { return ( + promiseChain.then(function (chainResult) { return ( + currentTask(chainResult) + ); } + ) + ); }, Reflect.apply(initPromise, null, args)) + ); + } + } + + /** + * 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$1(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$1(resolver, name, data, overwrite) { + if ( overwrite === void 0 ) overwrite = false; + + var check = objHasProp$1(resolver, name); + if (overwrite === false && check !== undefined) { + // console.info(`NOT INJECTED`) + return resolver; + } + /* this will throw error! + 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; + } + + // 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$1(contract) { + return isPlainObject(contract) + && ( + isObjectHasKey$3(contract, QUERY_NAME$1) + || isObjectHasKey$3(contract, MUTATION_NAME$1) + || isObjectHasKey$3(contract, SOCKET_NAME$1) + ) + } + + /** + * 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$1(contract) { + return checkIsContract$1(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$3(contract, 'socket')) { + return contract.socket; + } + return false; + } + + /** + * @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 + * @param {boolean} [fallback=false] this is a fall back option for old code + * @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, fallback) { + if ( fallback === void 0 ) fallback = false; + + var socket = extractSocketPart(contract); + if (socket === false) { + if (fallback) { + return contract; // just return the whole contract + } + throw new JsonqlError$2("socket not found in contract!") + } + var nspSet = {}; + var size = 0; + var publicNamespace; + for (var resolverName in socket) { + var params = socket[resolverName]; + var namespace = params.namespace; + if (namespace) { + if (!nspSet[namespace]) { + ++size; + nspSet[namespace] = {}; + } + nspSet[namespace][resolverName] = params; + if (!publicNamespace) { + if (params.public) { + publicNamespace = namespace; + } + } } - return false; - }; + } + return { size: size, nspSet: nspSet, publicNamespace: publicNamespace } + } - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); + /** + * @NOTE ported from jsonql-ws-client + * Got to make sure the connection order otherwise + * it will hang + * @param {object} nspSet contract + * @param {string} publicNamespace like the name said + * @return {array} namespaces in order + */ + function getNamespaceInOrder(nspSet, publicNamespace) { + var names = []; // need to make sure the order! + for (var namespace in nspSet) { + if (namespace === publicNamespace) { + names[1] = namespace; } else { - this.result = value; + names[0] = namespace; } - }; + } + return names; + } - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; + // ported from jsonql-params-validator - Object.defineProperties( EventService.prototype, prototypeAccessors ); + /** + * @param {*} args arguments to send + *@return {object} formatted payload + */ + var formatPayload$1 = function (args) { + var obj; - return EventService; - }(NbEventServiceBase)); + return ( + ( obj = {}, obj[QUERY_ARG_NAME$1] = args, obj ) + ); + }; - // default + /** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ + function getNameFromPayload$1(payload) { + return Object.keys(payload)[0] + } - // this will generate a event emitter and will be use everywhere - // output - function getEventEmitter(debugOn) { - var logger = debugOn ? function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + /** + * wrapper method to add the timestamp as well + * @param {string} resolverName + * @param {*} payload + * @return {object} delierable + */ + function createDeliverable$1(resolverName, payload) { + var obj; - args.unshift('[NBS]'); - console.log.apply(null, args); - }: undefined; - return new EventService({ logger: logger }) + return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME$1] = [ timestamp$2() ], obj ) } - // bunch of generic helpers + /** + * @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(resolverName) && isArray(args)) { + var payload = formatPayload$1(args); + if (jsonp === true) { + return payload; + } + return createDeliverable$1(resolverName, payload) + } + throw new JsonqlValidationError$2("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) + } /** - * DIY in Array - * @param {array} arr to check from - * @param {*} value to check against - * @return {boolean} true on found + * string version of the createQuery + * @return {string} */ - var inArray$2 = function (arr, value) { return !!arr.filter(function (a) { return a === value; }).length; }; + function createQueryStr(resolverName, args, jsonp) { + if ( args === void 0 ) args = []; + if ( jsonp === void 0 ) jsonp = false; - // quick and dirty to turn non array to array - var toArray$1 = function (arg) { return isArray(arg) ? arg : [arg]; }; + return JSON.stringify(createQuery$1(resolverName, args, jsonp)) + } /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false */ - var isObjectHasKey$3 = function(obj, key) { - try { - var keys = Object.keys(obj); - return inArray$2(keys, key) - } catch(e) { - // @BUG when the obj is not an OBJECT we got some weird output - return false; - /* - console.info('obj', obj) - console.error(e) - throw new Error(e) - */ - } - }; + function isNull(value) { + return value === null; + } /** - * create a event name - * @param {string[]} args - * @return {string} event name for use + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false */ - var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + function isUndefined(value) { + return value === undefined; + } - return args.join('_'); - }; + /** `Object#toString` result references. */ + var boolTag$2 = '[object Boolean]'; /** - * @param {boolean} sec return in second or not - * @return {number} timestamp + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false */ - var timestamp$2 = function (sec) { - if ( sec === void 0 ) sec = false; - - var time = Date.now(); - return sec ? Math.floor( time / 1000 ) : time; - }; + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag$2); + } /** - * Simple check if the prop is function - * @param {*} prop input - * @return {boolean} true on success + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} */ - var isFunc = function (prop) { - if (typeof prop === 'function') { + + function notEmpty (a) { + if (isArray(a)) { return true; } - console.error("Expect to be Function type!"); + return a !== undefined && a !== null && trim(a) !== ''; + } + + // validator numbers + /** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a check 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(value) ? false : !isNaN$1( parseFloat(value) ) + }; + + // validate string type + /** + * @param {string} value expected value + * @return {boolean} true if OK + */ + var checkIsString$1 = function(value) { + return (trim(value) !== '') ? isString(value) : false; + }; + + // check for boolean + /** + * @param {boolean} value expected + * @return {boolean} true if OK + */ + var checkIsBoolean$1 = function(value) { + return isBoolean(value); }; + // validate any thing only check if there is something /** - * 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 + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK */ - 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 ]; + var checkIsAny$1 = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; - 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$1(value)) - ); }, Reflect.apply(mainFn, null, args)) - ); + if (!isUndefined(value) && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && !isNull(value))) { + return true; + } } - ); + return false; }; - // break it out on its own because - + // Good practice rule - No magic number - /** - * This one return a different result from the chainPromises - * it will be the same like chainFns that take one promise resolve as the next fn parameter - * @param {function} initPromise a function that accept param and resolve result - * @param {array} promises array of function pass that resolve promises - * @return {promise} resolve the processed result - */ - function chainProcessPromises(initPromise) { - var promises = [], len = arguments.length - 1; - while ( len-- > 0 ) promises[ len ] = arguments[ len + 1 ]; + var ARGS_NOT_ARRAY_ERR$1 = "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$1 = "params is not an array! Did something gone wrong when you generate the contract.json?"; + var EXCEPTION_CASE_ERR$1 = 'Could not understand your arguments and parameter structure!'; + // @TODO the jsdoc return array. and we should also allow array syntax + var DEFAULT_TYPE$3 = DEFAULT_TYPE$2; + var ARRAY_TYPE_LFT$3 = ARRAY_TYPE_LFT$2; + var ARRAY_TYPE_RGT$3 = ARRAY_TYPE_RGT$2; + + var TYPE_KEY$3 = TYPE_KEY$2; + var OPTIONAL_KEY$3 = OPTIONAL_KEY$2; + var ENUM_KEY$3 = ENUM_KEY$2; + var ARGS_KEY$3 = ARGS_KEY$2; + var CHECKER_KEY$3 = CHECKER_KEY$2; + var ALIAS_KEY$3 = ALIAS_KEY$2; + + var ARRAY_TYPE$3 = ARRAY_TYPE$2; + var OBJECT_TYPE$3 = OBJECT_TYPE$2; + var STRING_TYPE$3 = STRING_TYPE$2; + var BOOLEAN_TYPE$3 = BOOLEAN_TYPE$2; + var NUMBER_TYPE$3 = NUMBER_TYPE$2; + var KEY_WORD$3 = KEY_WORD$2; + var OR_SEPERATOR$3 = OR_SEPERATOR$2; - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + // not actually in use + // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - return ( - promises.reduce(function (promiseChain, currentTask) { return ( - promiseChain.then(function (chainResult) { return ( - currentTask(chainResult) - ); } - ) - ); }, Reflect.apply(initPromise, null, args)) - ); - } - } + // primitive types /** - * 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 + * 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 */ - 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 - }); + var combineFn$1 = function(type) { + switch (type) { + case NUMBER_TYPE$3: + return checkIsNumber$1; + case STRING_TYPE$3: + return checkIsString$1; + case BOOLEAN_TYPE$3: + return checkIsBoolean$1; + default: + return checkIsAny$1; } - 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; - } + // validate array type /** - * 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 + * @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 */ - function injectToFn(resolver, name, data, overwrite) { - if ( overwrite === void 0 ) overwrite = false; + var checkIsArray$1 = function(value, type) { + if ( type === void 0 ) type=''; - var check = objHasProp(resolver, name); - if (overwrite === false && check !== undefined) { - // console.info(`NOT INJECTED`) - return resolver; - } - /* this will throw error! - if (overwrite === true && check !== undefined) { - delete resolver[name] // delete this property + 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$1(type)(v); }); + return !(c.length > 0) } - */ - // 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; - } + return false; + }; - // 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 + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array */ - function checkIsContract$1(contract) { - return isPlainObject(contract) - && ( - isObjectHasKey$3(contract, QUERY_NAME) - || isObjectHasKey$3(contract, MUTATION_NAME) - || isObjectHasKey$3(contract, SOCKET_NAME) - ) - } + var isArrayLike$2 = 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$3) > -1 && type.indexOf(ARRAY_TYPE_RGT$3) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$3, '').replace(ARRAY_TYPE_RGT$3, ''); + if (_type.indexOf(OR_SEPERATOR$3)) { + return _type.split(OR_SEPERATOR$3) + } + return [_type] + } + return false; + }; /** - * 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 + * 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 */ - function isContract$1(contract) { - return checkIsContract$1(contract) ? contract : false; - } + var arrayTypeHandler$1 = 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$1(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray$1(arg, t); }).length; + }; + // validate object type /** - * 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 + * @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 */ - function extractSocketPart(contract) { - if (isObjectHasKey$3(contract, 'socket')) { - return contract.socket; + var checkIsObject$1 = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray$1(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 (!isUndefined(_value)) { + if ((tmp = isArrayLike$2(type)) !== false) { + return !arrayTypeHandler$1({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$1(type)(_value) + } + return true; + }).length) + }).length; + } } return false; - } + }; /** - * @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 - * @param {boolean} [fallback=false] this is a fall back option for old code - * @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 + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} */ - function groupByNamespace(contract, fallback) { - if ( fallback === void 0 ) fallback = false; - - var socket = extractSocketPart(contract); - if (socket === false) { - if (fallback) { - return contract; // just return the whole contract - } - throw new JsonqlError("socket not found in contract!") + var objectTypeHandler$1 = 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); } - var nspSet = {}; - var size = 0; - var publicNamespace; - for (var resolverName in socket) { - var params = socket[resolverName]; - var namespace = params.namespace; - if (namespace) { - if (!nspSet[namespace]) { - ++size; - nspSet[namespace] = {}; - } - nspSet[namespace][resolverName] = params; - if (!publicNamespace) { - if (params.public) { - publicNamespace = namespace; - } - } + // just simple check + return checkIsObject$1.apply(null, _args) + }; + + /** + * just a simple util for helping to debug + * @param {array} args arguments + * @return {void} + */ + function log() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + try { + if (window && window.console) { + Reflect.apply(console.log, console, args); } - } - return { size: size, nspSet: nspSet, publicNamespace: publicNamespace } + } catch(e) {} } + // 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 + /** - * @NOTE ported from jsonql-ws-client - * Got to make sure the connection order otherwise - * it will hang - * @param {object} nspSet contract - * @param {string} publicNamespace like the name said - * @return {array} namespaces in order + * 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 */ - function getNamespaceInOrder(nspSet, publicNamespace) { - var names = []; // need to make sure the order! - for (var namespace in nspSet) { - if (namespace === publicNamespace) { - names[1] = namespace; - } else { - names[0] = namespace; - } + var optionalHandler$1 = function( params ) { + var arg = params.arg; + var param = params.param; + if (notEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler$2(type, params); } + ).length) } - return names; - } + return false; + }; - // ported from jsonql-params-validator + /** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ + var validateHandler$2 = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$3: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler$1(value) + case type === ARRAY_TYPE$3: + // debugFn('call ARRAY_TYPE') + return !checkIsArray$1(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$2(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler$1(value, tmp) + default: + return !combineFn$1(type)(value.arg) + } + }; /** - * @param {*} args arguments to send - *@return {object} formatted payload + * 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 formatPayload$1 = function (args) { - var obj; + var getOptionalValue$1 = function(arg, param) { + if (!isUndefined(arg)) { + return arg; + } + return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null) + }; - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); + /** + * 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$1 = 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$1(params)) { + // debugFn('params value', params) + throw new JsonqlError$2(PARAMS_NOT_ARRAY_ERR$1) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray$1(args)) { + throw new JsonqlError$2(ARGS_NOT_ARRAY_ERR$1) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + log(1); + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }) + case params[0].variable === true: // using spread syntax + log(2); + 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: + log(3); + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue$1(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: + log(4); + var ctn = params.length; + // this happens when we have those array. type + var _type = [ DEFAULT_TYPE$3 ]; + // 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$1(arg, param) : arg, + index: i, + param: param, + optional: optional + } + }) + // @TODO find out if there is more cases not cover + default: // this should never happen + log(5); + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError$2(EXCEPTION_CASE_ERR$1, { 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 /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments */ - function getNameFromPayload$1(payload) { - return Object.keys(payload)[0] - } + var processReturn$1 = function (result) { return result.map(function (r) { return r.arg; }); }; /** - * wrapper method to add the timestamp as well - * @param {string} resolverName - * @param {*} payload - * @return {object} delierable + * 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 */ - function createDeliverable(resolverName, payload) { + var validateSync$1 = function(args, params, withResult) { var obj; - return ( obj = {}, obj[resolverName] = payload, obj[TIMESTAMP_PARAM_NAME] = [ timestamp$2() ], obj ) - } + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs$1(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$1(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$2(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY$1] = checkResult, obj[DATA_KEY$1] = processReturn$1(cleanArgs), obj ) + }; /** - * @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 + * 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 */ - function createQuery$1(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; + var validateAsync$2 = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; - if (isString(resolverName) && isArray(args)) { - var payload = formatPayload$1(args); - if (jsonp === true) { - return payload; + return new Promise(function (resolver, rejecter) { + var result = validateSync$1(args, params, withResult); + if (withResult) { + return result[ERROR_KEY$1].length ? rejecter(result[ERROR_KEY$1]) + : resolver(result[DATA_KEY$1]) } - return createDeliverable(resolverName, payload) - } - throw new JsonqlValidationError$1("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) + }; /** - * string version of the createQuery - * @return {string} + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs */ - function createQueryStr(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; + var isInArray$1 = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; + }; - return JSON.stringify(createQuery$1(resolverName, args, jsonp)) - } + var isObjectHasKey$4 = function(obj, key) { + var keys = Object.keys(obj); + return isInArray$1(keys, key) + }; - // this will replace the preConfigCheck in jsonql-koa + // just not to make my head hurt + var isEmpty$1 = function (value) { return !notEmpty(value); }; /** - * the rest of the argument will be functions that - * need to add to the process chain, - * finally return a function to accept the config - * @param {object} defaultOptions prepared before hand - * @param {object} constProps prepare before hand - * @param {array} fns arguments see description - * @return {function} to perform the final configuration check + * 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 preConfigCheck(defaultOptions, constProps) { - var fns = [], len = arguments.length - 2; - while ( len-- > 0 ) fns[ len ] = arguments[ len + 2 ]; - - // should have just add the method to the last - var finalFn = function (opt) { return injectToFn(opt, CHECKED_KEY, timestamp$2()); }; - // if there is more than one then chain it otherwise just return the zero idx one - var fn = Reflect.apply(chainFns, null, fns.concat(finalFn)); - // 0.8.8 add a default property empty object - return function (config) { - if ( config === void 0 ) config = {}; + function mapAliasConfigKeys$1(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$3]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) + } - return fn(config, defaultOptions, constProps); + /** + * 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$1(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$1(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return isObjectHasKey$4(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !isObjectHasKey$4(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back } } - // breaking out the inner methods generator in here - /** - * generate authorisation specific methods - * @param {object} jsonqlInstance instance of this - * @param {string} name of method - * @param {object} opts configuration - * @param {object} contract to match - * @return {function} for use + * 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 */ - var authMethodGenerator = function (jsonqlInstance, name, opts, contract) { - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + function processConfigAction$1(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; - var params = contract.auth[name].params; - var values = params.map(function (p, i) { return args[i]; }); - var header = args[params.length] || {}; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [name, values, header]); } - ) - .catch(finalCatch) + return ( + isUndefined(config[key]) || (value[OPTIONAL_KEY$3] === true && isEmpty$1(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$3] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$3] = config[key], obj$1[TYPE_KEY$3] = value[TYPE_KEY$3], obj$1[OPTIONAL_KEY$3] = value[OPTIONAL_KEY$3] || false, obj$1[ENUM_KEY$3] = value[ENUM_KEY$3] || false, obj$1[CHECKER_KEY$3] = value[CHECKER_KEY$3] || false, obj$1 ) + ); } - }; + ) + } /** - * Break up the different type each - create query methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op + * 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 */ - var createQueryMethods = function (obj, jsonqlInstance, ee, config, contract) { - var query = {}; - var loop = function ( queryFn ) { - // to keep it clean we use a param to id the auth method - // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; - // generate the query method - query = injectToFn(query, queryFn, function queryFnHandler() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; + function prepareArgsForValidation$1(opts, appProps) { + var ref = preservePristineValues$1(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction$1(config, checkAgainstAppProps), + pristineValues + ] + } - // obj.query[queryFn] = (...args) => { - var params = contract.query[queryFn].params; - var _args = params.map(function (param, i) { return args[i]; }); - // debug('query', queryFn, _params); - // @TODO this need to change - // the +1 parameter is the extra headers we want to pass - var header = args[params.length] || {}; - // @TODO validate against the type - return validateAsync$1(_args, params) - .then(function () { return jsonqlInstance - .query - .apply(jsonqlInstance, [queryFn, _args, header]); } - ) - .catch(finalCatch) - }); - }; + // breaking the whole thing up to see what cause the multiple calls issue - for (var queryFn in contract.query) loop( queryFn ); - obj.query = query; - // create an alias to the helloWorld method - obj.helloWorld = query.helloWorld; - return [ obj, jsonqlInstance, ee, config, contract ] - }; + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:validation') /** - * create mutation methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output */ - var createMutationMethods = function (obj, jsonqlInstance, ee, config, contract) { - var mutation = {}; - // process the mutation, the reason the mutation has a fixed number of parameters - // there is only the payload, and conditions parameters - // plus a header at the end - var loop = function ( mutationFn ) { - mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header) { - if ( header === void 0 ) header = {}; - - //obj.mutation[mutationFn] = (payload, conditions, header = {}) => { - var args = [payload, conditions]; - var params = contract.mutation[mutationFn].params; - return validateAsync$1(args, params) - .then(function () { return jsonqlInstance - .mutation - .apply(jsonqlInstance, [mutationFn, payload, conditions, header]); } - ) - .catch(finalCatch) - }); - }; - - for (var mutationFn in contract.mutation) loop( mutationFn ); - obj.mutation = mutation; - return [ obj, jsonqlInstance, ee, config, contract ] - }; + var toArray$3 = function (arg) { return checkIsArray$1(arg) ? arg : [arg]; }; /** - * create auth methods - * @param {object} obj to hold all the objects - * @param {object} jsonqlInstance jsonql class instance - * @param {object} ee eventEmitter - * @param {object} config configuration - * @param {object} contract json - * @return {object} modified output for next op + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK */ - var createAuthMethods = function (obj, jsonqlInstance, ee, config, contract) { - if (config.enableAuth && contract.auth) { - var auth = {}; // v1.3.1 add back the auth prop name in contract - var loginHandlerName = config.loginHandlerName; - var logoutHandlerName = config.logoutHandlerName; - if (contract.auth[loginHandlerName]) { - // changing to the name the config specify - auth[loginHandlerName] = function loginHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLoginAction) - .then(function (token) { - ee.$trigger(ISSUER_NAME, token); - return token; - }) - }; - } - if (contract.auth[logoutHandlerName]) { - auth[logoutHandlerName] = function logoutHandlerFn() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract); - return fn.apply(null, args) - .then(jsonqlInstance.postLogoutAction) - .then(function (r) { - ee.$trigger(LOGOUT_NAME, r); - return r; - }) - }; - } else { - auth[logoutHandlerName] = function logoutHandlerFn() { - jsonqlInstance.postLogoutAction(KEY_WORD); - ee.$trigger(LOGOUT_NAME, KEY_WORD); - }; - } - obj.auth = auth; - } - return obj; - }; + var inArray$3 = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length + ); }; /** - * Here just generate the methods calls - * @param {object} jsonqlInstance what it said - * @param {object} ee event emitter - * @param {object} config configuration - * @param {object} contract the map - * @return {object} with mapped methods + * 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 methodsGenerator(jsonqlInstance, ee, config, contract) { - var obj = {}; - var executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods); - return executor(obj, jsonqlInstance, ee, config, contract) - } + function validateHandler$3(value, cb) { + var obj; - // Generate the resolver for developer to use + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$3] ], + [( obj = {}, obj[TYPE_KEY$3] = toArray$3(value[TYPE_KEY$3]), obj[OPTIONAL_KEY$3] = value[OPTIONAL_KEY$3], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) + } /** - * @param {object} jsonqlInstance jsonql class instance - * @param {object} config options - * @param {object} contract the contract - * @param {object} ee eventEmitter - * @return {object} constructed functions call - */ - var generator = function (jsonqlInstance, config, contract, ee) { - // V1.3.0 - now everything wrap inside this method - var client = methodsGenerator(jsonqlInstance, ee, config, contract); - // create the rest of the methods - if (config.enableAuth) { - /** - * new method to allow retrieve the current login user data - * @return {*} userdata - */ - client.userdata = function () { return jsonqlInstance.userdata; }; - // allow getting the token for valdiate agains the socket - // if it's not require auth there is no point of calling getToken - client.getToken = function () { return jsonqlInstance.rawAuthToken; }; - } - // this will pass to the ws-client if needed - // client.eventEmitter = ee; - // this will require a param - if (config.exposeContract) { - // 1.4.0 change from the get (raw) to the getContract cache and raw version - client.getContract = function () { return jsonqlInstance.getContract(); }; - } - // this is for the ws to use later - client.eventEmitter = ee; - client.version = '0.1.0'; - // output - return client; - }; - - // all the client configuration options here - var constProps = { - contract: false, - MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong? - CONTENT_TYPE: CONTENT_TYPE, - BEARER: BEARER, - AUTH_HEADER: AUTH_HEADER + * 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$1 = function (value, enumv) { + if (checkIsArray$1(enumv)) { + return inArray$3(enumv, value) + } + return true; }; - // grab the localhost name and put into the hostname as default - var getHostName = function () { + /** + * 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$1 = function (value, checker) { try { - return [window.location.protocol, window.location.host].join('//') - } catch(e) { - return null + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; } }; - var appProps$1 = { - - hostname: createConfig$1(getHostName(), [STRING_TYPE]), // required the hostname - jsonqlPath: createConfig$1(JSONQL_PATH, [STRING_TYPE]), // The path on the server - - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // add to koa v1.3.0 - this might remove in the future - enableJsonp: createConfig$1(false, [BOOLEAN_TYPE]), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - // enable useJwt by default - useJwt: createConfig$1(true, [BOOLEAN_TYPE]), - - // the header - // v1.2.0 we are using this option during the dev - // so it won't save anything to the localstorage and fetch a new contract - // whenever the browser reload - useLocalstorage: createConfig$1(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage - storageKey: createConfig$1(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage - authKey: createConfig$1(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage - contractExpired: createConfig$1(0, [NUMBER_TYPE]),// -1 always fetch contract, - // 0 never expired, - // > 0 then compare the timestamp with the current one to see if we need to get contract again - // useful during development - keepContract: createConfig$1(true, [BOOLEAN_TYPE]), - exposeContract: createConfig$1(false, [BOOLEAN_TYPE]), - // @1.2.1 new option for the contract-console to fetch the contract with description - showContractDesc: createConfig$1(false, [BOOLEAN_TYPE]), - contractKey: createConfig$1(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this - contractKeyName: createConfig$1(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs - enableTimeout: createConfig$1(false, [BOOLEAN_TYPE]), // @TODO - timeout: createConfig$1(5000, [NUMBER_TYPE]), // 5 seconds - returnInstance: createConfig$1(false, [BOOLEAN_TYPE]), - allowReturnRawToken: createConfig$1(false, [BOOLEAN_TYPE]), - debugOn: createConfig$1(false, [BOOLEAN_TYPE]) - }; - - // we must ensure the user passing the correct options - - function checkOptionsAsync$1(config) { - var contract = config.contract; - return checkConfigAsync$1(config, appProps$1, constProps) - .then(function (opts) { - opts.contract = contract; - return opts; - }) + /** + * 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$1(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$3]) { + return value[ARGS_KEY$3] + } + var check = validateHandler$3(value, cb); + if (check.length) { + log('runValidationAction', key, value); + throw new JsonqlTypeError$1(key, check) + } + if (value[ENUM_KEY$3] !== false && !enumHandler$1(value[ARGS_KEY$3], value[ENUM_KEY$3])) { + log(ENUM_KEY$3, value[ENUM_KEY$3]); + throw new JsonqlEnumError$1(key) + } + if (value[CHECKER_KEY$3] !== false && !checkerHandler$1(value[ARGS_KEY$3], value[CHECKER_KEY$3])) { + log(CHECKER_KEY$3, value[CHECKER_KEY$3]); + throw new JsonqlCheckerError$1(key) + } + return value[ARGS_KEY$3] + } } - // export interface /** - * 1.5.0 overload the orginal functions to pass over the check + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values */ - function checkOptionsAsync$2(config) { - return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsync$1(config) + function runValidation$1(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$1(cb)); + return merge(result, pristineValues) } - // new module interface for @jsonql/client + /// 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') /** - * Check if the contract has socket field and the socket client is suplied - * @param {object} client the http client - * @param {object} contract the json - * @param {object} config the checked configuration - * @param {object} socketClient from the original config - * @return {object} the completed client + * Quick transform + * @param {object} config that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args */ - function initSocketClient(client, contract, config, socketClient) { - if (isObjectHasKey$2(contract, SOCKET_NAME)) { - if (socketClient) { - // pass the contract here one more time in case the constProps overwritten it - config.contract = contract; - config.eventEmitter = client.eventEmitter; - return socketClient(config) - .then(function (sc) { - client[SOCKET_NAME] = sc; - return client; - }) - } else { - throw new JsonqlError("initSocketClient", "socketClient is missing!") - } - } - return client; - } + var configToArgs$1 = function (config, appProps) { + return Promise.resolve( + prepareArgsForValidation$1(config, appProps) + ) + }; /** - * Main interface for jsonql fetch api - * @1.4.8 change this to named export to diff this from the other - * and this is only use with the @jsonql/client to construct the client with ws - * @param {object} Fly the http engine - * @param {object} [config={}] configuration - * @return {object} jsonqlClient + * @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 jsonqlClientModule(fly, config) { + function checkOptionsAsync$3(config, appProps, constProps, cb) { if ( config === void 0 ) config = {}; - var socketClient = config.socketClient; - var debugOn = config.debugOn; - var ee = getEventEmitter(debugOn); - return checkOptionsAsync$2(config) - .then(function (opts) { return ( - { - opts: opts, - baseClient: new JsonqlBaseClient(fly, opts) - } - ); }) - .then(function (ref) { - var opts = ref.opts; - var baseClient = ref.baseClient; - - return getContractFromConfig(baseClient, opts.contract) - .then(function (contract) { return ( - { - opts: opts, - contract: contract, - client: generator(baseClient, opts, contract, ee) - } - ); } - ); - } - ) - .then(function (ref) { - var opts = ref.opts; - var contract = ref.contract; - var client = ref.client; - - return ( - initSocketClient(client, contract, opts, socketClient) - ); - }) + return configToArgs$1(config, appProps) + .then(function (args1) { + // debugFn('args', args1) + return runValidation$1(args1, cb) + }) + // next if every thing good then pass to final merging + .then(function (args2) { return merge({}, args2, constProps); }) } - // export the options for the pre-check to use - // just export the function here for use to save repeat coding - + // create function to construct the config entry so we don't need to keep building object + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:construct-config'); /** - * This will combine the socket client options and merge this one - * then do a pre-check on both at the same time - * @param {object} [extraProps = {}] - * @param {object} [extraConstProps = {}] - * @return {function} to process the developer options + * @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 getPreConfigCheck(extraProps, extraConstProps) { - if ( extraProps === void 0 ) extraProps = {}; - if ( extraConstProps === void 0 ) extraConstProps = {}; - - var aProps = merge({}, appProps$1, extraProps); - var cProps = merge({}, constProps, extraConstProps); + 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; - return preConfigCheck(aProps, cProps, checkConfig$1) + var base = {}; + base[ARGS_KEY$2] = args; + base[TYPE_KEY$2] = type; + if (optional === true) { + base[OPTIONAL_KEY$2] = true; + } + if (checkIsArray$1(enumv)) { + base[ENUM_KEY$2] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY$2] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY$2] = alias; + } + return base; } - // constants + // export also create wrapper methods - var SOCKET_IO = JS_WS_SOCKET_IO_NAME; + // import debug from 'debug'; + // const debugFn = debug('jsonql-params-validator:options:index'); - var MISSING_PROP_ERR = 'Missing property in contract!'; + /** + * 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 = {}; - var EMIT_EVT = EMIT_REPLY_TYPE; + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY$2]; + var e = params[ENUM_KEY$2]; + var c = params[CHECKER_KEY$2]; + var a = params[ALIAS_KEY$2]; + return constructConfig$1.apply(null, [value, type, o, e, c, a]) + }; - var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; + /** + * 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 + */ + var checkConfigAsync$2 = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps= {}; - var MY_NAMESPACE = 'myNamespace'; + return checkOptionsAsync$3(config, appProps, constantProps, validateSync) + } + }; - var CB_FN_NAME = 'on'; + // export + var isString$2 = checkIsString$1; + var validateAsync$3 = validateAsync$2; + + var createConfig$3 = createConfig$2; + + var checkConfigAsync$3 = checkConfigAsync$2(validateSync$1); var BASE_NAME = 'jsonql-ws-client'; /** @@ -9794,7 +10933,7 @@ if (result !== false) { return result } - throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR) + throw new JsonqlResolverNotFoundError$1(MISSING_PROP_ERR) }; /** @@ -9810,7 +10949,7 @@ if (enableAuth) { return groupByNamespace(contract) } - return ( obj$1 = {}, obj$1[NSP_SET] = ( obj = {}, obj[JSONQL_PATH] = getResolverList(contract), obj ), obj$1[PUBLIC_NAMESPACE] = JSONQL_PATH, obj$1 ) + return ( obj$1 = {}, obj$1[NSP_SET] = ( obj = {}, obj[JSONQL_PATH$1] = getResolverList(contract), obj ), obj$1[PUBLIC_NAMESPACE] = JSONQL_PATH$1, obj$1 ) } // group all the small functions here @@ -9844,7 +10983,7 @@ * @return {void} */ var clearMainEmitEvt = function (ee, namespace) { - var nsps = toArray$1(namespace); + var nsps = toArray$2(namespace); nsps.forEach(function (n) { ee.$off(createEvt(n, EMIT_REPLY_TYPE)); }); @@ -9861,12 +11000,12 @@ * @return {void} nothing */ function respondHandler(data, resolver, rejecter) { - if (isObjectHasKey$3(data, ERROR_KEY)) { - debugFn('-- rejecter called --', data[ERROR_KEY]); - rejecter(data[ERROR_KEY]); - } else if (isObjectHasKey$3(data, DATA_KEY)) { - debugFn('-- resolver called --', data[DATA_KEY]); - resolver(data[DATA_KEY]); + if (isObjectHasKey$3(data, ERROR_KEY$1)) { + debugFn('-- rejecter called --', data[ERROR_KEY$1]); + rejecter(data[ERROR_KEY$1]); + } else if (isObjectHasKey$3(data, DATA_KEY$1)) { + debugFn('-- resolver called --', data[DATA_KEY$1]); + resolver(data[DATA_KEY$1]); } else { debugFn('-- UNKNOWN_RESULT --', data); rejecter({message: UNKNOWN_RESULT, error: data}); @@ -9891,7 +11030,7 @@ var eventName = createEvt(namespace, EMIT_REPLY_TYPE); var RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME$1; debugFn$1(("actionCall: " + eventName + " --> " + resolverName), args); - ee.$trigger(eventName, [resolverName, toArray$1(args)]); + ee.$trigger(eventName, [resolverName, toArray$2(args)]); // once we trigger there is nothing return from the resolve // @TODO if we need the next then call to have the result back // then we need to listen to the event callback here as well @@ -9916,14 +11055,14 @@ debugFn$2('got payload for', messagePayload); // @NOTE change from sync interface to async @ 1.0.0 // this way we will able to catch all the error(s) - validateAsync$1(toArray$1(messagePayload), params.params, true) + validateAsync$3(toArray$2(messagePayload), params.params, true) .then(function (result) { // here is the different we don't throw error instead we trigger onError - if (result[ERROR_KEY] && result[ERROR_KEY].length) { - debugFn$2("got ERROR_KEY", result[ERROR_KEY]); + if (result[ERROR_KEY$1] && result[ERROR_KEY$1].length) { + debugFn$2("got ERROR_KEY", result[ERROR_KEY$1]); ee.$call( createEvt(namespace, resolverName, ERROR_SUBFIX), - [new JsonqlValidationError$1(resolverName, result[ERROR_KEY])] + [new JsonqlValidationError$2(resolverName, result[ERROR_KEY$1])] ); } else { // return it just for the catch to work - if any @@ -9934,7 +11073,7 @@ debugFn$2("error after validateAsync", err); ee.$call( createEvt(namespace, resolverName, ERROR_SUBFIX), - [new JsonqlValidationError$1(resolverName, err)] + [new JsonqlValidationError$2(resolverName, err)] ); }); }, function sendGetter() { // add in 1.1.4 @@ -9942,9 +11081,9 @@ var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; - return validateAsync$1(args, params.params, true) + return validateAsync$3(args, params.params, true) .then(function (_args) { return actionCall(ee, namespace, resolverName, useCallbackStyle, _args); }) - .catch(finalCatch) + .catch(finalCatch$1) } }) ); }; @@ -9963,8 +11102,8 @@ */ function setupCallbackApi(fn, ee, namespace, resolverName, params) { return [ - injectToFn(fn, CB_FN_NAME, function(evtName, callback) { - if (isString$1(evtName) && isFunc(callback)) { + injectToFn$1(fn, CB_FN_NAME, function(evtName, callback) { + if (isString$2(evtName) && isFunc(callback)) { switch(evtName) { case RESULT_PROP_NAME: ee.$on( @@ -9996,7 +11135,7 @@ default: ee.$trigger( createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), - new JsonqlError(resolverName, ("Unknown event name " + evtName + "!")) + new JsonqlError$2(resolverName, ("Unknown event name " + evtName + "!")) ); } } @@ -10016,7 +11155,7 @@ * @return {array} */ var setupNamespace = function (fn, ee, namespace, resolverName, params, useCallbackStyle) { return [ - injectToFn(fn, MY_NAMESPACE, namespace), + injectToFn$1(fn, MY_NAMESPACE, namespace), ee, namespace, resolverName, @@ -10099,7 +11238,7 @@ useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError); args.push(setupSend); // get the executor - var executor = Reflect.apply(chainFns, null, args); + var executor = Reflect.apply(chainFns$1, null, args); // debug(exe) return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle]) } @@ -10122,9 +11261,9 @@ var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; - return validateAsync$1(args, params.params, true) + return validateAsync$3(args, params.params, true) .then(function (_args) { return actionCall(ee, namespace, resolverName, useCallbackStyle, _args); }) - .catch(finalCatch) + .catch(finalCatch$1) } } @@ -10199,8 +11338,8 @@ * @return {object} obj */ function createCallbackHandler(obj, ee, nspSet, opts) { - return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) { - if (isString$1(evtName) && isFunc(callback)) { + return injectToFn$1(obj, CB_FN_NAME, function onHandler(evtName, callback) { + if (isString$2(evtName) && isFunc(callback)) { switch (evtName) { case ERROR_PROP_NAME: for (var namespace in nspSet) { @@ -10216,7 +11355,7 @@ ee.$on(READY_PROP_NAME$1, callback); break; default: - ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, ("Unknown event name " + evtName + "!"))); + ee.$trigger(ERROR_PROP_NAME, new JsonqlError$2(CB_FN_NAME, ("Unknown event name " + evtName + "!"))); } } // @TODO need to issue another error here! @@ -10235,12 +11374,12 @@ * @return {array} modified input */ var setupLoginHandler = function (obj, ee, opts) { return [ - injectToFn(obj, opts.loginHandlerName, function loginHandler(token) { - if (token && isString$1(token)) { + injectToFn$1(obj, opts.loginHandlerName, function loginHandler(token) { + if (token && isString$2(token)) { return ee.$trigger(LOGIN_EVENT_NAME, [token]) } // should trigger a global error instead @TODO - throw new JsonqlValidationError$1(opts.loginHandlerName, ("Unexpected token " + token)) + throw new JsonqlValidationError$2(opts.loginHandlerName, ("Unexpected token " + token)) }), ee, opts @@ -10254,7 +11393,7 @@ * @return {object} the modified obj */ var setupLogoutHandler = function (obj, ee, opts) { return ( - injectToFn(obj, opts.logoutHandlerName, function logoutHandler() { + injectToFn$1(obj, opts.logoutHandlerName, function logoutHandler() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; @@ -10271,7 +11410,7 @@ */ function createAuthMethods$1(obj, ee, opts) { if (opts.enableAuth) { - return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts) + return chainFns$1(setupLoginHandler, setupLogoutHandler)(obj, ee, opts) } return obj; } @@ -10299,7 +11438,7 @@ var fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle); // this should set as a getter therefore can not be overwrite by accident // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee) - obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle)); + obj = injectToFn$1(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle)); } } // move this two method down to helpers @@ -10553,7 +11692,7 @@ var toString$1 = {}.toString; - var isArray$3 = Array.isArray || function (arr) { + var isArray$1 = Array.isArray || function (arr) { return toString$1.call(arr) == '[object Array]'; }; @@ -10821,7 +11960,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$3(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -10886,7 +12025,7 @@ }; Buffer$2.concat = function concat (list, length) { - if (!isArray$3(list)) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -12321,22 +13460,22 @@ var AVAILABLE_METHODS = [IO_ROUNDTRIP_LOGIN, IO_HANDSHAKE_LOGIN]; var defaultOptions = { - useCallbackStyle: createConfig$1(false, [BOOLEAN_TYPE]), - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + useCallbackStyle: createConfig$3(false, [BOOLEAN_TYPE$2]), + loginHandlerName: createConfig$3(ISSUER_NAME$1, [STRING_TYPE$2]), + logoutHandlerName: createConfig$3(LOGOUT_NAME$1, [STRING_TYPE$2]), // this is for socket.io - loginMethod: createConfig$1(IO_HANDSHAKE_LOGIN, [STRING_TYPE], ( obj$9 = {}, obj$9[ENUM_KEY] = AVAILABLE_METHODS, obj$9 )), + loginMethod: createConfig$3(IO_HANDSHAKE_LOGIN, [STRING_TYPE$2], ( obj$9 = {}, obj$9[ENUM_KEY$2] = AVAILABLE_METHODS, obj$9 )), // we will use this for determine the socket.io client type as well - useJwt: createConfig$1(true, [BOOLEAN_TYPE, STRING_TYPE]), - hostname: createConfig$1(false, [STRING_TYPE]), - namespace: createConfig$1(JSONQL_PATH, [STRING_TYPE]), - wsOptions: createConfig$1({}, [OBJECT_TYPE]), + useJwt: createConfig$3(true, [BOOLEAN_TYPE$2, STRING_TYPE$2]), + hostname: createConfig$3(false, [STRING_TYPE$2]), + namespace: createConfig$3(JSONQL_PATH$1, [STRING_TYPE$2]), + wsOptions: createConfig$3({}, [OBJECT_TYPE$2]), // make this null as default don't set this here, only set in the down stream // serverType: createConfig(null, [STRING_TYPE], {[ENUM_KEY]: AVAILABLE_SERVERS}), // we require the contract already generated and pass here - contract: createConfig$1({}, [OBJECT_TYPE], ( obj$1$1 = {}, obj$1$1[CHECKER_KEY] = isContract$1, obj$1$1 )), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - token: createConfig$1(false, [STRING_TYPE]) + contract: createConfig$3({}, [OBJECT_TYPE$2], ( obj$1$1 = {}, obj$1$1[CHECKER_KEY$2] = isContract$1, obj$1$1 )), + enableAuth: createConfig$3(false, [BOOLEAN_TYPE$2]), + token: createConfig$3(false, [STRING_TYPE$2]) }; // create options @@ -12363,10 +13502,10 @@ * @return {promise} resolve to the checked opitons */ function checkOptionsWrapper(config, dOpt, cProps) { - if (objHasProp(config, CHECKED_KEY)) { + if (objHasProp$1(config, CHECKED_KEY$1)) { return Promise.resolve(config) } - return checkConfigAsync$1(config, dOpt, cProps) + return checkConfigAsync$3(config, dOpt, cProps) } /** @@ -12682,7 +13821,7 @@ */ var extractWsPayload = function (payload) { var data = payload.data; - var json = isString$1(data) ? JSON.parse(data) : data; + var json = isString$2(data) ? JSON.parse(data) : data; // debugFn('extractWsPayload', json) var fdata; if ((fdata = isWsReply(json)) !== false) { @@ -12692,7 +13831,7 @@ type: fdata[WS_REPLY_TYPE] }; } - throw new JsonqlError('payload can not be decoded', payload) + throw new JsonqlError$2('payload can not be decoded', payload) }; // the WebSocket main handler diff --git a/packages/@jsonql/client/dist/jsonql-client-ws.debug.js.map b/packages/@jsonql/client/dist/jsonql-client-ws.debug.js.map index d88bef65..557f896a 100644 --- a/packages/@jsonql/client/dist/jsonql-client-ws.debug.js.map +++ b/packages/@jsonql/client/dist/jsonql-client-ws.debug.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/lodash-es/isNull.js","../node_modules/rollup-plugin-node-globals/src/global.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/lodash-es/isUndefined.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.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/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-params-validator/src/not-empty.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/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/log.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/check-options-sync.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/store/plugins/defaults.js","../node_modules/store/plugins/expire.js","../node_modules/jsonql-client/src/stores/local-store.js","../node_modules/jsonql-client/src/stores/session-store.js","../node_modules/jsonql-client/src/stores/index.js","../node_modules/jsonql-client/src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-client/src/base/http-cls.js","../node_modules/jsonql-client/src/base/contract-cls.js","../node_modules/jsonql-client/src/base/auth-cls.js","../node_modules/jsonql-client/src/base/base-cls.js","../node_modules/jsonql-client/src/base/index.js","../node_modules/nb-event-service/src/hash-code.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../node_modules/jsonql-client/src/ee.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-utils/src/chain-promises.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-utils/src/pre-config-check.js","../node_modules/jsonql-client/src/core/methods-generator.js","../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../node_modules/jsonql-client/src/options/base-options.js","../node_modules/jsonql-client/src/options/check-options-async.js","../node_modules/jsonql-client/src/options/index.js","../node_modules/jsonql-client/module.js","../node_modules/jsonql-client/opt.js","../node_modules/jsonql-ws-client/src/options/constants.js","../node_modules/jsonql-ws-client/src/utils/process-contract.js","../node_modules/jsonql-ws-client/src/utils/helpers.js","../node_modules/jsonql-ws-client/src/core/respond-handler.js","../node_modules/jsonql-ws-client/src/core/action-call.js","../node_modules/jsonql-ws-client/src/core/setup-callback-api.js","../node_modules/jsonql-ws-client/src/core/setup-resolver.js","../node_modules/jsonql-ws-client/src/core/resolver-methods.js","../node_modules/jsonql-ws-client/src/core/setup-auth-methods.js","../node_modules/jsonql-ws-client/src/core/generator.js","../node_modules/buffer-es6/isArray.js","../node_modules/jsonql-ws-client/src/options/index.js","../node_modules/jsonql-ws-client/src/api.js","../node_modules/@jsonql/ws/src/options/index.js","../node_modules/@jsonql/ws/src/core/create-ws-client.js","../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../node_modules/@jsonql/ws/src/core/create-client.js","../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../node_modules/@jsonql/ws/src/ws-client-resolver.js","../node_modules/@jsonql/ws/index.js","../node_modules/@jsonql/ws/opt.js","../ws.js"],"sourcesContent":["/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\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","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\n","/**\n * Checks if `value` is `null`.\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 `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\nfunction isNull(value) {\n return value === null;\n}\n\nexport default isNull;\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\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","/**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\nfunction isUndefined(value) {\n return value === undefined;\n}\n\nexport default isUndefined;\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 * 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 * 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 * 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","/**\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","/** 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","/** 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 * 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","/** 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","/**\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","/**\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","/** 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","/** 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 * 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 * 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 * 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","/**\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","/**\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 * 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 * 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","/** 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 * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nimport { trim, isArray } from './lodash'\n\nexport default a => {\n if (isArray(a)) {\n return true;\n }\n return a !== undefined && a !== null && trim(a) !== '';\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\nimport { isNaN, isString } from './lodash'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a check 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 { isString, trim } from './lodash'\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\nimport { isBoolean } from './lodash'\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return isBoolean(value);\n};\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport { isNull, trim, isUndefined } from './lodash'\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 (!isUndefined(value) && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && !isNull(value))) {\n return true;\n }\n }\n return false;\n};\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const 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)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\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\nimport { isArray, trim } from './lodash'\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\nimport { isPlainObject, isUndefined, filter } from './lodash'\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 (!isUndefined(_value)) {\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 checkIsObject.apply(null, _args)\n}\n","/**\n * just a simple util for helping to debug\n * @param {array} args arguments\n * @return {void}\n */\nexport default function log(...args) {\n try {\n if (window && window.console) {\n Reflect.apply(console.log, console, args)\n }\n } catch(e) {}\n}\n","// move the index.js code here that make more sense to find where things are\nimport { isUndefined } from './lodash'\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\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 UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport log from './log'\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 (!isUndefined(arg)) {\n return arg;\n }\n return (param.optional === true && !isUndefined(param.defaultvalue) ? 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 JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n log(1)\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 log(2)\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 log(3)\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 log(4)\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 log(5)\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","/**\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, merge, mapValues } from '../lodash'\nimport {\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError\n} from 'jsonql-errors'\nimport log from '../log'\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\nimport { merge } from '../lodash'\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 => {\n // debugFn('args', args1)\n return runValidation(args1, cb)\n })\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// this is port back from the client to share across all projects\nimport { merge } from '../lodash'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\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 merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\n}\n","// create function to construct the config entry so we don't need to keep building object\nimport { isFunction, isString } from '../lodash'\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'\nimport 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// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:index');\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 * 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 */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = 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 checkConfigAsync,\n checkConfig,\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'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","var namespace = 'expire_mixin'\n\nmodule.exports = expirePlugin\n\nfunction expirePlugin() {\n\tvar expirations = this.createStore(this.storage, null, this._namespacePrefix+namespace)\n\t\n\treturn {\n\t\tset: expire_set,\n\t\tget: expire_get,\n\t\tremove: expire_remove,\n\t\tgetExpiration: getExpiration,\n\t\tremoveExpiredKeys: removeExpiredKeys\n\t}\n\t\n\tfunction expire_set(super_fn, key, val, expiration) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\texpirations.set(key, expiration)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction expire_get(super_fn, key) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\t_checkExpiration.call(this, key)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction expire_remove(super_fn, key) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\texpirations.remove(key)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction getExpiration(_, key) {\n\t\treturn expirations.get(key)\n\t}\n\t\n\tfunction removeExpiredKeys(_) {\n\t\tvar keys = []\n\t\tthis.each(function(val, key) {\n\t\t\tkeys.push(key)\n\t\t})\n\t\tfor (var i=0; i isObject(obj) && Object.keys(obj).length\n\n// export\nexport {\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n createEvt,\n\n createQuery,\n createMutation,\n getNameFromPayload,\n cacheBurst,\n urlParams,\n resultHandler,\n\n isContract,\n timestamp,\n inArray,\n isObjectHasKey,\n hasProp\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (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 var 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\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport { isString } from 'jsonql-params-validator'\nimport { JsonqlError } from 'jsonql-errors'\n\nconst timestamp = function (sec) {\n if ( sec === void 0 ) sec = false;\n\n var time = Date.now();\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload,\n cacheBurst,\n urlParams,\n resultHandler\n} from '../utils'\nimport {\n isObject,\n isString\n} from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nconst _log = (...args) => {\n try {\n if (window && window.console) {\n Reflect.apply(console.log, null, args)\n }\n } catch(e) {}\n}\n\nexport default class HttpClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n _log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n this.opts = opts;\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n return this.fly.request(\n this.jsonqlEndpoint,\n payload,\n merge({}, { method: POST, params }, options)\n )\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call')\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n */\n get() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\n\nimport { timestamp, isContract, ENDPOINT_TABLE } from '../utils'\nimport { localStore } from '../stores'\n\nimport HttpClass from './http-cls';\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contracts = this.readContract()\n this.log('getContract first call', contracts)\n if (contracts && Array.isArray(contracts)) {\n const contract = contracts[ this[ENDPOINT_TABLE + 'Index'] || 0 ]\n if (contract) {\n return Promise.resolve(contract)\n }\n }\n return this.get()\n .then( this.storeContract.bind(this) )\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object} contract\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n return contract ? this.opts.contract : localStore.get(this.opts.storageKey)\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt'\nimport {\n CREDENTIAL_STORAGE_KEY,\n AUTH_HEADER,\n BEARER\n} from 'jsonql-constants'\n// chain\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth && opts.useJwt) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * Getter to get the login userdata\n * @return {mixed} userdata\n */\n get userdata() {\n return this.jsonqlUserdata; // see base-cls\n }\n\n /**\n * Return the token from session store\n * @return {string} token\n */\n get rawAuthToken() {\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * Setter after login success\n * @TODO this move to a new class to handle multiple login\n * @param {string} token to store\n * @return {*} success store\n */\n storeToken(token) {\n return this.jsonqlToken = token;\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.rawAuthToken;\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\nimport { isObject, isArray } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\n// chaining into the classes\nimport { localStore, sessionStore } from '../stores'\nimport { timestamp, inArray, ENDPOINT_TABLE, USERDATA_TABLE } from '../utils'\n\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n\n super(opts)\n }\n\n // @TODO\n set storeIt(args) {\n // the args MUST contain [0] the key , [1] the content [2] optional expired in\n if (isArray(args) && args.length >= 2) {\n return Reflect.apply(localStore.set, localStore, args)\n }\n throw new JsonqlValidationError(`Expect argument to be array and least 2 items!`)\n }\n\n // this table index key will drive the contract\n // also it should not allow to change dynamicly\n // because this is how different client can id itself\n // OK this could be self manage because when init a new client\n // it will add a new endpoint and we will know if they are the same or not\n // but the check here\n set jsonqlEndpoint(endpoint) {\n let urls = localStore.get(ENDPOINT_TABLE) || []\n // should check if this url already existed?\n if (!inArray(urls, endpoint)) {\n urls.push(endpoint)\n this.storeId = [ENDPOINT_TABLE, urls]\n this[ENDPOINT_TABLE + 'Index'] = urls.length - 1;\n }\n }\n\n // by the time it call the save contract already been checked\n set jsonqlContract(args) {\n const key = this.opts.storageKey;\n let _args = [ key ]\n let [ contract, expired ] = args;\n // get the endpoint index\n let contracts = localStore.get(key) || []\n contracts[ this[ENDPOINT_TABLE + 'Index'] || 0 ] = contract;\n _args.push(contracts)\n if (expired) {\n _args.push(expired)\n }\n if (this.opts.keepContract) {\n this.storeIt = _args;\n }\n }\n\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const key = CREDENTIAL_STORAGE_KEY;\n let tokens = localStorage.get(key) || []\n if (!inArray(tokens, token)) {\n let index = tokens.length - 1;\n tokens[ index ] = token;\n this[key + 'Index'] = index;\n let args = [key, tokens]\n if (this.opts.tokenExpired) {\n const expired = parseFloat(this.opts.tokenExpired)\n if (!isNaN(expired) && expired > 0) {\n const ts = timestamp()\n args.push( ts + parseFloat(expired) )\n }\n }\n this.storeIt = args;\n // now decode it and store in the userdata\n this.jsonqlUserdata = this.decoder(token)\n return token;\n }\n return false;\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n */\n set jsonqlUserdata(userdata) {\n const args = [USERDATA_TABLE, userdata]\n if (userdata.exp) {\n args.push(userdata.exp)\n }\n return Reflect.apply(localStore.set, localStore, args)\n }\n\n /**\n * This also manage the index internally\n * There is NO need to store them in an array\n * because each instance contain one end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n let urls = localStore.get(ENDPOINT_TABLE)\n if (!urls) {\n const { hostname, jsonqlPath } = this.opts;\n let url = [hostname, jsonqlPath].join('/')\n this.jsonqlEndpoint = url;\n return url;\n }\n return urls[this[ENDPOINT_TABLE + 'Index']]\n }\n\n /**\n * If already stored then return it by the end point index\n * or false when there is none\n * 1.2.0 start using the keepContract option (replace the useLocalStorage)\n * @return {object|boolean} as described above\n */\n get jsonqlContract() {\n const key = this.opts.storageKey\n let contracts = localStore.get(key) || []\n return contracts[ this[ENDPOINT_TABLE + 'Index'] ] || false\n }\n\n /**\n * Jsonql token getter\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const key = CREDENTIAL_STORAGE_KEY;\n let tokens = localStorage.get(key)\n if (tokens) {\n return tokens[ this[key + 'Index'] ]\n }\n return false;\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * @return {object|null}\n */\n get jsonqlUserdata() {\n return sessionStore.get(USERDATA_TABLE)\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\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 default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.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 */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\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 * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\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 genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase 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 }\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 (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\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 return true;\n }\n }\n throw new Error(`callback required to be function type!`)\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 const types = ['on', 'only', 'once', 'onlyOnce']\n return !!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, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\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 if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\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 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 // 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 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(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\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 this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\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)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\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 return size;\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 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 * 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 return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\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} callback 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\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(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\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 const type = 'once';\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} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, 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 !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${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 const type = 'only';\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(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\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( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\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 const type = 'onlyOnce';\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 store`)\n added = this.addToNormalStore(evt, type, callback, context)\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 !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\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 * 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') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\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 // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not 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 ${evt}`)\n this.run(callback, payload, context || ctx)\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 around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\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 this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\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 this.validateEvt(evt)\n let store = this.normalStore;\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 [key, callback, ] = l;\n return callback;\n })\n }\n return false;\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)', '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 if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\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 * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\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 console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\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 * @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\n/**\n * construct a url with query parameters\n * @param {string} url to append\n * @param {object} params to append to url\n * @return {string} url with appended params\n */\nexport const urlParams = (url, params) => {\n let parts = [];\n for (let key in params) {\n parts.push( [key, params[key]].join('=') )\n }\n return [url, parts.join('&')].join('?')\n}\n\n/**\n * construct a url with cache burster\n * @param {string} url to append to\n * @return {object} _cb key timestamp\n */\nexport const cacheBurstUrl = url => urlParams(url, cacheBurst())\n\n/**\n * @return {object} _cb as key with timestamp\n */\nexport const cacheBurst = () => ({ _cb: timestamp() })\n\n/**\n * From underscore.string library\n * @BUG there is a bug here with the non-standard name start with _\n * @param {string} str string\n * @return {string} dasherize string\n */\nexport const dasherize = str => (\n trim(str)\n .replace(/([A-Z])/g, '-$1')\n .replace(/[-_\\s]+/g, '-')\n .toLowerCase()\n)\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 parse(n)\n }\n return JSON.parse(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!`)\n}\n","// 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","// 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')) {\n return contract.socket;\n }\n return false;\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 * @param {boolean} [fallback=false] this is a fall back option for old code\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, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\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} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\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","// 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'\nimport { JsonqlValidationError } from 'jsonql-errors'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './generic'\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) ? JSON.parse(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 * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\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(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\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]: payload[TIMESTAMP_PARAM_NAME]\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 = getNameFromPayload(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]: payload[TIMESTAMP_PARAM_NAME]\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","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './generic'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { injectToFn, chainFns } from 'jsonql-utils/module'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n // obj.query[queryFn] = (...args) => {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change\n // the +1 parameter is the extra headers we want to pass\n const header = args[params.length] || {};\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n //obj.mutation[mutationFn] = (payload, conditions, header = {}) => {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction)\n .then(token => {\n ee.$trigger(ISSUER_NAME, token)\n return token;\n })\n }\n }\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction)\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport default function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport methodsGenerator from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.userdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = () => jsonqlInstance.rawAuthToken;\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // this is for the ws to use later\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // output\n return client;\n};\n\nexport default generator;\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/module'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport {\n isContract,\n isObjectHasKey,\n getContractFromConfig\n} from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it \n config.contract = contract;\n config.eventEmitter = client.eventEmitter;\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc;\n return client;\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client;\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_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\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_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\n}\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\nimport getDebug from './get-debug'\nconst debug = getDebug('process-contract')\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/module'\n// import { getDebug } from './get-debug';\n// const debug = getDebug('helpers')\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\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\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 * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\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 { getDebug, isObjectHasKey } from '../utils'\nconst debugFn = getDebug('respondHandler')\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 resolver(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_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from 'jsonql-utils/module'\nimport { respondHandler } from './respond-handler'\nimport { getDebug } from '../utils'\nconst debugFn = getDebug(`action-call`)\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { getDebug, chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\nconst debugFn = getDebug('setup-resolver')\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from 'jsonql-utils/module'\n\nimport { respondHandler } from './respond-handler'\nimport { getDebug } from '../utils'\nconst debugFn = getDebug('setup-resolver')\n\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\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\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_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 respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property 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 {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n // debug(exe)\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\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\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n getDebug,\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\nconst debugFn = getDebug('resolver-methods')\n\n/**\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 {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\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} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\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_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\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 * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\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, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME:\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\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 ee,\n opts\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} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\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 { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { getDebug, injectToFn, chainProcessPromises } from '../utils'\nconst debugFn = getDebug('generator')\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\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 generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n obj3 => createOnLoginhandler(obj3, ee, opts),\n )\n }\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n\n /*\n return getMappedObj(opts, nspMap, ee)\n // add error handler\n .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet))\n // add onReady handler\n .then(obj2 => createOnReadyhandler(obj2, ee, nspSet))\n // add onLogin handler -- this is optional\n .then(obj3 => createOnLoginhandler(obj3, ee, opts))\n // Auth related methods -- this is optional\n .then(obj4 => createAuthMethods(obj4, ee, opts))\n */\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, getDebug, objHasProp } from '../utils'\nconst debug = getDebug('check-options')\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\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 opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\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 { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts;\n return checkOptions(opts, constProps)\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee()\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\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 */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri;\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url;\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false;\n }\n }\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\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, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\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, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-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 * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n\n\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\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\n\nimport { getDebug, createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\nconst debugFn = getDebug('client-event-handler')\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\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, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\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 let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n debugFn('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n debugFn('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport { getDebug } from 'jsonql-ws-client/share'\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst debugFn = getDebug('ws-main-handler')\n\n\n/**\n * under extremely circumstances 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 * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n debugFn(`a global error on ${namespace}`)\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_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 even 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 * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\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 // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\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 debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect,\n getDebug\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\nconst debugFn = getDebug('ws-create-client')\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\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 {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts;\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG 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\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\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(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// 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 WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\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 default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClient } from 'jsonql-ws-client'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClient(wsClientResolver, constProps)\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"jsonql-client-ws.debug.js","sources":["../node_modules/jsonql-client/node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/index.js","../node_modules/jsonql-client/node_modules/jsonql-errors/src/client-errors-handler.js","../node_modules/lodash-es/isArray.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/contract.js","../node_modules/nb-event-service/src/hash-code.js","../node_modules/jsonql-client/src/utils.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/lodash-es/_arrayMap.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-client/node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-client/node_modules/jsonql-jwt/src/client/decode-token/decode-token.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/array.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/isObject.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/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/validator.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/negate.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/options/check-options-sync.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-client/node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/timestamp.js","../node_modules/store/plugins/defaults.js","../node_modules/jsonql-client/src/stores/local-store.js","../node_modules/jsonql-client/src/stores/session-store.js","../node_modules/jsonql-client/src/stores/index.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/params-api.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/results.js","../node_modules/jsonql-client/src/base/store-cls.js","../node_modules/jsonql-client/src/base/http-cls.js","../node_modules/jsonql-client/src/base/contract-cls.js","../node_modules/jsonql-client/src/base/auth-cls.js","../node_modules/jsonql-client/src/base/base-cls.js","../node_modules/jsonql-client/src/base/index.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../node_modules/jsonql-client/src/ee.js","../node_modules/jsonql-client/src/core/methods-generator.js","../node_modules/jsonql-client/src/core/jsonql-api-generator.js","../node_modules/jsonql-client/src/options/base-options.js","../node_modules/jsonql-client/src/options/check-options-async.js","../node_modules/jsonql-client/src/options/index.js","../node_modules/jsonql-client/module.js","../node_modules/jsonql-client/node_modules/jsonql-utils/src/pre-config-check.js","../node_modules/jsonql-client/opt.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/resolver-not-found-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-ws-client/src/options/constants.js","../node_modules/jsonql-utils/src/generic.js","../node_modules/jsonql-utils/src/chain-promises.js","../node_modules/jsonql-utils/src/contract.js","../node_modules/jsonql-utils/src/params-api.js","../node_modules/lodash-es/isNull.js","../node_modules/lodash-es/isUndefined.js","../node_modules/jsonql-params-validator/src/not-empty.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/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/log.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.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-ws-client/src/utils/process-contract.js","../node_modules/jsonql-ws-client/src/utils/helpers.js","../node_modules/jsonql-ws-client/src/core/respond-handler.js","../node_modules/jsonql-ws-client/src/core/action-call.js","../node_modules/jsonql-ws-client/src/core/setup-callback-api.js","../node_modules/jsonql-ws-client/src/core/setup-resolver.js","../node_modules/jsonql-ws-client/src/core/resolver-methods.js","../node_modules/jsonql-ws-client/src/core/setup-auth-methods.js","../node_modules/jsonql-ws-client/src/core/generator.js","../node_modules/buffer-es6/isArray.js","../node_modules/jsonql-ws-client/src/options/index.js","../node_modules/jsonql-ws-client/src/api.js","../node_modules/@jsonql/ws/src/options/index.js","../node_modules/@jsonql/ws/src/core/create-ws-client.js","../node_modules/jsonql-ws-client/src/share/create-nsp-client.js","../node_modules/jsonql-ws-client/src/share/trigger-namespaces-on-error.js","../node_modules/jsonql-ws-client/src/share/client-event-handler.js","../node_modules/@jsonql/ws/src/core/extract-ws-payload.js","../node_modules/@jsonql/ws/src/core/ws-main-handler.js","../node_modules/@jsonql/ws/src/core/create-client.js","../node_modules/@jsonql/ws/src/core/create-client-resolver.js","../node_modules/@jsonql/ws/src/ws-client-resolver.js","../node_modules/@jsonql/ws/index.js","../node_modules/@jsonql/ws/opt.js","../ws.js"],"sourcesContent":["/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\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","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// server side\nimport Jsonql406Error from './406-error';\nimport Jsonql500Error from './500-error';\nimport JsonqlAuthorisationError from './authorisation-error';\nimport JsonqlContractAuthError from './contract-auth-error';\nimport JsonqlResolverAppError from './resolver-app-error';\nimport JsonqlResolverNotFoundError from './resolver-not-found-error';\n\n// check options error\nimport JsonqlEnumError from './enum-error';\nimport JsonqlTypeError from './type-error';\nimport JsonqlCheckerError from './checker-error';\n// share\nimport JsonqlValidationError from './validation-error';\nimport JsonqlError from './error';\n\nimport JsonqlServerError from './server-error';\n\nexport {\n Jsonql406Error,\n Jsonql500Error,\n JsonqlAuthorisationError,\n JsonqlContractAuthError,\n JsonqlResolverAppError,\n JsonqlResolverNotFoundError,\n\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError,\n\n JsonqlValidationError,\n JsonqlError,\n\n JsonqlServerError\n};\n","// this will add directly to the then call in each http call\n\nimport * as errors from './index';\nimport getErrorByStatus from './get-error-by-status';\nimport { NO_ERROR_MSG } from 'jsonql-constants';\nconst { JsonqlError } = errors;\n\n/**\n * We can not just check something like result.data what if the result if false?\n * @param {object} obj the result object\n * @param {string} key we want to check if its exist or not\n * @return {boolean} true on found\n */\nconst isObjectHasKey = (obj, key) => {\n const keys = Object.keys(obj)\n return !!keys.filter(k => key === k).length;\n}\n\n/**\n * It will ONLY have our own jsonql specific implement check\n * @param {object} result the server return result\n * @return {object} this will just throw error\n */\nexport default function clientErrorsHandler(result) {\n if (isObjectHasKey(result, 'error')) {\n const { error } = result;\n const { className, name } = error;\n const errorName = className || name;\n // just throw the whole thing back\n const msg = error.message || NO_ERROR_MSG;\n const detail = error.detail || error;\n if (errorName && errors[errorName]) {\n throw new errors[className](msg, detail)\n }\n throw new JsonqlError(msg, detail)\n }\n // pass through to the next\n return result;\n}\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","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","// bunch of generic helpers\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\n\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 * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\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 console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\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 parse(n)\n }\n return JSON.parse(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","// 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')) {\n return contract.socket;\n }\n return false;\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 * @param {boolean} [fallback=false] this is a fall back option for old code\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, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\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} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\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 * 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 default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// take only the module part which is what we use here\n// and export it again to use through out the client\n// this way we avoid those that we don't want node.js module got build into the code\nimport { isContract } from 'jsonql-utils/src/contract'\nimport hashCodeFn from 'nb-event-service/src/hash-code'\n/**\n * @param {object} jsonqlInstance the init instance of jsonql client\n * @param {object} contract the static contract\n * @return {object} contract may be from server\n */\nconst getContractFromConfig = function(jsonqlInstance, contract = {}) {\n if (isContract(contract)) {\n return Promise.resolve(contract)\n }\n return jsonqlInstance.getContract()\n}\n// wrapper method to make sure it's a string\nconst hashCode = str => hashCodeFn(str) + ''\n\n// simple util to check if an object has any properties\n// const hasProp = obj => isObject(obj) && Object.keys(obj).length\n\n// export some constants as well\n// since it's only use here there is no point of adding it to the constants module\n// or may be we add it back later\nconst ENDPOINT_TABLE = 'endpoint' // not in use anymore delete later @TODO\nconst USERDATA_TABLE = 'userdata'\nconst CLS_LOCAL_STORE_NAME = 'localStore'\nconst CLS_SESS_STORE_NAME = 'sessionStore'\nconst CLS_CONTRACT_NAME = 'contract'\nconst CLS_PROFILE_IDX = 'prof_idx'\nconst ZERO_IDX = 0\n// export\nexport {\n hashCode,\n getContractFromConfig,\n ENDPOINT_TABLE,\n USERDATA_TABLE,\n CLS_LOCAL_STORE_NAME,\n CLS_SESS_STORE_NAME,\n CLS_CONTRACT_NAME,\n CLS_PROFILE_IDX,\n ZERO_IDX\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (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 var 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\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\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","// 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","// when the user is login with the jwt\n// we use call this to decode the token and then add the payload\n// to the resolver so the user can call ResolverName.userdata\n// and get back the payload\nimport jwt_decode from 'jwt-decode'\nimport isString from 'jsonql-params-validator/src/string'\nimport JsonqlError from 'jsonql-errors/src/error'\n\nconst timestamp = function (sec = false) {\n var time = Date.now()\n return sec ? Math.floor( time / 1000 ) : time;\n}\n\n/**\n * We only check the nbf and exp\n * @param {object} token for checking\n * @return {object} token on success\n */\nfunction validate(token) {\n const start = token.iat || timestamp(true)\n // we only check the exp for the time being\n if (token.exp) {\n if (start >= token.exp) {\n const expired = new Date(token.exp).toISOString()\n throw new JsonqlError(`Token has expired on ${expired}`, token)\n }\n }\n return token;\n}\n\n/**\n * The browser client version it has far fewer options and it doesn't verify it\n * because it couldn't this is the job for the server\n * @TODO we need to add some extra proessing here to check for the exp field\n * @param {string} token to decrypted\n * @return {object} decrypted object\n */\nexport default function jwtDecode(token) {\n if (isString(token)) {\n const t = jwt_decode(token)\n return validate(t)\n }\n throw new JsonqlError('Token must be a string!')\n}\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","// 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\nexport const 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)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\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 * 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 * 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 * 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","/**\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","/** 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","/** 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 * 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","/** 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","/**\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","/**\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","/** 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","/** 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 * 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 * 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 * 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","// validate object type\n\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport filter from 'lodash-es/filter'\n\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 checkIsObject,\n combineFn,\n notEmpty\n} from './index'\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 UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\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 JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(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","/**\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","/**\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 * 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 * 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","/** 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","// this is port back from the client to share across all projects\nimport merge from 'lodash-es/merge'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\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 merge(\n runValidation(\n prepareArgsForValidation(config, appProps),\n cb\n ),\n constProps\n )\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'\nimport 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 * 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 */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = 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 checkConfigAsync,\n checkConfig,\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'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\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","module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","// sort of persist on the user side\nimport engine from 'store/src/store-engine'\n\nimport localStorage from 'store/storages/localStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// @1.5.0 stop using the expired plugin, and deal with it ourself\n// import expiredPlugin from 'store/plugins/expire'\nimport eventsPlugin from 'store/plugins/events'\nimport compressionPlugin from 'store/plugins/compression'\n\nconst storages = [localStorage, cookieStorage]\nconst plugins = [defaultPlugin, eventsPlugin, compressionPlugin]\n\nconst localStore = engine.createStore(storages, plugins)\n\nexport default localStore\n","// session store with watch\nimport engine from 'store/src/store-engine'\n\nimport sessionStorage from 'store/storages/sessionStorage'\nimport cookieStorage from 'store/storages/cookieStorage'\n\nimport defaultPlugin from 'store/plugins/defaults'\n// start using compression in 1.5.0 \nimport compressionPlugin from 'store/plugins/compression'\n// @1.5.0 stop using the expired plugin and deal it ourself\n// import expiredPlugin from 'store/plugins/expire'\n\nconst storages = [sessionStorage, cookieStorage]\nconst plugins = [defaultPlugin, compressionPlugin]\n\nconst sessionStore = engine.createStore(storages, plugins)\n\nexport default sessionStore\n","// export store interface\n// @TODO need to figure out how to make this as a outside dependencies instead of built into it\nimport localStoreEngine from './local-store'\nimport sessionStoreEngine from './session-store'\n\n// export back the raw version for development purposes\nexport const localStore = localStoreEngine\nexport const sessionStore = sessionStoreEngine\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'\nimport JsonqlValidationError from 'jsonql-errors/src/validation-error'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './timestamp'\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) ? JSON.parse(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 * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\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(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\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]: payload[TIMESTAMP_PARAM_NAME]\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 = getNameFromPayload(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]: payload[TIMESTAMP_PARAM_NAME]\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","// break up from node-middleware\nimport {\n QUERY_NAME,\n MUTATION_NAME,\n API_REQUEST_METHODS,\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME ,\n QUERY_ARG_NAME,\n DATA_KEY,\n ERROR_KEY,\n INDEX_KEY,\n EXT,\n TIMESTAMP_PARAM_NAME\n} from 'jsonql-constants'\nimport { isObjectHasKey } from './generic'\nimport { timestamp } from './timestamp'\nimport isArray from 'lodash-es/isArray'\nimport merge from 'lodash-es/merge'\n/**\n * getting what is calling after the above check\n * @param {string} method of call\n * @return {mixed} false on failed\n */\nexport const getCallMethod = method => {\n const [ POST, PUT ] = API_REQUEST_METHODS;\n switch (true) {\n case method === POST:\n return QUERY_NAME;\n case method === PUT:\n return MUTATION_NAME;\n default:\n return false;\n }\n}\n\n/**\n * wrapper method\n * @param {mixed} result of fn return\n * @param {boolean|array} [ts=false] when pass this then we append a new value to the end\n * @return {string} stringify data\n */\nexport const packResult = function(result, ts = false) {\n let payload = { [DATA_KEY]: result }\n if (ts && isArray(ts)) {\n ts.push(timestamp())\n payload[TIMESTAMP_PARAM_NAME] = ts\n }\n return JSON.stringify(payload)\n}\n\n/**\n * Check if the error object contain out custom key\n * @param {*} e object\n * @return {boolean} true\n */\nexport const isJsonqlErrorObj = e => {\n const searchFields = ['detail', 'className']\n const test = !!searchFields.filter(field => isObjectHasKey(e, field)).length\n if (test) {\n return ['className', 'message', 'statusCode']\n .filter(field => isObjectHasKey(e, field))\n .map(field => (\n {\n [field]: typeof e[field] === 'object' ? e[field].toString() : e[field]\n }\n ))\n .reduce(merge, {detail: e.toString()}) // can only get as much as possible\n }\n return false;\n}\n\n/**\n * wrapper method - the output is trying to match up the structure of the Error sub class\n * @param {mixed} detail of fn error\n * @param {string} [className=JsonqlError] the errorName\n * @param {number} [statusCode=500] the original error code\n * @return {string} stringify error\n */\nexport const packError = function(detail, className = 'JsonqlError', statusCode = 0, message = '') {\n let errorObj = { detail, className, statusCode, message }\n // we need to check the detail object to see if it has detail, className and message\n // if it has then we should merge the object instead\n return JSON.stringify({\n [ERROR_KEY]: isJsonqlErrorObj(detail) || errorObj,\n [TIMESTAMP_PARAM_NAME]: timestamp()\n })\n}\n\n// ported from http-client\n\n/**\n * handle the return data\n * @TODO how to handle the return timestamp and calculate the diff?\n * @param {object} result return from server\n * @return {object} strip the data part out, or if the error is presented\n */\nexport const resultHandler = result => (\n (isObjectHasKey(result, DATA_KEY) && !isObjectHasKey(result, ERROR_KEY)) ? result[DATA_KEY] : result\n)\n","// new 1.5.0\n// create a class method to handle all the saving and retriving data\n// using the instanceKey to id the data hence allow to use multiple instance\nimport merge from 'lodash-es/merge'\nimport { localStore, sessionStore } from '../stores'\nimport { CLS_SESS_STORE_NAME, CLS_LOCAL_STORE_NAME, hashCode } from '../utils'\n\n// this becomes the base class instead of the HttpCls\nexport default class StoreClass {\n\n constructor(opts) {\n this.opts = opts\n // make it a string\n this.instanceKey = hashCode(this.opts.hostname)\n // pass this store for use later\n this.localStore = localStore\n this.sessionStore = sessionStore\n /*\n if (this.opts.debugOn) { // reuse this to clear out the data\n this.log('clear all stores')\n localStore.clearAll()\n sessionStore.clearAll()\n\n localStore.set('TEST', Date.now())\n sessionStore.set('TEST', Date.now())\n }\n */\n }\n // store in local storage id by the instanceKey\n // values should be an object so with key so we just merge\n // into the existing store without going through the keys\n __setMethod(storeType, values) {\n let store = this[storeType]\n let data = this.__getMethod(storeType)\n const skey = this.opts.storageKey\n const ikey = this.instanceKey\n store.set(skey, {\n [ikey]: data ? merge({}, data, values) : values\n })\n }\n // return the data id by the instaceKey\n __getMethod(storeType) {\n let store = this[storeType]\n let data = store.get(this.opts.storageKey)\n return data ? data[this.instanceKey] : false\n }\n // remove from local store id by instanceKey\n __delMethod(storeType, key) {\n let data = this.__getMethod(storeType)\n if (data) {\n let store = {}\n for (let k in data) {\n if (k !== key) {\n store[k] = data[k]\n }\n }\n this.__setMethod(storeType, store)\n }\n }\n // clear everything by this instanceKey\n __clearMethod(storeKey) {\n const skey = this.opts.storageKey\n const store = this[storeKey]\n let data = store.get(skey)\n if (data) {\n let _store = {}\n for (let k in data) {\n if (k !== this.instanceKey) {\n _store[k] = data[k]\n }\n }\n store.set(skey, _store)\n }\n }\n // Alias for different store\n set lset(values) {\n return this.__setMethod(CLS_LOCAL_STORE_NAME, values)\n }\n\n get lget() {\n return this.__getMethod(CLS_LOCAL_STORE_NAME)\n }\n\n ldel(key) {\n return this.__delMethod(CLS_LOCAL_STORE_NAME, key)\n }\n\n lclear() {\n return this.__clearMethod(CLS_LOCAL_STORE_NAME)\n }\n\n // store in session store id by the instanceKey\n set sset(values) {\n // this.log('--- sset ---', values)\n return this.__setMethod(CLS_SESS_STORE_NAME, values)\n }\n\n get sget() {\n return this.__getMethod(CLS_SESS_STORE_NAME)\n }\n\n sdel(key) {\n return this.__delMethod(CLS_SESS_STORE_NAME, key)\n }\n\n sclear() {\n return this.__clearMethod(CLS_SESS_STORE_NAME)\n }\n\n\n}\n","// base HttpClass\nimport merge from 'lodash-es/merge'\nimport {\n createQuery,\n createMutation,\n getNameFromPayload\n} from 'jsonql-utils/src/params-api'\nimport { cacheBurst, urlParams } from 'jsonql-utils/src/urls'\nimport { resultHandler } from 'jsonql-utils/src/results'\nimport { isObject, isString } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlServerError,\n clientErrorsHandler\n} from 'jsonql-errors'\nimport {\n API_REQUEST_METHODS,\n DEFAULT_HEADER,\n JSONP_CALLBACK_NAME,\n SHOW_CONTRACT_DESC_PARAM\n} from 'jsonql-constants'\n\n// extract the one we need\nconst [ POST, PUT ] = API_REQUEST_METHODS\n\nimport StoreClass from './store-cls'\n\nexport default class HttpClass extends StoreClass {\n /**\n * The opts has been check at the init stage\n * @param {object} opts configuration options\n */\n constructor(opts) {\n super(opts)\n // change the way how we init Fly\n // flyio now become external depedencies and it makes it easier to switch\n // @BUG should we run test to check if we have the windows object?\n // this.log(opts)\n // this.fly = opts.Fly ? new opts.Fly() : new Fly()\n // to a different environment like WeChat mini app\n\n this.extraHeader = {};\n // @1.2.1 for adding query to the call on the fly\n this.extraParams = {};\n // this.log('start up opts', opts);\n this.reqInterceptor()\n this.resInterceptor()\n }\n\n // set headers for that one call\n set headers(header) {\n this.extraHeader = header;\n }\n\n /**\n * Create the reusage request method\n * @param {object} payload jsonql payload\n * @param {object} options extra options add the request\n * @param {object} headers extra headers add to the call\n * @return {object} the fly request instance\n */\n request(payload, options = {}, headers = {}) {\n this.headers = headers;\n let params = merge({}, cacheBurst(), this.extraParams)\n // @TODO need to add a jsonp url and payload\n if (this.opts.enableJsonp) {\n let resolverName = getNameFromPayload(payload)\n params = merge({}, params, {[JSONP_CALLBACK_NAME]: resolverName})\n payload = payload[resolverName]\n }\n // double up the url param and see what happen @TODO remove later\n const reqParams = merge({}, { method: POST, params }, options)\n this.log('request params', reqParams, this.jsonqlEndpoint)\n\n return this.fly.request(this.jsonqlEndpoint, payload, reqParams)\n }\n\n /**\n * This will replace the create baseRequest method\n *\n */\n reqInterceptor() {\n this.fly.interceptors.request.use(\n req => {\n const headers = this.getHeaders()\n this.log('request interceptor call', headers)\n\n for (let key in headers) {\n req.headers[key] = headers[key]\n }\n return req;\n }\n )\n }\n\n // @TODO\n processJsonp(result) {\n return resultHandler(result)\n }\n\n /**\n * This will be replacement of the first then call\n *\n */\n resInterceptor() {\n const self = this;\n const jsonp = self.opts.enableJsonp;\n this.fly.interceptors.response.use(\n res => {\n this.log('response interceptor call', res)\n self.cleanUp()\n // now more processing here\n // there is a problem if we throw the result.error here\n // the original data is lost, so we need to do what we did before\n // deal with that error in the first then instead\n const result = isString(res.data) ? JSON.parse(res.data) : res.data;\n if (jsonp) {\n return self.processJsonp(result)\n }\n return resultHandler(result)\n },\n // this get call when it's not 200\n err => {\n self.cleanUp()\n console.error(err)\n throw new JsonqlServerError('Server side error', err)\n }\n )\n }\n\n /**\n * Get the headers inject into the call\n * @return {object} headers\n */\n getHeaders() {\n if (this.opts.enableAuth) {\n return merge({}, DEFAULT_HEADER, this.getAuthHeader(), this.extraHeader)\n }\n return merge({}, DEFAULT_HEADER, this.extraHeader)\n }\n\n /**\n * Post http call operation to clean up things we need\n */\n cleanUp() {\n this.extraHeader = {}\n this.extraParams = {}\n }\n\n /**\n * GET for contract only\n * @return {promise} resolve the contract\n */\n getRemoteContract() {\n if (this.opts.showContractDesc) {\n this.extraParams = merge({}, this.extraParams, SHOW_CONTRACT_DESC_PARAM)\n }\n return this.request({}, {method: 'GET'}, this.contractHeader)\n .then(clientErrorsHandler)\n .then(result => {\n this.log('get contract result', result)\n // when refresh the window the result is different!\n // @TODO need to check the Koa side about why is that\n // also it should set a flag if we want the description or not\n if (result.cache && result.contract) {\n return result.contract;\n }\n // just the normal result\n return result\n })\n .catch(err => {\n console.error('getRemoteContract err', err)\n throw new JsonqlServerError('getRemoteContract', err)\n })\n }\n\n /**\n * POST to server - query\n * @param {object} name of the resolver\n * @param {array} args arguments\n * @return {object} promise resolve to the resolver return\n */\n query(name, args = []) {\n return this.request(createQuery(name, args))\n .then(clientErrorsHandler)\n }\n\n /**\n * PUT to server - mutation\n * @param {string} name of resolver\n * @param {object} payload what it said\n * @param {object} conditions what it said\n * @return {object} promise resolve to the resolver return\n */\n mutation(name, payload = {}, conditions = {}) {\n return this.request(createMutation(name, payload, conditions), {method: PUT})\n .then(clientErrorsHandler)\n }\n\n}\n","// all the contract related methods will be here\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { timestamp } from 'jsonql-utils/src/timestamp'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { ENDPOINT_TABLE, CLS_CONTRACT_NAME } from '../utils'\nimport { localStore } from '../stores'\nimport HttpClass from './http-cls'\n\n// export\nexport default class ContractClass extends HttpClass {\n\n constructor(opts) {\n super(opts)\n }\n\n /**\n * return the contract public api\n * @return {object} contract\n */\n getContract() {\n const contract = this.readContract()\n this.log('getContract first call', contract)\n return contract ? Promise.resolve(contract)\n : this.getRemoteContract().then(this.storeContract.bind(this))\n }\n\n /**\n * We are changing the way how to auth to get the contract.json\n * Instead of in the url, we will be putting that key value in the header\n * @return {object} header\n */\n get contractHeader() {\n let base = {};\n if (this.opts.contractKey !== false) {\n base[this.opts.contractKeyName] = this.opts.contractKey;\n }\n return base;\n }\n\n /**\n * Save the contract to local store\n * @param {object} contract to save\n * @return {object|boolean} false when its not a contract or contract on OK\n */\n storeContract(contract) {\n // first need to check if the contract is a contract\n if (!isContract(contract)) {\n throw new JsonqlValidationError(`Contract is malformed!`)\n //return false;\n }\n /* @TODO need to rethink how to expired the contract\n let args = [contract]\n if (this.opts.contractExpired) {\n let expired = parseFloat(this.opts.contractExpired)\n if (!isNaN(expired) && expired > 0) {\n args.push(expired)\n }\n }\n // calling the setter\n this.jsonqlContract = args;\n */\n this.lset = {[CLS_CONTRACT_NAME]: contract}\n // return it\n this.log('storeContract return result', contract)\n return contract;\n }\n\n /**\n * return the contract from options or localStore\n * @return {object|boolean} false on not found\n */\n readContract() {\n let contract = isContract(this.opts.contract)\n if (contract !== false) {\n return contract;\n }\n let data = this.lget\n if (data) {\n return data[CLS_CONTRACT_NAME]\n }\n return false;\n }\n}\n","// this is the new auth class that integrate with the jsonql-jwt\n// all the auth related methods will be here\nimport { decodeToken } from 'jsonql-jwt/src/client'\nimport { isNumber } from 'jsonql-params-validator'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { CREDENTIAL_STORAGE_KEY, AUTH_HEADER, BEARER } from 'jsonql-constants'\nimport { CLS_PROFILE_IDX, ZERO_IDX, USERDATA_TABLE } from '../utils'\nimport ContractClass from './contract-cls'\n// export\nexport default class AuthClass extends ContractClass {\n\n constructor(opts) {\n super(opts)\n if (opts.enableAuth) {\n this.setDecoder = decodeToken;\n }\n }\n\n /**\n * for overwrite\n * @param {string} token stored token\n * @return {string} token\n */\n decoder(token) {\n return token;\n }\n\n /**\n * set the profile index\n * @param {number} idx\n */\n set profileIndex(idx) {\n const key = CLS_PROFILE_IDX\n if (isNumber(idx)) {\n this[key] = idx;\n if (this.opts.persistToken) {\n this.lset = {[key]: idx}\n }\n return;\n }\n throw new JsonqlValidationError('profileIndex', `Expect idx to be number but got ${typeof idx}`)\n }\n\n /**\n * get the profile index\n * @return {number} idx\n */\n get profileIndex() {\n const key = CLS_PROFILE_IDX\n if (this.opts.persistToken) {\n const data = this.lget;\n if (data[key]) {\n return data[key]\n }\n }\n return this[key] ? this[key] : ZERO_IDX\n }\n\n /**\n * Return the token from session store\n * @param {number} [idx=false] profile index\n * @return {string} token\n */\n rawAuthToken(idx = false) {\n if (idx !== false) {\n this.profileIndex = idx;\n }\n // this should return from the base\n return this.jsonqlToken; // see base-cls\n }\n\n /**\n * Setter to add a decoder when retrieve user token\n * @param {function} d a decoder\n */\n set setDecoder(d) {\n if (typeof d === 'function') {\n this.decoder = d;\n }\n }\n\n /**\n * getter to return the session or local store set method\n * @param {*} data to save\n * @return {object} set method\n */\n set saveProfile(data) {\n if (this.opts.persistToken) {\n // this.log('--- saveProfile lset ---', data)\n this.lset = data\n } else {\n // this.log('--- saveProfile sset ---', data)\n this.sset = data\n }\n }\n\n /**\n * getter to return the session or local store get method\n * @return {object} get method\n */\n get readProfile() {\n return this.opts.persistToken ? this.lget : this.sget\n }\n\n // these were in the base class before but it should be here\n /**\n * save token\n * @param {string} token to store\n * @return {string|boolean} false on failed\n */\n set jsonqlToken(token) {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n // @TODO also have to make sure the token is not already existed!\n let tokens = (data && data[key]) ? data[key] : []\n tokens.push(token)\n this.saveProfile = {[key]: tokens}\n // store the userdata\n this.jsonqlUserdata = this.decoder(token)\n }\n\n /**\n * Jsonql token getter\n * 1.5.1 each token associate with the same profileIndex\n * @return {string|boolean} false when failed\n */\n get jsonqlToken() {\n const data = this.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n this.log('-- jsonqlToken --', data[key], this.profileIndex, data[key][this.profileIndex])\n return data[key][this.profileIndex]\n }\n return false\n }\n\n /**\n * this one will use the sessionStore\n * basically we hook this onto the token store and decode it to store here\n * we only store one decoded user data at a time, but the token can be multiple\n */\n set jsonqlUserdata(userdata) {\n this.sset = {[USERDATA_TABLE]: userdata}\n }\n\n /**\n * this one store in the session store\n * get login userdata decoded jwt\n * 1.5.1 each userdata associate with the same profileIndex\n * @return {object|null}\n */\n get jsonqlUserdata() {\n const data = this.sget\n return data ? data[USERDATA_TABLE] : false\n }\n\n /**\n * Construct the auth header\n * @return {object} header\n */\n getAuthHeader() {\n const token = this.jsonqlToken // only call the getter to get the default one\n return token ? {[this.opts.AUTH_HEADER]: `${BEARER} ${token}`} : {};\n }\n\n /**\n * return all the stored token and decode it\n * @param {number} [idx=false] profile index\n * @return {array|boolean|string} false not found or array\n */\n getProfiles(idx = false) {\n const self = this; // just in case the scope problem\n const data = self.readProfile\n const key = CREDENTIAL_STORAGE_KEY\n if (data && data[key]) {\n if (idx !== false && isNumber(idx)) {\n return data[key][idx] || false\n }\n return data[key].map(self.decoder.bind(self))\n }\n return false\n }\n\n /**\n * call after the login\n * @param {string} token return from server\n * @return {object} decoded token to userdata object\n */\n postLoginAction(token) {\n this.jsonqlToken = token\n return token\n }\n\n /**\n * call after the logout @TODO\n */\n postLogoutAction(...args) {\n console.info(`postLogoutAction`, args)\n }\n}\n","// this the core of the internal storage management\nimport { CREDENTIAL_STORAGE_KEY } from 'jsonql-constants'\n// import { isObject, isArray } from 'jsonql-params-validator'\n// import { JsonqlValidationError } from 'jsonql-errors'\n// import { timestamp } from 'jsonql-utils/src/timestamp'\n// import { inArray } from 'jsonql-utils/src/generic'\nimport { USERDATA_TABLE } from '../utils'\nimport AuthCls from './auth-cls'\n\n// This class will only focus on the storage system\nexport default class JsonqlBaseClient extends AuthCls {\n // change the order of the interface in 1.4.10 to match up the top level\n constructor(fly, opts) {\n // change at 1.4.10 pass it directly without init it\n this.fly = fly;\n super(opts)\n }\n\n /**\n * construct the end point\n * @return {string} the end point to call\n */\n get jsonqlEndpoint() {\n const baseUrl = this.opts.hostname || ''\n return [baseUrl, this.opts.jsonqlPath].join('/')\n }\n\n /**\n * simple log\n */\n log(...args) {\n if (this.opts.debugOn === true) {\n Reflect.apply(console.info, console, args)\n }\n }\n\n}\n","// export interface\n// @public\nimport JsonqlBaseClient from './base-cls'\n\nexport default JsonqlBaseClient\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.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 */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\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 * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\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 genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase 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 }\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 (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\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 return true;\n }\n }\n throw new Error(`callback required to be function type!`)\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 const types = ['on', 'only', 'once', 'onlyOnce']\n return !!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, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\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 if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\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 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 // 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 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(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\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 this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\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)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\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 return size;\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 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 * 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 return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\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} callback 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\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(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($on)`, `call run on ${evt}`)\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\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 const type = 'once';\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} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, 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 !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger('($once)', `call run for ${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 const type = 'only';\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(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\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( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($only)`, `call run for ${evt}`)\n this.run(callback, payload, context || ctx)\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 const type = 'onlyOnce';\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 store`)\n added = this.addToNormalStore(evt, type, callback, context)\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 !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.logger(`($onlyOnce)`, `call run for ${evt}`)\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 * 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') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n this.logger(`($replace)`, evt, callback)\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 // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n this.logger('($trigger)', evt, 'not 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 ${evt}`)\n this.run(callback, payload, context || ctx)\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 around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params, context, type]\n return Reflect.apply(this.$trigger, this, args)\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 this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n this.logger('($off)', evt)\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\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 this.validateEvt(evt)\n let store = this.normalStore;\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 [key, callback, ] = l;\n return callback;\n })\n }\n return false;\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)', '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 if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// this will generate a event emitter and will be use everywhere\nimport NBEventService from 'nb-event-service'\n// output\nexport default function(debugOn) {\n let logger = debugOn ? (...args) => {\n args.unshift('[NBS]')\n console.log.apply(null, args)\n }: undefined;\n return new NBEventService({ logger })\n}\n","// breaking out the inner methods generator in here\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport { LOGOUT_NAME, LOGIN_NAME, KEY_WORD } from 'jsonql-constants'\nimport { chainFns } from 'jsonql-utils/src/chain-fns'\nimport { injectToFn } from 'jsonql-utils/src/obj-define-props'\n\n/**\n * generate authorisation specific methods\n * @param {object} jsonqlInstance instance of this\n * @param {string} name of method\n * @param {object} opts configuration\n * @param {object} contract to match\n * @return {function} for use\n */\nconst authMethodGenerator = (jsonqlInstance, name, opts, contract) => {\n return (...args) => {\n const params = contract.auth[name].params;\n const values = params.map((p, i) => args[i])\n const header = args[params.length] || {};\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [name, values, header])\n )\n .catch(finalCatch)\n }\n}\n\n/**\n * Break up the different type each - create query methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createQueryMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let query = {}\n for (let queryFn in contract.query) {\n // to keep it clean we use a param to id the auth method\n // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn;\n // generate the query method\n query = injectToFn(query, queryFn, function queryFnHandler(...args) {\n const params = contract.query[queryFn].params;\n const _args = params.map((param, i) => args[i])\n // debug('query', queryFn, _params);\n // @TODO this need to change to a different way to add an extra header\n const header = {}\n // @TODO validate against the type\n return validateAsync(_args, params)\n .then(() => jsonqlInstance\n .query\n .apply(jsonqlInstance, [queryFn, _args, header])\n )\n .catch(finalCatch)\n })\n }\n obj.query = query;\n // create an alias to the helloWorld method\n obj.helloWorld = query.helloWorld;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create mutation methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createMutationMethods = (obj, jsonqlInstance, ee, config, contract) => {\n let mutation = {}\n // process the mutation, the reason the mutation has a fixed number of parameters\n // there is only the payload, and conditions parameters\n // plus a header at the end\n for (let mutationFn in contract.mutation) {\n mutation = injectToFn(mutation, mutationFn, function mutationFnHandler(payload, conditions, header = {}) {\n const args = [payload, conditions];\n const params = contract.mutation[mutationFn].params;\n return validateAsync(args, params)\n .then(() => jsonqlInstance\n .mutation\n .apply(jsonqlInstance, [mutationFn, payload, conditions, header])\n )\n .catch(finalCatch)\n })\n }\n obj.mutation = mutation;\n return [ obj, jsonqlInstance, ee, config, contract ]\n}\n\n/**\n * create auth methods\n * @param {object} obj to hold all the objects\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} ee eventEmitter\n * @param {object} config configuration\n * @param {object} contract json\n * @return {object} modified output for next op\n */\nconst createAuthMethods = (obj, jsonqlInstance, ee, config, contract) => {\n if (config.enableAuth && contract.auth) {\n let auth = {} // v1.3.1 add back the auth prop name in contract\n const { loginHandlerName, logoutHandlerName } = config;\n if (contract.auth[loginHandlerName]) {\n // changing to the name the config specify\n auth[loginHandlerName] = function loginHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLoginAction.bind(jsonqlInstance))\n .then(token => {\n ee.$trigger(LOGIN_NAME, token)\n return token;\n })\n }\n }\n // @TODO allow to logout one particular profile or all of them\n if (contract.auth[logoutHandlerName]) {\n auth[logoutHandlerName] = function logoutHandlerFn(...args) {\n const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract)\n return fn.apply(null, args)\n .then(jsonqlInstance.postLogoutAction.bind(jsonqlInstance))\n .then(r => {\n ee.$trigger(LOGOUT_NAME, r)\n return r;\n })\n }\n } else {\n auth[logoutHandlerName] = function logoutHandlerFn() {\n jsonqlInstance.postLogoutAction(KEY_WORD)\n ee.$trigger(LOGOUT_NAME, KEY_WORD)\n }\n }\n obj.auth = auth;\n }\n\n return obj;\n}\n\n/**\n * Here just generate the methods calls\n * @param {object} jsonqlInstance what it said\n * @param {object} ee event emitter\n * @param {object} config configuration\n * @param {object} contract the map\n * @return {object} with mapped methods\n */\nexport function methodsGenerator(jsonqlInstance, ee, config, contract) {\n let obj = {}\n const executor = chainFns(createQueryMethods, createMutationMethods, createAuthMethods)\n return executor(obj, jsonqlInstance, ee, config, contract)\n}\n","// Generate the resolver for developer to use\n\n// @TODO when enableAuth we need to add one extra check\n// before the resolver call make it to the core\n// which is checking the login state, if the developer\n// is calling a private method without logging in\n// then we should throw the JsonqlForbiddenError at this point\n// instead of making a round trip to the server\nimport { LOGOUT_NAME, ISSUER_NAME, KEY_WORD } from 'jsonql-constants'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n JsonqlValidationError,\n JsonqlError,\n clientErrorsHandler,\n finalCatch\n} from 'jsonql-errors'\n\nimport { methodsGenerator } from './methods-generator'\n\n/**\n * @param {object} jsonqlInstance jsonql class instance\n * @param {object} config options\n * @param {object} contract the contract\n * @param {object} ee eventEmitter\n * @return {object} constructed functions call\n */\nconst generator = (jsonqlInstance, config, contract, ee) => {\n // V1.3.0 - now everything wrap inside this method\n let client = methodsGenerator(jsonqlInstance, ee, config, contract)\n // create the rest of the methods\n if (config.enableAuth) {\n /**\n * new method to allow retrieve the current login user data\n * @TODO allow to pass an id to switch to different userdata\n * @return {*} userdata\n */\n client.userdata = () => jsonqlInstance.jsonqlUserdata;\n // allow getting the token for valdiate agains the socket\n // if it's not require auth there is no point of calling getToken\n client.getToken = (idx = false) => jsonqlInstance.rawAuthToken(idx);\n // switch profile or read back what is the currenct index\n client.profileIndex = (idx = false) => {\n if (idx === false) {\n return jsonqlInstance.profileIndex\n }\n jsonqlInstance.profileIndex = idx\n }\n // new in 1.5.1 to return different profiles\n client.getProfiles = (idx = false) => jsonqlInstance.getProfiles(idx);\n }\n // this will pass to the ws-client if needed\n // client.eventEmitter = ee;\n // this will require a param\n if (config.exposeContract) {\n // 1.4.0 change from the get (raw) to the getContract cache and raw version\n client.getContract = () => jsonqlInstance.getContract()\n }\n // allow developer to access the store api\n if (config.exposeStore) {\n // @TODO in 1.5.2\n client.tmpSave = data => {}\n client.tmpGet = (key = false) => {}\n client.tmpDel = (key = false) => {}\n\n client.persistSave = data => {}\n client.persistGet = (key = false) => {}\n client.persistDel = (key = false) => {}\n }\n // this is for the ws to use later - but this could be dangerous because it's expose the internal\n client.eventEmitter = ee;\n client.version = '__VERSION__';\n // use this method then we can hook into the debugOn at the same time\n client.log = (...args) => Reflect.apply(jsonqlInstance.log, jsonqlInstance, ['[DEV DEBUG]'].concat(args))\n // output\n return client;\n}\n// export\nexport default generator\n","// all the client configuration options here\nimport {\n JSONQL_PATH,\n CONTENT_TYPE,\n BEARER,\n CLIENT_STORAGE_KEY,\n CLIENT_AUTH_KEY,\n CONTRACT_KEY_NAME,\n AUTH_HEADER,\n ISSUER_NAME,\n LOGOUT_NAME,\n BOOLEAN_TYPE,\n STRING_TYPE,\n NUMBER_TYPE,\n DEFAULT_HEADER\n} from 'jsonql-constants'\nimport { createConfig } from 'jsonql-params-validator'\nexport const constProps = {\n contract: false,\n MUTATION_ARGS: ['name', 'payload', 'conditions'], // this seems wrong?\n CONTENT_TYPE,\n BEARER,\n AUTH_HEADER\n}\n\n// grab the localhost name and put into the hostname as default\nconst getHostName = () => {\n try {\n return [window.location.protocol, window.location.host].join('//')\n } catch(e) {\n return null\n }\n}\n\nexport const appProps = {\n\n hostname: createConfig(getHostName(), [STRING_TYPE]), // required the hostname\n jsonqlPath: createConfig(JSONQL_PATH, [STRING_TYPE]), // The path on the server\n\n loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]),\n logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]),\n // add to koa v1.3.0 - this might remove in the future\n enableJsonp: createConfig(false, [BOOLEAN_TYPE]),\n enableAuth: createConfig(false, [BOOLEAN_TYPE]),\n // enable useJwt by default @TODO replace with something else and remove them later\n useJwt: createConfig(true, [BOOLEAN_TYPE]),\n // when true then store infinity or pass a time in seconds then we check against\n // the token date of creation\n persistToken: createConfig(false, [BOOLEAN_TYPE, NUMBER_TYPE]),\n // the header\n // v1.2.0 we are using this option during the dev\n // so it won't save anything to the localstorage and fetch a new contract\n // whenever the browser reload\n useLocalstorage: createConfig(true, [BOOLEAN_TYPE]), // should we store the contract into localStorage\n storageKey: createConfig(CLIENT_STORAGE_KEY, [STRING_TYPE]),// the key to use when store into localStorage\n authKey: createConfig(CLIENT_AUTH_KEY, [STRING_TYPE]),// the key to use when store into the sessionStorage\n contractExpired: createConfig(0, [NUMBER_TYPE]),// -1 always fetch contract,\n // 0 never expired,\n // > 0 then compare the timestamp with the current one to see if we need to get contract again\n // useful during development\n keepContract: createConfig(true, [BOOLEAN_TYPE]),\n exposeContract: createConfig(false, [BOOLEAN_TYPE]),\n exposeStore: createConfig(false, [BOOLEAN_TYPE]), // whether to allow developer to access the store fn \n // @1.2.1 new option for the contract-console to fetch the contract with description\n showContractDesc: createConfig(false, [BOOLEAN_TYPE]),\n contractKey: createConfig(false, [BOOLEAN_TYPE]), // if the server side is lock by the key you need this\n contractKeyName: createConfig(CONTRACT_KEY_NAME, [STRING_TYPE]), // same as above they go in pairs\n enableTimeout: createConfig(false, [BOOLEAN_TYPE]), // @TODO\n timeout: createConfig(5000, [NUMBER_TYPE]), // 5 seconds\n returnInstance: createConfig(false, [BOOLEAN_TYPE]),\n allowReturnRawToken: createConfig(false, [BOOLEAN_TYPE]),\n debugOn: createConfig(false, [BOOLEAN_TYPE])\n}\n","// we must ensure the user passing the correct options\n// therefore we need to validate against the properties as well\n\nimport { appProps, constProps } from './base-options'\nimport { checkConfigAsync } from 'jsonql-params-validator'\n\nexport default function checkOptionsAsync(config) {\n let { contract } = config;\n return checkConfigAsync(config, appProps, constProps)\n .then(opts => {\n opts.contract = contract;\n return opts;\n })\n}\n","// export interface\nimport checkOptionsAsyncLocal from './check-options-async'\nimport checkOptionsLocal from './check-options'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport { objHasProp } from 'jsonql-utils/src/obj-define-props'\n/**\n * 1.5.0 overload the orginal functions to pass over the check\n */\nfunction checkOptionsAsync(config) {\n return objHasProp(config, CHECKED_KEY) ? Promise.resolve(config) : checkOptionsAsyncLocal(config)\n}\n\n// sync version without needing the promise\nfunction checkOptions(config) {\n return objHasProp(config, CHECKED_KEY) ? config : checkOptionsLocal(config)\n}\n\nexport {\n checkOptionsAsync,\n checkOptions\n}\n","// new module interface for @jsonql/client\n// this will be use with the @jsonql/ws, @jsonql/socketio\nimport { SOCKET_NAME } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport JsonqlBaseClient from './src/base'\nimport getEventEmitter from './src/ee'\nimport generator from './src/core/jsonql-api-generator'\nimport { checkOptionsAsync } from './src/options'\nimport { isContract } from 'jsonql-utils/src/contract'\nimport { isObjectHasKey } from 'jsonql-utils/src/generic'\nimport { getContractFromConfig } from './src/utils'\n\n/**\n * Check if the contract has socket field and the socket client is suplied\n * @param {object} client the http client\n * @param {object} contract the json\n * @param {object} config the checked configuration\n * @param {object} socketClient from the original config\n * @return {object} the completed client\n */\nfunction initSocketClient(client, contract, config, socketClient) {\n if (isObjectHasKey(contract, SOCKET_NAME)) {\n if (socketClient) {\n // pass the contract here one more time in case the constProps overwritten it\n config.contract = contract;\n config.eventEmitter = client.eventEmitter;\n return socketClient(config)\n .then(sc => {\n client[SOCKET_NAME] = sc;\n return client;\n })\n } else {\n throw new JsonqlError(`initSocketClient`, `socketClient is missing!`)\n }\n }\n return client;\n}\n\n/**\n * Main interface for jsonql fetch api\n * @1.4.8 change this to named export to diff this from the other\n * and this is only use with the @jsonql/client to construct the client with ws\n * @param {object} Fly the http engine\n * @param {object} [config={}] configuration\n * @return {object} jsonqlClient\n */\nfunction jsonqlClientModule(fly, config = {}) {\n const { socketClient, debugOn } = config;\n const ee = getEventEmitter(debugOn)\n return checkOptionsAsync(config)\n .then(opts => (\n {\n opts,\n baseClient: new JsonqlBaseClient(fly, opts)\n }\n ))\n .then(({opts, baseClient}) => getContractFromConfig(baseClient, opts.contract)\n .then(contract => (\n {\n opts,\n contract,\n client: generator(baseClient, opts, contract, ee)\n }\n )\n )\n )\n .then(({opts, contract, client}) => (\n initSocketClient(client, contract, opts, socketClient)\n ))\n}\n// export it\nexport { jsonqlClientModule }\n","// this will replace the preConfigCheck in jsonql-koa\n// also this will get use in the client as well\n// basically this is just a wrapper method to load everything together\n// and then add the CHECKED_KEY to it\nimport { CHECKED_KEY } from 'jsonql-constants'\n\nimport { chainFns } from './chain-fns'\nimport { timestamp } from './timestamp'\nimport { injectToFn } from './obj-define-props'\n\n/**\n * the rest of the argument will be functions that\n * need to add to the process chain,\n * finally return a function to accept the config\n * @param {object} defaultOptions prepared before hand\n * @param {object} constProps prepare before hand\n * @param {array} fns arguments see description\n * @return {function} to perform the final configuration check\n */\nexport function preConfigCheck(defaultOptions, constProps, ...fns) {\n // should have just add the method to the last\n const finalFn = opt => injectToFn(opt, CHECKED_KEY, timestamp())\n // if there is more than one then chain it otherwise just return the zero idx one\n const fn = Reflect.apply(chainFns, null, fns.concat(finalFn))\n // 0.8.8 add a default property empty object\n return (config = {}) => fn(config, defaultOptions, constProps)\n}\n","// export the options for the pre-check to use\nimport { preConfigCheck } from 'jsonql-utils/module'\nimport { checkConfig } from 'jsonql-params-validator'\nimport merge from 'lodash-es/merge'\n\nimport { appProps, constProps } from './src/options/base-options'\n// just export the function here for use to save repeat coding\n\n/**\n * This will combine the socket client options and merge this one\n * then do a pre-check on both at the same time\n * @param {object} [extraProps = {}]\n * @param {object} [extraConstProps = {}]\n * @return {function} to process the developer options\n */\nexport function getPreConfigCheck(extraProps = {}, extraConstProps = {}) {\n const aProps = merge({}, appProps, extraProps)\n const cProps = merge({}, constProps, extraConstProps)\n\n return preConfigCheck(aProps, cProps, checkConfig)\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error)\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","/**\n * This is a custom error to throw when could not find the resolver\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class JsonqlResolverNotFoundError extends Error {\n constructor(...args) {\n super(...args)\n\n this.message = args[0]\n this.detail = args[1]\n\n this.className = JsonqlResolverNotFoundError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlResolverNotFoundError);\n }\n }\n\n static get statusCode() {\n return 404;\n }\n\n static get name() {\n return 'JsonqlResolverNotFoundError';\n }\n}\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","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message)\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_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\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_PROP_NAME,\n ON_RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE,\n CB_FN_NAME\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 * @return {*} json object on success\n */\nconst parse = function(n) {\n try {\n return JSON.parse(n)\n } catch(e) {\n return n;\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 console.info('obj', obj)\n console.error(e)\n throw new Error(e)\n */\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 * @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\n/**\n * construct a url with query parameters\n * @param {string} url to append\n * @param {object} params to append to url\n * @return {string} url with appended params\n */\nexport const urlParams = (url, params) => {\n let parts = [];\n for (let key in params) {\n parts.push( [key, params[key]].join('=') )\n }\n return [url, parts.join('&')].join('?')\n}\n\n/**\n * construct a url with cache burster\n * @param {string} url to append to\n * @return {object} _cb key timestamp\n */\nexport const cacheBurstUrl = url => urlParams(url, cacheBurst())\n\n/**\n * @return {object} _cb as key with timestamp\n */\nexport const cacheBurst = () => ({ _cb: timestamp() })\n\n/**\n * From underscore.string library\n * @BUG there is a bug here with the non-standard name start with _\n * @param {string} str string\n * @return {string} dasherize string\n */\nexport const dasherize = str => (\n trim(str)\n .replace(/([A-Z])/g, '-$1')\n .replace(/[-_\\s]+/g, '-')\n .toLowerCase()\n)\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 parse(n)\n }\n return JSON.parse(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!`)\n}\n","// 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","// 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')) {\n return contract.socket;\n }\n return false;\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 * @param {boolean} [fallback=false] this is a fall back option for old code\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, fallback = false) {\n let socket = extractSocketPart(contract)\n if (socket === false) {\n if (fallback) {\n return contract; // just return the whole contract\n }\n throw new JsonqlError(`socket not found in contract!`)\n }\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\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} nspSet contract\n * @param {string} publicNamespace like the name said\n * @return {array} namespaces in order\n */\nexport function getNamespaceInOrder(nspSet, publicNamespace) {\n let names = []; // need to make sure the order!\n for (let namespace in nspSet) {\n if (namespace === publicNamespace) {\n names[1] = namespace;\n } else {\n names[0] = namespace;\n }\n }\n return names;\n}\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","// 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'\nimport { JsonqlValidationError } from 'jsonql-errors'\n\nimport isArray from 'lodash-es/isArray'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport isString from 'lodash-es/isString'\n\nimport { timestamp } from './generic'\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) ? JSON.parse(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 * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * wrapper method to add the timestamp as well\n * @param {string} resolverName\n * @param {*} payload\n * @return {object} delierable\n */\nexport function createDeliverable(resolverName, payload) {\n return {\n [resolverName]: payload,\n [TIMESTAMP_PARAM_NAME]: [ timestamp() ]\n }\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(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\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]: payload[TIMESTAMP_PARAM_NAME]\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 = getNameFromPayload(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]: payload[TIMESTAMP_PARAM_NAME]\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","/**\n * Checks if `value` is `null`.\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 `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\nfunction isNull(value) {\n return value === null;\n}\n\nexport default isNull;\n","/**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\nfunction isUndefined(value) {\n return value === undefined;\n}\n\nexport default isUndefined;\n","/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nimport { trim, isArray } from './lodash'\n\nexport default a => {\n if (isArray(a)) {\n return true;\n }\n return a !== undefined && a !== null && trim(a) !== '';\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\nimport { isNaN, isString } from './lodash'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a check 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 { isString, trim } from './lodash'\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\nimport { isBoolean } from './lodash'\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return isBoolean(value);\n};\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\n\nimport { isNull, trim, isUndefined } from './lodash'\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 (!isUndefined(value) && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && !isNull(value))) {\n return true;\n }\n }\n return false;\n};\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const 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)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\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\nimport { isArray, trim } from './lodash'\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\nimport { isPlainObject, isUndefined, filter } from './lodash'\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 (!isUndefined(_value)) {\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 checkIsObject.apply(null, _args)\n}\n","/**\n * just a simple util for helping to debug\n * @param {array} args arguments\n * @return {void}\n */\nexport default function log(...args) {\n try {\n if (window && window.console) {\n Reflect.apply(console.log, console, args)\n }\n } catch(e) {}\n}\n","// move the index.js code here that make more sense to find where things are\nimport { isUndefined } from './lodash'\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\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 UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\nimport log from './log'\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 (!isUndefined(arg)) {\n return arg;\n }\n return (param.optional === true && !isUndefined(param.defaultvalue) ? 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 JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n log(1)\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 log(2)\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 log(3)\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 log(4)\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 log(5)\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","/**\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, merge, mapValues } from '../lodash'\nimport {\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError\n} from 'jsonql-errors'\nimport log from '../log'\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\nimport { merge } from '../lodash'\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 => {\n // debugFn('args', args1)\n return runValidation(args1, cb)\n })\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\nimport { isFunction, isString } from '../lodash'\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'\nimport 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// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:index');\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 * 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 */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = 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 checkConfigAsync,\n checkConfig,\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'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\n// export the two extra functions\nimport isInArray from './src/is-in-array'\nimport isObjectHasKeyFn from './src/is-key-in-object'\n\nexport const inArray = isInArray;\nexport const isObjectHasKey = isObjectHasKeyFn;\n","// mapping the resolver to their respective nsp\nimport { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants'\nimport { groupByNamespace, extractSocketPart } from 'jsonql-utils/module'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from '../options/constants'\n\nimport getDebug from './get-debug'\nconst debug = getDebug('process-contract')\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n const result = extractSocketPart(contract)\n if (result !== false) {\n return result\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n [NSP_SET]: { [JSONQL_PATH]: getResolverList(contract) },\n [PUBLIC_NAMESPACE]: JSONQL_PATH\n }\n}\n","// group all the small functions here\nimport { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { toArray, createEvt } from 'jsonql-utils/module'\n// import { getDebug } from './get-debug';\n// const debug = getDebug('helpers')\n\n// we shouldn't do this anymore\nexport const fixWss = (url, serverType) => {\n // ws only allow ws:// path\n if (serverType === JS_WS_NAME) {\n return url.replace('http://', 'ws://')\n }\n return url;\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\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 * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nexport const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n // @TODO need to figure out a better way here?\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('Disconnect call failed', e)\n }\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 { getDebug, isObjectHasKey } from '../utils'\nconst debugFn = getDebug('respondHandler')\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 resolver(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_PROP_NAME, RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants'\nimport { createEvt, toArray } from 'jsonql-utils/module'\nimport { respondHandler } from './respond-handler'\nimport { getDebug } from '../utils'\nconst debugFn = getDebug(`action-call`)\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {boolean} useCallbackStyle use on or not\n * @param {array} args arguments\n * @return {void} nothing\n */\nexport function actionCall(ee, namespace, resolverName, useCallbackStyle, args = []) {\n const eventName = createEvt(namespace, EMIT_REPLY_TYPE)\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME\n debugFn(`actionCall: ${eventName} --> ${resolverName}`, args)\n ee.$trigger(eventName, [resolverName, toArray(args)])\n // once we trigger there is nothing return from the resolve\n // @TODO if we need the next then call to have the result back\n // then we need to listen to the event callback here as well\n return new Promise((resolver, rejecter) => {\n ee.$on(\n createEvt(namespace, resolverName, RESULT_SUBFIX),\n function actionCallResultHandler(result) {\n debugFn(`got the first result`, result)\n respondHandler(result, resolver, rejecter)\n }\n )\n })\n}\n","// @TODO using the obj.on syntax to do the same thing\n/*\nThe new callback style `useCallbackStyle` set to true then use this one\nclient.resolverName.on(EVENT_NAME, cb)\n*/\nimport { JsonqlValidationError, JsonqlError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { CB_FN_NAME } from '../options/constants'\n\nimport { respondHandler } from './respond-handler'\nimport { getDebug, chainFns, injectToFn, createEvt, toArray, isFunc, isString } from '../utils'\nconst debugFn = getDebug('setup-resolver')\n\n/**\n * Add extra property to the resolver via the getter\n * @param {function} fn the resolver itself\n * @param {object} ee event emitter\n * @param {string} namespace the namespace this belongs to\n * @param {string} resolverName resolver namee\n * @param {object} params from the contract\n * @return {array} same as what goes in\n */\nexport function setupCallbackApi(fn, ee, namespace, resolverName, params) {\n return [\n injectToFn(fn, CB_FN_NAME, function(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch(evtName) {\n case RESULT_PROP_NAME:\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n // register the handler for this message event\n case MESSAGE_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME),\n function onMessageCallback(args) {\n respondHandler(args, callback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n break;\n case READY_PROP_NAME:\n ee.$only(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n callback\n )\n break;\n default:\n ee.$trigger(\n createEvt(namespace, resolverName, ON_ERROR_PROP_NAME),\n new JsonqlError(resolverName, `Unknown event name ${evtName}!`)\n )\n }\n }\n }),\n ee,\n namespace,\n resolverName,\n params\n ]\n}\n","// break up the original setup resolver method here\nimport { JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME\n} from 'jsonql-constants'\nimport { MY_NAMESPACE } from '../options/constants'\nimport { chainFns, objDefineProps, injectToFn, createEvt, toArray, isFunc } from 'jsonql-utils/module'\n\nimport { respondHandler } from './respond-handler'\nimport { getDebug } from '../utils'\nconst debugFn = getDebug('setup-resolver')\n\nimport { setupSend } from './setup-send'\nimport { setupCallbackApi } from './setup-callback-api'\n\n/**\n * The first one in the chain\n * @return {array}\n */\nconst setupNamespace = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n injectToFn(fn, MY_NAMESPACE, namespace),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// onResult handler\nconst setupOnResult = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_RESULT_PROP_NAME, function(resultCallback) {\n if (isFunc(resultCallback)) {\n ee.$on(\n createEvt(namespace, resolverName, ON_RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n )\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\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\nconst setupOnMessage = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_MESSAGE_PROP_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 respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, ON_MESSAGE_PROP_NAME), onMessageCallback)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n// add an ON_ERROR_PROP_NAME handler\nconst setupOnError = (fn, ee, namespace, resolverName, params, useCallbackStyle) => [\n objDefineProps(fn, ON_ERROR_PROP_NAME, function(resolverErrorHandler) {\n if (isFunc(resolverErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ON_ERROR_PROP_NAME), resolverErrorHandler)\n }\n }),\n ee,\n namespace,\n resolverName,\n params,\n useCallbackStyle\n]\n\n/**\n * Add extra property 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 {boolean} useCallbackStyle new callback style\n * @return {function} resolver\n */\nexport function setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle) {\n // also need to setup a getter to get back the namespace of this resolver\n let args = [setupNamespace]\n useCallbackStyle ? args.push(setupCallbackApi) : args.push(setupOnResult, setupOnMessage, setupOnError)\n args.push(setupSend)\n // get the executor\n const executor = Reflect.apply(chainFns, null, args)\n // debug(exe)\n return Reflect.apply(executor, null, [fn, ee, namespace, resolverName, params, useCallbackStyle])\n}\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\nimport { JsonqlError, JsonqlValidationError, finalCatch } from 'jsonql-errors'\nimport { validateAsync } from 'jsonql-params-validator'\nimport {\n ERROR_PROP_NAME,\n LOGIN_PROP_NAME,\n READY_PROP_NAME,\n ON_ERROR_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n ON_READY_PROP_NAME\n} from 'jsonql-constants'\nimport { actionCall } from './action-call'\nimport {\n getDebug,\n createEvt,\n toArray,\n injectToFn,\n objDefineProps,\n chainFns,\n isString,\n isFunc,\n isObjectHasKey\n} from '../utils'\nimport { CB_FN_NAME } from '../options/constants'\nconst debugFn = getDebug('resolver-methods')\n\n/**\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 {boolean} useCallbackStyle on style or not\n * @return {function} resolver\n */\nexport function createResolver(ee, namespace, resolverName, params, useCallbackStyle) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then(_args => actionCall(ee, namespace, resolverName, useCallbackStyle, _args))\n .catch(finalCatch)\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} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @param {boolean} useCallbackStyle use cb or not\n * @return {object} obj with onError prop\n */\nexport function createNamespaceErrorHandler(obj, ee, nspSet) {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n return objDefineProps(obj, ON_ERROR_PROP_NAME, function namespaceErrorCallbackHandler(namespaceErrorHandler) {\n if (isFunc(namespaceErrorHandler)) {\n // please note ON_ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\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_PROP_NAME), namespaceErrorHandler)\n }\n }\n })\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {object} obj with onReady prop\n */\nexport function createOnReadyhandler(obj, ee, nspSet) {\n return objDefineProps(obj, ON_READY_PROP_NAME, function onReadyCallbackHandler(onReadyCallback) {\n if (isFunc(onReadyCallback)) {\n // reduce it down to just one flat level\n ee.$on(ON_READY_PROP_NAME, onReadyCallback)\n }\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 * @param {object} opts configuration\n * @return {object} obj with onLogin prop\n */\nexport function createOnLoginhandler(obj, ee, opts) {\n if (opts.enableAuth) {\n return objDefineProps(obj, ON_LOGIN_PROP_NAME, function onLoginCallbackHandler(onLoginCallback) {\n if (isFunc(onLoginCallback)) {\n // only one callback can registered with it, TBC\n ee.$only(ON_LOGIN_PROP_NAME, onLoginCallback)\n }\n })\n }\n // just skip it\n return obj\n}\n\n/**\n * when useCallbackStyle=true use this instead of the above method\n * @param {object} obj the base object to attach to\n * @param {object} ee EventEmitter\n * @param {object} nspSet the map\n * @param {object} opts configuration\n * @return {object} obj\n */\nexport function createCallbackHandler(obj, ee, nspSet, opts) {\n return injectToFn(obj, CB_FN_NAME, function onHandler(evtName, callback) {\n if (isString(evtName) && isFunc(callback)) {\n switch (evtName) {\n case ERROR_PROP_NAME:\n for (let namespace in nspSet) {\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, ERROR_PROP_NAME), callback)\n }\n break;\n case LOGIN_PROP_NAME:\n ee.$only(LOGIN_PROP_NAME, callback)\n break;\n case READY_PROP_NAME:\n ee.$on(READY_PROP_NAME, callback)\n break;\n default:\n ee.$trigger(ERROR_PROP_NAME, new JsonqlError(CB_FN_NAME, `Unknown event name ${evtName}!`))\n }\n }\n // @TODO need to issue another error here!\n })\n}\n","// take out from the resolver-methods\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\nimport { injectToFn, chainFns, isString } from '../utils'\n\n/**\n * @TODO this is now become unnecessary because the login is a slave to the\n * http-client - but keep this for now and see what we want to do with it later\n * break out from createAuthMethods to allow chaining call\n * @param {object} obj the main client object\n * @param {object} ee event emitter\n * @param {object} opts configuration\n * @return {array} modified input\n */\nconst setupLoginHandler = (obj, ee, opts) => [\n injectToFn(obj, opts.loginHandlerName, function loginHandler(token) {\n if (token && isString(token)) {\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 ee,\n opts\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} ee event emitter\n * @param {object} opts configuration\n * @return {object} the modified obj\n */\nconst setupLogoutHandler = (obj, ee, opts) => (\n injectToFn(obj, opts.logoutHandlerName, function logoutHandler(...args) {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n })\n)\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {object} obj with auth methods if any\n */\nexport function createAuthMethods(obj, ee, opts) {\n if (opts.enableAuth) {\n return chainFns(setupLoginHandler, setupLogoutHandler)(obj, ee, opts)\n }\n return obj;\n}\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 { setupResolver } from './setup-resolver'\nimport {\n createResolver,\n createNamespaceErrorHandler,\n createOnReadyhandler,\n createOnLoginhandler,\n createCallbackHandler\n} from './resolver-methods'\nimport { createAuthMethods } from './setup-auth-methods'\nimport { getDebug, injectToFn, chainProcessPromises } from '../utils'\nconst debugFn = getDebug('generator')\n\n/**\n * step one get the obj map with the namespace\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {promise} resolve the obj mapped, and start the chain\n */\nfunction getMappedObj(opts, nspMap, ee) {\n let obj = {};\n // let resolverNames = [];\n const { nspSet } = nspMap;\n const { useCallbackStyle } = opts; // @1.2.1\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n // resolverNames.push(resolverName)\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params, useCallbackStyle)\n // this should set as a getter therefore can not be overwrite by accident\n // obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n obj = injectToFn(obj, resolverName, setupResolver(namespace, resolverName, params, fn, ee, useCallbackStyle))\n }\n }\n // move this two method down to helpers\n // we want these methods visible in debug or console.log\n obj.devHelpers = {\n // this is a helper method for the developer to know the namespace inside\n getNsp: () => Object.keys(nspSet),\n // simple get version trick\n getVer: () => opts.version || 'NOT SET'\n // not really necessary because the dev can query the contract\n // getResolverNames: () => resolverNames\n }\n // resolve the obj to start the chain\n // chain the result to allow the chain processing\n return Promise.resolve(obj)\n}\n\n/**\n * prepare the methods\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 generator(opts, nspMap, ee) {\n const { nspSet } = nspMap\n const { useCallbackStyle } = opts;\n let args = [getMappedObj]\n if (useCallbackStyle) {\n args.push(obj => createCallbackHandler(obj, ee, nspSet, opts))\n } else {\n args.push(\n obj1 => createNamespaceErrorHandler(obj1, ee, nspSet),\n obj2 => createOnReadyhandler(obj2, ee, nspSet),\n obj3 => createOnLoginhandler(obj3, ee, opts),\n )\n }\n args.push(obj4 => createAuthMethods(obj4, ee, opts))\n // run it\n const executor = Reflect.apply(chainProcessPromises, null, args)\n return executor(opts, nspMap, ee)\n\n /*\n return getMappedObj(opts, nspMap, ee)\n // add error handler\n .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet))\n // add onReady handler\n .then(obj2 => createOnReadyhandler(obj2, ee, nspSet))\n // add onLogin handler -- this is optional\n .then(obj3 => createOnLoginhandler(obj3, ee, opts))\n // Auth related methods -- this is optional\n .then(obj4 => createAuthMethods(obj4, ee, opts))\n */\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","// create options\nimport { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator'\nimport { CHECKED_KEY } from 'jsonql-constants'\n// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors'\n// this should be remove - we have to make it generic\nimport { defaultOptions } from './defaults'\nimport { fixWss, getHostName, getDebug, objHasProp } from '../utils'\nconst debug = getDebug('check-options')\n// constant props\nconst defaultConstProps = {\n eventEmitter: null,\n // we unify the two different client into one now\n // only expect different parameter\n nspClient: null,\n nspAuthClient: null,\n // contructed path\n wssPath: ''\n}\n// for export\nconst jsonqlWsDefaultOptions = defaultOptions\nconst jsonqlWsDefaultConstProps = defaultConstProps\n\n/**\n * wrapper method to check this already did the pre check\n * @param {object} config\n * @param {object} dOpt\n * @param {object} cProps\n * @return {promise} resolve to the checked opitons\n */\nfunction checkOptionsWrapper(config, dOpt, cProps) {\n if (objHasProp(config, CHECKED_KEY)) {\n return Promise.resolve(config)\n }\n return checkConfigAsync(config, dOpt, cProps)\n}\n\n/**\n * check the configuration\n * @param {object} config user supplied configuration\n * @param {object} constProps developer supplied configuration\n * @return {object} after checked\n */\nfunction checkOptions(config, constProps) {\n return checkOptionsWrapper(config, defaultOptions, Object.assign(defaultConstProps, constProps))\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 opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType)\n debug('CONFIGURATION OPTIONS', opts)\n return opts;\n })\n}\n\nexport {\n jsonqlWsDefaultConstProps,\n jsonqlWsDefaultOptions,\n checkOptions\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 { generator } from './core'\nimport { checkOptions } from './options'\nimport { ee, processContract } from './utils'\n\n/**\n * The main interface which will generate the socket clients and map all events\n * @param {object} socketClientResolver this is the one method export by various clients\n * @param {object} [constProps={}] add this to supply the constProps from the downstream client\n * @return {object} the wsClient instance with all the available API\n */\nexport default function wsClient(socketClientResolver, constProps = {}) {\n // we need to inject property to this client later\n // therefore we need to do it this way\n return (opts) => {\n const { eventEmitter } = opts;\n return checkOptions(opts, constProps)\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee()\n }))\n .then(\n ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee)\n )\n .then(\n ({opts, nspMap, ee}) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error(`jsonql-ws-client init error`, err)\n })\n }\n}\n","// where all the base options are\n// create options\nimport { JS_WS_NAME } from 'jsonql-constants'\n// constant props\nconst constProps = {\n version: '__PLACEHOLDER__', // will get replace\n serverType: JS_WS_NAME\n}\n\nexport { constProps }\n","// pass the different type of ws to generate the client\nimport { TOKEN_PARAM_NAME } from 'jsonql-constants'\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 */\nconst fixWss = url => {\n const uri = url.toLowerCase()\n if (uri.indexOf('http') > -1) {\n if (uri.indexOf('https') > -1) {\n return uri.replace('https', 'wss')\n }\n return uri.replace('http', 'ws')\n }\n return uri;\n}\n\n/**\n * The bug was in the wsOptions where ws doesn't need it but socket.io do\n * therefore the object was pass as second parameter!\n * @param {object} WebSocket the client or node version of ws\n * @param {boolean} auth if it's auth then 3 param or just one\n */\nexport function createWsClient(WebSocket, auth = false) {\n if (auth === false) {\n return function createWsClientHandler(url) {\n return new WebSocket(fixWss(url))\n }\n }\n\n /**\n * Create a client with auth token\n * @param {string} url start with ws:// @TODO check this?\n * @param {string} token the jwt token\n * @return {object} ws instance\n */\n return function createWsAuthClientHandler(url, token) {\n const ws_url = fixWss(url)\n // console.log('what happen here?', url, ws_url, token)\n const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url;\n try {\n return new WebSocket(uri)\n } catch(e) {\n console.error('WebSocket Connection Error', e)\n return false;\n }\n }\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\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, wsOptions, nspClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return nspClient(url, wsOptions)\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, wsOptions, nspAuthClient } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n if (token && typeof token !== 'string') {\n throw new Error(`Expect token to be string, but got ${token}`)\n }\n return nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n createNspClient,\n createNspAuthClient\n}\n","// this use by client-event-handler\nimport { ON_ERROR_PROP_NAME, ERROR_PROP_NAME } from 'jsonql-constants'\nimport { createEvt } from 'jsonql-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 * @param {object} opts configuration\n * @return {void}\n */\nexport function triggerNamespacesOnError(ee, namespaces, message, opts = {}) {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n namespaces.forEach( namespace => {\n ee.$call(createEvt(namespace, ERROR_SUBFIX), [{ message, namespace }])\n })\n}\n","// This is share between different clients so we export it\n\n\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\nimport { EMIT_EVT, SOCKET_IO, WS } from '../options/constants'\nimport {\n ERROR_PROP_NAME,\n RESULT_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ON_ERROR_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n} from 'jsonql-constants'\n\nimport { getDebug, createEvt, clearMainEmitEvt } from '../utils'\nimport { triggerNamespacesOnError } from './trigger-namespaces-on-error'\nconst debugFn = getDebug('client-event-handler')\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee, opts) => {\n const { useCallbackStyle } = opts;\n const ERROR_SUBFIX = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n const RESULT_SUBFIX = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function notLoginHandlerCallback(resolverName, args) {\n debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\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, ERROR_SUBFIX), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_SUBFIX), [{ error }])\n }\n )\n}\n\n/**\n * get the private namespace\n * @param {array} namespaces array\n * @return {*} string on success\n */\nconst getPrivateNamespace = (namespaces) => (\n namespaces.length > 1 ? namespaces[0] : false\n)\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws --> this is the core bit\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\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 let isPrivate = false;\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n isPrivate = privateNamespace === namespace;\n if (nsps[namespace]) {\n debugFn('call bindWsHandler', isPrivate, namespace)\n let args = [namespace, nsps[namespace], ee, isPrivate, opts]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee, opts)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() {\n debugFn('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee, opts)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString } from 'jsonql-params-validator'\nimport { isObjectHasKey } from 'jsonql-utils/module'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isObjectHasKey(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport { getDebug } from 'jsonql-ws-client/share'\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n\n ON_ERROR_PROP_NAME,\n ON_MESSAGE_PROP_NAME,\n ON_RESULT_PROP_NAME,\n ON_READY_PROP_NAME,\n ON_LOGIN_PROP_NAME,\n\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n READY_PROP_NAME,\n LOGIN_PROP_NAME\n} from 'jsonql-constants'\nimport { createQueryStr, createEvt } from 'jsonql-utils/module'\nimport extractWsPayload from './extract-ws-payload'\nconst debugFn = getDebug('ws-main-handler')\n\n\n/**\n * under extremely circumstances 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 * @param {string} ERROR_EVT_NAME the error event name\n * @return {undefined} nothing return\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json, ERROR_EVT_NAME) => {\n let evt = [namespace]\n if (resolverName) {\n debugFn(`a global error on ${namespace}`)\n evt.push(resolverName)\n }\n evt.push(ERROR_EVT_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 even 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 * @return {object} promise resolve after the onopen event\n */\nexport function wsMainHandler(namespace, ws, ee, isPrivate, opts) {\n const { useCallbackStyle } = opts;\n const READY_EVT_NAME = useCallbackStyle ? READY_PROP_NAME : ON_READY_PROP_NAME;\n const LOGIN_EVT_NAME = useCallbackStyle ? LOGIN_PROP_NAME : ON_LOGIN_PROP_NAME;\n const MESSAGE_EVT_NAME = useCallbackStyle ? MESSAGE_PROP_NAME : ON_MESSAGE_PROP_NAME;\n const RESULT_EVT_NAME = useCallbackStyle ? RESULT_PROP_NAME : ON_RESULT_PROP_NAME;\n const ERROR_EVT_NAME = useCallbackStyle ? ERROR_PROP_NAME : ON_ERROR_PROP_NAME;\n // connection open\n ws.onopen = function onOpenCallback() {\n debugFn('ws.onopen listened')\n // we just call the onReady\n ee.$call(READY_EVT_NAME, namespace)\n // need an extra parameter here to id the private nsp\n if (isPrivate) {\n console.log(`isPrivate and fire the ${LOGIN_EVT_NAME}`)\n ee.$call(LOGIN_EVT_NAME, namespace)\n }\n // add listener only after the open is called\n ee.$only(\n createEvt(namespace, EMIT_REPLY_TYPE),\n function wsMainOnEvtHandler(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\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 // console.log(`on.message`, typeof payload, payload)\n try {\n const json = extractWsPayload(payload)\n const { resolverName, type } = json;\n debugFn('Hear from server', type, json)\n switch (type) {\n case EMIT_REPLY_TYPE:\n let e1 = createEvt(namespace, resolverName, MESSAGE_EVT_NAME)\n let r = ee.$trigger(e1, [json])\n debugFn(`EMIT_REPLY_TYPE`, e1, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n let e2 = createEvt(namespace, resolverName, RESULT_EVT_NAME)\n let x = ee.$trigger(e2, [json])\n debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n debugFn(`ERROR_TYPE`)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\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 debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json, ERROR_EVT_NAME)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, ON_RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n console.error(`ws.onmessage error`, e)\n errorTypeHandler(ee, namespace, false, e, ERROR_EVT_NAME)\n }\n }\n // when the server close the connection\n ws.onclose = function onCloseCallback() {\n debugFn('ws.onclose callback')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n console.error('ws.terminate error', e)\n }\n })\n}\n","// actually binding the event client to the socket client\nimport { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport {\n createNspClient,\n createNspAuthClient,\n clientEventHandler,\n triggerNamespacesOnError,\n clearMainEmitEvt,\n disconnect,\n getDebug\n} from 'jsonql-ws-client/share'\nimport { wsMainHandler } from './ws-main-handler'\n\nconst debugFn = getDebug('ws-create-client')\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\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 {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth) { // && opts.useJwt\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n // console.log('create createNspAuthClient at run time', opts)\n return {[namespace]: createNspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: createNspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = createNspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport function createClient(opts, nspMap, ee) {\n // arguments that don't change\n const args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n const { token } = opts;\n const { nsps, namespaces, login } = createNsps(opts, nspMap, token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) {\n debugFn(`LOGIN_EVENT_NAME called with token:`, tokenLater)\n // @BUG 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\n // disconnect(nsps, JS_WS_NAME)\n\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n // console.log('LOGIN_EVENT_NAME', token)\n const newNsps = createNsps(opts, nspMap, tokenLater)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// share method to create the wsClientResolver\n\nimport { createWsClient } from './create-ws-client'\nimport { createClient } from './create-client'\n\n/**\n * combine the create client resolver\n * @param {object} ws the different WebSocket module\n * @return {function} the wsClientResolver\n */\nexport default function createClientResolver(ws) {\n const client = createWsClient(ws)\n const authClient = createWsClient(ws, true)\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(opts, nspMap, ee) {\n opts.nspClient = client;\n opts.nspAuthClient = authClient;\n\n // console.log(`contract`, opts.contract)\n\n return createClient(opts, nspMap, ee)\n }\n}\n","// 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 WebSocket from './core/ws'\nimport createClientResolver from './core/create-client-resolver'\n\n/**\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 default createClientResolver(WebSocket)\n","// this is the module entry point for ES6 for client\n// the main will point to the node.js server side setup\nimport { jsonqlWsClient } from 'jsonql-ws-client'\n\nimport { constProps } from './src/options'\nimport wsClientResolver from './src/ws-client-resolver'\n\n// export back the function and that's it\nexport default jsonqlWsClient(wsClientResolver, constProps)\n","// export the required options here to merge with the http client to do a combine check\nimport { jsonqlWsDefaultConstProps, jsonqlWsDefaultOptions } from 'jsonql-ws-client'\nimport { constProps as localConstProps } from './src/options'\n\nconst defaultOptions = jsonqlWsDefaultOptions\nconst constProps = Object.assign(jsonqlWsDefaultConstProps, localConstProps)\n\n\nexport {\n defaultOptions,\n constProps\n}\n","// this is the jsonql client with ws\n// use like import jsonqlClient from '@jsonql/client/ws'\nimport { jsonqlClientModule } from 'jsonql-client/module'\nimport { getPreConfigCheck } from 'jsonql-client/opt'\nimport jsonqlWsClient from '@jsonql/ws'\nimport { CHECKED_KEY } from 'jsonql-constants'\nimport {\n defaultOptions as wsDefaultOptions,\n constProps as wsConstProps\n} from '@jsonql/ws/opt'\n// import debug from 'debug'\n// const debugFn = debug('jsonql-client:test:ws')\n// debugFn(jsonqlWsClient)\n\n/**\n * @param {object} Fly the fly module\n * @param {object} [config={}] developer supply options\n * @return {object} the jsonql browser client with ws socket\n * @public\n */\nexport default function createJsonqlHttpWsClient(Fly, config = {}) {\n // @NOTE it return a function to accept the config\n const fn = getPreConfigCheck(wsDefaultOptions, wsConstProps)\n const opts = fn(config)\n opts.socketClient = jsonqlWsClient\n // init the client\n return jsonqlClientModule(Fly, opts)\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/@jsonql/client/dist/jsonql-client-ws.js b/packages/@jsonql/client/dist/jsonql-client-ws.js index aa74c4bd..a913fa07 100644 --- a/packages/@jsonql/client/dist/jsonql-client-ws.js +++ b/packages/@jsonql/client/dist/jsonql-client-ws.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(t=t||self).jsonqlClientWs=r()}(this,(function(){"use strict";var t="data",r="error",e="jsonql",n="application/vnd.api+json",o={Accept:n,"Content-Type":[n,"charset=utf-8"].join(";")},i="query",a="mutation",u="socket",c="TS",s=["POST","PUT"],f="type",l="optional",h="enumv",p="args",g="checker",v="alias",d="__checked__",y={desc:"y"},b="No message",w="__login__",m="__logout__",_="emit",E="acknowledge",j="error",O="nspSet",A="publicNamespace",S="onMessage",k="onResult",T="onError",P="onReady",R="onLogin",C="message",x="result",N="error",$="ready",U="login",I="token",q=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,e),r}(Error),M=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,e),r}(Error),z=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,e),r}(Error),B=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,e),r}(Error),L=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,e),r}(Error),F=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,e),r}(Error),Y=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,e),r}(Error),D=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,e),r}(Error),J=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,e),r}(Error),H=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(Error),W=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(r,e),r}(Error),K=function(t){function r(e,n){t.call(this,n),this.statusCode=e,this.className=r.name}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,e),r}(Error),V=Object.freeze({__proto__:null,Jsonql406Error:q,Jsonql500Error:M,JsonqlAuthorisationError:z,JsonqlContractAuthError:B,JsonqlResolverAppError:L,JsonqlResolverNotFoundError:F,JsonqlEnumError:Y,JsonqlTypeError:D,JsonqlCheckerError:J,JsonqlValidationError:H,JsonqlError:W,JsonqlServerError:K}),G=W,Q=function(t,r){return!!Object.keys(t).filter((function(t){return r===t})).length};function X(t){if(Q(t,"error")){var r=t.error,e=r.className,n=r.name,o=e||n,i=r.message||b,a=r.detail||r;if(o&&V[o])throw new V[e](i,a);throw new G(i,a)}return t}function Z(t){if(Array.isArray(t))throw new H("",t);var r=t.message||b,e=t.detail||t;switch(!0){case t instanceof q:throw new q(r,e);case t instanceof M:throw new M(r,e);case t instanceof z:throw new z(r,e);case t instanceof B:throw new B(r,e);case t instanceof L:throw new L(r,e);case t instanceof F:throw new F(r,e);case t instanceof Y:throw new Y(r,e);case t instanceof D:throw new D(r,e);case t instanceof J:throw new J(r,e);case t instanceof H:throw new H(r,e);case t instanceof K:throw new K(r,e);default:throw new W(r,e)}}var tt="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},rt="object"==typeof tt&&tt&&tt.Object===Object&&tt,et="object"==typeof self&&self&&self.Object===Object&&self,nt=rt||et||Function("return this")(),ot=nt.Symbol;function it(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var i=Array(o);++n-1;);return e}(n,o),function(t,r){for(var e=t.length;e--&&At(r,t[e],0)>-1;);return e}(n,o)+1).join("")}function Lt(t){return void 0===t}var Ft="[object Boolean]";var Yt="[object Number]";function Dt(t){return function(t){return"number"==typeof t||dt(t)&&vt(t)==Yt}(t)&&t!=+t}var Jt="[object String]";function Ht(t){return"string"==typeof t||!at(t)&&dt(t)&&vt(t)==Jt}function Wt(t,r){return function(e){return t(r(e))}}var Kt=Wt(Object.getPrototypeOf,Object),Vt="[object Object]",Gt=Function.prototype,Qt=Object.prototype,Xt=Gt.toString,Zt=Qt.hasOwnProperty,tr=Xt.call(Object);function rr(t){if(!dt(t)||vt(t)!=Vt)return!1;var r=Kt(t);if(null===r)return!0;var e=Zt.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&Xt.call(e)==tr}var er,nr=function(t,r,e){for(var n=-1,o=Object(t),i=e(t),a=i.length;a--;){var u=i[er?a:++n];if(!1===r(o[u],u,o))break}return t};var or="[object Arguments]";function ir(t){return dt(t)&&vt(t)==or}var ar=Object.prototype,ur=ar.hasOwnProperty,cr=ar.propertyIsEnumerable,sr=ir(function(){return arguments}())?ir:function(t){return dt(t)&&ur.call(t,"callee")&&!cr.call(t,"callee")};var fr="object"==typeof exports&&exports&&!exports.nodeType&&exports,lr=fr&&"object"==typeof module&&module&&!module.nodeType&&module,hr=lr&&lr.exports===fr?nt.Buffer:void 0,pr=(hr?hr.isBuffer:void 0)||function(){return!1},gr=9007199254740991,vr=/^(?:0|[1-9]\d*)$/;function dr(t,r){var e=typeof t;return!!(r=null==r?gr:r)&&("number"==e||"symbol"!=e&&vr.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=yr}var wr={};wr["[object Float32Array]"]=wr["[object Float64Array]"]=wr["[object Int8Array]"]=wr["[object Int16Array]"]=wr["[object Int32Array]"]=wr["[object Uint8Array]"]=wr["[object Uint8ClampedArray]"]=wr["[object Uint16Array]"]=wr["[object Uint32Array]"]=!0,wr["[object Arguments]"]=wr["[object Array]"]=wr["[object ArrayBuffer]"]=wr["[object Boolean]"]=wr["[object DataView]"]=wr["[object Date]"]=wr["[object Error]"]=wr["[object Function]"]=wr["[object Map]"]=wr["[object Number]"]=wr["[object Object]"]=wr["[object RegExp]"]=wr["[object Set]"]=wr["[object String]"]=wr["[object WeakMap]"]=!1;var mr,_r="object"==typeof exports&&exports&&!exports.nodeType&&exports,Er=_r&&"object"==typeof module&&module&&!module.nodeType&&module,jr=Er&&Er.exports===_r&&rt.process,Or=function(){try{var t=Er&&Er.require&&Er.require("util").types;return t||jr&&jr.binding&&jr.binding("util")}catch(t){}}(),Ar=Or&&Or.isTypedArray,Sr=Ar?(mr=Ar,function(t){return mr(t)}):function(t){return dt(t)&&br(t.length)&&!!wr[vt(t)]},kr=Object.prototype.hasOwnProperty;function Tr(t,r){var e=at(t),n=!e&&sr(t),o=!e&&!n&&pr(t),i=!e&&!n&&!o&&Sr(t),a=e||n||o||i,u=a?function(t,r){for(var e=-1,n=Array(t);++e-1},Jr.prototype.set=function(t,r){var e=this.__data__,n=Yr(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var Hr,Wr=nt["__core-js_shared__"],Kr=(Hr=/[^.]+$/.exec(Wr&&Wr.keys&&Wr.keys.IE_PROTO||""))?"Symbol(src)_1."+Hr:"";var Vr=Function.prototype.toString;function Gr(t){if(null!=t){try{return Vr.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var Qr=/^\[object .+?Constructor\]$/,Xr=Function.prototype,Zr=Object.prototype,te=Xr.toString,re=Zr.hasOwnProperty,ee=RegExp("^"+te.call(re).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ne(t){return!(!Nr(t)||function(t){return!!Kr&&Kr in t}(t))&&(Mr(t)?ee:Qr).test(Gr(t))}function oe(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return ne(e)?e:void 0}var ie=oe(nt,"Map"),ae=oe(Object,"create");var ue="__lodash_hash_undefined__",ce=Object.prototype.hasOwnProperty;var se=Object.prototype.hasOwnProperty;var fe="__lodash_hash_undefined__";function le(t){var r=-1,e=null==t?0:t.length;for(this.clear();++ru))return!1;var s=i.get(t);if(s&&i.get(r))return s==r;var f=-1,l=!0,h=e&me?new ye:void 0;for(i.set(t,r),i.set(r,t);++f0){if(++r>=co)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(uo);function ho(t,r){return lo(function(t,r,e){return r=ao(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,i=ao(n.length-r,0),a=Array(i);++o1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=po.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!Nr(e))return!1;var n=typeof r;return!!("number"==n?zr(e)&&dr(r,e.length):"string"==n&&r in e)&&Fr(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0))},Io=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},qo=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!$o(r)(t)})).length)})).length:r.length>r.filter((function(t){return!Uo(e,t)})).length},Mo=function(t,r){if(void 0===r&&(r=null),rr(t)){if(!r)return!0;if(Uo(r))return!r.filter((function(r){var e=t[r.name];return!(r.type.length>r.type.filter((function(t){var r;return!!Lt(e)||(!1!==(r=Io(t))?!qo({arg:e},r):!$o(t)(e))})).length)})).length}return!1},zo=function(t){var r=t.arg,e=t.param,n=[r];return Array.isArray(e.keys)&&e.keys.length&&n.push(e.keys),Mo.apply(null,n)};function Bo(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.console&&Reflect.apply(console.log,console,t)}catch(t){}}var Lo=function(t,r){var e;switch(!0){case"object"===t:return!zo(r);case"array"===t:return!Uo(r.arg);case!1!==(e=Io(t)):return!qo(r,e);default:return!$o(t)(r.arg)}},Fo=function(t,r){return Lt(t)?!0!==r.optional||Lt(r.defaultvalue)?null:r.defaultvalue:t},Yo=function(e,n,o){var i;void 0===o&&(o=!1);var a=function(t,r){if(!Uo(r))throw new W("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!Uo(t))throw new W("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==r.length:return Bo(1),t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:Bo(2);var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:Bo(4);var n=r.length,o=["any"];return t.map((function(t,e){var i=e>=n||!!r[e].optional,a=r[e]||{type:o,name:"_"+e};return{arg:i?Fo(t,a):t,index:e,param:a,optional:i}}));default:throw Bo(5),new W("Could not understand your arguments and parameter structure!",{args:t,params:r})}}(e,n),u=a.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var r=t.arg,e=t.param;return!!Eo(r)&&!(e.type.length>e.type.filter((function(r){return Lo(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return Lo(r,t)})).length)}));return o?((i={})[r]=u,i[t]=a.map((function(t){return t.arg})),i):u},Do=function(t,r){var e,n=Object.keys(t);return e=r,!!n.filter((function(t){return t===e})).length},Jo=function(t){return!Eo(t)};function Ho(t,r){var e=_o(r,(function(t,r){return!t[xo]}));return pn(e,{})?t:function(t,r){var e={};return r=zn(r),Lr(t,(function(t,n,o){Ln(e,r(t,n,o),t)})),e}(t,(function(t,r){return function(t,r,e){var n;return e(t,(function(t,e,o){if(r(t,e,o))return n=e,!1})),n}(e,zn((function(t){return t.alias===r})),Lr)||r}))}function Wo(t,r){return vo(r,(function(r,e){var n,o;return Lt(t[e])||!0===r[To]&&Jo(t[e])?go({},r,((n={})[No]=!0,n)):((o={})[Ro]=t[e],o[ko]=r[ko],o[To]=r[To]||!1,o[Po]=r[Po]||!1,o[Co]=r[Co]||!1,o)}))}function Ko(t,r){var e=function(t,r){var e=Ho(t,r);return{pristineValues:vo(_o(r,(function(t,r){return Do(e,r)})),(function(t){return t.args})),checkAgainstAppProps:_o(r,(function(t,r){return!Do(e,r)})),config:e}}(t,r),n=e.config,o=e.pristineValues;return[Wo(n,e.checkAgainstAppProps),o]}var Vo=function(t){return Uo(t)?t:[t]};var Go=function(t,r){return!Uo(r)||function(t,r){return!!t.filter((function(t){return t===r})).length}(r,t)},Qo=function(t,r){try{return!!Mr(r)&&r.apply(null,[t])}catch(t){return!1}};function Xo(t){return function(r,e){if(r[No])return r[Ro];var n=function(t,r){var e,n=[[t[Ro]],[(e={},e[ko]=Vo(t[ko]),e[To]=t[To],e)]];return Reflect.apply(r,null,n)}(r,t);if(n.length)throw Bo("runValidationAction",e,r),new D(e,n);if(!1!==r[Po]&&!Go(r[Ro],r[Po]))throw Bo(Po,r[Po]),new Y(e);if(!1!==r[Co]&&!Qo(r[Ro],r[Co]))throw Bo(Co,r[Co]),new J(e);return r[Ro]}}function Zo(t,r){var e=t[0],n=t[1],o=vo(e,Xo(r));return go(o,n)}var ti=function(t,r){return Promise.resolve(Ko(t,r))};function ri(t,r,e,n,o,i){void 0===e&&(e=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===i&&(i=!1);var a={};return a[p]=t,a[f]=r,!0===e&&(a[l]=!0),Uo(n)&&(a[h]=n),Mr(o)&&(a[g]=o),Ht(i)&&(a[v]=i),a}var ei=Oo,ni=Uo,oi=function(e,n,o){return void 0===o&&(o=!1),new Promise((function(i,a){var u=Yo(e,n,o);return o?u[r].length?a(u[r]):i(u[t]):u.length?a(u):i([])}))},ii=function(t,r,e){void 0===e&&(e={});var n=e[l],o=e[h],i=e[g],a=e[v];return ri.apply(null,[t,r,n,o,i,a])},ai=function(t){return function(r,e,n){return void 0===n&&(n={}),function(t,r,e,n){return void 0===t&&(t={}),ti(t,r).then((function(t){return Zo(t,n)})).then((function(t){return go({},t,e)}))}(r,e,n,t)}}(Yo),ui=function(t){return function(r,e,n){return void 0===n&&(n={}),function(t,r,e,n){return void 0===t&&(t={}),go(Zo(Ko(t,r),n),e)}(r,e,n,t)}}(Yo),ci="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var si=Object.assign?Object.assign:function(t,r,e,n){for(var o=arguments,i=1;i=0;r--){var e=Ci().key(r);t(xi(e),e)}},remove:function(t){return Ci().removeItem(t)},clearAll:function(){return Ci().clear()}};function Ci(){return Pi.localStorage}function xi(t){return Ci().getItem(t)}var Ni=pi.trim,$i={name:"cookieStorage",read:function(t){if(!t||!Mi(t))return null;var r="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(Ui.cookie.replace(new RegExp(r),"$1"))},write:function(t,r){if(!t)return;Ui.cookie=escape(t)+"="+escape(r)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Ii,remove:qi,clearAll:function(){Ii((function(t,r){qi(r)}))}},Ui=pi.Global.document;function Ii(t){for(var r=Ui.cookie.split(/; ?/g),e=r.length-1;e>=0;e--)if(Ni(r[e])){var n=r[e].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function qi(t){t&&Mi(t)&&(Ui.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Mi(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(Ui.cookie)}var zi=function(){var t={};return{defaults:function(r,e){t=e},get:function(r,e){var n=r();return void 0!==n?n:t[e]}}};var Bi="expire_mixin",Li=function(){var t=this.createStore(this.storage,null,this._namespacePrefix+Bi);return{set:function(r,e,n,o){this.hasNamespace(Bi)||t.set(e,o);return r()},get:function(t,e){this.hasNamespace(Bi)||r.call(this,e);return t()},remove:function(r,e){this.hasNamespace(Bi)||t.remove(e);return r()},getExpiration:function(r,e){return t.get(e)},removeExpiredKeys:function(t){var e=[];this.each((function(t,r){e.push(r)}));for(var n=0;n>>8,e[2*n+1]=a%256}return e},decompressFromUint8Array:function(r){if(null==r)return i.decompress(r);for(var e=new Array(r.length/2),n=0,o=e.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,p),p++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,p),p++),a[s]=h++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,p),p++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,p),p++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,d==r-1){g.push(e(v));break}d++}return g.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(r){return t.charCodeAt(r)}))},_decompress:function(r,e,n){var o,i,a,u,c,s,f,l=[],h=4,p=4,g=3,v="",d=[],y={val:n(0),position:e,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,d.push(f);;){if(y.index>r)return"";for(a=0,c=Math.pow(2,g),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[p++]=t(a),f=p-1,h--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[p++]=t(a),f=p-1,h--;break;case 2:return d.join("")}if(0==h&&(h=Math.pow(2,g),g++),l[f])v=l[f];else{if(f!==p)return null;v=i+i.charAt(0)}d.push(v),l[p++]=i+v.charAt(0),i=v,0==--h&&(h=Math.pow(2,g),g++)}}};return i}();null!=t&&(t.exports=r)}));var Vi=[Ri,$i],Gi=[zi,Li,Hi,function(){return{get:function(t,r){var e=t(r);if(!e)return e;var n=Ki.decompress(e);return null==n?e:this._deserialize(n)},set:function(t,r,e){var n=Ki.compress(this._serialize(e));t(r,n)}}}],Qi=Si.createStore(Vi,Gi),Xi=pi.Global;function Zi(){return Xi.sessionStorage}function ta(t){return Zi().getItem(t)}var ra=[{name:"sessionStorage",read:ta,write:function(t,r){return Zi().setItem(t,r)},each:function(t){for(var r=Zi().length-1;r>=0;r--){var e=Zi().key(r);t(ta(e),e)}},remove:function(t){return Zi().removeItem(t)},clearAll:function(){return Zi().clear()}},$i],ea=[zi,Li],na=Si.createStore(ra,ea),oa=Qi,ia=na,aa=Array.isArray,ua=void 0!==tt?tt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},ca="object"==typeof ua&&ua&&ua.Object===Object&&ua,sa="object"==typeof self&&self&&self.Object===Object&&self,fa=(ca||sa||Function("return this")()).Symbol,la=Object.prototype,ha=la.hasOwnProperty,pa=la.toString,ga=fa?fa.toStringTag:void 0;var va=Object.prototype.toString;var da="[object Null]",ya="[object Undefined]",ba=fa?fa.toStringTag:void 0;function wa(t){return null==t?void 0===t?ya:da:ba&&ba in Object(t)?function(t){var r=ha.call(t,ga),e=t[ga];try{t[ga]=void 0;var n=!0}catch(t){}var o=pa.call(t);return n&&(r?t[ga]=e:delete t[ga]),o}(t):function(t){return va.call(t)}(t)}var ma=function(t,r){return function(e){return t(r(e))}}(Object.getPrototypeOf,Object);function _a(t){return null!=t&&"object"==typeof t}var Ea="[object Object]",ja=Function.prototype,Oa=Object.prototype,Aa=ja.toString,Sa=Oa.hasOwnProperty,ka=Aa.call(Object);var Ta=fa?fa.prototype:void 0,Pa=(Ta&&Ta.toString,"[object String]");function Ra(t){return"string"==typeof t||!aa(t)&&_a(t)&&wa(t)==Pa}var Ca=function(t,r){return!!t.filter((function(t){return t===r})).length},xa=function(t,r){var e=Object.keys(t);return Ca(e,r)},Na=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r},$a="query",Ua="mutation",Ia="socket",qa="payload",Ma="condition",za=function(){try{if(window||document)return!0}catch(t){}return!1},Ba=function(){try{if(!za()&&ua)return!0}catch(t){}return!1};var La=function(t){function r(){for(var e=arguments,n=[],o=arguments.length;o--;)n[o]=e[o];t.apply(this,n),this.message=n[0],this.detail=n[1],this.className=r.name,Error.captureStackTrace&&Error.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(function(t){function r(){for(var r=arguments,e=[],n=arguments.length;n--;)e[n]=r[n];t.apply(this,e)}return t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r,r.where=function(){return za()?"browser":Ba()?"node":"unknown"},r}(Error));var Fa=function(t){var r;return(r={}).args=t,r};var Ya=function(t){return xa(t,"data")&&!xa(t,"error")?t.data:t},Da=function(t){return function(t){if(!_a(t)||wa(t)!=Ea)return!1;var r=ma(t);if(null===r)return!0;var e=Sa.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&Aa.call(e)==ka}(t)&&(xa(t,$a)||xa(t,Ua)||xa(t,Ia))},Ja=function(t,r){return void 0===r&&(r={}),Da(r)?Promise.resolve(r):t.getContract()},Ha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Wa(t){this.message=t}Wa.prototype=new Error,Wa.prototype.name="InvalidCharacterError";var Ka="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var r=String(t).replace(/=+$/,"");if(r.length%4==1)throw new Wa("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,o=0,i=0,a="";n=r.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?a+=String.fromCharCode(255&e>>(-2*o&6)):0)n=Ha.indexOf(n);return a};var Va=function(t){var r=t.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Ka(t).replace(/(.)/g,(function(t,r){var e=r.charCodeAt(0).toString(16).toUpperCase();return e.length<2&&(e="0"+e),"%"+e})))}(r)}catch(t){return Ka(r)}};function Ga(t){this.message=t}Ga.prototype=new Error,Ga.prototype.name="InvalidTokenError";var Qa=function(t,r){if("string"!=typeof t)throw new Ga("Invalid token specified");var e=!0===(r=r||{}).header?0:1;try{return JSON.parse(Va(t.split(".")[e]))}catch(t){throw new Ga("Invalid token specified: "+t.message)}},Xa=Ga;Qa.InvalidTokenError=Xa;var Za,tu,ru,eu,nu,ou,iu,au,uu,cu=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r};function su(t){if(ei(t))return function(t){var r=t.iat||cu(!0);if(t.exp&&r>=t.exp){var e=new Date(t.exp).toISOString();throw new W("Token has expired on "+e,t)}return t}(Qa(t));throw new W("Token must be a string!")}ii("HS256",["string"]),ii(!1,["boolean","number","string"],((Za={})[v]="exp",Za[l]=!0,Za)),ii(!1,["boolean","number","string"],((tu={})[v]="nbf",tu[l]=!0,tu)),ii(!1,["boolean","string"],((ru={})[v]="iss",ru[l]=!0,ru)),ii(!1,["boolean","string"],((eu={})[v]="sub",eu[l]=!0,eu)),ii(!1,["boolean","string"],((nu={})[v]="iss",nu[l]=!0,nu)),ii(!1,["boolean"],((ou={})[l]=!0,ou)),ii(!1,["boolean","string"],((iu={})[l]=!0,iu)),ii(!1,["boolean","string"],((au={})[l]=!0,au)),ii(!1,["boolean"],((uu={})[l]=!0,uu));var fu=s[0],lu=s[1],hu=function(t){!function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.console&&Reflect.apply(console.log,null,t)}catch(t){}}(t),this.fly=t.Fly?new t.Fly:new Fly,this.opts=t,this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()},pu={headers:{configurable:!0}};pu.headers.set=function(t){this.extraHeader=t},hu.prototype.request=function(t,r,e){var n;void 0===r&&(r={}),void 0===e&&(e={}),this.headers=e;var o=go({},{_cb:Na()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=go({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}return this.fly.request(this.jsonqlEndpoint,t,go({},{method:fu,params:o},r))},hu.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(r){var e=t.getHeaders();for(var n in t.log("request interceptor call",e),e)r.headers[n]=e[n];return r}))},hu.prototype.processJsonp=function(t){return Ya(t)},hu.prototype.resInterceptor=function(){var t=this,r=this,e=r.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call"),r.cleanUp();var o=ei(n.data)?JSON.parse(n.data):n.data;return e?r.processJsonp(o):Ya(o)}),(function(t){throw r.cleanUp(),console.error(t),new K("Server side error",t)}))},hu.prototype.getHeaders=function(){return this.opts.enableAuth?go({},o,this.getAuthHeader(),this.extraHeader):go({},o,this.extraHeader)},hu.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},hu.prototype.get=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=go({},this.extraParams,y)),this.request({},{method:"GET"},this.contractHeader).then(X).then((function(r){return t.log("get contract result",r),r.cache&&r.contract?r.contract:r}))},hu.prototype.query=function(t,r){return void 0===r&&(r=[]),this.request(function(t,r,e){var n;if(void 0===r&&(r=[]),void 0===e&&(e=!1),Ra(t)&&aa(r)){var o=Fa(r);return!0===e?o:((n={})[t]=o,n)}throw new La("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}(t,r)).then(X)},hu.prototype.mutation=function(t,r,e){return void 0===r&&(r={}),void 0===e&&(e={}),this.request(function(t,r,e,n){var o;void 0===e&&(e={}),void 0===n&&(n=!1);var i={};if(i[qa]=r,i[Ma]=e,!0===n)return i;if(Ra(t))return(o={})[t]=i,o;throw new La("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:e})}(t,r,e),{method:lu}).then(X)},Object.defineProperties(hu.prototype,pu);var gu=function(t){function r(r,e){void 0===e&&(e=null),e&&(r.Fly=e),t.call(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={storeIt:{configurable:!0},jsonqlEndpoint:{configurable:!0},jsonqlContract:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return e.storeIt.set=function(t){throw console.info("storeIt",t),ni(t)&&t.length>=2&&Reflect.apply(oa.set,oa,t),new H("Expect argument to be array and least 2 items!")},e.jsonqlEndpoint.set=function(t){var r=oa.get("endpoint")||[];Ca(r,t)||(r.push(t),this.storeId=["endpoint",r],this.endpointIndex=r.length-1)},e.jsonqlContract.set=function(t){var r=this.opts.storageKey,e=[r],n=t[0],o=t[1],i=oa.get(r)||[];i[this.endpointIndex||0]=n,e.push(i),o&&e.push(o),this.opts.keepContract&&(this.storeIt=e)},e.jsonqlToken.set=function(t){var r="credential",e=localStorage.get(r)||[];if(!Ca(e,t)){var n=e.length-1;e[n]=t,this[r+"Index"]=n;var o=[r,e];if(this.opts.tokenExpired){var i=parseFloat(this.opts.tokenExpired);if(!isNaN(i)&&i>0){var a=Na();o.push(a+parseFloat(i))}}return this.storeIt=o,this.jsonqlUserdata=this.decoder(t),t}return!1},e.jsonqlUserdata.set=function(t){var r=["userdata",t];return t.exp&&r.push(t.exp),Reflect.apply(oa.set,oa,r)},e.jsonqlEndpoint.get=function(){var t=oa.get("endpoint");if(!t){var r=this.opts,e=[r.hostname,r.jsonqlPath].join("/");return this.jsonqlEndpoint=e,e}return t[this.endpointIndex]},e.jsonqlContract.get=function(){var t=this.opts.storageKey;return(oa.get(t)||[])[this.endpointIndex]||!1},e.jsonqlToken.get=function(){var t="credential",r=localStorage.get(t);return!!r&&r[this[t+"Index"]]},e.jsonqlUserdata.get=function(){return ia.get("userdata")},r.prototype.log=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(r.prototype,e),r}(function(t){function r(r){t.call(this,r),r.enableAuth&&r.useJwt&&(this.setDecoder=su)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={userdata:{configurable:!0},rawAuthToken:{configurable:!0},setDecoder:{configurable:!0}};return e.userdata.get=function(){return this.jsonqlUserdata},e.rawAuthToken.get=function(){return this.jsonqlToken},e.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},r.prototype.storeToken=function(t){return this.jsonqlToken=t},r.prototype.decoder=function(t){return t},r.prototype.getAuthHeader=function(){var t,r=this.rawAuthToken;return r?((t={})[this.opts.AUTH_HEADER]="Bearer "+r,t):{}},Object.defineProperties(r.prototype,e),r}(function(t){function r(r){t.call(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={contractHeader:{configurable:!0}};return r.prototype.getContract=function(){var t=this.readContract();if(this.log("getContract first call",t),t&&Array.isArray(t)){var r=t[this.endpointIndex||0];if(r)return Promise.resolve(r)}return this.get().then(this.storeContract.bind(this))},e.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},r.prototype.storeContract=function(t){if(!Da(t))throw new H("Contract is malformed!");var r=[t];if(this.opts.contractExpired){var e=parseFloat(this.opts.contractExpired);!isNaN(e)&&e>0&&r.push(e)}return this.jsonqlContract=r,this.log("storeContract return result",t),t},r.prototype.readContract=function(){return Da(this.opts.contract)?this.opts.contract:oa.get(this.opts.storageKey)},Object.defineProperties(r.prototype,e),r}(hu))),vu=new WeakMap,du=new WeakMap;var yu=function(){this.__suspend__=null,this.queueStore=new Set},bu={$suspend:{configurable:!0},$queues:{configurable:!0}};bu.$suspend.set=function(t){var r=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var e=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+e+" --\x3e "+t),!0===e&&!1===t&&setTimeout((function(){r.release()}),1)},yu.prototype.$queue=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},bu.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},yu.prototype.release=function(){var t=this,r=this.queueStore.size;if(this.logger("(release)","Release was called "+r),r>0){var e=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",e),e.forEach((function(r){t.logger(r),Reflect.apply(t.$trigger,t,r)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(yu.prototype,bu);var wu=function(t){function r(r){void 0===r&&(r={}),t.call(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={$done:{configurable:!0}};return r.prototype.logger=function(){},r.prototype.$on=function(t,r,e){var n=this;void 0===e&&(e=null);this.validate(t,r);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",r,e);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(r,a,e||u),i+=n.addToNormalStore(t,"on",r,e||u)})),i},r.prototype.$once=function(t,r,e){void 0===e&&(e=null),this.validate(t,r);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",r,e);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(r,i,e||a),this.$off(t)},r.prototype.$only=function(t,r,e){var n=this;void 0===e&&(e=null),this.validate(t,r);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",r,e)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(r,i,e||a)})));return o},r.prototype.$onlyOnce=function(t,r,e){void 0===e&&(e=null),this.validate(t,r);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",r,e)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(r,a,e||u),this.$off(t)}return n},r.prototype.$replace=function(t,r,e,n){if(void 0===e&&(e=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,r),Reflect.apply(o,this,[t,r,e])}throw new Error(n+" is not supported!")},r.prototype.$trigger=function(t,r,e,n){void 0===r&&(r=[]),void 0===e&&(e=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,r,e,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(r)?(this.logger("(addToStore)",r+" existed"),e=t.get(r)):(this.logger("(addToStore)","create new Set for "+r),e=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(r,i)||e.add(n)}else this.checkContentExist(n,e)||(this.logger("(addToStore)","insert new",n),e.add(n));else e.add(n);return t.set(r,e),[t,e.size]},r.prototype.checkContentExist=function(t,r){return!!Array.from(r).filter((function(r){return r[0]===t[0]})).length},r.prototype.checkTypeInStore=function(t,r){this.validateEvt(t,r);var e=this.$get(t,!0);return!1===e||!e.filter((function(t){var e=t[3];return r!==e})).length},r.prototype.checkTypeInLazyStore=function(t,r){this.validateEvt(t,r);var e=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",e),!!e&&!!Array.from(e).filter((function(t){return t[2]!==r})).length},r.prototype.addToNormalStore=function(t,r,e,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,r,"try to add to normal store"),this.checkTypeInStore(t,r)){this.logger("(addToNormalStore)",r+" can add to "+t+" normal store");var o=this.hashFnToKey(e),i=[this.normalStore,t,o,e,n,r],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},r.prototype.addToLazyStore=function(t,r,e,n){void 0===r&&(r=[]),void 0===e&&(e=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(r),e];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},r.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},e.normalStore.set=function(t){vu.set(this,t)},e.normalStore.get=function(){return vu.get(this)},e.lazyStore.set=function(t){du.set(this,t)},e.lazyStore.get=function(){return du.get(this)},r.prototype.hashFnToKey=function(t){return t.toString().split("").reduce((function(t,r){return(t=(t<<5)-t+r.charCodeAt(0))&t}),0)+""},Object.defineProperties(r.prototype,e),r}(yu));var mu=function(t){return at(t)?t:[t]},_u=function(t,r){try{var e=Object.keys(t);return n=r,!!e.filter((function(t){return t===n})).length}catch(t){return!1}var n},Eu=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},ju=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r},Ou=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type!")},Au=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,mu(t))}),Reflect.apply(t,null,e))}};function Su(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}}function ku(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t}function Tu(t,r){var e=Object.getOwnPropertyDescriptor(t,r);return void 0!==e&&e.value?e.value:e}function Pu(t,r,e,n){void 0===n&&(n=!1);var o=Tu(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)}function Ru(t){return!!_u(t,"socket")&&t.socket}var Cu=function(t){var r;return(r={}).args=t,r};function xu(t,r,e){if(void 0===r&&(r=[]),void 0===e&&(e=!1),Ht(t)&&at(r)){var n=Cu(r);return!0===e?n:function(t,r){var e;return(e={})[t]=r,e[c]=[ju()],e}(t,n)}throw new H("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}var Nu=function(t,r,e,n){return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var i=n.auth[r].params,a=i.map((function(t,r){return e[r]})),u=e[i.length]||{};return oi(e,i).then((function(){return t.query.apply(t,[r,a,u])})).catch(Z)}},$u=function(t,r,e,n,o){var i={},a=function(t){i=Pu(i,t,(function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,r){return e[r]})),u=e[i.length]||{};return oi(a,i).then((function(){return r.query.apply(r,[t,a,u])})).catch(Z)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,r,e,n,o]},Uu=function(t,r,e,n,o){var i={},a=function(t){i=Pu(i,t,(function(e,n,i){void 0===i&&(i={});var a=[e,n],u=o.mutation[t].params;return oi(a,u).then((function(){return r.mutation.apply(r,[t,e,n,i])})).catch(Z)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,r,e,n,o]},Iu=function(t,r,e,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Nu(r,a,0,o);return i.apply(null,t).then(r.postLoginAction).then((function(t){return e.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Nu(r,u,0,o);return i.apply(null,t).then(r.postLogoutAction).then((function(t){return e.$trigger("logout",t),t}))}:i[u]=function(){r.postLogoutAction("continue"),e.$trigger("logout","continue")},t.auth=i}return t};var qu=function(t,r,e,n){var o=function(t,r,e,n){return Au($u,Uu,Iu)({},t,r,e,n)}(t,n,r,e);return r.enableAuth&&(o.userdata=function(){return t.userdata},o.getToken=function(){return t.rawAuthToken}),r.exposeContract&&(o.getContract=function(){return t.getContract()}),o.eventEmitter=n,o.version="0.1.0",o},Mu={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:n,BEARER:"Bearer",AUTH_HEADER:"Authorization"},zu={hostname:ii(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ii(e,["string"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),enableJsonp:ii(!1,["boolean"]),enableAuth:ii(!1,["boolean"]),useJwt:ii(!0,["boolean"]),useLocalstorage:ii(!0,["boolean"]),storageKey:ii("storageKey",["string"]),authKey:ii("authKey",["string"]),contractExpired:ii(0,["number"]),keepContract:ii(!0,["boolean"]),exposeContract:ii(!1,["boolean"]),showContractDesc:ii(!1,["boolean"]),contractKey:ii(!1,["boolean"]),contractKeyName:ii("X-JSONQL-CV-KEY",["string"]),enableTimeout:ii(!1,["boolean"]),timeout:ii(5e3,["number"]),returnInstance:ii(!1,["boolean"]),allowReturnRawToken:ii(!1,["boolean"]),debugOn:ii(!1,["boolean"])};function Bu(t){return t[d]?t:function(t){var r=t.contract;return ai(t,zu,Mu).then((function(t){return t.contract=r,t}))}(t)}function Lu(t,r){void 0===r&&(r={});var e=r.socketClient,n=function(t){return new wu({logger:t?function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})}(r.debugOn);return Bu(r).then((function(r){return{opts:r,baseClient:new gu(r,t)}})).then((function(t){var r=t.opts,e=t.baseClient;return Ja(e,r.contract).then((function(t){return{opts:r,contract:t,client:qu(e,r,t,n)}}))})).then((function(t){var r=t.opts,n=t.contract;return function(t,r,e,n){if(xa(r,u)){if(n)return e.eventEmitter=t.eventEmitter,n(e).then((function(r){return t[u]=r,t}));throw new W("initSocketClient","socketClient is missing!")}return t}(t.client,n,r,e)}))}function Fu(t,r){return void 0===t&&(t={}),void 0===r&&(r={}),function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(Au,null,e.concat((function(t){return Pu(t,d,ju())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}}(go({},zu,t),go({},Mu,r),ui)}var Yu="socket.io",Du=_,Ju="UKNNOWN RESULT!",Hu="on",Wu="jsonql-ws-client",Ku=function(t){try{if(window.debug)return window.debug(Wu).extend(t)}catch(t){}try{if(tt.debug)return tt.debug(Wu).extend(t)}catch(t){}return function(){for(var r=[],e=arguments.length;e--;)r[e]=arguments[e];console.info.apply(null,[Wu,t].concat(r))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",Wu+"*")}catch(t){}var Vu=function(t){function r(){t.call(this,{logger:Ku("nb-event-service")})}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"jsonql-ws-client"},Object.defineProperties(r.prototype,e),r}(wu),Gu=(Ku("process-contract"),function(t){var r=Ru(t);if(!1!==r)return r;throw new F("Missing property in contract!")});function Qu(t){var r,n,o=t.contract;return t.enableAuth?function(t,r){void 0===r&&(r=!1);var e=Ru(t);if(!1===e){if(r)return t;throw new W("socket not found in contract!")}var n,o={},i=0;for(var a in e){var u=e[a],c=u.namespace;c&&(o[c]||(++i,o[c]={}),o[c][a]=u,n||u.public&&(n=c))}return{size:i,nspSet:o,publicNamespace:n}}(o):((n={})[O]=((r={})[e]=Gu(o),r),n[A]=e,n)}var Xu=function(t,r){return"ws"===r?t.replace("http://","ws://"):t},Zu=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}},tc=function(t,r){mu(r).forEach((function(r){t.$off(Eu(r,_))}))},rc=Ku("respondHandler");function ec(e,n,o){_u(e,r)?(rc("-- rejecter called --",e[r]),o(e[r])):_u(e,t)?(rc("-- resolver called --",e[t]),n(e[t])):(rc("-- UNKNOWN_RESULT --",e),o({message:Ju,error:e}))}var nc=Ku("action-call");function oc(t,r,e,n,o){void 0===o&&(o=[]);var i=Eu(r,_),a=n?x:k;return nc("actionCall: "+i+" --\x3e "+e,o),t.$trigger(i,[e,mu(o)]),new Promise((function(n,o){t.$on(Eu(r,e,a),(function(t){nc("got the first result",t),ec(t,n,o)}))}))}var ic=Ku("setup-send"),ac=function(t,e,n,o,i,a){return ku(t,"send",(function(t){var u=a?N:T;ic("got payload for",t),oi(mu(t),i.params,!0).then((function(i){if(!i[r]||!i[r].length)return oc(e,n,o,a,t);ic("got ERROR_KEY",i[r]),e.$call(Eu(n,o,u),[new H(o,i[r])])})).catch((function(t){ic("error after validateAsync",t),e.$call(Eu(n,o,u),[new H(o,t)])}))}),(function(){return function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return oi(t,i.params,!0).then((function(t){return oc(e,n,o,a,t)})).catch(Z)}}))};Ku("setup-resolver");function uc(t,r,e,n,o){return[Pu(t,Hu,(function(t,o){if(ei(t)&&Ou(o))switch(t){case x:r.$on(Eu(e,n,ON_RESULT_PROP_NAME),(function(t){ec(t,o,(function(t){r.$trigger(Eu(e,n,ON_ERROR_PROP_NAME),t)}))}));break;case C:r.$only(Eu(e,n,ON_MESSAGE_PROP_NAME),(function(t){ec(t,o,(function(t){r.$trigger(Eu(e,n,ON_ERROR_PROP_NAME),t)}))}));break;case READY_PROP_NAME:r.$only(Eu(e,n,ON_ERROR_PROP_NAME),o);break;default:r.$trigger(Eu(e,n,ON_ERROR_PROP_NAME),new W(n,"Unknown event name "+t+"!"))}})),r,e,n,o]}Ku("setup-resolver");var cc=function(t,r,e,n,o,i){return[Pu(t,"myNamespace",e),r,e,n,o,i]},sc=function(t,r,e,n,o,i){return[ku(t,k,(function(t){Ou(t)&&r.$on(Eu(e,n,k),(function(o){ec(o,t,(function(t){r.$trigger(Eu(e,n,T),t)}))}))})),r,e,n,o,i]},fc=function(t,r,e,n,o,i){return[ku(t,S,(function(t){if(Ou(t)){r.$only(Eu(e,n,S),(function(o){ec(o,t,(function(t){r.$trigger(Eu(e,n,T),t)}))}))}})),r,e,n,o,i]},lc=function(t,r,e,n,o,i){return[ku(t,T,(function(t){Ou(t)&&r.$only(Eu(e,n,T),t)})),r,e,n,o,i]};function hc(t,r,e,n,o,i){var a=[cc];i?a.push(uc):a.push(sc,fc,lc),a.push(ac);var u=Reflect.apply(Au,null,a);return Reflect.apply(u,null,[n,o,t,r,e,i])}Ku("resolver-methods");function pc(t,r,e,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return oi(i,n.params,!0).then((function(n){return oc(t,r,e,o,n)})).catch(Z)}}var gc=function(t,r,e){return[Pu(t,e.loginHandlerName,(function(t){if(t&&ei(t))return r.$trigger(w,[t]);throw new H(e.loginHandlerName,"Unexpected token "+t)})),r,e]},vc=function(t,r,e){return Pu(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger(m,t)}))};Ku("generator");function dc(t,r,e){var n={},o=r.nspSet,i=t.useCallbackStyle;for(var a in o){var u=o[a];for(var c in u){var s=u[c];n=Pu(n,c,hc(a,c,s,pc(e,a,c,s,i),e,i))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function yc(t,r,e){var n=r.nspSet,o=[dc];return t.useCallbackStyle?o.push((function(t){return function(t,r,e,n){return Pu(t,Hu,(function(t,n){if(ei(t)&&Ou(n))switch(t){case N:for(var o in e)r.$on(Eu(o,N),n);break;case U:r.$only(U,n);break;case $:r.$on($,n);break;default:r.$trigger(N,new W(Hu,"Unknown event name "+t+"!"))}}))}(t,e,n)})):o.push((function(t){return function(t,r,e){return ku(t,T,(function(t){if(Ou(t))for(var n in e)r.$on(Eu(n,T),t)}))}(t,e,n)}),(function(t){return function(t,r,e){return ku(t,P,(function(t){Ou(t)&&r.$on(P,t)}))}(t,e)}),(function(r){return function(t,r,e){return e.enableAuth?ku(t,R,(function(t){Ou(t)&&r.$only(R,t)})):t}(r,e,t)})),o.push((function(r){return function(t,r,e){return e.enableAuth?Au(gc,vc)(t,r,e):t}(r,e,t)})),Reflect.apply(Su,null,o)(t,r,e)}var bc=[],wc=[],mc="undefined"!=typeof Uint8Array?Uint8Array:Array,_c=!1;function Ec(){_c=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,e=t.length;r>18&63]+bc[o>>12&63]+bc[o>>6&63]+bc[63&o]);return i.join("")}function Oc(t){var r;_c||Ec();for(var e=t.length,n=e%3,o="",i=[],a=0,u=e-n;au?u:a+16383));return 1===n?(r=t[e-1],o+=bc[r>>2],o+=bc[r<<4&63],o+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],o+=bc[r>>10],o+=bc[r>>4&63],o+=bc[r<<2&63],o+="="),i.push(o),i.join("")}function Ac(t,r,e,n,o){var i,a,u=8*o-n-1,c=(1<>1,f=-7,l=e?o-1:0,h=e?-1:1,p=t[r+l];for(l+=h,i=p&(1<<-f)-1,p>>=-f,f+=u;f>0;i=256*i+t[r+l],l+=h,f-=8);for(a=i&(1<<-f)-1,i>>=-f,f+=n;f>0;a=256*a+t[r+l],l+=h,f-=8);if(0===i)i=1-s;else{if(i===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),i-=s}return(p?-1:1)*a*Math.pow(2,i-n)}function Sc(t,r,e,n,o,i){var a,u,c,s=8*i-o-1,f=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:i-1,g=n?1:-1,v=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,a=f):(a=Math.floor(Math.log(r)/Math.LN2),r*(c=Math.pow(2,-a))<1&&(a--,c*=2),(r+=a+l>=1?h/c:h*Math.pow(2,1-l))*c>=2&&(a++,c/=2),a+l>=f?(u=0,a=f):a+l>=1?(u=(r*c-1)*Math.pow(2,o),a+=l):(u=r*Math.pow(2,l-1)*Math.pow(2,o),a=0));o>=8;t[e+p]=255&u,p+=g,u/=256,o-=8);for(a=a<0;t[e+p]=255&a,p+=g,a/=256,s-=8);t[e+p-g]|=128*v}var kc={}.toString,Tc=Array.isArray||function(t){return"[object Array]"==kc.call(t)};function Pc(){return Cc.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Rc(t,r){if(Pc()=Pc())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Pc().toString(16)+" bytes");return 0|t}function qc(t){return!(null==t||!t._isBuffer)}function Mc(t,r){if(qc(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 e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return ps(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return gs(t).length;default:if(n)return ps(t).length;r=(""+r).toLowerCase(),n=!0}}function zc(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return ts(this,r,e);case"utf8":case"utf-8":return Gc(this,r,e);case"ascii":return Xc(this,r,e);case"latin1":case"binary":return Zc(this,r,e);case"base64":return Vc(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return rs(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Bc(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function Lc(t,r,e,n,o){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(o)return-1;e=t.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof r&&(r=Cc.from(r,n)),qc(r))return 0===r.length?-1:Fc(t,r,e,n,o);if("number"==typeof r)return r&=255,Cc.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):Fc(t,[r],e,n,o);throw new TypeError("val must be string, number or Buffer")}function Fc(t,r,e,n,o){var i,a=1,u=t.length,c=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;a=2,u/=2,c/=2,e/=2}function s(t,r){return 1===a?t[r]:t.readUInt16BE(r*a)}if(o){var f=-1;for(i=e;iu&&(e=u-c),i=e;i>=0;i--){for(var l=!0,h=0;ho&&(n=o):n=o;var i=r.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var a=0;a>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function Vc(t,r,e){return 0===r&&e===t.length?Oc(t):Oc(t.slice(r,e))}function Gc(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o239?4:s>223?3:s>191?2:1;if(o+l<=e)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],a=t[o+2],128==(192&i)&&128==(192&a)&&(c=(15&s)<<12|(63&i)<<6|63&a)>2047&&(c<55296||c>57343)&&(f=c);break;case 4:i=t[o+1],a=t[o+2],u=t[o+3],128==(192&i)&&128==(192&a)&&128==(192&u)&&(c=(15&s)<<18|(63&i)<<12|(63&a)<<6|63&u)>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 r=t.length;if(r<=Qc)return String.fromCharCode.apply(String,t);var e="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},Cc.prototype.compare=function(t,r,e,n,o){if(!qc(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||e>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=e)return 0;if(n>=o)return-1;if(r>=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),a=(e>>>=0)-(r>>>=0),u=Math.min(i,a),c=this.slice(n,o),s=t.slice(r,e),f=0;fo)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Yc(this,t,r,e);case"utf8":case"utf-8":return Dc(this,t,r,e);case"ascii":return Jc(this,t,r,e);case"latin1":case"binary":return Hc(this,t,r,e);case"base64":return Wc(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Kc(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Cc.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Qc=4096;function Xc(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;on)&&(e=n);for(var o="",i=r;ie)throw new RangeError("Trying to access beyond buffer length")}function ns(t,r,e,n,o,i){if(!qc(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||rt.length)throw new RangeError("Index out of range")}function os(t,r,e,n){r<0&&(r=65535+r+1);for(var o=0,i=Math.min(t.length-e,2);o>>8*(n?o:1-o)}function is(t,r,e,n){r<0&&(r=4294967295+r+1);for(var o=0,i=Math.min(t.length-e,4);o>>8*(n?o:3-o)&255}function as(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function us(t,r,e,n,o){return o||as(t,0,e,4),Sc(t,r,e,n,23,4),e+4}function cs(t,r,e,n,o){return o||as(t,0,e,8),Sc(t,r,e,n,52,8),e+8}Cc.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r0&&(o*=256);)n+=this[t+--r]*o;return n},Cc.prototype.readUInt8=function(t,r){return r||es(t,1,this.length),this[t]},Cc.prototype.readUInt16LE=function(t,r){return r||es(t,2,this.length),this[t]|this[t+1]<<8},Cc.prototype.readUInt16BE=function(t,r){return r||es(t,2,this.length),this[t]<<8|this[t+1]},Cc.prototype.readUInt32LE=function(t,r){return r||es(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Cc.prototype.readUInt32BE=function(t,r){return r||es(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Cc.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||es(t,r,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*r)),n},Cc.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||es(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},Cc.prototype.readInt8=function(t,r){return r||es(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Cc.prototype.readInt16LE=function(t,r){r||es(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},Cc.prototype.readInt16BE=function(t,r){r||es(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},Cc.prototype.readInt32LE=function(t,r){return r||es(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Cc.prototype.readInt32BE=function(t,r){return r||es(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Cc.prototype.readFloatLE=function(t,r){return r||es(t,4,this.length),Ac(this,t,!0,23,4)},Cc.prototype.readFloatBE=function(t,r){return r||es(t,4,this.length),Ac(this,t,!1,23,4)},Cc.prototype.readDoubleLE=function(t,r){return r||es(t,8,this.length),Ac(this,t,!0,52,8)},Cc.prototype.readDoubleBE=function(t,r){return r||es(t,8,this.length),Ac(this,t,!1,52,8)},Cc.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||ns(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i=0&&(i*=256);)this[r+o]=t/i&255;return r+e},Cc.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,1,255,0),Cc.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},Cc.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,2,65535,0),Cc.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):os(this,t,r,!0),r+2},Cc.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,2,65535,0),Cc.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):os(this,t,r,!1),r+2},Cc.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,4,4294967295,0),Cc.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):is(this,t,r,!0),r+4},Cc.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,4,4294967295,0),Cc.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):is(this,t,r,!1),r+4},Cc.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);ns(this,t,r,e,o-1,-o)}var i=0,a=1,u=0;for(this[r]=255&t;++i>0)-u&255;return r+e},Cc.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);ns(this,t,r,e,o-1,-o)}var i=e-1,a=1,u=0;for(this[r+i]=255&t;--i>=0&&(a*=256);)t<0&&0===u&&0!==this[r+i+1]&&(u=1),this[r+i]=(t/a>>0)-u&255;return r+e},Cc.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,1,127,-128),Cc.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},Cc.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,2,32767,-32768),Cc.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):os(this,t,r,!0),r+2},Cc.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,2,32767,-32768),Cc.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):os(this,t,r,!1),r+2},Cc.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,4,2147483647,-2147483648),Cc.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):is(this,t,r,!0),r+4},Cc.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||ns(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Cc.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):is(this,t,r,!1),r+4},Cc.prototype.writeFloatLE=function(t,r,e){return us(this,t,r,!0,e)},Cc.prototype.writeFloatBE=function(t,r,e){return us(this,t,r,!1,e)},Cc.prototype.writeDoubleLE=function(t,r,e){return cs(this,t,r,!0,e)},Cc.prototype.writeDoubleBE=function(t,r,e){return cs(this,t,r,!1,e)},Cc.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=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-r=0;--o)t[o+r]=this[o+e];else if(i<1e3||!Cc.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function gs(t){return function(t){var r,e,n,o,i,a;_c||Ec();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[u-2]?2:"="===t[u-1]?1:0,a=new mc(3*u/4-i),n=i>0?u-4:u;var c=0;for(r=0,e=0;r>16&255,a[c++]=o>>8&255,a[c++]=255&o;return 2===i?(o=wc[t.charCodeAt(r)]<<2|wc[t.charCodeAt(r+1)]>>4,a[c++]=255&o):1===i&&(o=wc[t.charCodeAt(r)]<<10|wc[t.charCodeAt(r+1)]<<4|wc[t.charCodeAt(r+2)]>>2,a[c++]=o>>8&255,a[c++]=255&o),a}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace(ls,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function vs(t,r,e,n){for(var o=0;o=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function ds(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ys=["roundtip","handshake"],bs={useCallbackStyle:ii(!1,["boolean"]),loginHandlerName:ii("login",["string"]),logoutHandlerName:ii("logout",["string"]),loginMethod:ii("handshake",["string"],(ss={},ss[h]=ys,ss)),useJwt:ii(!0,["boolean","string"]),hostname:ii(!1,["string"]),namespace:ii(e,["string"]),wsOptions:ii({},["object"]),contract:ii({},["object"],(fs={},fs[g]=function(t){return!!function(t){return rr(t)&&(_u(t,i)||_u(t,a)||_u(t,u))}(t)&&t},fs)),enableAuth:ii(!1,["boolean"]),token:ii(!1,["string"])},ws=Ku("check-options"),ms={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""},_s=bs,Es=ms;function js(t,r){return function(t,r,e){return Tu(t,d)?Promise.resolve(t):ai(t,r,e)}(t,bs,Object.assign(ms,r)).then((function(t){return t.hostname||(t.hostname=Zu()),t.wssPath=Xu([t.hostname,t.namespace].join("/"),t.serverType),ws("CONFIGURATION OPTIONS",t),t}))}var Os={version:"__PLACEHOLDER__",serverType:"ws"},As=null;"undefined"!=typeof WebSocket?As=WebSocket:"undefined"!=typeof MozWebSocket?As=MozWebSocket:void 0!==tt?As=tt.WebSocket||tt.MozWebSocket:"undefined"!=typeof window?As=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(As=self.WebSocket||self.MozWebSocket);var Ss=As,ks=function(t){var r=t.toLowerCase();return r.indexOf("http")>-1?r.indexOf("https")>-1?r.replace("https","wss"):r.replace("http","ws"):r};function Ts(t,r){return void 0===r&&(r=!1),!1===r?function(r){return new t(ks(r))}:function(r,e){var n=ks(r),o=e&&"string"==typeof e?n+"?"+I+"="+e:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}function Ps(t,r){var e=r.hostname,n=r.wssPath,o=r.wsOptions;return(0,r.nspClient)(t?[e,t].join("/"):n,o)}var Rs=Ku("client-event-handler"),Cs=function(t,r,e){var n=e.useCallbackStyle,o=n?N:T,i=n?x:k;r.$only(Eu(t,Du),(function(e,n){Rs("noLoginHandler hijack the ws call",t,e,n);var a={message:"NOT LOGIN"};r.$call(Eu(t,e,o),[a]),r.$call(Eu(t,e,i),[{error:a}])}))},xs=function(t){return t.length>1&&t[0]};function Ns(t,r,e,n,o,i){var a=xs(o),u=!1;o.forEach((function(o){if(u=a===o,i[o]){Rs("call bindWsHandler",u,o);var c=[o,i[o],e,u,t];if(t.serverType===Yu){var s=r.nspSet;c.push(s[o])}Reflect.apply(n,null,c)}else Cs(o,e,t)})),e.$on(m,(function(){Rs("LOGOUT_EVENT_NAME"),function(t,r,e,n){void 0===n&&(n={});var o=n.useCallbackStyle?N:T;r.forEach((function(r){t.$call(Eu(r,o),[{message:e,namespace:r}])}))}(e,o,m),o.forEach((function(r){tc(e,r),i[r]=!1,Cs(r,e,t)}))}))}var $s=["__reply__","__event__","__data__"],Us=function(t){var r,e=t.data;if(!1!==(r=function(t){var r=t.data;return!!r&&($s.filter((function(t){return _u(r,t)})).length===$s.length&&r)}(ei(e)?JSON.parse(e):e)))return{resolverName:r.__event__,data:r.__data__,type:r.__reply__};throw new W("payload can not be decoded",t)},Is=Ku("ws-main-handler"),qs=function(t,r,e,n,o){var i=[r];e&&(Is("a global error on "+r),i.push(e)),i.push(o);var a=Reflect.apply(Eu,null,i),u=n.data||n;t.$trigger(a,[u])};function Ms(t,r,e,n,o){var i=o.useCallbackStyle,a=i?$:P,u=i?U:R,c=i?C:S,s=i?x:k,f=i?N:T;r.onopen=function(){Is("ws.onopen listened"),e.$call(a,t),n&&(console.log("isPrivate and fire the "+u),e.$call(u,t)),e.$only(Eu(t,_),(function(t,e){Is("calling server",t,e),r.send(function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(xu(t,r,e))}(t,e))}))},r.onmessage=function(r){try{var n=Us(r),o=n.resolverName,i=n.type;switch(Is("Hear from server",i,n),i){case _:var a=Eu(t,o,c),u=e.$trigger(a,[n]);Is("EMIT_REPLY_TYPE",a,u);break;case E:var l=Eu(t,o,s);e.$trigger(l,[n]);Is("ACKNOWLEDGE_REPLY_TYPE",l,n);break;case j:Is("ERROR_TYPE"),qs(e,t,o,n,f);break;default:Is("Unhandled event!",n),qs(e,t,o,n,f)}}catch(r){console.error("ws.onmessage error",r),qs(e,t,!1,r,f)}},r.onclose=function(){Is("ws.onclose callback")},e.$on(m,(function(){try{Is("terminate ws connection"),r.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var zs=Ku("ws-create-client"),Bs=function(t,r,e){var n,o=r.nspSet,i=r.publicNamespace,a=!1,u=[],c={};if(t.enableAuth)a=!0,c=(u=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e}(o,i)).map((function(r,n){var o,i,a;return 0===n?e?(t.token=e,(o={})[r]=function(t,r){var e=r.hostname,n=r.wssPath,o=r.token,i=r.wsOptions,a=r.nspAuthClient,u=t?[e,t].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return a(u,o,i)}(r,t),o):((i={})[r]=!1,i):((a={})[r]=Ps(r,t),a)})).reduce((function(t,r){return Object.assign(t,r)}),{});else{var s=(n=o,Object.keys(n)[0]);u.push(s),c[s]=Ps(!1,t)}return{nsps:c,namespaces:u,login:a}};var Ls=function(t,r){return void 0===r&&(r={}),function(e){var n=e.eventEmitter;return js(e,r).then((function(t){return{opts:t,nspMap:Qu(t),ee:n||new Vu}})).then((function(r){var e=r.opts,n=r.nspMap,o=r.ee;return t(e,n,o)})).then((function(t){return yc(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var r=Ts(t),e=Ts(t,!0);return function(t,n,o){return t.nspClient=r,t.nspAuthClient=e,function(t,r,e){var n=[t,r,e,Ms],o=t.token,i=Bs(t,r,o),a=i.nsps,u=i.namespaces,c=i.login;return Reflect.apply(Ns,null,n.concat([u,a])),c&&e.$only(w,(function(o){zs("LOGIN_EVENT_NAME called with token:",o),tc(e,u);var i=Bs(t,r,o);Reflect.apply(Ns,null,n.concat([i.namespaces,i.nsps]))})),{opts:t,nspMap:r,ee:e}}(t,n,o)}}(Ss),Os),Fs=_s,Ys=Object.assign(Es,Os);return function(t,r){void 0===r&&(r={});var e=Fu(Fs,Ys)(r);return e.socketClient=Ls,Lu(t,e)}})); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(t=t||self).jsonqlClientWs=r()}(this,(function(){"use strict";var t="application/vnd.api+json",r={Accept:t,"Content-Type":[t,"charset=utf-8"].join(";")},e="query",n="mutation",o="socket",i="payload",a="condition",u="TS",c=["POST","PUT"],s="type",f="optional",l="enumv",p="args",h="checker",g="alias",v="__checked__",d={desc:"y"},y="No message",b=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,e),r}(Error),m=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,e),r}(Error),_=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,e),r}(Error),w=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,e),r}(Error),E=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,e),r}(Error),j=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,e),r}(Error),S=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,e),r}(Error),O=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,e),r}(Error),A=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,e),r}(Error),k=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(Error),T=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(r,e),r}(Error),P=function(t){function r(e,n){t.call(this,n),this.statusCode=e,this.className=r.name}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,e),r}(Error),R=Object.freeze({__proto__:null,Jsonql406Error:b,Jsonql500Error:m,JsonqlAuthorisationError:_,JsonqlContractAuthError:w,JsonqlResolverAppError:E,JsonqlResolverNotFoundError:j,JsonqlEnumError:S,JsonqlTypeError:O,JsonqlCheckerError:A,JsonqlValidationError:k,JsonqlError:T,JsonqlServerError:P}),C=T,x=function(t,r){return!!Object.keys(t).filter((function(t){return r===t})).length};function N(t){if(x(t,"error")){var r=t.error,e=r.className,n=r.name,o=e||n,i=r.message||y,a=r.detail||r;if(o&&R[o])throw new R[e](i,a);throw new C(i,a)}return t}function $(t){if(Array.isArray(t))throw new k("",t);var r=t.message||y,e=t.detail||t;switch(!0){case t instanceof b:throw new b(r,e);case t instanceof m:throw new m(r,e);case t instanceof _:throw new _(r,e);case t instanceof w:throw new w(r,e);case t instanceof E:throw new E(r,e);case t instanceof j:throw new j(r,e);case t instanceof S:throw new S(r,e);case t instanceof O:throw new O(r,e);case t instanceof A:throw new A(r,e);case t instanceof k:throw new k(r,e);case t instanceof P:throw new P(r,e);default:throw new T(r,e)}}var q=Array.isArray,M="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},U="object"==typeof M&&M&&M.Object===Object&&M,I="object"==typeof self&&self&&self.Object===Object&&self,z=U||I||Function("return this")(),B=z.Symbol,L=Object.prototype,D=L.hasOwnProperty,Y=L.toString,J=B?B.toStringTag:void 0;var F=Object.prototype.toString;var H="[object Null]",W="[object Undefined]",K=B?B.toStringTag:void 0;function V(t){return null==t?void 0===t?W:H:K&&K in Object(t)?function(t){var r=D.call(t,J),e=t[J];try{t[J]=void 0;var n=!0}catch(t){}var o=Y.call(t);return n&&(r?t[J]=e:delete t[J]),o}(t):function(t){return F.call(t)}(t)}function G(t,r){return function(e){return t(r(e))}}var Q=G(Object.getPrototypeOf,Object);function Z(t){return null!=t&&"object"==typeof t}var X="[object Object]",tt=Function.prototype,rt=Object.prototype,et=tt.toString,nt=rt.hasOwnProperty,ot=et.call(Object);function it(t){if(!Z(t)||V(t)!=X)return!1;var r=Q(t);if(null===r)return!0;var e=nt.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&et.call(e)==ot}var at=function(t){return q(t)?t:[t]},ut=function(t,r){try{var e=Object.keys(t);return n=r,!!e.filter((function(t){return t===n})).length}catch(t){return!1}var n};function ct(t){return!!function(t){return it(t)&&(ut(t,e)||ut(t,n)||ut(t,o))}(t)&&t}function st(t){return t.split("").reduce((function(t,r){return(t=(t<<5)-t+r.charCodeAt(0))&t}),0)}var ft=function(t,r){return void 0===r&&(r={}),ct(r)?Promise.resolve(r):t.getContract()},lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function pt(t){this.message=t}pt.prototype=new Error,pt.prototype.name="InvalidCharacterError";var ht="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var r=String(t).replace(/=+$/,"");if(r.length%4==1)throw new pt("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,o=0,i=0,a="";n=r.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?a+=String.fromCharCode(255&e>>(-2*o&6)):0)n=lt.indexOf(n);return a};var gt=function(t){var r=t.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(ht(t).replace(/(.)/g,(function(t,r){var e=r.charCodeAt(0).toString(16).toUpperCase();return e.length<2&&(e="0"+e),"%"+e})))}(r)}catch(t){return ht(r)}};function vt(t){this.message=t}vt.prototype=new Error,vt.prototype.name="InvalidTokenError";var dt=function(t,r){if("string"!=typeof t)throw new vt("Invalid token specified");var e=!0===(r=r||{}).header?0:1;try{return JSON.parse(gt(t.split(".")[e]))}catch(t){throw new vt("Invalid token specified: "+t.message)}},yt=vt;function bt(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var i=Array(o);++n-1;);return e}(n,o),function(t,r){for(var e=t.length;e--&&kt(r,t[e],0)>-1;);return e}(n,o)+1).join("")}var Yt="[object String]";function Jt(t){return"string"==typeof t||!q(t)&&Z(t)&&V(t)==Yt}var Ft=function(t){return""!==Dt(t)&&Jt(t)},Ht=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r};function Wt(t){if(Ft(t))return function(t){var r=t.iat||Ht(!0);if(t.exp&&r>=t.exp){var e=new Date(t.exp).toISOString();throw new T("Token has expired on "+e,t)}return t}(dt(t));throw new T("Token must be a string!")}var Kt=function(t){return!!q(t)||null!=t&&""!==Dt(t)},Vt="[object Number]";function Gt(t){return function(t){return"number"==typeof t||Z(t)&&V(t)==Vt}(t)&&t!=+t}var Qt=function(t){return!Jt(t)&&!Gt(parseFloat(t))},Zt=function(t){return null!=t&&"boolean"==typeof t},Xt=function(t,r){return void 0===r&&(r=!0),void 0!==t&&""!==t&&""!==Dt(t)&&(!1===r||!0===r&&null!==t)},tr=s,rr=f,er=l,nr=p,or=h,ir=g,ar="continue",ur=function(t){switch(t){case"number":return Qt;case"string":return Ft;case"boolean":return Zt;default:return Xt}},cr=function(t,r){return void 0===r&&(r=""),!!q(t)&&(""===r||""===Dt(r)||!(t.filter((function(t){return!ur(r)(t)})).length>0))},sr=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},fr=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!ur(r)(t)})).length)})).length:r.length>r.filter((function(t){return!cr(e,t)})).length};var lr,pr=function(t,r,e){for(var n=-1,o=Object(t),i=e(t),a=i.length;a--;){var u=i[lr?a:++n];if(!1===r(o[u],u,o))break}return t};var hr="[object Arguments]";function gr(t){return Z(t)&&V(t)==hr}var vr=Object.prototype,dr=vr.hasOwnProperty,yr=vr.propertyIsEnumerable,br=gr(function(){return arguments}())?gr:function(t){return Z(t)&&dr.call(t,"callee")&&!yr.call(t,"callee")};var mr="object"==typeof exports&&exports&&!exports.nodeType&&exports,_r=mr&&"object"==typeof module&&module&&!module.nodeType&&module,wr=_r&&_r.exports===mr?z.Buffer:void 0,Er=(wr?wr.isBuffer:void 0)||function(){return!1},jr=9007199254740991,Sr=/^(?:0|[1-9]\d*)$/;function Or(t,r){var e=typeof t;return!!(r=null==r?jr:r)&&("number"==e||"symbol"!=e&&Sr.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Ar}var Tr={};Tr["[object Float32Array]"]=Tr["[object Float64Array]"]=Tr["[object Int8Array]"]=Tr["[object Int16Array]"]=Tr["[object Int32Array]"]=Tr["[object Uint8Array]"]=Tr["[object Uint8ClampedArray]"]=Tr["[object Uint16Array]"]=Tr["[object Uint32Array]"]=!0,Tr["[object Arguments]"]=Tr["[object Array]"]=Tr["[object ArrayBuffer]"]=Tr["[object Boolean]"]=Tr["[object DataView]"]=Tr["[object Date]"]=Tr["[object Error]"]=Tr["[object Function]"]=Tr["[object Map]"]=Tr["[object Number]"]=Tr["[object Object]"]=Tr["[object RegExp]"]=Tr["[object Set]"]=Tr["[object String]"]=Tr["[object WeakMap]"]=!1;var Pr,Rr="object"==typeof exports&&exports&&!exports.nodeType&&exports,Cr=Rr&&"object"==typeof module&&module&&!module.nodeType&&module,xr=Cr&&Cr.exports===Rr&&U.process,Nr=function(){try{var t=Cr&&Cr.require&&Cr.require("util").types;return t||xr&&xr.binding&&xr.binding("util")}catch(t){}}(),$r=Nr&&Nr.isTypedArray,qr=$r?(Pr=$r,function(t){return Pr(t)}):function(t){return Z(t)&&kr(t.length)&&!!Tr[V(t)]},Mr=Object.prototype.hasOwnProperty;function Ur(t,r){var e=q(t),n=!e&&br(t),o=!e&&!n&&Er(t),i=!e&&!n&&!o&&qr(t),a=e||n||o||i,u=a?function(t,r){for(var e=-1,n=Array(t);++e-1},te.prototype.set=function(t,r){var e=this.__data__,n=Zr(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var re,ee=z["__core-js_shared__"],ne=(re=/[^.]+$/.exec(ee&&ee.keys&&ee.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"";var oe=Function.prototype.toString;function ie(t){if(null!=t){try{return oe.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ae=/^\[object .+?Constructor\]$/,ue=Function.prototype,ce=Object.prototype,se=ue.toString,fe=ce.hasOwnProperty,le=RegExp("^"+se.call(fe).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pe(t){return!(!Dr(t)||function(t){return!!ne&&ne in t}(t))&&(Wr(t)?le:ae).test(ie(t))}function he(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return pe(e)?e:void 0}var ge=he(z,"Map"),ve=he(Object,"create");var de="__lodash_hash_undefined__",ye=Object.prototype.hasOwnProperty;var be=Object.prototype.hasOwnProperty;var me="__lodash_hash_undefined__";function _e(t){var r=-1,e=null==t?0:t.length;for(this.clear();++ru))return!1;var s=i.get(t);if(s&&i.get(r))return s==r;var f=-1,l=!0,p=e&Pe?new Ae:void 0;for(i.set(t,r),i.set(r,t);++fr.type.filter((function(t){var r;return void 0===e||(!1!==(r=sr(t))?!fr({arg:e},r):!ur(t)(e))})).length)})).length}return!1},Gn=function(t,r){var e,n,o,i,a;switch(!0){case"object"===t:return o=(n=r).arg,i=n.param,a=[o],Array.isArray(i.keys)&&i.keys.length&&a.push(i.keys),!Reflect.apply(Vn,null,a);case"array"===t:return!cr(r.arg);case!1!==(e=sr(t)):return!fr(r,e);default:return!ur(t)(r.arg)}},Qn=function(t,r){return void 0!==t?t:!0===r.optional&&void 0!==r.defaultvalue?r.defaultvalue:null},Zn=function(t,r,e){var n;void 0===e&&(e=!1);var o=function(t,r){if(!cr(r))throw new T("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!cr(t))throw new T("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==r.length:return t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:var n=r.length,o=["any"];return t.map((function(t,e){var i=e>=n||!!r[e].optional,a=r[e]||{type:o,name:"_"+e};return{arg:i?Qn(t,a):t,index:e,param:a,optional:i}}));default:throw new T("Could not understand your arguments and parameter structure!",{args:t,params:r})}}(t,r),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var r=t.arg,e=t.param;return!!Kt(r)&&!(e.type.length>e.type.filter((function(r){return Gn(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return Gn(r,t)})).length)}));return e?((n={}).error=i,n.data=o.map((function(t){return t.arg})),n):i},Xn=function(){try{var t=he(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function to(t,r,e){"__proto__"==r&&Xn?Xn(t,r,{configurable:!0,enumerable:!0,value:e,writable:!0}):t[r]=e}function ro(t,r,e){(void 0===e||Qr(t[r],e))&&(void 0!==e||r in t)||to(t,r,e)}var eo="object"==typeof exports&&exports&&!exports.nodeType&&exports,no=eo&&"object"==typeof module&&module&&!module.nodeType&&module,oo=no&&no.exports===eo?z.Buffer:void 0,io=oo?oo.allocUnsafe:void 0;function ao(t,r){var e,n,o=r?(e=t.buffer,n=new e.constructor(e.byteLength),new Ce(n).set(new Ce(e)),n):t.buffer;return new t.constructor(o,t.byteOffset,t.length)}var uo=Object.create,co=function(){function t(){}return function(r){if(!Dr(r))return{};if(uo)return uo(r);t.prototype=r;var e=new t;return t.prototype=void 0,e}}();function so(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var fo=Object.prototype.hasOwnProperty;function lo(t,r,e){var n=t[r];fo.call(t,r)&&Qr(n,e)&&(void 0!==e||r in t)||to(t,r,e)}var po=Object.prototype.hasOwnProperty;function ho(t){if(!Dr(t))return function(t){var r=[];if(null!=t)for(var e in Object(t))r.push(e);return r}(t);var r=zr(t),e=[];for(var n in t)("constructor"!=n||!r&&po.call(t,n))&&e.push(n);return e}function go(t){return Kr(t)?Ur(t,!0):ho(t)}function vo(t){return function(t,r,e,n){var o=!e;e||(e={});for(var i=-1,a=r.length;++i0){if(++r>=Eo)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(wo);function Ao(t,r){return Oo(function(t,r,e){return r=_o(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,i=_o(n.length-r,0),a=Array(i);++o1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=ko.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!Dr(e))return!1;var n=typeof r;return!!("number"==n?Kr(e)&&Or(r,e.length):"string"==n&&r in e)&&Qr(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++e=0;r--){var e=qi().key(r);t(Mi(e),e)}},remove:function(t){return qi().removeItem(t)},clearAll:function(){return qi().clear()}};function qi(){return Ni.localStorage}function Mi(t){return qi().getItem(t)}var Ui=yi.trim,Ii={name:"cookieStorage",read:function(t){if(!t||!Di(t))return null;var r="(?:^|.*;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(zi.cookie.replace(new RegExp(r),"$1"))},write:function(t,r){if(!t)return;zi.cookie=escape(t)+"="+escape(r)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:Bi,remove:Li,clearAll:function(){Bi((function(t,r){Li(r)}))}},zi=yi.Global.document;function Bi(t){for(var r=zi.cookie.split(/; ?/g),e=r.length-1;e>=0;e--)if(Ui(r[e])){var n=r[e].split("="),o=unescape(n[0]);t(unescape(n[1]),o)}}function Li(t){t&&Di(t)&&(zi.cookie=escape(t)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Di(t){return new RegExp("(?:^|;\\s*)"+escape(t).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(zi.cookie)}var Yi=function(){var t={};return{defaults:function(r,e){t=e},get:function(r,e){var n=r();return void 0!==n?n:t[e]}}};var Ji=yi.bind,Fi=yi.each,Hi=yi.create,Wi=yi.slice,Ki=function(){var t=Hi(Vi,{_id:0,_subSignals:{},_subCallbacks:{}});return{watch:function(r,e,n){return t.on(e,Ji(this,n))},unwatch:function(r,e){t.off(e)},once:function(r,e,n){t.once(e,Ji(this,n))},set:function(r,e,n){var o=this.get(e);r(),t.fire(e,n,o)},remove:function(r,e){var n=this.get(e);r(),t.fire(e,void 0,n)},clearAll:function(r){var e={};this.each((function(t,r){e[r]=t})),r(),Fi(e,(function(r,e){t.fire(e,void 0,r)}))}}};var Vi={_id:null,_subCallbacks:null,_subSignals:null,on:function(t,r){return this._subCallbacks[t]||(this._subCallbacks[t]={}),this._id+=1,this._subCallbacks[t][this._id]=r,this._subSignals[this._id]=t,this._id},off:function(t){var r=this._subSignals[t];delete this._subCallbacks[r][t],delete this._subSignals[t]},once:function(t,r){var e=this.on(t,Ji(this,(function(){r.apply(this,arguments),this.off(e)})))},fire:function(t){var r=Wi(arguments,1);Fi(this._subCallbacks[t],(function(t){t.apply(this,r)}))}},Gi=function(t,r){return t(r={exports:{}},r.exports),r.exports}((function(t){var r=function(){var t=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(t,r){if(!n[t]){n[t]={};for(var e=0;e>>8,e[2*n+1]=a%256}return e},decompressFromUint8Array:function(r){if(null==r)return i.decompress(r);for(var e=new Array(r.length/2),n=0,o=e.length;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++),a[s]=p++,f=String(c)}if(""!==f){if(Object.prototype.hasOwnProperty.call(u,f)){if(f.charCodeAt(0)<256){for(n=0;n>=1}else{for(o=1,n=0;n>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[f]}else for(o=a[f],n=0;n>=1;0==--l&&(l=Math.pow(2,h),h++)}for(o=2,n=0;n>=1;for(;;){if(v<<=1,d==r-1){g.push(e(v));break}d++}return g.join("")},decompress:function(t){return null==t?"":""==t?null:i._decompress(t.length,32768,(function(r){return t.charCodeAt(r)}))},_decompress:function(r,e,n){var o,i,a,u,c,s,f,l=[],p=4,h=4,g=3,v="",d=[],y={val:n(0),position:e,index:1};for(o=0;o<3;o+=1)l[o]=o;for(a=0,c=Math.pow(2,2),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;f=t(a);break;case 2:return""}for(l[3]=f,i=f,d.push(f);;){if(y.index>r)return"";for(a=0,c=Math.pow(2,g),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;switch(f=a){case 0:for(a=0,c=Math.pow(2,8),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 1:for(a=0,c=Math.pow(2,16),s=1;s!=c;)u=y.val&y.position,y.position>>=1,0==y.position&&(y.position=e,y.val=n(y.index++)),a|=(u>0?1:0)*s,s<<=1;l[h++]=t(a),f=h-1,p--;break;case 2:return d.join("")}if(0==p&&(p=Math.pow(2,g),g++),l[f])v=l[f];else{if(f!==h)return null;v=i+i.charAt(0)}d.push(v),l[h++]=i+v.charAt(0),i=v,0==--p&&(p=Math.pow(2,g),g++)}}};return i}();null!=t&&(t.exports=r)})),Qi=function(){return{get:function(t,r){var e=t(r);if(!e)return e;var n=Gi.decompress(e);return null==n?e:this._deserialize(n)},set:function(t,r,e){var n=Gi.compress(this._serialize(e));t(r,n)}}};var Zi=[$i,Ii],Xi=[Yi,Ki,Qi],ta=Ri.createStore(Zi,Xi),ra=yi.Global;function ea(){return ra.sessionStorage}function na(t){return ea().getItem(t)}var oa=[{name:"sessionStorage",read:na,write:function(t,r){return ea().setItem(t,r)},each:function(t){for(var r=ea().length-1;r>=0;r--){var e=ea().key(r);t(na(e),e)}},remove:function(t){return ea().removeItem(t)},clearAll:function(){return ea().clear()}},Ii],ia=[Yi,Qi],aa=Ri.createStore(oa,ia),ua=ta,ca=aa,sa=function(t){var r;return(r={}).args=t,r};function fa(t,r){var e;return(e={})[t]=r,e[u]=[li()],e}var la=function(t){return ut(t,"data")&&!ut(t,"error")?t.data:t},pa=function(t){this.opts=t,this.instanceKey=st(this.opts.hostname)+"",this.localStore=ua,this.sessionStore=ca},ha={lset:{configurable:!0},lget:{configurable:!0},sset:{configurable:!0},sget:{configurable:!0}};pa.prototype.__setMethod=function(t,r){var e,n=this[t],o=this.__getMethod(t),i=this.opts.storageKey,a=this.instanceKey;n.set(i,((e={})[a]=o?To({},o,r):r,e))},pa.prototype.__getMethod=function(t){var r=this[t].get(this.opts.storageKey);return!!r&&r[this.instanceKey]},pa.prototype.__delMethod=function(t,r){var e=this.__getMethod(t);if(e){var n={};for(var o in e)o!==r&&(n[o]=e[o]);this.__setMethod(t,n)}},pa.prototype.__clearMethod=function(t){var r=this.opts.storageKey,e=this[t],n=e.get(r);if(n){var o={};for(var i in n)i!==this.instanceKey&&(o[i]=n[i]);e.set(r,o)}},ha.lset.set=function(t){return this.__setMethod("localStore",t)},ha.lget.get=function(){return this.__getMethod("localStore")},pa.prototype.ldel=function(t){return this.__delMethod("localStore",t)},pa.prototype.lclear=function(){return this.__clearMethod("localStore")},ha.sset.set=function(t){return this.__setMethod("sessionStore",t)},ha.sget.get=function(){return this.__getMethod("sessionStore")},pa.prototype.sdel=function(t){return this.__delMethod("sessionStore",t)},pa.prototype.sclear=function(){return this.__clearMethod("sessionStore")},Object.defineProperties(pa.prototype,ha);var ga=c[0],va=c[1],da=function(t){function r(r,e){this.fly=r,t.call(this,e)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={jsonqlEndpoint:{configurable:!0}};return e.jsonqlEndpoint.get=function(){return[this.opts.hostname||"",this.opts.jsonqlPath].join("/")},r.prototype.log=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];!0===this.opts.debugOn&&Reflect.apply(console.info,console,t)},Object.defineProperties(r.prototype,e),r}(function(t){function r(r){t.call(this,r),r.enableAuth&&(this.setDecoder=Wt)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={profileIndex:{configurable:!0},setDecoder:{configurable:!0},saveProfile:{configurable:!0},readProfile:{configurable:!0},jsonqlToken:{configurable:!0},jsonqlUserdata:{configurable:!0}};return r.prototype.decoder=function(t){return t},e.profileIndex.set=function(t){var r;if(ai(t))return this.prof_idx=t,void(this.opts.persistToken&&(this.lset=((r={}).prof_idx=t,r)));throw new k("profileIndex","Expect idx to be number but got "+typeof t)},e.profileIndex.get=function(){var t="prof_idx";if(this.opts.persistToken){var r=this.lget;if(r[t])return r[t]}return this[t]?this[t]:0},r.prototype.rawAuthToken=function(t){return void 0===t&&(t=!1),!1!==t&&(this.profileIndex=t),this.jsonqlToken},e.setDecoder.set=function(t){"function"==typeof t&&(this.decoder=t)},e.saveProfile.set=function(t){this.opts.persistToken?this.lset=t:this.sset=t},e.readProfile.get=function(){return this.opts.persistToken?this.lget:this.sget},e.jsonqlToken.set=function(t){var r,e=this.readProfile,n="jsonqlcredential",o=e&&e[n]?e[n]:[];o.push(t),this.saveProfile=((r={})[n]=o,r),this.jsonqlUserdata=this.decoder(t)},e.jsonqlToken.get=function(){var t=this.readProfile,r="jsonqlcredential";return!(!t||!t[r])&&(this.log("-- jsonqlToken --",t[r],this.profileIndex,t[r][this.profileIndex]),t[r][this.profileIndex])},e.jsonqlUserdata.set=function(t){var r;this.sset=((r={}).userdata=t,r)},e.jsonqlUserdata.get=function(){var t=this.sget;return!!t&&t.userdata},r.prototype.getAuthHeader=function(){var t,r=this.jsonqlToken;return r?((t={})[this.opts.AUTH_HEADER]="Bearer "+r,t):{}},r.prototype.getProfiles=function(t){void 0===t&&(t=!1);var r=this.readProfile,e="jsonqlcredential";return!(!r||!r[e])&&(!1!==t&&ai(t)?r[e][t]||!1:r[e].map(this.decoder.bind(this)))},r.prototype.postLoginAction=function(t){return this.jsonqlToken=t,t},r.prototype.postLogoutAction=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];console.info("postLogoutAction",t)},Object.defineProperties(r.prototype,e),r}(function(t){function r(r){t.call(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={contractHeader:{configurable:!0}};return r.prototype.getContract=function(){var t=this.readContract();return this.log("getContract first call",t),t?Promise.resolve(t):this.getRemoteContract().then(this.storeContract.bind(this))},e.contractHeader.get=function(){var t={};return!1!==this.opts.contractKey&&(t[this.opts.contractKeyName]=this.opts.contractKey),t},r.prototype.storeContract=function(t){var r;if(!ct(t))throw new k("Contract is malformed!");return this.lset=((r={}).contract=t,r),this.log("storeContract return result",t),t},r.prototype.readContract=function(){var t=ct(this.opts.contract);if(!1!==t)return t;var r=this.lget;return!!r&&r.contract},Object.defineProperties(r.prototype,e),r}(function(t){function e(r){t.call(this,r),this.extraHeader={},this.extraParams={},this.reqInterceptor(),this.resInterceptor()}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={headers:{configurable:!0}};return n.headers.set=function(t){this.extraHeader=t},e.prototype.request=function(t,r,e){var n;void 0===r&&(r={}),void 0===e&&(e={}),this.headers=e;var o=To({},{_cb:li()},this.extraParams);if(this.opts.enableJsonp){var i=function(t){return Object.keys(t)[0]}(t);o=To({},o,((n={}).jsonqlJsonpCallback=i,n)),t=t[i]}var a=To({},{method:ga,params:o},r);return this.log("request params",a,this.jsonqlEndpoint),this.fly.request(this.jsonqlEndpoint,t,a)},e.prototype.reqInterceptor=function(){var t=this;this.fly.interceptors.request.use((function(r){var e=t.getHeaders();for(var n in t.log("request interceptor call",e),e)r.headers[n]=e[n];return r}))},e.prototype.processJsonp=function(t){return la(t)},e.prototype.resInterceptor=function(){var t=this,r=this,e=r.opts.enableJsonp;this.fly.interceptors.response.use((function(n){t.log("response interceptor call",n),r.cleanUp();var o=ii(n.data)?JSON.parse(n.data):n.data;return e?r.processJsonp(o):la(o)}),(function(t){throw r.cleanUp(),console.error(t),new P("Server side error",t)}))},e.prototype.getHeaders=function(){return this.opts.enableAuth?To({},r,this.getAuthHeader(),this.extraHeader):To({},r,this.extraHeader)},e.prototype.cleanUp=function(){this.extraHeader={},this.extraParams={}},e.prototype.getRemoteContract=function(){var t=this;return this.opts.showContractDesc&&(this.extraParams=To({},this.extraParams,d)),this.request({},{method:"GET"},this.contractHeader).then(N).then((function(r){return t.log("get contract result",r),r.cache&&r.contract?r.contract:r})).catch((function(t){throw console.error("getRemoteContract err",t),new P("getRemoteContract",t)}))},e.prototype.query=function(t,r){return void 0===r&&(r=[]),this.request(function(t,r,e){if(void 0===r&&(r=[]),void 0===e&&(e=!1),Jt(t)&&q(r)){var n=sa(r);return!0===e?n:fa(t,n)}throw new k("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}(t,r)).then(N)},e.prototype.mutation=function(t,r,e){return void 0===r&&(r={}),void 0===e&&(e={}),this.request(function(t,r,e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o={};if(o[i]=r,o[a]=e,!0===n)return o;if(Jt(t))return fa(t,o);throw new k("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:e})}(t,r,e),{method:va}).then(N)},Object.defineProperties(e.prototype,n),e}(pa)))),ya=new WeakMap,ba=new WeakMap,ma=function(){this.__suspend__=null,this.queueStore=new Set},_a={$suspend:{configurable:!0},$queues:{configurable:!0}};_a.$suspend.set=function(t){var r=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var e=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+e+" --\x3e "+t),!0===e&&!1===t&&setTimeout((function(){r.release()}),1)},ma.prototype.$queue=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},_a.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},ma.prototype.release=function(){var t=this,r=this.queueStore.size;if(this.logger("(release)","Release was called "+r),r>0){var e=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",e),e.forEach((function(r){t.logger(r),Reflect.apply(t.$trigger,t,r)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(ma.prototype,_a);var wa=function(t){function r(r){void 0===r&&(r={}),t.call(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={$done:{configurable:!0}};return r.prototype.logger=function(){},r.prototype.$on=function(t,r,e){var n=this;void 0===e&&(e=null);this.validate(t,r);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",r,e);this.logger("($on)",t+" found in lazy store");var i=0;return o.forEach((function(o){var a=o[0],u=o[1],c=o[2];if(c&&"on"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);n.logger("($on)","call run on "+t),n.run(r,a,e||u),i+=n.addToNormalStore(t,"on",r,e||u)})),i},r.prototype.$once=function(t,r,e){void 0===e&&(e=null),this.validate(t,r);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",r,e);this.logger("($once)",n);var o=Array.from(n)[0],i=o[0],a=o[1],u=o[2];if(u&&"once"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);this.logger("($once)","call run for "+t),this.run(r,i,e||a),this.$off(t)},r.prototype.$only=function(t,r,e){var n=this;void 0===e&&(e=null),this.validate(t,r);var o=!1,i=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",r,e)),!1!==i)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(i).forEach((function(o){var i=o[0],a=o[1],u=o[2];if(u&&"only"!==u)throw new Error("You are trying to register an event already been taken by other type: "+u);n.logger("($only)","call run for "+t),n.run(r,i,e||a)})));return o},r.prototype.$onlyOnce=function(t,r,e){void 0===e&&(e=null),this.validate(t,r);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",r,e)),!1!==o){this.logger("($onlyOnce)",o);var i=Array.from(o)[0],a=i[0],u=i[1],c=i[2];if(c&&"onlyOnce"!==c)throw new Error("You are trying to register an event already been taken by other type: "+c);this.logger("($onlyOnce)","call run for "+t),this.run(r,a,e||u),this.$off(t)}return n},r.prototype.$replace=function(t,r,e,n){if(void 0===e&&(e=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,r),Reflect.apply(o,this,[t,r,e])}throw new Error(n+" is not supported!")},r.prototype.$trigger=function(t,r,e,n){void 0===r&&(r=[]),void 0===e&&(e=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,i=this.normalStore;if(this.logger("($trigger)","normalStore",i),i.has(t)){var a=this.$queue(t,r,e,n);if(this.logger("($trigger)",t,"found; add to queue: ",a),!0===a)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(i.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(r)?(this.logger("(addToStore)",r+" existed"),e=t.get(r)):(this.logger("(addToStore)","create new Set for "+r),e=new Set),n.length>2)if(Array.isArray(n[0])){var i=n[2];this.checkTypeInLazyStore(r,i)||e.add(n)}else this.checkContentExist(n,e)||(this.logger("(addToStore)","insert new",n),e.add(n));else e.add(n);return t.set(r,e),[t,e.size]},r.prototype.checkContentExist=function(t,r){return!!Array.from(r).filter((function(r){return r[0]===t[0]})).length},r.prototype.checkTypeInStore=function(t,r){this.validateEvt(t,r);var e=this.$get(t,!0);return!1===e||!e.filter((function(t){var e=t[3];return r!==e})).length},r.prototype.checkTypeInLazyStore=function(t,r){this.validateEvt(t,r);var e=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",e),!!e&&!!Array.from(e).filter((function(t){return t[2]!==r})).length},r.prototype.addToNormalStore=function(t,r,e,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,r,"try to add to normal store"),this.checkTypeInStore(t,r)){this.logger("(addToNormalStore)",r+" can add to "+t+" normal store");var o=this.hashFnToKey(e),i=[this.normalStore,t,o,e,n,r],a=Reflect.apply(this.addToStore,this,i),u=a[0],c=a[1];return this.normalStore=u,c}return!1},r.prototype.addToLazyStore=function(t,r,e,n){void 0===r&&(r=[]),void 0===e&&(e=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(r),e];n&&o.push(n);var i=Reflect.apply(this.addToStore,this,o),a=i[0],u=i[1];return this.lazyStore=a,u},r.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},e.normalStore.set=function(t){ya.set(this,t)},e.normalStore.get=function(){return ya.get(this)},e.lazyStore.set=function(t){ba.set(this,t)},e.lazyStore.get=function(){return ba.get(this)},r.prototype.hashFnToKey=function(t){return st(t.toString())+""},Object.defineProperties(r.prototype,e),r}(ma));var Ea=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,at(t))}),Reflect.apply(t,null,e))}};function ja(t,r){var e=Object.getOwnPropertyDescriptor(t,r);return void 0!==e&&e.value?e.value:e}function Sa(t,r,e,n){void 0===n&&(n=!1);var o=ja(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)}var Oa=function(t,r,e,n){return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var i=n.auth[r].params,a=i.map((function(t,r){return e[r]})),u=e[i.length]||{};return ui(e,i).then((function(){return t.query.apply(t,[r,a,u])})).catch($)}},Aa=function(t,r,e,n,o){var i={},a=function(t){i=Sa(i,t,(function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var i=o.query[t].params,a=i.map((function(t,r){return e[r]})),u={};return ui(a,i).then((function(){return r.query.apply(r,[t,a,u])})).catch($)}))};for(var u in o.query)a(u);return t.query=i,t.helloWorld=i.helloWorld,[t,r,e,n,o]},ka=function(t,r,e,n,o){var i={},a=function(t){i=Sa(i,t,(function(e,n,i){void 0===i&&(i={});var a=[e,n],u=o.mutation[t].params;return ui(a,u).then((function(){return r.mutation.apply(r,[t,e,n,i])})).catch($)}))};for(var u in o.mutation)a(u);return t.mutation=i,[t,r,e,n,o]},Ta=function(t,r,e,n,o){if(n.enableAuth&&o.auth){var i={},a=n.loginHandlerName,u=n.logoutHandlerName;o.auth[a]&&(i[a]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Oa(r,a,0,o);return i.apply(null,t).then(r.postLoginAction.bind(r)).then((function(t){return e.$trigger("login",t),t}))}),o.auth[u]?i[u]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];var i=Oa(r,u,0,o);return i.apply(null,t).then(r.postLogoutAction.bind(r)).then((function(t){return e.$trigger("logout",t),t}))}:i[u]=function(){r.postLogoutAction("continue"),e.$trigger("logout","continue")},t.auth=i}return t};var Pa=function(t,r,e,n){var o=function(t,r,e,n){return Ea(Aa,ka,Ta)({},t,r,e,n)}(t,n,r,e);return r.enableAuth&&(o.userdata=function(){return t.jsonqlUserdata},o.getToken=function(r){return void 0===r&&(r=!1),t.rawAuthToken(r)},o.profileIndex=function(r){if(void 0===r&&(r=!1),!1===r)return t.profileIndex;t.profileIndex=r},o.getProfiles=function(r){return void 0===r&&(r=!1),t.getProfiles(r)}),r.exposeContract&&(o.getContract=function(){return t.getContract()}),r.exposeStore&&(o.tmpSave=function(t){},o.tmpGet=function(t){},o.tmpDel=function(t){},o.persistSave=function(t){},o.persistGet=function(t){},o.persistDel=function(t){}),o.eventEmitter=n,o.version="0.1.0",o.log=function(){for(var r=[],e=arguments.length;e--;)r[e]=arguments[e];return Reflect.apply(t.log,t,["[DEV DEBUG]"].concat(r))},o},Ra={contract:!1,MUTATION_ARGS:["name","payload","conditions"],CONTENT_TYPE:t,BEARER:"Bearer",AUTH_HEADER:"Authorization"},Ca={hostname:ci(function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){return null}}(),["string"]),jsonqlPath:ci("jsonql",["string"]),loginHandlerName:ci("login",["string"]),logoutHandlerName:ci("logout",["string"]),enableJsonp:ci(!1,["boolean"]),enableAuth:ci(!1,["boolean"]),useJwt:ci(!0,["boolean"]),persistToken:ci(!1,["boolean","number"]),useLocalstorage:ci(!0,["boolean"]),storageKey:ci("jsonqlstore",["string"]),authKey:ci("jsonqlauthkey",["string"]),contractExpired:ci(0,["number"]),keepContract:ci(!0,["boolean"]),exposeContract:ci(!1,["boolean"]),exposeStore:ci(!1,["boolean"]),showContractDesc:ci(!1,["boolean"]),contractKey:ci(!1,["boolean"]),contractKeyName:ci("X-JSONQL-CV-KEY",["string"]),enableTimeout:ci(!1,["boolean"]),timeout:ci(5e3,["number"]),returnInstance:ci(!1,["boolean"]),allowReturnRawToken:ci(!1,["boolean"]),debugOn:ci(!1,["boolean"])};function xa(t){return ja(t,v)?Promise.resolve(t):function(t){var r=t.contract;return si(t,Ca,Ra).then((function(t){return t.contract=r,t}))}(t)}function Na(t,r){void 0===r&&(r={});var e=r.socketClient,n=function(t){return new wa({logger:t?function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];t.unshift("[NBS]"),console.log.apply(null,t)}:void 0})}(r.debugOn);return xa(r).then((function(r){return{opts:r,baseClient:new da(t,r)}})).then((function(t){var r=t.opts,e=t.baseClient;return ft(e,r.contract).then((function(t){return{opts:r,contract:t,client:Pa(e,r,t,n)}}))})).then((function(t){var r=t.opts,n=t.contract;return function(t,r,e,n){if(ut(r,o)){if(n)return e.contract=r,e.eventEmitter=t.eventEmitter,n(e).then((function(r){return t[o]=r,t}));throw new T("initSocketClient","socketClient is missing!")}return t}(t.client,n,r,e)}))}function $a(t,r){return void 0===t&&(t={}),void 0===r&&(r={}),function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(Ea,null,e.concat((function(t){return Sa(t,v,li())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}}(To({},Ca,t),To({},Ra,r),fi)}var qa=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,e),r}(Error),Ma=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,e),r}(Error),Ua=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,e),r}(Error),Ia=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,e),r}(Error),za=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,e),r}(Error),Ba=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,e),r}(Error),La=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,e),r}(Error),Da=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,e),r}(Error),Ya=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,e),r}(Error),Ja=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,e),r}(Error),Fa="data",Ha="error",Wa="jsonql",Ka="query",Va="mutation",Ga="socket",Qa="TS",Za="type",Xa="optional",tu="enumv",ru="args",eu="checker",nu="alias",ou="__checked__",iu="No message",au="__login__",uu="__logout__",cu="emit",su="acknowledge",fu="error",lu="nspSet",pu="publicNamespace",hu="onMessage",gu="onResult",vu="onError",du="onReady",yu="onLogin",bu="message",mu="result",_u="error",wu="ready",Eu="login",ju="token",Su=function(t){function r(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=r.name,t.captureStackTrace&&t.captureStackTrace(this,r)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(r,e),r}(Error),Ou=function(t){function r(e,n){t.call(this,n),this.statusCode=e,this.className=r.name}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,e),r}(Error);function Au(t){if(Array.isArray(t))throw new Ja("",t);var r=t.message||iu,e=t.detail||t;switch(!0){case t instanceof qa:throw new qa(r,e);case t instanceof Ma:throw new Ma(r,e);case t instanceof Ua:throw new Ua(r,e);case t instanceof Ia:throw new Ia(r,e);case t instanceof za:throw new za(r,e);case t instanceof Ba:throw new Ba(r,e);case t instanceof La:throw new La(r,e);case t instanceof Da:throw new Da(r,e);case t instanceof Ya:throw new Ya(r,e);case t instanceof Ja:throw new Ja(r,e);case t instanceof Ou:throw new Ou(r,e);default:throw new Su(r,e)}}var ku="socket.io",Tu=cu,Pu="UKNNOWN RESULT!",Ru="on",Cu=function(t){return q(t)?t:[t]},xu=function(t,r){try{var e=Object.keys(t);return n=r,!!e.filter((function(t){return t===n})).length}catch(t){return!1}var n},Nu=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},$u=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r},qu=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type!")},Mu=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,Cu(t))}),Reflect.apply(t,null,e))}};function Uu(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}}function Iu(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t}function zu(t,r){var e=Object.getOwnPropertyDescriptor(t,r);return void 0!==e&&e.value?e.value:e}function Bu(t,r,e,n){void 0===n&&(n=!1);var o=zu(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)}function Lu(t){return!!xu(t,"socket")&&t.socket}var Du=function(t){var r;return(r={}).args=t,r};function Yu(t,r,e){if(void 0===r&&(r=[]),void 0===e&&(e=!1),Jt(t)&&q(r)){var n=Du(r);return!0===e?n:function(t,r){var e;return(e={})[t]=r,e[Qa]=[$u()],e}(t,n)}throw new Ja("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}function Ju(t){return void 0===t}var Fu="[object Boolean]";function Hu(t){return!!q(t)||null!=t&&""!==Dt(t)}var Wu=function(t){return!Jt(t)&&!Gt(parseFloat(t))},Ku=function(t){return""!==Dt(t)&&Jt(t)},Vu=function(t){return function(t){return!0===t||!1===t||Z(t)&&V(t)==Fu}(t)},Gu=function(t,r){return void 0===r&&(r=!0),!Ju(t)&&""!==t&&""!==Dt(t)&&(!1===r||!0===r&&!function(t){return null===t}(t))},Qu=Za,Zu=Xa,Xu=tu,tc=ru,rc=eu,ec=nu,nc="continue",oc=function(t){switch(t){case"number":return Wu;case"string":return Ku;case"boolean":return Vu;default:return Gu}},ic=function(t,r){return void 0===r&&(r=""),!!q(t)&&(""===r||""===Dt(r)||!(t.filter((function(t){return!oc(r)(t)})).length>0))},ac=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var r=t.replace("array.<","").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1},uc=function(t,r){var e=t.arg;return r.length>1?!e.filter((function(t){return!(r.length>r.filter((function(r){return!oc(r)(t)})).length)})).length:r.length>r.filter((function(t){return!ic(e,t)})).length},cc=function(t,r){if(void 0===r&&(r=null),it(t)){if(!r)return!0;if(ic(r))return!r.filter((function(r){var e=t[r.name];return!(r.type.length>r.type.filter((function(t){var r;return!!Ju(e)||(!1!==(r=ac(t))?!uc({arg:e},r):!oc(t)(e))})).length)})).length}return!1},sc=function(t){var r=t.arg,e=t.param,n=[r];return Array.isArray(e.keys)&&e.keys.length&&n.push(e.keys),cc.apply(null,n)};function fc(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.console&&Reflect.apply(console.log,console,t)}catch(t){}}var lc=function(t,r){var e;switch(!0){case"object"===t:return!sc(r);case"array"===t:return!ic(r.arg);case!1!==(e=ac(t)):return!uc(r,e);default:return!oc(t)(r.arg)}},pc=function(t,r){return Ju(t)?!0!==r.optional||Ju(r.defaultvalue)?null:r.defaultvalue:t},hc=function(t,r,e){var n;void 0===e&&(e=!1);var o=function(t,r){if(!ic(r))throw new Su("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===r.length)return[];if(!ic(t))throw new Su("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==r.length:return fc(1),t.map((function(t,e){return{arg:t,index:e,param:r[e]}}));case!0===r[0].variable:fc(2);var e=r[0].type;return t.map((function(t,n){return{arg:t,index:n,param:r[n]||{type:e,name:"_"}}}));case t.lengthr.length:fc(4);var n=r.length,o=["any"];return t.map((function(t,e){var i=e>=n||!!r[e].optional,a=r[e]||{type:o,name:"_"+e};return{arg:i?pc(t,a):t,index:e,param:a,optional:i}}));default:throw fc(5),new Su("Could not understand your arguments and parameter structure!",{args:t,params:r})}}(t,r),i=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var r=t.arg,e=t.param;return!!Hu(r)&&!(e.type.length>e.type.filter((function(r){return lc(r,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(r){return lc(r,t)})).length)}));return e?((n={})[Ha]=i,n[Fa]=o.map((function(t){return t.arg})),n):i},gc=function(t,r){var e,n=Object.keys(t);return e=r,!!n.filter((function(t){return t===e})).length},vc=function(t){return!Hu(t)};function dc(t,r){var e=function(t,r){var e=qo(r,(function(t,r){return!t[ec]}));return Mo(e,{})?t:Ro(t,(function(t,r){return Uo(e,(function(t){return t.alias===r}))||r}))}(t,r);return{pristineValues:Po(qo(r,(function(t,r){return gc(e,r)})),(function(t){return t.args})),checkAgainstAppProps:qo(r,(function(t,r){return!gc(e,r)})),config:e}}function yc(t,r){return Po(r,(function(r,e){var n,o;return Ju(t[e])||!0===r[Zu]&&vc(t[e])?To({},r,((n={})[nc]=!0,n)):((o={})[tc]=t[e],o[Qu]=r[Qu],o[Zu]=r[Zu]||!1,o[Xu]=r[Xu]||!1,o[rc]=r[rc]||!1,o)}))}var bc=function(t){return ic(t)?t:[t]};var mc=function(t,r){return!ic(r)||function(t,r){return!!t.filter((function(t){return t===r})).length}(r,t)},_c=function(t,r){try{return!!Wr(r)&&r.apply(null,[t])}catch(t){return!1}};function wc(t){return function(r,e){if(r[nc])return r[tc];var n=function(t,r){var e,n=[[t[tc]],[(e={},e[Qu]=bc(t[Qu]),e[Zu]=t[Zu],e)]];return Reflect.apply(r,null,n)}(r,t);if(n.length)throw fc("runValidationAction",e,r),new Da(e,n);if(!1!==r[Xu]&&!mc(r[tc],r[Xu]))throw fc(Xu,r[Xu]),new La(e);if(!1!==r[rc]&&!_c(r[tc],r[rc]))throw fc(rc,r[rc]),new Ya(e);return r[tc]}}var Ec=function(t,r){return Promise.resolve(function(t,r){var e=dc(t,r),n=e.config,o=e.pristineValues;return[yc(n,e.checkAgainstAppProps),o]}(t,r))};function jc(t,r,e,n){return void 0===t&&(t={}),Ec(t,r).then((function(t){return function(t,r){var e=t[0],n=t[1],o=Po(e,wc(r));return To(o,n)}(t,n)})).then((function(t){return To({},t,e)}))}function Sc(t,r,e,n,o,i){void 0===e&&(e=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===i&&(i=!1);var a={};return a[ru]=t,a[Za]=r,!0===e&&(a[Xa]=!0),ic(n)&&(a[tu]=n),Wr(o)&&(a[eu]=o),Jt(i)&&(a[nu]=i),a}var Oc=Ku,Ac=function(t,r,e){return void 0===e&&(e=!1),new Promise((function(n,o){var i=hc(t,r,e);return e?i[Ha].length?o(i[Ha]):n(i[Fa]):i.length?o(i):n([])}))},kc=function(t,r,e){void 0===e&&(e={});var n=e[Xa],o=e[tu],i=e[eu],a=e[nu];return Sc.apply(null,[t,r,n,o,i,a])},Tc=function(t){return function(r,e,n){return void 0===n&&(n={}),jc(r,e,n,t)}}(hc),Pc="jsonql-ws-client",Rc=function(t){try{if(window.debug)return window.debug(Pc).extend(t)}catch(t){}try{if(M.debug)return M.debug(Pc).extend(t)}catch(t){}return function(){for(var r=[],e=arguments.length;e--;)r[e]=arguments[e];console.info.apply(null,[Pc,t].concat(r))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",Pc+"*")}catch(t){}var Cc=function(t){function r(){t.call(this,{logger:Rc("nb-event-service")})}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var e={name:{configurable:!0}};return e.name.get=function(){return"jsonql-ws-client"},Object.defineProperties(r.prototype,e),r}(wa),xc=(Rc("process-contract"),function(t){var r=Lu(t);if(!1!==r)return r;throw new Ba("Missing property in contract!")});function Nc(t){var r,e,n=t.contract;return t.enableAuth?function(t,r){void 0===r&&(r=!1);var e=Lu(t);if(!1===e){if(r)return t;throw new Su("socket not found in contract!")}var n,o={},i=0;for(var a in e){var u=e[a],c=u.namespace;c&&(o[c]||(++i,o[c]={}),o[c][a]=u,n||u.public&&(n=c))}return{size:i,nspSet:o,publicNamespace:n}}(n):((e={})[lu]=((r={})[Wa]=xc(n),r),e[pu]=Wa,e)}var $c=function(t,r){return"ws"===r?t.replace("http://","ws://"):t},qc=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}},Mc=function(t,r){Cu(r).forEach((function(r){t.$off(Nu(r,cu))}))},Uc=Rc("respondHandler");function Ic(t,r,e){xu(t,Ha)?(Uc("-- rejecter called --",t[Ha]),e(t[Ha])):xu(t,Fa)?(Uc("-- resolver called --",t[Fa]),r(t[Fa])):(Uc("-- UNKNOWN_RESULT --",t),e({message:Pu,error:t}))}var zc=Rc("action-call");function Bc(t,r,e,n,o){void 0===o&&(o=[]);var i=Nu(r,cu),a=n?mu:gu;return zc("actionCall: "+i+" --\x3e "+e,o),t.$trigger(i,[e,Cu(o)]),new Promise((function(n,o){t.$on(Nu(r,e,a),(function(t){zc("got the first result",t),Ic(t,n,o)}))}))}var Lc=Rc("setup-send"),Dc=function(t,r,e,n,o,i){return Iu(t,"send",(function(t){var a=i?_u:vu;Lc("got payload for",t),Ac(Cu(t),o.params,!0).then((function(o){if(!o[Ha]||!o[Ha].length)return Bc(r,e,n,i,t);Lc("got ERROR_KEY",o[Ha]),r.$call(Nu(e,n,a),[new Ja(n,o[Ha])])})).catch((function(t){Lc("error after validateAsync",t),r.$call(Nu(e,n,a),[new Ja(n,t)])}))}),(function(){return function(){for(var t=[],a=arguments.length;a--;)t[a]=arguments[a];return Ac(t,o.params,!0).then((function(t){return Bc(r,e,n,i,t)})).catch(Au)}}))};Rc("setup-resolver");function Yc(t,r,e,n,o){return[Bu(t,Ru,(function(t,o){if(Oc(t)&&qu(o))switch(t){case mu:r.$on(Nu(e,n,ON_RESULT_PROP_NAME),(function(t){Ic(t,o,(function(t){r.$trigger(Nu(e,n,ON_ERROR_PROP_NAME),t)}))}));break;case bu:r.$only(Nu(e,n,ON_MESSAGE_PROP_NAME),(function(t){Ic(t,o,(function(t){r.$trigger(Nu(e,n,ON_ERROR_PROP_NAME),t)}))}));break;case READY_PROP_NAME:r.$only(Nu(e,n,ON_ERROR_PROP_NAME),o);break;default:r.$trigger(Nu(e,n,ON_ERROR_PROP_NAME),new Su(n,"Unknown event name "+t+"!"))}})),r,e,n,o]}Rc("setup-resolver");var Jc=function(t,r,e,n,o,i){return[Bu(t,"myNamespace",e),r,e,n,o,i]},Fc=function(t,r,e,n,o,i){return[Iu(t,gu,(function(t){qu(t)&&r.$on(Nu(e,n,gu),(function(o){Ic(o,t,(function(t){r.$trigger(Nu(e,n,vu),t)}))}))})),r,e,n,o,i]},Hc=function(t,r,e,n,o,i){return[Iu(t,hu,(function(t){if(qu(t)){r.$only(Nu(e,n,hu),(function(o){Ic(o,t,(function(t){r.$trigger(Nu(e,n,vu),t)}))}))}})),r,e,n,o,i]},Wc=function(t,r,e,n,o,i){return[Iu(t,vu,(function(t){qu(t)&&r.$only(Nu(e,n,vu),t)})),r,e,n,o,i]};function Kc(t,r,e,n,o,i){var a=[Jc];i?a.push(Yc):a.push(Fc,Hc,Wc),a.push(Dc);var u=Reflect.apply(Mu,null,a);return Reflect.apply(u,null,[n,o,t,r,e,i])}Rc("resolver-methods");function Vc(t,r,e,n,o){return function(){for(var i=[],a=arguments.length;a--;)i[a]=arguments[a];return Ac(i,n.params,!0).then((function(n){return Bc(t,r,e,o,n)})).catch(Au)}}var Gc=function(t,r,e){return[Bu(t,e.loginHandlerName,(function(t){if(t&&Oc(t))return r.$trigger(au,[t]);throw new Ja(e.loginHandlerName,"Unexpected token "+t)})),r,e]},Qc=function(t,r,e){return Bu(t,e.logoutHandlerName,(function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.$trigger(uu,t)}))};Rc("generator");function Zc(t,r,e){var n={},o=r.nspSet,i=t.useCallbackStyle;for(var a in o){var u=o[a];for(var c in u){var s=u[c];n=Bu(n,c,Kc(a,c,s,Vc(e,a,c,s,i),e,i))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function Xc(t,r,e){var n=r.nspSet,o=[Zc];return t.useCallbackStyle?o.push((function(t){return function(t,r,e,n){return Bu(t,Ru,(function(t,n){if(Oc(t)&&qu(n))switch(t){case _u:for(var o in e)r.$on(Nu(o,_u),n);break;case Eu:r.$only(Eu,n);break;case wu:r.$on(wu,n);break;default:r.$trigger(_u,new Su(Ru,"Unknown event name "+t+"!"))}}))}(t,e,n)})):o.push((function(t){return function(t,r,e){return Iu(t,vu,(function(t){if(qu(t))for(var n in e)r.$on(Nu(n,vu),t)}))}(t,e,n)}),(function(t){return function(t,r,e){return Iu(t,du,(function(t){qu(t)&&r.$on(du,t)}))}(t,e)}),(function(r){return function(t,r,e){return e.enableAuth?Iu(t,yu,(function(t){qu(t)&&r.$only(yu,t)})):t}(r,e,t)})),o.push((function(r){return function(t,r,e){return e.enableAuth?Mu(Gc,Qc)(t,r,e):t}(r,e,t)})),Reflect.apply(Uu,null,o)(t,r,e)}var ts=[],rs=[],es="undefined"!=typeof Uint8Array?Uint8Array:Array,ns=!1;function os(){ns=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,e=t.length;r>18&63]+ts[o>>12&63]+ts[o>>6&63]+ts[63&o]);return i.join("")}function as(t){var r;ns||os();for(var e=t.length,n=e%3,o="",i=[],a=0,u=e-n;au?u:a+16383));return 1===n?(r=t[e-1],o+=ts[r>>2],o+=ts[r<<4&63],o+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],o+=ts[r>>10],o+=ts[r>>4&63],o+=ts[r<<2&63],o+="="),i.push(o),i.join("")}function us(t,r,e,n,o){var i,a,u=8*o-n-1,c=(1<>1,f=-7,l=e?o-1:0,p=e?-1:1,h=t[r+l];for(l+=p,i=h&(1<<-f)-1,h>>=-f,f+=u;f>0;i=256*i+t[r+l],l+=p,f-=8);for(a=i&(1<<-f)-1,i>>=-f,f+=n;f>0;a=256*a+t[r+l],l+=p,f-=8);if(0===i)i=1-s;else{if(i===c)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,n),i-=s}return(h?-1:1)*a*Math.pow(2,i-n)}function cs(t,r,e,n,o,i){var a,u,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=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,a=f):(a=Math.floor(Math.log(r)/Math.LN2),r*(c=Math.pow(2,-a))<1&&(a--,c*=2),(r+=a+l>=1?p/c:p*Math.pow(2,1-l))*c>=2&&(a++,c/=2),a+l>=f?(u=0,a=f):a+l>=1?(u=(r*c-1)*Math.pow(2,o),a+=l):(u=r*Math.pow(2,l-1)*Math.pow(2,o),a=0));o>=8;t[e+h]=255&u,h+=g,u/=256,o-=8);for(a=a<0;t[e+h]=255&a,h+=g,a/=256,s-=8);t[e+h-g]|=128*v}var ss={}.toString,fs=Array.isArray||function(t){return"[object Array]"==ss.call(t)};function ls(){return hs.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ps(t,r){if(ls()=ls())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ls().toString(16)+" bytes");return 0|t}function ms(t){return!(null==t||!t._isBuffer)}function _s(t,r){if(ms(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 e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return Vs(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return Gs(t).length;default:if(n)return Vs(t).length;r=(""+r).toLowerCase(),n=!0}}function ws(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return Ms(this,r,e);case"utf8":case"utf-8":return xs(this,r,e);case"ascii":return $s(this,r,e);case"latin1":case"binary":return qs(this,r,e);case"base64":return Cs(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Us(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function Es(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function js(t,r,e,n,o){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(o)return-1;e=t.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof r&&(r=hs.from(r,n)),ms(r))return 0===r.length?-1:Ss(t,r,e,n,o);if("number"==typeof r)return r&=255,hs.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):Ss(t,[r],e,n,o);throw new TypeError("val must be string, number or Buffer")}function Ss(t,r,e,n,o){var i,a=1,u=t.length,c=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;a=2,u/=2,c/=2,e/=2}function s(t,r){return 1===a?t[r]:t.readUInt16BE(r*a)}if(o){var f=-1;for(i=e;iu&&(e=u-c),i=e;i>=0;i--){for(var l=!0,p=0;po&&(n=o):n=o;var i=r.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var a=0;a>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function Cs(t,r,e){return 0===r&&e===t.length?as(t):as(t.slice(r,e))}function xs(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o239?4:s>223?3:s>191?2:1;if(o+l<=e)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],a=t[o+2],128==(192&i)&&128==(192&a)&&(c=(15&s)<<12|(63&i)<<6|63&a)>2047&&(c<55296||c>57343)&&(f=c);break;case 4:i=t[o+1],a=t[o+2],u=t[o+3],128==(192&i)&&128==(192&a)&&128==(192&u)&&(c=(15&s)<<18|(63&i)<<12|(63&a)<<6|63&u)>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 r=t.length;if(r<=Ns)return String.fromCharCode.apply(String,t);var e="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},hs.prototype.compare=function(t,r,e,n,o){if(!ms(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||e>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=e)return 0;if(n>=o)return-1;if(r>=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),a=(e>>>=0)-(r>>>=0),u=Math.min(i,a),c=this.slice(n,o),s=t.slice(r,e),f=0;fo)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return Os(this,t,r,e);case"utf8":case"utf-8":return As(this,t,r,e);case"ascii":return ks(this,t,r,e);case"latin1":case"binary":return Ts(this,t,r,e);case"base64":return Ps(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Rs(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},hs.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ns=4096;function $s(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;on)&&(e=n);for(var o="",i=r;ie)throw new RangeError("Trying to access beyond buffer length")}function zs(t,r,e,n,o,i){if(!ms(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||rt.length)throw new RangeError("Index out of range")}function Bs(t,r,e,n){r<0&&(r=65535+r+1);for(var o=0,i=Math.min(t.length-e,2);o>>8*(n?o:1-o)}function Ls(t,r,e,n){r<0&&(r=4294967295+r+1);for(var o=0,i=Math.min(t.length-e,4);o>>8*(n?o:3-o)&255}function Ds(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function Ys(t,r,e,n,o){return o||Ds(t,0,e,4),cs(t,r,e,n,23,4),e+4}function Js(t,r,e,n,o){return o||Ds(t,0,e,8),cs(t,r,e,n,52,8),e+8}hs.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r0&&(o*=256);)n+=this[t+--r]*o;return n},hs.prototype.readUInt8=function(t,r){return r||Is(t,1,this.length),this[t]},hs.prototype.readUInt16LE=function(t,r){return r||Is(t,2,this.length),this[t]|this[t+1]<<8},hs.prototype.readUInt16BE=function(t,r){return r||Is(t,2,this.length),this[t]<<8|this[t+1]},hs.prototype.readUInt32LE=function(t,r){return r||Is(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},hs.prototype.readUInt32BE=function(t,r){return r||Is(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},hs.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||Is(t,r,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*r)),n},hs.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||Is(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},hs.prototype.readInt8=function(t,r){return r||Is(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},hs.prototype.readInt16LE=function(t,r){r||Is(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},hs.prototype.readInt16BE=function(t,r){r||Is(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},hs.prototype.readInt32LE=function(t,r){return r||Is(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},hs.prototype.readInt32BE=function(t,r){return r||Is(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},hs.prototype.readFloatLE=function(t,r){return r||Is(t,4,this.length),us(this,t,!0,23,4)},hs.prototype.readFloatBE=function(t,r){return r||Is(t,4,this.length),us(this,t,!1,23,4)},hs.prototype.readDoubleLE=function(t,r){return r||Is(t,8,this.length),us(this,t,!0,52,8)},hs.prototype.readDoubleBE=function(t,r){return r||Is(t,8,this.length),us(this,t,!1,52,8)},hs.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||zs(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i=0&&(i*=256);)this[r+o]=t/i&255;return r+e},hs.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,1,255,0),hs.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},hs.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,2,65535,0),hs.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):Bs(this,t,r,!0),r+2},hs.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,2,65535,0),hs.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):Bs(this,t,r,!1),r+2},hs.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,4,4294967295,0),hs.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):Ls(this,t,r,!0),r+4},hs.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,4,4294967295,0),hs.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Ls(this,t,r,!1),r+4},hs.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);zs(this,t,r,e,o-1,-o)}var i=0,a=1,u=0;for(this[r]=255&t;++i>0)-u&255;return r+e},hs.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var o=Math.pow(2,8*e-1);zs(this,t,r,e,o-1,-o)}var i=e-1,a=1,u=0;for(this[r+i]=255&t;--i>=0&&(a*=256);)t<0&&0===u&&0!==this[r+i+1]&&(u=1),this[r+i]=(t/a>>0)-u&255;return r+e},hs.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,1,127,-128),hs.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},hs.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,2,32767,-32768),hs.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):Bs(this,t,r,!0),r+2},hs.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,2,32767,-32768),hs.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):Bs(this,t,r,!1),r+2},hs.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,4,2147483647,-2147483648),hs.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):Ls(this,t,r,!0),r+4},hs.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||zs(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),hs.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):Ls(this,t,r,!1),r+4},hs.prototype.writeFloatLE=function(t,r,e){return Ys(this,t,r,!0,e)},hs.prototype.writeFloatBE=function(t,r,e){return Ys(this,t,r,!1,e)},hs.prototype.writeDoubleLE=function(t,r,e){return Js(this,t,r,!0,e)},hs.prototype.writeDoubleBE=function(t,r,e){return Js(this,t,r,!1,e)},hs.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=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-r=0;--o)t[o+r]=this[o+e];else if(i<1e3||!hs.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function Gs(t){return function(t){var r,e,n,o,i,a;ns||os();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[u-2]?2:"="===t[u-1]?1:0,a=new es(3*u/4-i),n=i>0?u-4:u;var c=0;for(r=0,e=0;r>16&255,a[c++]=o>>8&255,a[c++]=255&o;return 2===i?(o=rs[t.charCodeAt(r)]<<2|rs[t.charCodeAt(r+1)]>>4,a[c++]=255&o):1===i&&(o=rs[t.charCodeAt(r)]<<10|rs[t.charCodeAt(r+1)]<<4|rs[t.charCodeAt(r+2)]>>2,a[c++]=o>>8&255,a[c++]=255&o),a}(function(t){if((t=function(t){if(t.trim)return t.trim();return t.replace(/^\s+|\s+$/g,"")}(t).replace(Ws,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Qs(t,r,e,n){for(var o=0;o=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function Zs(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var Xs=["roundtip","handshake"],tf={useCallbackStyle:kc(!1,["boolean"]),loginHandlerName:kc("login",["string"]),logoutHandlerName:kc("logout",["string"]),loginMethod:kc("handshake",["string"],(Fs={},Fs[tu]=Xs,Fs)),useJwt:kc(!0,["boolean","string"]),hostname:kc(!1,["string"]),namespace:kc(Wa,["string"]),wsOptions:kc({},["object"]),contract:kc({},["object"],(Hs={},Hs[eu]=function(t){return!!function(t){return it(t)&&(xu(t,Ka)||xu(t,Va)||xu(t,Ga))}(t)&&t},Hs)),enableAuth:kc(!1,["boolean"]),token:kc(!1,["string"])},rf=Rc("check-options"),ef={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""},nf=tf,of=ef;function af(t,r){return function(t,r,e){return zu(t,ou)?Promise.resolve(t):Tc(t,r,e)}(t,tf,Object.assign(ef,r)).then((function(t){return t.hostname||(t.hostname=qc()),t.wssPath=$c([t.hostname,t.namespace].join("/"),t.serverType),rf("CONFIGURATION OPTIONS",t),t}))}var uf={version:"__PLACEHOLDER__",serverType:"ws"},cf=null;"undefined"!=typeof WebSocket?cf=WebSocket:"undefined"!=typeof MozWebSocket?cf=MozWebSocket:void 0!==M?cf=M.WebSocket||M.MozWebSocket:"undefined"!=typeof window?cf=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(cf=self.WebSocket||self.MozWebSocket);var sf=cf,ff=function(t){var r=t.toLowerCase();return r.indexOf("http")>-1?r.indexOf("https")>-1?r.replace("https","wss"):r.replace("http","ws"):r};function lf(t,r){return void 0===r&&(r=!1),!1===r?function(r){return new t(ff(r))}:function(r,e){var n=ff(r),o=e&&"string"==typeof e?n+"?"+ju+"="+e:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}function pf(t,r){var e=r.hostname,n=r.wssPath,o=r.wsOptions;return(0,r.nspClient)(t?[e,t].join("/"):n,o)}var hf=Rc("client-event-handler"),gf=function(t,r,e){var n=e.useCallbackStyle,o=n?_u:vu,i=n?mu:gu;r.$only(Nu(t,Tu),(function(e,n){hf("noLoginHandler hijack the ws call",t,e,n);var a={message:"NOT LOGIN"};r.$call(Nu(t,e,o),[a]),r.$call(Nu(t,e,i),[{error:a}])}))},vf=function(t){return t.length>1&&t[0]};function df(t,r,e,n,o,i){var a=vf(o),u=!1;o.forEach((function(o){if(u=a===o,i[o]){hf("call bindWsHandler",u,o);var c=[o,i[o],e,u,t];if(t.serverType===ku){var s=r.nspSet;c.push(s[o])}Reflect.apply(n,null,c)}else gf(o,e,t)})),e.$on(uu,(function(){hf("LOGOUT_EVENT_NAME"),function(t,r,e,n){void 0===n&&(n={});var o=n.useCallbackStyle?_u:vu;r.forEach((function(r){t.$call(Nu(r,o),[{message:e,namespace:r}])}))}(e,o,uu),o.forEach((function(r){Mc(e,r),i[r]=!1,gf(r,e,t)}))}))}var yf=["__reply__","__event__","__data__"],bf=function(t){var r,e=t.data;if(!1!==(r=function(t){var r=t.data;return!!r&&(yf.filter((function(t){return xu(r,t)})).length===yf.length&&r)}(Oc(e)?JSON.parse(e):e)))return{resolverName:r.__event__,data:r.__data__,type:r.__reply__};throw new Su("payload can not be decoded",t)},mf=Rc("ws-main-handler"),_f=function(t,r,e,n,o){var i=[r];e&&(mf("a global error on "+r),i.push(e)),i.push(o);var a=Reflect.apply(Nu,null,i),u=n.data||n;t.$trigger(a,[u])};function wf(t,r,e,n,o){var i=o.useCallbackStyle,a=i?wu:du,u=i?Eu:yu,c=i?bu:hu,s=i?mu:gu,f=i?_u:vu;r.onopen=function(){mf("ws.onopen listened"),e.$call(a,t),n&&(console.log("isPrivate and fire the "+u),e.$call(u,t)),e.$only(Nu(t,cu),(function(t,e){mf("calling server",t,e),r.send(function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(Yu(t,r,e))}(t,e))}))},r.onmessage=function(r){try{var n=bf(r),o=n.resolverName,i=n.type;switch(mf("Hear from server",i,n),i){case cu:var a=Nu(t,o,c),u=e.$trigger(a,[n]);mf("EMIT_REPLY_TYPE",a,u);break;case su:var l=Nu(t,o,s);e.$trigger(l,[n]);mf("ACKNOWLEDGE_REPLY_TYPE",l,n);break;case fu:mf("ERROR_TYPE"),_f(e,t,o,n,f);break;default:mf("Unhandled event!",n),_f(e,t,o,n,f)}}catch(r){console.error("ws.onmessage error",r),_f(e,t,!1,r,f)}},r.onclose=function(){mf("ws.onclose callback")},e.$on(uu,(function(){try{mf("terminate ws connection"),r.terminate()}catch(t){console.error("ws.terminate error",t)}}))}var Ef=Rc("ws-create-client"),jf=function(t,r,e){var n,o=r.nspSet,i=r.publicNamespace,a=!1,u=[],c={};if(t.enableAuth)a=!0,c=(u=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e}(o,i)).map((function(r,n){var o,i,a;return 0===n?e?(t.token=e,(o={})[r]=function(t,r){var e=r.hostname,n=r.wssPath,o=r.token,i=r.wsOptions,a=r.nspAuthClient,u=t?[e,t].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return a(u,o,i)}(r,t),o):((i={})[r]=!1,i):((a={})[r]=pf(r,t),a)})).reduce((function(t,r){return Object.assign(t,r)}),{});else{var s=(n=o,Object.keys(n)[0]);u.push(s),c[s]=pf(!1,t)}return{nsps:c,namespaces:u,login:a}};var Sf=function(t,r){return void 0===r&&(r={}),function(e){var n=e.eventEmitter;return af(e,r).then((function(t){return{opts:t,nspMap:Nc(t),ee:n||new Cc}})).then((function(r){var e=r.opts,n=r.nspMap,o=r.ee;return t(e,n,o)})).then((function(t){return Xc(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var r=lf(t),e=lf(t,!0);return function(t,n,o){return t.nspClient=r,t.nspAuthClient=e,function(t,r,e){var n=[t,r,e,wf],o=t.token,i=jf(t,r,o),a=i.nsps,u=i.namespaces,c=i.login;return Reflect.apply(df,null,n.concat([u,a])),c&&e.$only(au,(function(o){Ef("LOGIN_EVENT_NAME called with token:",o),Mc(e,u);var i=jf(t,r,o);Reflect.apply(df,null,n.concat([i.namespaces,i.nsps]))})),{opts:t,nspMap:r,ee:e}}(t,n,o)}}(sf),uf),Of=nf,Af=Object.assign(of,uf);return function(t,r){void 0===r&&(r={});var e=$a(Of,Af)(r);return e.socketClient=Sf,Na(t,e)}})); //# sourceMappingURL=jsonql-client-ws.js.map diff --git a/packages/@jsonql/client/dist/jsonql-client-ws.js.map b/packages/@jsonql/client/dist/jsonql-client-ws.js.map index 5cdcdd1e..efbd9724 100644 --- a/packages/@jsonql/client/dist/jsonql-client-ws.js.map +++ b/packages/@jsonql/client/dist/jsonql-client-ws.js.map @@ -1 +1 @@ -{"version":3,"file":"jsonql-client-ws.js","sources":["../node_modules/store/plugins/defaults.js","../node_modules/store/plugins/expire.js","../node_modules/buffer-es6/isArray.js"],"sourcesContent":["module.exports = defaultsPlugin\n\nfunction defaultsPlugin() {\n\tvar defaultValues = {}\n\t\n\treturn {\n\t\tdefaults: defaults,\n\t\tget: get\n\t}\n\t\n\tfunction defaults(_, values) {\n\t\tdefaultValues = values\n\t}\n\t\n\tfunction get(super_fn, key) {\n\t\tvar val = super_fn()\n\t\treturn (val !== undefined ? val : defaultValues[key])\n\t}\n}\n","var namespace = 'expire_mixin'\n\nmodule.exports = expirePlugin\n\nfunction expirePlugin() {\n\tvar expirations = this.createStore(this.storage, null, this._namespacePrefix+namespace)\n\t\n\treturn {\n\t\tset: expire_set,\n\t\tget: expire_get,\n\t\tremove: expire_remove,\n\t\tgetExpiration: getExpiration,\n\t\tremoveExpiredKeys: removeExpiredKeys\n\t}\n\t\n\tfunction expire_set(super_fn, key, val, expiration) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\texpirations.set(key, expiration)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction expire_get(super_fn, key) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\t_checkExpiration.call(this, key)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction expire_remove(super_fn, key) {\n\t\tif (!this.hasNamespace(namespace)) {\n\t\t\texpirations.remove(key)\n\t\t}\n\t\treturn super_fn()\n\t}\n\t\n\tfunction getExpiration(_, key) {\n\t\treturn expirations.get(key)\n\t}\n\t\n\tfunction removeExpiredKeys(_) {\n\t\tvar keys = []\n\t\tthis.each(function(val, key) {\n\t\t\tkeys.push(key)\n\t\t})\n\t\tfor (var i=0; i Date: Sun, 8 Dec 2019 15:40:06 +0800 Subject: [PATCH 3/8] jsonql-ws-server to 1.4.11 --- packages/@jsonql/client/package.json | 2 +- .../client/tests/qunit/files/ws-basic-test.js | 15 +++++++++++---- packages/ws-server/package.json | 12 ++++++------ packages/ws-server/src/core/ws-create-server.js | 7 ++++++- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index 79ce0dfe..1ff0c5a2 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -18,7 +18,7 @@ "test:basic": "DEBUG=jsonql-client* ava ./tests/basic.test.js", "test:login": "DEBUG=jsonql-client* ava ./tests/login.test.js", "_prepare": "NODE_ENV=production npm run build", - "test:browser": "npm run build:ws && npm run qunit", + "test:browser:ws": "npm run build:ws && npm run qunit", "start": "rollup -c -w --environment NODE_ENV:dev", "build": "npm run build:umd && npm run build:browser && npm run build:static && npm run build:full", "build:umd": "rollup -c", diff --git a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js index 9b11c4d8..5a9df3b8 100644 --- a/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js +++ b/packages/@jsonql/client/tests/qunit/files/ws-basic-test.js @@ -1,10 +1,19 @@ -QUnit.test('It should able to say Hello world!', function(assert) { +QUnit.test('jsonql client should have http and ws clients', function(assert) { + var done = [] + var ctn = 1; // just change this number as the test increase + for (var i = 0; i < ctn; ++i) { + done.push(assert.async()) + } jsonqlClientWs(fly, { - hostname: 'http://localhost:7890' + hostname: 'http://localhost:7890', + debugOn: true }) .then(function(client) { + console.log(client) + assert.equal(true, client.socket !== undefined, "Init client test to check if there is a socket") + done[0]() }) .catch(function(err) { console.error('Init jsonqlClientWs error', err) @@ -15,8 +24,6 @@ QUnit.test('It should able to say Hello world!', function(assert) { // console.log(client) - var result = 'yes'; - assert.equal('yes', result, "Init client test") }) diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 1236752b..6c26bf52 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server", - "version": "1.4.10", + "version": "1.4.11", "description": "Setup WebSocket server for the jsonql to run on the same host, automatic generate public / private channel using contract", "main": "index.js", "files": [ @@ -31,12 +31,12 @@ "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "jsonql-constants": "^1.8.12", - "jsonql-errors": "^1.1.7", - "jsonql-jwt": "^1.3.5", - "jsonql-params-validator": "^1.4.13", + "jsonql-constants": "^1.8.13", + "jsonql-errors": "^1.1.8", + "jsonql-jwt": "^1.3.6", + "jsonql-params-validator": "^1.5.0", "jsonql-resolver": "^0.9.11", - "jsonql-utils": "^0.8.11", + "jsonql-utils": "^0.9.0", "lodash": "^4.17.15", "ws": "^7.2.0" }, diff --git a/packages/ws-server/src/core/ws-create-server.js b/packages/ws-server/src/core/ws-create-server.js index 981a96be..cbc7d116 100644 --- a/packages/ws-server/src/core/ws-create-server.js +++ b/packages/ws-server/src/core/ws-create-server.js @@ -71,10 +71,15 @@ function wsCreateServer(config, server) { debug('found a srv to handle the call') srv.emit('connection', ws, req) }) - } else { + } + /* @1.4.11 we dont' destroy the connection any more + because during init the client there might not be a call + here to get handle + else { debug('Unhandled socket destroy') socket.destroy() } + */ }) return nsps } -- Gitee From 5ef08b1cef346ffa80d01a8d63d5ebd391dff762 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 15:48:20 +0800 Subject: [PATCH 4/8] move the koa specific methods from jsonql-utils back to jsonql-koa --- packages/koa/src/middlewares/auth-middleware.js | 1 + .../src/node-koa.js => koa/src/utils/helpers.js} | 16 +++++++++------- packages/utils/index.js | 6 ++---- packages/utils/package.json | 2 +- 4 files changed, 13 insertions(+), 12 deletions(-) rename packages/{utils/src/node-koa.js => koa/src/utils/helpers.js} (89%) diff --git a/packages/koa/src/middlewares/auth-middleware.js b/packages/koa/src/middlewares/auth-middleware.js index 80532b00..6e8e3b3d 100644 --- a/packages/koa/src/middlewares/auth-middleware.js +++ b/packages/koa/src/middlewares/auth-middleware.js @@ -47,6 +47,7 @@ export default function authMiddleware(config) { return forbiddenHandler(ctx, {message: 'userdata is empty?'}) } } else { + // @BUG this was throw a wrong error debug('throw at headers not found', ctx.request.headers) return forbiddenHandler(ctx, {message: 'Auth header not found!'}) } diff --git a/packages/utils/src/node-koa.js b/packages/koa/src/utils/helpers.js similarity index 89% rename from packages/utils/src/node-koa.js rename to packages/koa/src/utils/helpers.js index a7e6b87c..e5bf16b7 100644 --- a/packages/utils/src/node-koa.js +++ b/packages/koa/src/utils/helpers.js @@ -1,3 +1,5 @@ +// this was move back from jsonql-utils +// because this is all koa specific there is no reason to put into a global module // koa specific methods import { CONTENT_TYPE, @@ -6,17 +8,16 @@ import { } from 'jsonql-constants' // fix the default is not export by module error import * as jsonqlErrors from 'jsonql-errors' + import { getDocLen, headerParser, - getPathToFn -} from './node-middleware' -import { + getPathToFn, getCallMethod, packResult, - packError -} from './results' -import { dasherize } from './dasherize' + packError, + dasherize +} from 'jsonql-utils' /** * Handle the output @@ -76,10 +77,11 @@ export const ctxErrorHandler = function(ctx, code, e, message = '') { /** * Just a wrapper to be clearer what error is it + * * @param {object} ctx koa * @param {object} e error * @return {undefined} nothing */ export const forbiddenHandler = (ctx, e) => ( - ctxErrorHandler(ctx, FORBIDDEN_STATUS, e, 'JsonqlAuthorisationError') + ctxErrorHandler(ctx, FORBIDDEN_STATUS, e, 'JsonqlForbiddenError') ) diff --git a/packages/utils/index.js b/packages/utils/index.js index 4f90ac49..03e177d8 100644 --- a/packages/utils/index.js +++ b/packages/utils/index.js @@ -62,12 +62,14 @@ import { isJsonqlRequest, isJsonqlConsoleUrl } from './src/jsonql-handlers' +/* move back to the jsonql-koa since 0.9.1 import { handleOutput, handleHtmlOutput, ctxErrorHandler, forbiddenHandler } from './src/node-koa' +*/ import { getDocLen, headerParser, @@ -87,10 +89,6 @@ export { isJsonqlPath, isJsonqlRequest, isJsonqlConsoleUrl, - handleOutput, - handleHtmlOutput, - ctxErrorHandler, - forbiddenHandler, // middleware getDocLen, headerParser, diff --git a/packages/utils/package.json b/packages/utils/package.json index 91b4a448..db839e57 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-utils", - "version": "0.9.0", + "version": "0.9.1", "description": "This is a jsonql dependency module, not for generate use.", "main": "main.js", "module": "index.js", -- Gitee From 9b31bdb4c7f91254118bb4c9fc661f97ad577584 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 15:49:04 +0800 Subject: [PATCH 5/8] jsonql-utils 0.9.1 build --- packages/utils/browser.js | 2 +- packages/utils/main.js | 2 +- packages/utils/main.js.map | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/utils/browser.js b/packages/utils/browser.js index ecde1463..6f11565f 100644 --- a/packages/utils/browser.js +++ b/packages/utils/browser.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,g,b=(h=Object.getPrototypeOf,g=Object,function(t){return h(g(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=b(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N=function(t,r){return!!t.filter((function(t){return t===r})).length},k=function(t){return r(t)?t:[t]},z=function(t,r){try{var e=Object.keys(t);return N(e,r)}catch(t){return!1}},F=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,k(t))}),Reflect.apply(t,null,e))}};function E(t,r){return t===r||t!=t&&r!=r}function x(t,r){for(var e=t.length;e--;)if(E(t[e][0],r))return e;return-1}var T=Array.prototype.splice;function C(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},C.prototype.set=function(t,r){var e=this.__data__,n=x(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var R="[object AsyncFunction]",M="[object Function]",U="[object GeneratorFunction]",q="[object Proxy]";function B(t){if(!J(t))return!1;var r=y(t);return r==M||r==U||r==R||r==q}var $,D=u["__core-js_shared__"],I=($=/[^.]+$/.exec(D&&D.keys&&D.keys.IE_PROTO||""))?"Symbol(src)_1."+$:"";var Q=Function.prototype.toString;var V=/^\[object .+?Constructor\]$/,G=Function.prototype,H=Object.prototype,L=G.toString,K=H.hasOwnProperty,W=RegExp("^"+L.call(K).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Z(t){return!(!J(t)||function(t){return!!I&&I in t}(t))&&(B(t)?W:V).test(function(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function X(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return Z(e)?e:void 0}var Y=X(u,"Map"),tt=X(Object,"create");var rt="__lodash_hash_undefined__",et=Object.prototype.hasOwnProperty;var nt=Object.prototype.hasOwnProperty;var ot="__lodash_hash_undefined__";function ut(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Et}function Tt(t){return null!=t&&xt(t.length)&&!B(t)}var Ct="object"==typeof t&&t&&!t.nodeType&&t,Jt=Ct&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Jt&&Jt.exports===Ct?u.Buffer:void 0,Mt=(Rt?Rt.isBuffer:void 0)||function(){return!1},Ut={};Ut["[object Float32Array]"]=Ut["[object Float64Array]"]=Ut["[object Int8Array]"]=Ut["[object Int16Array]"]=Ut["[object Int32Array]"]=Ut["[object Uint8Array]"]=Ut["[object Uint8ClampedArray]"]=Ut["[object Uint16Array]"]=Ut["[object Uint32Array]"]=!0,Ut["[object Arguments]"]=Ut["[object Array]"]=Ut["[object ArrayBuffer]"]=Ut["[object Boolean]"]=Ut["[object DataView]"]=Ut["[object Date]"]=Ut["[object Error]"]=Ut["[object Function]"]=Ut["[object Map]"]=Ut["[object Number]"]=Ut["[object Object]"]=Ut["[object RegExp]"]=Ut["[object Set]"]=Ut["[object String]"]=Ut["[object WeakMap]"]=!1;var qt="object"==typeof t&&t&&!t.nodeType&&t,Bt=qt&&"object"==typeof module&&module&&!module.nodeType&&module,$t=Bt&&Bt.exports===qt&&n.process,Dt=function(){try{var t=Bt&&Bt.require&&Bt.require("util").types;return t||$t&&$t.binding&&$t.binding("util")}catch(t){}}(),It=Dt&&Dt.isTypedArray,Qt=It?function(t){return function(r){return t(r)}}(It):function(t){return _(t)&&xt(t.length)&&!!Ut[y(t)]};function Vt(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var Gt=Object.prototype.hasOwnProperty;function Ht(t,r,e){var n=t[r];Gt.call(t,r)&&E(n,e)&&(void 0!==e||r in t)||lt(t,r,e)}var Lt=9007199254740991,Kt=/^(?:0|[1-9]\d*)$/;function Wt(t,r){var e=typeof t;return!!(r=null==r?Lt:r)&&("number"==e||"symbol"!=e&&Kt.test(t))&&t>-1&&t%1==0&&t0){if(++r>=fr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(cr);function vr(t,r){return pr(function(t,r,e){return r=ar(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=ar(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=dr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!J(e))return!1;var n=typeof r;return!!("number"==n?Tt(e)&&Wt(r,e.length):"string"==n&&r in e)&&E(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&Br(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var re=function(t,r){var e=[];for(var n in r)e.push([n,r[n]].join("="));return[t,e.join("&")].join("?")},ee=function(){return{_cb:xr()}},ne="[object String]";function oe(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==ne}var ue=function(t){return oe(t)?JSON.parse(t):t},ie=function(t){var r;return(r={})[Pr]=t,r};function ae(t){return Object.keys(t)[0]}function ce(t,r){var e;return(e={})[t]=r,e[Sr]=[xr()],e}function fe(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),oe(t)&&r(e)){var o=ie(e);return!0===n?o:ce(t,o)}throw new zr("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}function se(t,r,e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o={};if(o[mr]=r,o[Or]=e,!0===n)return o;if(oe(t))return ce(t,o);throw new zr("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:e})}function le(t,r){var e;if(t&&A(r)){var n=r[t];if(n[Pr])return(e={})[wr]=t,e[Pr]=n[Pr],e[Sr]=r[Sr],e}return!1}function pe(t,r){var e=ue(t),n=ae(e);return Reflect.apply(r,null,[n,e])}function ve(t,r){var e;if(t&&A(r)){var n=r[t];if(n)return(e={})[wr]=t,e[mr]=n[mr],e[Or]=n[Or],e[Sr]=r[Sr],e}return!1}var de=function(t){return!!["detail","className"].filter((function(r){return z(t,r)})).length&&["className","message","statusCode"].filter((function(r){return z(t,r)})).map((function(r){var e;return(e={})[r]="object"==typeof t[r]?t[r].toString():t[r],e})).reduce(yr,{detail:t.toString()})};t.VERSION="0.9.0",t.cacheBurst=ee,t.cacheBurstUrl=function(t){return re(t,ee())},t.chainFns=F,t.chainProcessPromises=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):yr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=se,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(se(t,r,e,n))},t.createQuery=fe,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(fe(t,r,e))},t.dasherize=function(t){return te(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case br:return t[Pr];case _r:return[t[mr],t[Or]];default:throw new Fr("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new kr(e,r);return n}catch(t){throw new kr(e,t)}},t.extractSocketPart=Er,t.formatPayload=ie,t.getCallMethod=function(t){switch(!0){case t===Ar[0]:return br;case t===Ar[1]:return _r;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=ve,t.getMutationFromPayload=function(t){var r=pe(t,ve);if(!1!==r)return r;throw new zr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ae,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=le,t.getQueryFromPayload=function(t){var r=pe(t,le);if(!1!==r)return r;throw new zr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=Er(t);if(!1===e){if(r)return t;throw new Fr("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=N,t.injectToFn=gr,t.isContract=function(t){return!!function(t){return A(t)&&(z(t,br)||z(t,_r)||z(t,jr))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=de,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==trim(t)},t.isObjectHasKey=z,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=hr,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=de(t)||u,o[Sr]=xr(),o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(xr()),n[Sr]=e),JSON.stringify(n)},t.preConfigCheck=function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(F,null,e.concat((function(t){return gr(t,Nr,xr())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}},t.resultHandler=function(t){return z(t,"data")&&!z(t,"error")?t.data:t},t.timestamp=xr,t.toArray=k,t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ue,t.urlParams=re,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,g,b=(h=Object.getPrototypeOf,g=Object,function(t){return h(g(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=b(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N=function(t,r){return!!t.filter((function(t){return t===r})).length},k=function(t){return r(t)?t:[t]},z=function(t,r){try{var e=Object.keys(t);return N(e,r)}catch(t){return!1}},F=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,k(t))}),Reflect.apply(t,null,e))}};function E(t,r){return t===r||t!=t&&r!=r}function x(t,r){for(var e=t.length;e--;)if(E(t[e][0],r))return e;return-1}var T=Array.prototype.splice;function C(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},C.prototype.set=function(t,r){var e=this.__data__,n=x(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var R="[object AsyncFunction]",M="[object Function]",U="[object GeneratorFunction]",q="[object Proxy]";function B(t){if(!J(t))return!1;var r=y(t);return r==M||r==U||r==R||r==q}var $,D=u["__core-js_shared__"],I=($=/[^.]+$/.exec(D&&D.keys&&D.keys.IE_PROTO||""))?"Symbol(src)_1."+$:"";var Q=Function.prototype.toString;var V=/^\[object .+?Constructor\]$/,G=Function.prototype,H=Object.prototype,L=G.toString,K=H.hasOwnProperty,W=RegExp("^"+L.call(K).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Z(t){return!(!J(t)||function(t){return!!I&&I in t}(t))&&(B(t)?W:V).test(function(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function X(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return Z(e)?e:void 0}var Y=X(u,"Map"),tt=X(Object,"create");var rt="__lodash_hash_undefined__",et=Object.prototype.hasOwnProperty;var nt=Object.prototype.hasOwnProperty;var ot="__lodash_hash_undefined__";function ut(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Et}function Tt(t){return null!=t&&xt(t.length)&&!B(t)}var Ct="object"==typeof t&&t&&!t.nodeType&&t,Jt=Ct&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Jt&&Jt.exports===Ct?u.Buffer:void 0,Mt=(Rt?Rt.isBuffer:void 0)||function(){return!1},Ut={};Ut["[object Float32Array]"]=Ut["[object Float64Array]"]=Ut["[object Int8Array]"]=Ut["[object Int16Array]"]=Ut["[object Int32Array]"]=Ut["[object Uint8Array]"]=Ut["[object Uint8ClampedArray]"]=Ut["[object Uint16Array]"]=Ut["[object Uint32Array]"]=!0,Ut["[object Arguments]"]=Ut["[object Array]"]=Ut["[object ArrayBuffer]"]=Ut["[object Boolean]"]=Ut["[object DataView]"]=Ut["[object Date]"]=Ut["[object Error]"]=Ut["[object Function]"]=Ut["[object Map]"]=Ut["[object Number]"]=Ut["[object Object]"]=Ut["[object RegExp]"]=Ut["[object Set]"]=Ut["[object String]"]=Ut["[object WeakMap]"]=!1;var qt="object"==typeof t&&t&&!t.nodeType&&t,Bt=qt&&"object"==typeof module&&module&&!module.nodeType&&module,$t=Bt&&Bt.exports===qt&&n.process,Dt=function(){try{var t=Bt&&Bt.require&&Bt.require("util").types;return t||$t&&$t.binding&&$t.binding("util")}catch(t){}}(),It=Dt&&Dt.isTypedArray,Qt=It?function(t){return function(r){return t(r)}}(It):function(t){return _(t)&&xt(t.length)&&!!Ut[y(t)]};function Vt(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var Gt=Object.prototype.hasOwnProperty;function Ht(t,r,e){var n=t[r];Gt.call(t,r)&&E(n,e)&&(void 0!==e||r in t)||lt(t,r,e)}var Lt=9007199254740991,Kt=/^(?:0|[1-9]\d*)$/;function Wt(t,r){var e=typeof t;return!!(r=null==r?Lt:r)&&("number"==e||"symbol"!=e&&Kt.test(t))&&t>-1&&t%1==0&&t0){if(++r>=fr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(cr);function vr(t,r){return pr(function(t,r,e){return r=ar(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=ar(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=dr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!J(e))return!1;var n=typeof r;return!!("number"==n?Tt(e)&&Wt(r,e.length):"string"==n&&r in e)&&E(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&Br(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var re=function(t,r){var e=[];for(var n in r)e.push([n,r[n]].join("="));return[t,e.join("&")].join("?")},ee=function(){return{_cb:xr()}},ne="[object String]";function oe(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==ne}var ue=function(t){return oe(t)?JSON.parse(t):t},ie=function(t){var r;return(r={})[Pr]=t,r};function ae(t){return Object.keys(t)[0]}function ce(t,r){var e;return(e={})[t]=r,e[Sr]=[xr()],e}function fe(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),oe(t)&&r(e)){var o=ie(e);return!0===n?o:ce(t,o)}throw new zr("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}function se(t,r,e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o={};if(o[mr]=r,o[Or]=e,!0===n)return o;if(oe(t))return ce(t,o);throw new zr("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:e})}function le(t,r){var e;if(t&&A(r)){var n=r[t];if(n[Pr])return(e={})[wr]=t,e[Pr]=n[Pr],e[Sr]=r[Sr],e}return!1}function pe(t,r){var e=ue(t),n=ae(e);return Reflect.apply(r,null,[n,e])}function ve(t,r){var e;if(t&&A(r)){var n=r[t];if(n)return(e={})[wr]=t,e[mr]=n[mr],e[Or]=n[Or],e[Sr]=r[Sr],e}return!1}var de=function(t){return!!["detail","className"].filter((function(r){return z(t,r)})).length&&["className","message","statusCode"].filter((function(r){return z(t,r)})).map((function(r){var e;return(e={})[r]="object"==typeof t[r]?t[r].toString():t[r],e})).reduce(yr,{detail:t.toString()})};t.VERSION="0.9.1",t.cacheBurst=ee,t.cacheBurstUrl=function(t){return re(t,ee())},t.chainFns=F,t.chainProcessPromises=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):yr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=se,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(se(t,r,e,n))},t.createQuery=fe,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(fe(t,r,e))},t.dasherize=function(t){return te(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case br:return t[Pr];case _r:return[t[mr],t[Or]];default:throw new Fr("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new kr(e,r);return n}catch(t){throw new kr(e,t)}},t.extractSocketPart=Er,t.formatPayload=ie,t.getCallMethod=function(t){switch(!0){case t===Ar[0]:return br;case t===Ar[1]:return _r;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=ve,t.getMutationFromPayload=function(t){var r=pe(t,ve);if(!1!==r)return r;throw new zr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ae,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=le,t.getQueryFromPayload=function(t){var r=pe(t,le);if(!1!==r)return r;throw new zr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=Er(t);if(!1===e){if(r)return t;throw new Fr("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=N,t.injectToFn=gr,t.isContract=function(t){return!!function(t){return A(t)&&(z(t,br)||z(t,_r)||z(t,jr))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=de,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==trim(t)},t.isObjectHasKey=z,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=hr,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=de(t)||u,o[Sr]=xr(),o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(xr()),n[Sr]=e),JSON.stringify(n)},t.preConfigCheck=function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(F,null,e.concat((function(t){return gr(t,Nr,xr())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}},t.resultHandler=function(t){return z(t,"data")&&!z(t,"error")?t.data:t},t.timestamp=xr,t.toArray=k,t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ue,t.urlParams=re,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/main.js b/packages/utils/main.js index b0c44059..2ae592b7 100644 --- a/packages/utils/main.js +++ b/packages/utils/main.js @@ -1,2 +1,2 @@ -"use strict";function _interopDefault(r){return r&&"object"==typeof r&&"default"in r?r.default:r}Object.defineProperty(exports,"__esModule",{value:!0});var fs=_interopDefault(require("fs")),path=require("path"),isArray=Array.isArray,global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(r){var t=hasOwnProperty.call(r,symToStringTag),e=r[symToStringTag];try{r[symToStringTag]=void 0;var n=!0}catch(r){}var o=nativeObjectToString.call(r);return n&&(t?r[symToStringTag]=e:delete r[symToStringTag]),o}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(r){return nativeObjectToString$1.call(r)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(r){return null==r?void 0===r?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(r)?getRawTag(r):objectToString(r)}function overArg(r,t){return function(e){return r(t(e))}}var getPrototype=overArg(Object.getPrototypeOf,Object);function isObjectLike(r){return null!=r&&"object"==typeof r}var objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(r){if(!isObjectLike(r)||baseGetTag(r)!=objectTag)return!1;var t=getPrototype(r);if(null===t)return!0;var e=hasOwnProperty$1.call(t,"constructor")&&t.constructor;return"function"==typeof e&&e instanceof e&&funcToString.call(e)==objectCtorString}var inArray=function(r,t){return!!r.filter((function(r){return r===t})).length},toArray=function(r){return isArray(r)?r:[r]},parse=function(r){try{return JSON.parse(r)}catch(t){return r}},isObjectHasKey=function(r,t){try{var e=Object.keys(r);return inArray(e,t)}catch(r){return!1}},createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},getConfigValue=function(r,t){return t&&isPlainObject(t)&&r in t?t[r]:void 0},toJson=function(r){return"string"==typeof r?parse(r):JSON.parse(JSON.stringify(r))},isNotEmpty=function(r){return void 0!==r&&!1!==r&&null!==r&&""!==trim(r)},chainFns=function(r){for(var t=[],e=arguments.length-1;e-- >0;)t[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return t.reduce((function(r,t){return Reflect.apply(t,null,toArray(r))}),Reflect.apply(r,null,e))}};function listCacheClear(){this.__data__=[],this.size=0}function eq(r,t){return r===t||r!=r&&t!=t}function assocIndexOf(r,t){for(var e=r.length;e--;)if(eq(r[e][0],t))return e;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(r){var t=this.__data__,e=assocIndexOf(t,r);return!(e<0)&&(e==t.length-1?t.pop():splice.call(t,e,1),--this.size,!0)}function listCacheGet(r){var t=this.__data__,e=assocIndexOf(t,r);return e<0?void 0:t[e][1]}function listCacheHas(r){return assocIndexOf(this.__data__,r)>-1}function listCacheSet(r,t){var e=this.__data__,n=assocIndexOf(e,r);return n<0?(++this.size,e.push([r,t])):e[n][1]=t,this}function ListCache(r){var t=-1,e=null==r?0:r.length;for(this.clear();++t-1&&r%1==0&&r<=MAX_SAFE_INTEGER}function isArrayLike(r){return null!=r&&isLength(r.length)&&!isFunction(r)}function isArrayLikeObject(r){return isObjectLike(r)&&isArrayLike(r)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,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]",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]",typedArrayTags={};function baseIsTypedArray(r){return isObjectLike(r)&&isLength(r.length)&&!!typedArrayTags[baseGetTag(r)]}function baseUnary(r){return function(t){return r(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var r=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return r||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(r){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(r,t){if(("constructor"!==t||"function"!=typeof r[t])&&"__proto__"!=t)return r[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(r,t,e){var n=r[t];hasOwnProperty$6.call(r,t)&&eq(n,e)&&(void 0!==e||t in r)||baseAssignValue(r,t,e)}function copyObject(r,t,e,n){var o=!e;e||(e={});for(var a=-1,i=t.length;++a-1&&r%1==0&&r0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return r.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(r,t){return setToString(overRest(r,t,identity),r+"")}function isIterateeCall(r,t,e){if(!isObject(e))return!1;var n=typeof t;return!!("number"==n?isArrayLike(e)&&isIndex(t,e.length):"string"==n&&t in e)&&eq(e[t],r)}function createAssigner(r){return baseRest((function(t,e){var n=-1,o=e.length,a=o>1?e[o-1]:void 0,i=o>2?e[2]:void 0;for(a=r.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(e[0],e[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++no?0:o+t),(e=e>o?o:e)<0&&(e+=o),o=t>e?0:e-t>>>0,t>>>=0;for(var a=Array(o);++n=n?r:baseSlice(r,t,e)}function baseFindIndex(r,t,e,n){for(var o=r.length,a=e+(n?1:-1);n?a--:++a-1;);return e}function charsStartIndex(r,t){for(var e=-1,n=r.length;++e-1;);return e}function asciiToArray(r){return r.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(r){return reHasUnicode.test(r)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(r){return r.match(reUnicode)||[]}function stringToArray(r){return hasUnicode(r)?unicodeToArray(r):asciiToArray(r)}function toString(r){return null==r?"":baseToString(r)}var reTrim=/^\s+|\s+$/g;function trim$1(r,t,e){if((r=toString(r))&&(e||void 0===t))return r.replace(reTrim,"");if(!r||!(t=baseToString(t)))return r;var n=stringToArray(r),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var dasherize=function(r){return trim$1(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},urlParams=function(r,t){var e=[];for(var n in t)e.push([n,t[n]].join("="));return[r,e.join("&")].join("?")},cacheBurstUrl=function(r){return urlParams(r,cacheBurst())},cacheBurst=function(){return{_cb:timestamp()}},stringTag$1="[object String]";function isString(r){return"string"==typeof r||!isArray(r)&&isObjectLike(r)&&baseGetTag(r)==stringTag$1}var toPayload=function(r){return isString(r)?JSON.parse(r):r},formatPayload=function(r){var t;return(t={})[QUERY_ARG_NAME]=r,t};function getNameFromPayload(r){return Object.keys(r)[0]}function createDeliverable(r,t){var e;return(e={})[r]=t,e[TIMESTAMP_PARAM_NAME]=[timestamp()],e}function createQuery(r,t,e){if(void 0===t&&(t=[]),void 0===e&&(e=!1),isString(r)&&isArray(t)){var n=formatPayload(t);return!0===e?n:createDeliverable(r,n)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:r,args:t})}function createQueryStr(r,t,e){return void 0===t&&(t=[]),void 0===e&&(e=!1),JSON.stringify(createQuery(r,t,e))}function createMutation(r,t,e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o={};if(o[PAYLOAD_PARAM_NAME]=t,o[CONDITION_PARAM_NAME]=e,!0===n)return o;if(isString(r))return createDeliverable(r,o);throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:r,payload:t,condition:e})}function createMutationStr(r,t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(createMutation(r,t,e,n))}function getQueryFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n[QUERY_ARG_NAME])return(e={})[RESOLVER_PARAM_NAME]=r,e[QUERY_ARG_NAME]=n[QUERY_ARG_NAME],e[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],e}return!1}function processPayload(r,t){var e=toPayload(r),n=getNameFromPayload(e);return Reflect.apply(t,null,[n,e])}function getQueryFromPayload(r){var t=processPayload(r,getQueryFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",r)}function getMutationFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n)return(e={})[RESOLVER_PARAM_NAME]=r,e[PAYLOAD_PARAM_NAME]=n[PAYLOAD_PARAM_NAME],e[CONDITION_PARAM_NAME]=n[CONDITION_PARAM_NAME],e[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],e}return!1}function getMutationFromPayload(r){var t=processPayload(r,getMutationFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",r)}var getCallMethod=function(r){var t=API_REQUEST_METHODS[0],e=API_REQUEST_METHODS[1];switch(!0){case r===t:return QUERY_NAME;case r===e:return MUTATION_NAME;default:return!1}},packResult=function(r,t){void 0===t&&(t=!1);var e={};return e[DATA_KEY]=r,t&&isArray(t)&&(t.push(timestamp()),e[TIMESTAMP_PARAM_NAME]=t),JSON.stringify(e)},isJsonqlErrorObj=function(r){return!!["detail","className"].filter((function(t){return isObjectHasKey(r,t)})).length&&["className","message","statusCode"].filter((function(t){return isObjectHasKey(r,t)})).map((function(t){var e;return(e={})[t]="object"==typeof r[t]?r[t].toString():r[t],e})).reduce(merge,{detail:r.toString()})},packError=function(r,t,e,n){var o;void 0===t&&(t="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var a={detail:r,className:t,statusCode:e,message:n};return JSON.stringify(((o={})[ERROR_KEY]=isJsonqlErrorObj(r)||a,o[TIMESTAMP_PARAM_NAME]=timestamp(),o))},resultHandler=function(r){return isObjectHasKey(r,DATA_KEY)&&!isObjectHasKey(r,ERROR_KEY)?r[DATA_KEY]:r};function preConfigCheck(r,t){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(chainFns,null,e.concat((function(r){return injectToFn(r,CHECKED_KEY,timestamp())})));return function(e){return void 0===e&&(e={}),o(e,r,t)}}var VERSION="0.9.0",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,e=r.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===r[s-2]?2:"="===r[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,e=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[r.charCodeAt(t)]<<2|revLookup[r.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[r.charCodeAt(t)]<<10|revLookup[r.charCodeAt(t+1)]<<4|revLookup[r.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(r){return lookup[r>>18&63]+lookup[r>>12&63]+lookup[r>>6&63]+lookup[63&r]}function encodeChunk(r,t,e){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=r[e-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(r[e-2]<<8)+r[e-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(r,t,e,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=e?o-1:0,p=e?-1:1,h=r[t+l];for(l+=p,a=h&(1<<-c)-1,h>>=-c,c+=s;c>0;a=256*a+r[t+l],l+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+r[t+l],l+=p,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(h?-1:1);i+=Math.pow(2,n),a-=f}return(h?-1:1)*i*Math.pow(2,a-n)}function write(r,t,e,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?p/u:p*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;r[e+h]=255&s,h+=g,s/=256,o-=8);for(i=i<0;r[e+h]=255&i,h+=g,i/=256,f-=8);r[e+h-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(r){return"[object Array]"==toString$1.call(r)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(r,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|r}function internalIsBuffer(r){return!(null==r||!r._isBuffer)}function byteLength(r,t){if(internalIsBuffer(r))return r.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;"string"!=typeof r&&(r=""+r);var e=r.length;if(0===e)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return utf8ToBytes(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return base64ToBytes(r).length;default:if(n)return utf8ToBytes(r).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(r,t,e){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(t>>>=0))return"";for(r||(r="utf8");;)switch(r){case"hex":return hexSlice(this,t,e);case"utf8":case"utf-8":return utf8Slice(this,t,e);case"ascii":return asciiSlice(this,t,e);case"latin1":case"binary":return latin1Slice(this,t,e);case"base64":return base64Slice(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,e);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}function swap(r,t,e){var n=r[t];r[t]=r[e],r[e]=n}function bidirectionalIndexOf(r,t,e,n,o){if(0===r.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:r.length-1),e<0&&(e=r.length+e),e>=r.length){if(o)return-1;e=r.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(r,t,e,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(r,t,e):Uint8Array.prototype.lastIndexOf.call(r,t,e):arrayIndexOf(r,[t],e,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(r,t,e,n,o){var a,i=1,s=r.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(r.length<2||t.length<2)return-1;i=2,s/=2,u/=2,e/=2}function f(r,t){return 1===i?r[t]:r.readUInt16BE(t*i)}if(o){var c=-1;for(a=e;as&&(e=s-u),a=e;a>=0;a--){for(var l=!0,p=0;po&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=e)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=r[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=r[o+1],i=r[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=r[o+1],i=r[o+2],s=r[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(r){return r.__proto__=Buffer$2.prototype,r},Buffer$2.from=function(r,t,e){return from(null,r,t,e)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(r,t,e){return alloc(null,r,t,e)},Buffer$2.allocUnsafe=function(r){return allocUnsafe$1(null,r)},Buffer$2.allocUnsafeSlow=function(r){return allocUnsafe$1(null,r)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(r,t){if(!internalIsBuffer(r)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(r===t)return 0;for(var e=r.length,n=t.length,o=0,a=Math.min(e,n);o0&&(r=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(r+=" ... ")),""},Buffer$2.prototype.compare=function(r,t,e,n,o){if(!internalIsBuffer(r))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===e&&(e=r?r.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||e>r.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=e)return 0;if(n>=o)return-1;if(t>=e)return 1;if(this===r)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(e>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=r.slice(t,e),c=0;co)&&(e=o),r.length>0&&(e<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,r,t,e);case"utf8":case"utf-8":return utf8Write(this,r,t,e);case"ascii":return asciiWrite(this,r,t,e);case"latin1":case"binary":return latin1Write(this,r,t,e);case"base64":return base64Write(this,r,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,r,t,e);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(r){var t=r.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,r);for(var e="",n=0;nn)&&(e=n);for(var o="",a=t;ae)throw new RangeError("Trying to access beyond buffer length")}function checkInt(r,t,e,n,o,a){if(!internalIsBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||tr.length)throw new RangeError("Index out of range")}function objectWriteUInt16(r,t,e,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(r.length-e,2);o>>8*(n?o:1-o)}function objectWriteUInt32(r,t,e,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(r.length-e,4);o>>8*(n?o:3-o)&255}function checkIEEE754(r,t,e,n,o,a){if(e+n>r.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function writeFloat(r,t,e,n,o){return o||checkIEEE754(r,t,e,4),write(r,t,e,n,23,4),e+4}function writeDouble(r,t,e,n,o){return o||checkIEEE754(r,t,e,8),write(r,t,e,n,52,8),e+8}Buffer$2.prototype.slice=function(r,t){var e,n=this.length;if((r=~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[r+--t]*o;return n},Buffer$2.prototype.readUInt8=function(r,t){return t||checkOffset(r,1,this.length),this[r]},Buffer$2.prototype.readUInt16LE=function(r,t){return t||checkOffset(r,2,this.length),this[r]|this[r+1]<<8},Buffer$2.prototype.readUInt16BE=function(r,t){return t||checkOffset(r,2,this.length),this[r]<<8|this[r+1]},Buffer$2.prototype.readUInt32LE=function(r,t){return t||checkOffset(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+16777216*this[r+3]},Buffer$2.prototype.readUInt32BE=function(r,t){return t||checkOffset(r,4,this.length),16777216*this[r]+(this[r+1]<<16|this[r+2]<<8|this[r+3])},Buffer$2.prototype.readIntLE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=this[r],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=t,o=1,a=this[r+--n];n>0&&(o*=256);)a+=this[r+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(r,t){return t||checkOffset(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},Buffer$2.prototype.readInt16LE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r]|this[r+1]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt16BE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r+1]|this[r]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt32LE=function(r,t){return t||checkOffset(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},Buffer$2.prototype.readInt32BE=function(r,t){return t||checkOffset(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},Buffer$2.prototype.readFloatLE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!0,23,4)},Buffer$2.prototype.readFloatBE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(r,t,e,n){(r=+r,t|=0,e|=0,n)||checkInt(this,r,t,e,Math.pow(2,8*e)-1,0);var o=1,a=0;for(this[t]=255&r;++a=0&&(a*=256);)this[t+o]=r/a&255;return t+e},Buffer$2.prototype.writeUInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[t]=255&r,t+1},Buffer$2.prototype.writeUInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=r>>>24,this[t+2]=r>>>16,this[t+1]=r>>>8,this[t]=255&r):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&r;++a>0)-s&255;return t+e},Buffer$2.prototype.writeIntBE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=e-1,i=1,s=0;for(this[t+a]=255&r;--a>=0&&(i*=256);)r<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(r/i>>0)-s&255;return t+e},Buffer$2.prototype.writeInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[t]=255&r,t+1},Buffer$2.prototype.writeInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8,this[t+2]=r>>>16,this[t+3]=r>>>24):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(r,t,e){return writeFloat(this,r,t,!0,e)},Buffer$2.prototype.writeFloatBE=function(r,t,e){return writeFloat(this,r,t,!1,e)},Buffer$2.prototype.writeDoubleLE=function(r,t,e){return writeDouble(this,r,t,!0,e)},Buffer$2.prototype.writeDoubleBE=function(r,t,e){return writeDouble(this,r,t,!1,e)},Buffer$2.prototype.copy=function(r,t,e,n){if(e||(e=0),n||0===n||(n=this.length),t>=r.length&&(t=r.length),t||(t=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),r.length-t=0;--o)r[o+t]=this[o+e];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,r||(r=0),"number"==typeof r)for(a=t;a55295&&e<57344){if(!o){if(e>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=e;continue}if(e<56320){(t-=3)>-1&&a.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,e<128){if((t-=1)<0)break;a.push(e)}else if(e<2048){if((t-=2)<0)break;a.push(e>>6|192,63&e|128)}else if(e<65536){if((t-=3)<0)break;a.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return a}function asciiToBytes(r){for(var t=[],e=0;e>8,o=e%256,a.push(o),a.push(n);return a}function base64ToBytes(r){return toByteArray(base64clean(r))}function blitBuffer(r,t,e,n){for(var o=0;o=t.length||o>=r.length);++o)t[o+e]=r[o];return o}function isnan(r){return r!=r}function isBuffer$1(r){return null!=r&&(!!r._isBuffer||isFastBuffer(r)||isSlowBuffer(r))}function isFastBuffer(r){return!!r.constructor&&"function"==typeof r.constructor.isBuffer&&r.constructor.isBuffer(r)}function isSlowBuffer(r){return"function"==typeof r.readFloatLE&&"function"==typeof r.slice&&isFastBuffer(r.slice(0,0))}function buff(r,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(r)?r:new Buffer$2.from(r,t)}var replaceErrors=function(r,t){if(t instanceof Error){var e={};return Object.getOwnPropertyNames(t).forEach((function(r){e[r]=t[r]})),e}return t},printError=function(r){return JSON.stringify(r,replaceErrors)};function findFromContract(r,t,e){return!!(e[r]&&e[r][t]&&e[r][t].file&&fs.existsSync(e[r][t].file))&&e[r][t].file}var DOT=".",getDocLen=function(r){return Buffer$2.byteLength(r,"utf8")},headerParser=function(r,t){try{var e=r.headers.accept.split(",");return t?e.filter((function(r){return r===t})):e}catch(r){return[]}},isHeaderPresent=function(r,t){return!!headerParser(r,t).length},getPathToFn=function(r,t,e){var n=e.resolverDir,o=dasherize(r),a=[];e.contract&&e.contract[t]&&e.contract[t].path&&a.push(e.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;s0;)t[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return t.reduce((function(e,t){return Reflect.apply(t,null,toArray(e))}),Reflect.apply(e,null,r))}};function listCacheClear(){this.__data__=[],this.size=0}function eq(e,t){return e===t||e!=e&&t!=t}function assocIndexOf(e,t){for(var r=e.length;r--;)if(eq(e[r][0],t))return r;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var t=this.__data__,r=assocIndexOf(t,e);return!(r<0)&&(r==t.length-1?t.pop():splice.call(t,r,1),--this.size,!0)}function listCacheGet(e){var t=this.__data__,r=assocIndexOf(t,e);return r<0?void 0:t[r][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,t){var r=this.__data__,n=assocIndexOf(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}function ListCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,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]",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]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(e,t,r){var n=e[t];hasOwnProperty$6.call(e,t)&&eq(n,r)&&(void 0!==r||t in e)||baseAssignValue(e,t,r)}function copyObject(e,t,r,n){var o=!r;r||(r={});for(var a=-1,i=t.length;++a-1&&e%1==0&&e0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,t){return setToString(overRest(e,t,identity),e+"")}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var n=typeof t;return!!("number"==n?isArrayLike(r)&&isIndex(t,r.length):"string"==n&&t in r)&&eq(r[t],e)}function createAssigner(e){return baseRest((function(t,r){var n=-1,o=r.length,a=o>1?r[o-1]:void 0,i=o>2?r[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(r[0],r[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++no?0:o+t),(r=r>o?o:r)<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,t,r)}function baseFindIndex(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a-1;);return r}function charsStartIndex(e,t){for(var r=-1,n=e.length;++r-1;);return r}function asciiToArray(e){return e.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function toString(e){return null==e?"":baseToString(e)}var reTrim=/^\s+|\s+$/g;function trim$1(e,t,r){if((e=toString(e))&&(r||void 0===t))return e.replace(reTrim,"");if(!e||!(t=baseToString(t)))return e;var n=stringToArray(e),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var dasherize=function(e){return trim$1(e).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},urlParams=function(e,t){var r=[];for(var n in t)r.push([n,t[n]].join("="));return[e,r.join("&")].join("?")},cacheBurstUrl=function(e){return urlParams(e,cacheBurst())},cacheBurst=function(){return{_cb:timestamp()}},stringTag$1="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag$1}var toPayload=function(e){return isString(e)?JSON.parse(e):e},formatPayload=function(e){var t;return(t={})[QUERY_ARG_NAME]=e,t};function getNameFromPayload(e){return Object.keys(e)[0]}function createDeliverable(e,t){var r;return(r={})[e]=t,r[TIMESTAMP_PARAM_NAME]=[timestamp()],r}function createQuery(e,t,r){if(void 0===t&&(t=[]),void 0===r&&(r=!1),isString(e)&&isArray(t)){var n=formatPayload(t);return!0===r?n:createDeliverable(e,n)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:t})}function createQueryStr(e,t,r){return void 0===t&&(t=[]),void 0===r&&(r=!1),JSON.stringify(createQuery(e,t,r))}function createMutation(e,t,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[PAYLOAD_PARAM_NAME]=t,o[CONDITION_PARAM_NAME]=r,!0===n)return o;if(isString(e))return createDeliverable(e,o);throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:e,payload:t,condition:r})}function createMutationStr(e,t,r,n){return void 0===r&&(r={}),void 0===n&&(n=!1),JSON.stringify(createMutation(e,t,r,n))}function getQueryFromArgs(e,t){var r;if(e&&isPlainObject(t)){var n=t[e];if(n[QUERY_ARG_NAME])return(r={})[RESOLVER_PARAM_NAME]=e,r[QUERY_ARG_NAME]=n[QUERY_ARG_NAME],r[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],r}return!1}function processPayload(e,t){var r=toPayload(e),n=getNameFromPayload(r);return Reflect.apply(t,null,[n,r])}function getQueryFromPayload(e){var t=processPayload(e,getQueryFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",e)}function getMutationFromArgs(e,t){var r;if(e&&isPlainObject(t)){var n=t[e];if(n)return(r={})[RESOLVER_PARAM_NAME]=e,r[PAYLOAD_PARAM_NAME]=n[PAYLOAD_PARAM_NAME],r[CONDITION_PARAM_NAME]=n[CONDITION_PARAM_NAME],r[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],r}return!1}function getMutationFromPayload(e){var t=processPayload(e,getMutationFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",e)}var getCallMethod=function(e){var t=API_REQUEST_METHODS[0],r=API_REQUEST_METHODS[1];switch(!0){case e===t:return QUERY_NAME;case e===r:return MUTATION_NAME;default:return!1}},packResult=function(e,t){void 0===t&&(t=!1);var r={};return r[DATA_KEY]=e,t&&isArray(t)&&(t.push(timestamp()),r[TIMESTAMP_PARAM_NAME]=t),JSON.stringify(r)},isJsonqlErrorObj=function(e){return!!["detail","className"].filter((function(t){return isObjectHasKey(e,t)})).length&&["className","message","statusCode"].filter((function(t){return isObjectHasKey(e,t)})).map((function(t){var r;return(r={})[t]="object"==typeof e[t]?e[t].toString():e[t],r})).reduce(merge,{detail:e.toString()})},packError=function(e,t,r,n){var o;void 0===t&&(t="JsonqlError"),void 0===r&&(r=0),void 0===n&&(n="");var a={detail:e,className:t,statusCode:r,message:n};return JSON.stringify(((o={})[ERROR_KEY]=isJsonqlErrorObj(e)||a,o[TIMESTAMP_PARAM_NAME]=timestamp(),o))},resultHandler=function(e){return isObjectHasKey(e,DATA_KEY)&&!isObjectHasKey(e,ERROR_KEY)?e[DATA_KEY]:e};function preConfigCheck(e,t){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=Reflect.apply(chainFns,null,r.concat((function(e){return injectToFn(e,CHECKED_KEY,timestamp())})));return function(r){return void 0===r&&(r={}),o(r,e,t)}}var VERSION="0.9.1",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===e[s-2]?2:"="===e[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,r){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=e[r-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(e,t,r,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=r?o-1:0,h=r?-1:1,p=e[t+l];for(l+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+e[t+l],l+=h,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+e[t+l],l+=h,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(p?-1:1);i+=Math.pow(2,n),a-=f}return(p?-1:1)*i*Math.pow(2,a-n)}function write(e,t,r,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?h/u:h*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;e[r+p]=255&s,p+=g,s/=256,o-=8);for(i=i<0;e[r+p]=255&i,p+=g,i/=256,f-=8);e[r+p-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(e){return"[object Array]"==toString$1.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return base64ToBytes(e).length;default:if(n)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,r);case"utf8":case"utf-8":return utf8Slice(this,t,r);case"ascii":return asciiSlice(this,t,r);case"latin1":case"binary":return latin1Slice(this,t,r);case"base64":return base64Slice(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function swap(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function bidirectionalIndexOf(e,t,r,n,o){if(0===e.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:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,r,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):arrayIndexOf(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,r,n,o){var a,i=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;i=2,s/=2,u/=2,r/=2}function f(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){var c=-1;for(a=r;as&&(r=s-u),a=r;a>=0;a--){for(var l=!0,h=0;ho&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=r)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=e[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=e[o+1],i=e[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=e[o+1],i=e[o+2],s=e[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(e){return e.__proto__=Buffer$2.prototype,e},Buffer$2.from=function(e,t,r){return from(null,e,t,r)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(e,t,r){return alloc(null,e,t,r)},Buffer$2.allocUnsafe=function(e){return allocUnsafe$1(null,e)},Buffer$2.allocUnsafeSlow=function(e){return allocUnsafe$1(null,e)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,a=Math.min(r,n);o0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer$2.prototype.compare=function(e,t,r,n,o){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(r>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=e.slice(t,r),c=0;co)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,e,t,r);case"utf8":case"utf-8":return utf8Write(this,e,t,r);case"ascii":return asciiWrite(this,e,t,r);case"latin1":case"binary":return latin1Write(this,e,t,r);case"base64":return base64Write(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,r,n,o,a){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function objectWriteUInt32(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function checkIEEE754(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function writeFloat(e,t,r,n,o){return o||checkIEEE754(e,t,r,4),write(e,t,r,n,23,4),r+4}function writeDouble(e,t,r,n,o){return o||checkIEEE754(e,t,r,8),write(e,t,r,n,52,8),r+8}Buffer$2.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},Buffer$2.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer$2.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer$2.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer$2.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer$2.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer$2.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=this[e],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=t,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer$2.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer$2.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer$2.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer$2.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+r},Buffer$2.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer$2.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},Buffer$2.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=r-1,i=1,s=0;for(this[t+a]=255&e;--a>=0&&(i*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/i>>0)-s&255;return t+r},Buffer$2.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer$2.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(e,t,r){return writeFloat(this,e,t,!0,r)},Buffer$2.prototype.writeFloatBE=function(e,t,r){return writeFloat(this,e,t,!1,r)},Buffer$2.prototype.writeDoubleLE=function(e,t,r){return writeDouble(this,e,t,!0,r)},Buffer$2.prototype.writeDoubleBE=function(e,t,r){return writeDouble(this,e,t,!1,r)},Buffer$2.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=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),e.length-t=0;--o)e[o+t]=this[o+r];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function asciiToBytes(e){for(var t=[],r=0;r>8,o=r%256,a.push(o),a.push(n);return a}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function isnan(e){return e!=e}function isBuffer$1(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function buff(e,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(e)?e:new Buffer$2.from(e,t)}var replaceErrors=function(e,t){if(t instanceof Error){var r={};return Object.getOwnPropertyNames(t).forEach((function(e){r[e]=t[e]})),r}return t},printError=function(e){return JSON.stringify(e,replaceErrors)};function findFromContract(e,t,r){return!!(r[e]&&r[e][t]&&r[e][t].file&&fs.existsSync(r[e][t].file))&&r[e][t].file}var DOT=".",getDocLen=function(e){return Buffer$2.byteLength(e,"utf8")},headerParser=function(e,t){try{var r=e.headers.accept.split(",");return t?r.filter((function(e){return e===t})):r}catch(e){return[]}},isHeaderPresent=function(e,t){return!!headerParser(e,t).length},getPathToFn=function(e,t,r){var n=r.resolverDir,o=dasherize(e),a=[];r.contract&&r.contract[t]&&r.contract[t].path&&a.push(r.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;s Date: Sun, 8 Dec 2019 16:01:23 +0800 Subject: [PATCH 6/8] remap the import and export from jsonql-utils to the local version --- packages/koa/package.json | 14 +++++++------- packages/koa/src/utils/helpers.js | 1 + packages/koa/src/utils/index.js | 10 +++++++--- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/packages/koa/package.json b/packages/koa/package.json index f02d22a1..34d212b8 100644 --- a/packages/koa/package.json +++ b/packages/koa/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-koa", - "version": "1.4.22", + "version": "1.5.0", "description": "jsonql Koa middleware", "main": "main.js", "module": "index.js", @@ -74,21 +74,21 @@ "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "jsonql-constants": "^1.8.12", + "jsonql-constants": "^1.8.13", "jsonql-contract": "^1.8.4", - "jsonql-errors": "^1.1.7", - "jsonql-jwt": "^1.3.5", + "jsonql-errors": "^1.1.8", + "jsonql-jwt": "^1.3.6", "jsonql-node-client": "^1.2.5", - "jsonql-params-validator": "^1.4.13", + "jsonql-params-validator": "^1.5.0", "jsonql-resolver": "^0.9.11", - "jsonql-utils": "^0.8.11", + "jsonql-utils": "^0.9.1", "jsonql-web-console": "^0.4.4", "koa-compose": "^4.1.0", "lodash": "^4.17.15" }, "devDependencies": { "ava": "^2.4.0", - "jsonql-ws-server": "^1.4.9", + "jsonql-ws-server": "^1.4.11", "jwt-decode": "^2.2.0", "koa": "^2.11.0", "koa-bodyparser": "^4.2.1", diff --git a/packages/koa/src/utils/helpers.js b/packages/koa/src/utils/helpers.js index e5bf16b7..2c5d8650 100644 --- a/packages/koa/src/utils/helpers.js +++ b/packages/koa/src/utils/helpers.js @@ -34,6 +34,7 @@ export const handleOutput = function(opts) { } /** + * @TODO this was never use anywhere, remove later * handle HTML output for the web console * @param {object} ctx koa context * @param {string} body output content diff --git a/packages/koa/src/utils/index.js b/packages/koa/src/utils/index.js index 83b9ef62..f82efcc0 100644 --- a/packages/koa/src/utils/index.js +++ b/packages/koa/src/utils/index.js @@ -12,8 +12,6 @@ import { getDocLen, packResult, printError, - forbiddenHandler, - ctxErrorHandler, isJsonqlPath, isJsonqlRequest, @@ -24,7 +22,7 @@ import { isNotEmpty, isContract, - handleOutput, + extractArgsFromPayload, getNameFromPayload, @@ -37,6 +35,12 @@ import { objHasProp } from 'jsonql-utils' +import { + handleOutput, + forbiddenHandler, + ctxErrorHandler +} from './helpers' + // export export { processJwtKeys, -- Gitee From 3383886c897e8ffc48f9767f095b1dda851ba794 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 17:32:02 +0800 Subject: [PATCH 7/8] Fix the missing import for isNotEmpty --- packages/utils/browser.js | 2 +- packages/utils/main.js | 2 +- packages/utils/main.js.map | 2 +- packages/utils/package.json | 2 +- packages/utils/src/generic.js | 2 +- packages/utils/tests/fn.test.js | 2 ++ 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/utils/browser.js b/packages/utils/browser.js index 6f11565f..6938f8b0 100644 --- a/packages/utils/browser.js +++ b/packages/utils/browser.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,g,b=(h=Object.getPrototypeOf,g=Object,function(t){return h(g(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=b(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N=function(t,r){return!!t.filter((function(t){return t===r})).length},k=function(t){return r(t)?t:[t]},z=function(t,r){try{var e=Object.keys(t);return N(e,r)}catch(t){return!1}},F=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,k(t))}),Reflect.apply(t,null,e))}};function E(t,r){return t===r||t!=t&&r!=r}function x(t,r){for(var e=t.length;e--;)if(E(t[e][0],r))return e;return-1}var T=Array.prototype.splice;function C(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},C.prototype.set=function(t,r){var e=this.__data__,n=x(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var R="[object AsyncFunction]",M="[object Function]",U="[object GeneratorFunction]",q="[object Proxy]";function B(t){if(!J(t))return!1;var r=y(t);return r==M||r==U||r==R||r==q}var $,D=u["__core-js_shared__"],I=($=/[^.]+$/.exec(D&&D.keys&&D.keys.IE_PROTO||""))?"Symbol(src)_1."+$:"";var Q=Function.prototype.toString;var V=/^\[object .+?Constructor\]$/,G=Function.prototype,H=Object.prototype,L=G.toString,K=H.hasOwnProperty,W=RegExp("^"+L.call(K).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Z(t){return!(!J(t)||function(t){return!!I&&I in t}(t))&&(B(t)?W:V).test(function(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function X(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return Z(e)?e:void 0}var Y=X(u,"Map"),tt=X(Object,"create");var rt="__lodash_hash_undefined__",et=Object.prototype.hasOwnProperty;var nt=Object.prototype.hasOwnProperty;var ot="__lodash_hash_undefined__";function ut(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Et}function Tt(t){return null!=t&&xt(t.length)&&!B(t)}var Ct="object"==typeof t&&t&&!t.nodeType&&t,Jt=Ct&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Jt&&Jt.exports===Ct?u.Buffer:void 0,Mt=(Rt?Rt.isBuffer:void 0)||function(){return!1},Ut={};Ut["[object Float32Array]"]=Ut["[object Float64Array]"]=Ut["[object Int8Array]"]=Ut["[object Int16Array]"]=Ut["[object Int32Array]"]=Ut["[object Uint8Array]"]=Ut["[object Uint8ClampedArray]"]=Ut["[object Uint16Array]"]=Ut["[object Uint32Array]"]=!0,Ut["[object Arguments]"]=Ut["[object Array]"]=Ut["[object ArrayBuffer]"]=Ut["[object Boolean]"]=Ut["[object DataView]"]=Ut["[object Date]"]=Ut["[object Error]"]=Ut["[object Function]"]=Ut["[object Map]"]=Ut["[object Number]"]=Ut["[object Object]"]=Ut["[object RegExp]"]=Ut["[object Set]"]=Ut["[object String]"]=Ut["[object WeakMap]"]=!1;var qt="object"==typeof t&&t&&!t.nodeType&&t,Bt=qt&&"object"==typeof module&&module&&!module.nodeType&&module,$t=Bt&&Bt.exports===qt&&n.process,Dt=function(){try{var t=Bt&&Bt.require&&Bt.require("util").types;return t||$t&&$t.binding&&$t.binding("util")}catch(t){}}(),It=Dt&&Dt.isTypedArray,Qt=It?function(t){return function(r){return t(r)}}(It):function(t){return _(t)&&xt(t.length)&&!!Ut[y(t)]};function Vt(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var Gt=Object.prototype.hasOwnProperty;function Ht(t,r,e){var n=t[r];Gt.call(t,r)&&E(n,e)&&(void 0!==e||r in t)||lt(t,r,e)}var Lt=9007199254740991,Kt=/^(?:0|[1-9]\d*)$/;function Wt(t,r){var e=typeof t;return!!(r=null==r?Lt:r)&&("number"==e||"symbol"!=e&&Kt.test(t))&&t>-1&&t%1==0&&t0){if(++r>=fr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(cr);function vr(t,r){return pr(function(t,r,e){return r=ar(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=ar(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=dr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!J(e))return!1;var n=typeof r;return!!("number"==n?Tt(e)&&Wt(r,e.length):"string"==n&&r in e)&&E(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&Br(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var re=function(t,r){var e=[];for(var n in r)e.push([n,r[n]].join("="));return[t,e.join("&")].join("?")},ee=function(){return{_cb:xr()}},ne="[object String]";function oe(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==ne}var ue=function(t){return oe(t)?JSON.parse(t):t},ie=function(t){var r;return(r={})[Pr]=t,r};function ae(t){return Object.keys(t)[0]}function ce(t,r){var e;return(e={})[t]=r,e[Sr]=[xr()],e}function fe(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),oe(t)&&r(e)){var o=ie(e);return!0===n?o:ce(t,o)}throw new zr("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}function se(t,r,e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o={};if(o[mr]=r,o[Or]=e,!0===n)return o;if(oe(t))return ce(t,o);throw new zr("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:e})}function le(t,r){var e;if(t&&A(r)){var n=r[t];if(n[Pr])return(e={})[wr]=t,e[Pr]=n[Pr],e[Sr]=r[Sr],e}return!1}function pe(t,r){var e=ue(t),n=ae(e);return Reflect.apply(r,null,[n,e])}function ve(t,r){var e;if(t&&A(r)){var n=r[t];if(n)return(e={})[wr]=t,e[mr]=n[mr],e[Or]=n[Or],e[Sr]=r[Sr],e}return!1}var de=function(t){return!!["detail","className"].filter((function(r){return z(t,r)})).length&&["className","message","statusCode"].filter((function(r){return z(t,r)})).map((function(r){var e;return(e={})[r]="object"==typeof t[r]?t[r].toString():t[r],e})).reduce(yr,{detail:t.toString()})};t.VERSION="0.9.1",t.cacheBurst=ee,t.cacheBurstUrl=function(t){return re(t,ee())},t.chainFns=F,t.chainProcessPromises=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):yr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=se,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(se(t,r,e,n))},t.createQuery=fe,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(fe(t,r,e))},t.dasherize=function(t){return te(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case br:return t[Pr];case _r:return[t[mr],t[Or]];default:throw new Fr("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new kr(e,r);return n}catch(t){throw new kr(e,t)}},t.extractSocketPart=Er,t.formatPayload=ie,t.getCallMethod=function(t){switch(!0){case t===Ar[0]:return br;case t===Ar[1]:return _r;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=ve,t.getMutationFromPayload=function(t){var r=pe(t,ve);if(!1!==r)return r;throw new zr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ae,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=le,t.getQueryFromPayload=function(t){var r=pe(t,le);if(!1!==r)return r;throw new zr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=Er(t);if(!1===e){if(r)return t;throw new Fr("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=N,t.injectToFn=gr,t.isContract=function(t){return!!function(t){return A(t)&&(z(t,br)||z(t,_r)||z(t,jr))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=de,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==trim(t)},t.isObjectHasKey=z,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=hr,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=de(t)||u,o[Sr]=xr(),o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(xr()),n[Sr]=e),JSON.stringify(n)},t.preConfigCheck=function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(F,null,e.concat((function(t){return gr(t,Nr,xr())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}},t.resultHandler=function(t){return z(t,"data")&&!z(t,"error")?t.data:t},t.timestamp=xr,t.toArray=k,t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ue,t.urlParams=re,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,g,b=(h=Object.getPrototypeOf,g=Object,function(t){return h(g(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=b(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N="[object Symbol]";var k=1/0,z=i?i.prototype:void 0,F=z?z.toString:void 0;function E(t){if("string"==typeof t)return t;if(r(t))return function(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&C(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var K=function(t,r){return!!t.filter((function(t){return t===r})).length},W=function(t){return r(t)?t:[t]},Z=function(t,r){try{var e=Object.keys(t);return K(e,r)}catch(t){return!1}},X=function(t){for(var r=[],e=arguments.length-1;e-- >0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,W(t))}),Reflect.apply(t,null,e))}};function Y(t,r){return t===r||t!=t&&r!=r}function tt(t,r){for(var e=t.length;e--;)if(Y(t[e][0],r))return e;return-1}var rt=Array.prototype.splice;function et(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},et.prototype.set=function(t,r){var e=this.__data__,n=tt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var ot="[object AsyncFunction]",ut="[object Function]",it="[object GeneratorFunction]",at="[object Proxy]";function ct(t){if(!nt(t))return!1;var r=y(t);return r==ut||r==it||r==ot||r==at}var ft,st=u["__core-js_shared__"],lt=(ft=/[^.]+$/.exec(st&&st.keys&&st.keys.IE_PROTO||""))?"Symbol(src)_1."+ft:"";var pt=Function.prototype.toString;var vt=/^\[object .+?Constructor\]$/,dt=Function.prototype,yt=Object.prototype,ht=dt.toString,gt=yt.hasOwnProperty,bt=RegExp("^"+ht.call(gt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _t(t){return!(!nt(t)||function(t){return!!lt&< in t}(t))&&(ct(t)?bt:vt).test(function(t){if(null!=t){try{return pt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function jt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return _t(e)?e:void 0}var mt=jt(u,"Map"),Ot=jt(Object,"create");var wt="__lodash_hash_undefined__",Pt=Object.prototype.hasOwnProperty;var St=Object.prototype.hasOwnProperty;var At="__lodash_hash_undefined__";function Nt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Yt}function rr(t){return null!=t&&tr(t.length)&&!ct(t)}var er="object"==typeof t&&t&&!t.nodeType&&t,nr=er&&"object"==typeof module&&module&&!module.nodeType&&module,or=nr&&nr.exports===er?u.Buffer:void 0,ur=(or?or.isBuffer:void 0)||function(){return!1},ir={};ir["[object Float32Array]"]=ir["[object Float64Array]"]=ir["[object Int8Array]"]=ir["[object Int16Array]"]=ir["[object Int32Array]"]=ir["[object Uint8Array]"]=ir["[object Uint8ClampedArray]"]=ir["[object Uint16Array]"]=ir["[object Uint32Array]"]=!0,ir["[object Arguments]"]=ir["[object Array]"]=ir["[object ArrayBuffer]"]=ir["[object Boolean]"]=ir["[object DataView]"]=ir["[object Date]"]=ir["[object Error]"]=ir["[object Function]"]=ir["[object Map]"]=ir["[object Number]"]=ir["[object Object]"]=ir["[object RegExp]"]=ir["[object Set]"]=ir["[object String]"]=ir["[object WeakMap]"]=!1;var ar="object"==typeof t&&t&&!t.nodeType&&t,cr=ar&&"object"==typeof module&&module&&!module.nodeType&&module,fr=cr&&cr.exports===ar&&n.process,sr=function(){try{var t=cr&&cr.require&&cr.require("util").types;return t||fr&&fr.binding&&fr.binding("util")}catch(t){}}(),lr=sr&&sr.isTypedArray,pr=lr?function(t){return function(r){return t(r)}}(lr):function(t){return _(t)&&tr(t.length)&&!!ir[y(t)]};function vr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var dr=Object.prototype.hasOwnProperty;function yr(t,r,e){var n=t[r];dr.call(t,r)&&Y(n,e)&&(void 0!==e||r in t)||Tt(t,r,e)}var hr=9007199254740991,gr=/^(?:0|[1-9]\d*)$/;function br(t,r){var e=typeof t;return!!(r=null==r?hr:r)&&("number"==e||"symbol"!=e&&gr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=Er)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Fr);function Jr(t,r){return Cr(function(t,r,e){return r=zr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=zr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Rr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!nt(e))return!1;var n=typeof r;return!!("number"==n?rr(e)&&br(r,e.length):"string"==n&&r in e)&&Y(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return t.then((function(t){return r(t)}))}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):Mr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=se,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(se(t,r,e,n))},t.createQuery=fe,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(fe(t,r,e))},t.dasherize=function(t){return L(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case Br:return t[Gr];case $r:return[t[Ir],t[Qr]];default:throw new Xr("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Wr(e,r);return n}catch(t){throw new Wr(e,t)}},t.extractSocketPart=Yr,t.formatPayload=ie,t.getCallMethod=function(t){switch(!0){case t===Lr[0]:return Br;case t===Lr[1]:return $r;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=ve,t.getMutationFromPayload=function(t){var r=pe(t,ve);if(!1!==r)return r;throw new Zr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ae,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=le,t.getQueryFromPayload=function(t){var r=pe(t,le);if(!1!==r)return r;throw new Zr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=Yr(t);if(!1===e){if(r)return t;throw new Xr("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=K,t.injectToFn=qr,t.isContract=function(t){return!!function(t){return A(t)&&(Z(t,Br)||Z(t,$r)||Z(t,Dr))}(t)&&t},t.isFunc=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type! Got "+typeof t)},t.isJsonqlErrorObj=de,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==L(t)},t.isObjectHasKey=Z,t.logger=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.DEBUG&&Reflect.apply(console.log,console,t)}catch(t){}},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.objHasProp=Ur,t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=de(t)||u,o[Hr]=te(),o))},t.packResult=function(t,e){void 0===e&&(e=!1);var n={};return n.data=t,e&&r(e)&&(e.push(te()),n[Hr]=e),JSON.stringify(n)},t.preConfigCheck=function(t,r){for(var e=[],n=arguments.length-2;n-- >0;)e[n]=arguments[n+2];var o=Reflect.apply(X,null,e.concat((function(t){return qr(t,Kr,te())})));return function(e){return void 0===e&&(e={}),o(e,t,r)}},t.resultHandler=function(t){return Z(t,"data")&&!Z(t,"error")?t.data:t},t.timestamp=te,t.toArray=W,t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ue,t.urlParams=re,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/main.js b/packages/utils/main.js index 2ae592b7..5a217274 100644 --- a/packages/utils/main.js +++ b/packages/utils/main.js @@ -1,2 +1,2 @@ -"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var fs=_interopDefault(require("fs")),path=require("path"),isArray=Array.isArray,global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(e){var t=hasOwnProperty.call(e,symToStringTag),r=e[symToStringTag];try{e[symToStringTag]=void 0;var n=!0}catch(e){}var o=nativeObjectToString.call(e);return n&&(t?e[symToStringTag]=r:delete e[symToStringTag]),o}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function overArg(e,t){return function(r){return e(t(r))}}var getPrototype=overArg(Object.getPrototypeOf,Object);function isObjectLike(e){return null!=e&&"object"==typeof e}var objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag)return!1;var t=getPrototype(e);if(null===t)return!0;var r=hasOwnProperty$1.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)==objectCtorString}var inArray=function(e,t){return!!e.filter((function(e){return e===t})).length},toArray=function(e){return isArray(e)?e:[e]},parse=function(e){try{return JSON.parse(e)}catch(t){return e}},isObjectHasKey=function(e,t){try{var r=Object.keys(e);return inArray(r,t)}catch(e){return!1}},createEvt=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return e.join("_")},getConfigValue=function(e,t){return t&&isPlainObject(t)&&e in t?t[e]:void 0},toJson=function(e){return"string"==typeof e?parse(e):JSON.parse(JSON.stringify(e))},isNotEmpty=function(e){return void 0!==e&&!1!==e&&null!==e&&""!==trim(e)},chainFns=function(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return t.reduce((function(e,t){return Reflect.apply(t,null,toArray(e))}),Reflect.apply(e,null,r))}};function listCacheClear(){this.__data__=[],this.size=0}function eq(e,t){return e===t||e!=e&&t!=t}function assocIndexOf(e,t){for(var r=e.length;r--;)if(eq(e[r][0],t))return r;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var t=this.__data__,r=assocIndexOf(t,e);return!(r<0)&&(r==t.length-1?t.pop():splice.call(t,r,1),--this.size,!0)}function listCacheGet(e){var t=this.__data__,r=assocIndexOf(t,e);return r<0?void 0:t[r][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,t){var r=this.__data__,n=assocIndexOf(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}function ListCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,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]",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]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(e,t,r){var n=e[t];hasOwnProperty$6.call(e,t)&&eq(n,r)&&(void 0!==r||t in e)||baseAssignValue(e,t,r)}function copyObject(e,t,r,n){var o=!r;r||(r={});for(var a=-1,i=t.length;++a-1&&e%1==0&&e0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,t){return setToString(overRest(e,t,identity),e+"")}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var n=typeof t;return!!("number"==n?isArrayLike(r)&&isIndex(t,r.length):"string"==n&&t in r)&&eq(r[t],e)}function createAssigner(e){return baseRest((function(t,r){var n=-1,o=r.length,a=o>1?r[o-1]:void 0,i=o>2?r[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(r[0],r[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++no?0:o+t),(r=r>o?o:r)<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,t,r)}function baseFindIndex(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a-1;);return r}function charsStartIndex(e,t){for(var r=-1,n=e.length;++r-1;);return r}function asciiToArray(e){return e.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function toString(e){return null==e?"":baseToString(e)}var reTrim=/^\s+|\s+$/g;function trim$1(e,t,r){if((e=toString(e))&&(r||void 0===t))return e.replace(reTrim,"");if(!e||!(t=baseToString(t)))return e;var n=stringToArray(e),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var dasherize=function(e){return trim$1(e).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},urlParams=function(e,t){var r=[];for(var n in t)r.push([n,t[n]].join("="));return[e,r.join("&")].join("?")},cacheBurstUrl=function(e){return urlParams(e,cacheBurst())},cacheBurst=function(){return{_cb:timestamp()}},stringTag$1="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag$1}var toPayload=function(e){return isString(e)?JSON.parse(e):e},formatPayload=function(e){var t;return(t={})[QUERY_ARG_NAME]=e,t};function getNameFromPayload(e){return Object.keys(e)[0]}function createDeliverable(e,t){var r;return(r={})[e]=t,r[TIMESTAMP_PARAM_NAME]=[timestamp()],r}function createQuery(e,t,r){if(void 0===t&&(t=[]),void 0===r&&(r=!1),isString(e)&&isArray(t)){var n=formatPayload(t);return!0===r?n:createDeliverable(e,n)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:t})}function createQueryStr(e,t,r){return void 0===t&&(t=[]),void 0===r&&(r=!1),JSON.stringify(createQuery(e,t,r))}function createMutation(e,t,r,n){void 0===r&&(r={}),void 0===n&&(n=!1);var o={};if(o[PAYLOAD_PARAM_NAME]=t,o[CONDITION_PARAM_NAME]=r,!0===n)return o;if(isString(e))return createDeliverable(e,o);throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:e,payload:t,condition:r})}function createMutationStr(e,t,r,n){return void 0===r&&(r={}),void 0===n&&(n=!1),JSON.stringify(createMutation(e,t,r,n))}function getQueryFromArgs(e,t){var r;if(e&&isPlainObject(t)){var n=t[e];if(n[QUERY_ARG_NAME])return(r={})[RESOLVER_PARAM_NAME]=e,r[QUERY_ARG_NAME]=n[QUERY_ARG_NAME],r[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],r}return!1}function processPayload(e,t){var r=toPayload(e),n=getNameFromPayload(r);return Reflect.apply(t,null,[n,r])}function getQueryFromPayload(e){var t=processPayload(e,getQueryFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",e)}function getMutationFromArgs(e,t){var r;if(e&&isPlainObject(t)){var n=t[e];if(n)return(r={})[RESOLVER_PARAM_NAME]=e,r[PAYLOAD_PARAM_NAME]=n[PAYLOAD_PARAM_NAME],r[CONDITION_PARAM_NAME]=n[CONDITION_PARAM_NAME],r[TIMESTAMP_PARAM_NAME]=t[TIMESTAMP_PARAM_NAME],r}return!1}function getMutationFromPayload(e){var t=processPayload(e,getMutationFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",e)}var getCallMethod=function(e){var t=API_REQUEST_METHODS[0],r=API_REQUEST_METHODS[1];switch(!0){case e===t:return QUERY_NAME;case e===r:return MUTATION_NAME;default:return!1}},packResult=function(e,t){void 0===t&&(t=!1);var r={};return r[DATA_KEY]=e,t&&isArray(t)&&(t.push(timestamp()),r[TIMESTAMP_PARAM_NAME]=t),JSON.stringify(r)},isJsonqlErrorObj=function(e){return!!["detail","className"].filter((function(t){return isObjectHasKey(e,t)})).length&&["className","message","statusCode"].filter((function(t){return isObjectHasKey(e,t)})).map((function(t){var r;return(r={})[t]="object"==typeof e[t]?e[t].toString():e[t],r})).reduce(merge,{detail:e.toString()})},packError=function(e,t,r,n){var o;void 0===t&&(t="JsonqlError"),void 0===r&&(r=0),void 0===n&&(n="");var a={detail:e,className:t,statusCode:r,message:n};return JSON.stringify(((o={})[ERROR_KEY]=isJsonqlErrorObj(e)||a,o[TIMESTAMP_PARAM_NAME]=timestamp(),o))},resultHandler=function(e){return isObjectHasKey(e,DATA_KEY)&&!isObjectHasKey(e,ERROR_KEY)?e[DATA_KEY]:e};function preConfigCheck(e,t){for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];var o=Reflect.apply(chainFns,null,r.concat((function(e){return injectToFn(e,CHECKED_KEY,timestamp())})));return function(r){return void 0===r&&(r={}),o(r,e,t)}}var VERSION="0.9.1",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===e[s-2]?2:"="===e[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,r){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=e[r-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(e,t,r,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=r?o-1:0,h=r?-1:1,p=e[t+l];for(l+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+e[t+l],l+=h,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+e[t+l],l+=h,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(p?-1:1);i+=Math.pow(2,n),a-=f}return(p?-1:1)*i*Math.pow(2,a-n)}function write(e,t,r,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?h/u:h*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;e[r+p]=255&s,p+=g,s/=256,o-=8);for(i=i<0;e[r+p]=255&i,p+=g,i/=256,f-=8);e[r+p-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(e){return"[object Array]"==toString$1.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return base64ToBytes(e).length;default:if(n)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,r);case"utf8":case"utf-8":return utf8Slice(this,t,r);case"ascii":return asciiSlice(this,t,r);case"latin1":case"binary":return latin1Slice(this,t,r);case"base64":return base64Slice(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function swap(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function bidirectionalIndexOf(e,t,r,n,o){if(0===e.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:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,r,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):arrayIndexOf(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,r,n,o){var a,i=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;i=2,s/=2,u/=2,r/=2}function f(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){var c=-1;for(a=r;as&&(r=s-u),a=r;a>=0;a--){for(var l=!0,h=0;ho&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=r)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=e[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=e[o+1],i=e[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=e[o+1],i=e[o+2],s=e[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(e){return e.__proto__=Buffer$2.prototype,e},Buffer$2.from=function(e,t,r){return from(null,e,t,r)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(e,t,r){return alloc(null,e,t,r)},Buffer$2.allocUnsafe=function(e){return allocUnsafe$1(null,e)},Buffer$2.allocUnsafeSlow=function(e){return allocUnsafe$1(null,e)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,a=Math.min(r,n);o0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer$2.prototype.compare=function(e,t,r,n,o){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(r>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=e.slice(t,r),c=0;co)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,e,t,r);case"utf8":case"utf-8":return utf8Write(this,e,t,r);case"ascii":return asciiWrite(this,e,t,r);case"latin1":case"binary":return latin1Write(this,e,t,r);case"base64":return base64Write(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,r,n,o,a){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function objectWriteUInt32(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function checkIEEE754(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function writeFloat(e,t,r,n,o){return o||checkIEEE754(e,t,r,4),write(e,t,r,n,23,4),r+4}function writeDouble(e,t,r,n,o){return o||checkIEEE754(e,t,r,8),write(e,t,r,n,52,8),r+8}Buffer$2.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},Buffer$2.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer$2.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer$2.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer$2.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer$2.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer$2.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=this[e],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=t,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer$2.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer$2.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer$2.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer$2.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+r},Buffer$2.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer$2.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},Buffer$2.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=r-1,i=1,s=0;for(this[t+a]=255&e;--a>=0&&(i*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/i>>0)-s&255;return t+r},Buffer$2.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer$2.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(e,t,r){return writeFloat(this,e,t,!0,r)},Buffer$2.prototype.writeFloatBE=function(e,t,r){return writeFloat(this,e,t,!1,r)},Buffer$2.prototype.writeDoubleLE=function(e,t,r){return writeDouble(this,e,t,!0,r)},Buffer$2.prototype.writeDoubleBE=function(e,t,r){return writeDouble(this,e,t,!1,r)},Buffer$2.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=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),e.length-t=0;--o)e[o+t]=this[o+r];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function asciiToBytes(e){for(var t=[],r=0;r>8,o=r%256,a.push(o),a.push(n);return a}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function isnan(e){return e!=e}function isBuffer$1(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function buff(e,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(e)?e:new Buffer$2.from(e,t)}var replaceErrors=function(e,t){if(t instanceof Error){var r={};return Object.getOwnPropertyNames(t).forEach((function(e){r[e]=t[e]})),r}return t},printError=function(e){return JSON.stringify(e,replaceErrors)};function findFromContract(e,t,r){return!!(r[e]&&r[e][t]&&r[e][t].file&&fs.existsSync(r[e][t].file))&&r[e][t].file}var DOT=".",getDocLen=function(e){return Buffer$2.byteLength(e,"utf8")},headerParser=function(e,t){try{var r=e.headers.accept.split(",");return t?r.filter((function(e){return e===t})):r}catch(e){return[]}},isHeaderPresent=function(e,t){return!!headerParser(e,t).length},getPathToFn=function(e,t,r){var n=r.resolverDir,o=dasherize(e),a=[];r.contract&&r.contract[t]&&r.contract[t].path&&a.push(r.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;so?0:o+t),(r=r>o?o:r)<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,t,r)}function baseFindIndex(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a-1;);return r}function charsStartIndex(e,t){for(var r=-1,n=e.length;++r-1;);return r}function asciiToArray(e){return e.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}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",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",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("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function toString(e){return null==e?"":baseToString(e)}var reTrim=/^\s+|\s+$/g;function trim(e,t,r){if((e=toString(e))&&(r||void 0===t))return e.replace(reTrim,"");if(!e||!(t=baseToString(t)))return e;var n=stringToArray(e),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var inArray=function(e,t){return!!e.filter((function(e){return e===t})).length},toArray=function(e){return isArray(e)?e:[e]},parse=function(e){try{return JSON.parse(e)}catch(t){return e}},isObjectHasKey=function(e,t){try{var r=Object.keys(e);return inArray(r,t)}catch(e){return!1}},createEvt=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return e.join("_")},getConfigValue=function(e,t){return t&&isPlainObject(t)&&e in t?t[e]:void 0},toJson=function(e){return"string"==typeof e?parse(e):JSON.parse(JSON.stringify(e))},isNotEmpty=function(e){return void 0!==e&&!1!==e&&null!==e&&""!==trim(e)},chainFns=function(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return t.reduce((function(e,t){return Reflect.apply(t,null,toArray(e))}),Reflect.apply(e,null,r))}};function listCacheClear(){this.__data__=[],this.size=0}function eq(e,t){return e===t||e!=e&&t!=t}function assocIndexOf(e,t){for(var r=e.length;r--;)if(eq(e[r][0],t))return r;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var t=this.__data__,r=assocIndexOf(t,e);return!(r<0)&&(r==t.length-1?t.pop():splice.call(t,r,1),--this.size,!0)}function listCacheGet(e){var t=this.__data__,r=assocIndexOf(t,e);return r<0?void 0:t[r][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,t){var r=this.__data__,n=assocIndexOf(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}function ListCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,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]",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]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,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]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(e,t,r){var n=e[t];hasOwnProperty$6.call(e,t)&&eq(n,r)&&(void 0!==r||t in e)||baseAssignValue(e,t,r)}function copyObject(e,t,r,n){var o=!r;r||(r={});for(var a=-1,i=t.length;++a-1&&e%1==0&&e0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,t){return setToString(overRest(e,t,identity),e+"")}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var n=typeof t;return!!("number"==n?isArrayLike(r)&&isIndex(t,r.length):"string"==n&&t in r)&&eq(r[t],e)}function createAssigner(e){return baseRest((function(t,r){var n=-1,o=r.length,a=o>1?r[o-1]:void 0,i=o>2?r[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(r[0],r[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++n0;)r[n]=arguments[n+2];var o=Reflect.apply(chainFns,null,r.concat((function(e){return injectToFn(e,CHECKED_KEY,timestamp())})));return function(r){return void 0===r&&(r={}),o(r,e,t)}}var VERSION="0.9.2",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===e[s-2]?2:"="===e[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,r){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=e[r-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(e,t,r,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=r?o-1:0,h=r?-1:1,p=e[t+l];for(l+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+e[t+l],l+=h,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+e[t+l],l+=h,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(p?-1:1);i+=Math.pow(2,n),a-=f}return(p?-1:1)*i*Math.pow(2,a-n)}function write(e,t,r,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?h/u:h*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;e[r+p]=255&s,p+=g,s/=256,o-=8);for(i=i<0;e[r+p]=255&i,p+=g,i/=256,f-=8);e[r+p-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(e){return"[object Array]"==toString$1.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return base64ToBytes(e).length;default:if(n)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,r);case"utf8":case"utf-8":return utf8Slice(this,t,r);case"ascii":return asciiSlice(this,t,r);case"latin1":case"binary":return latin1Slice(this,t,r);case"base64":return base64Slice(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function swap(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function bidirectionalIndexOf(e,t,r,n,o){if(0===e.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:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,r,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):arrayIndexOf(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,r,n,o){var a,i=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;i=2,s/=2,u/=2,r/=2}function f(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){var c=-1;for(a=r;as&&(r=s-u),a=r;a>=0;a--){for(var l=!0,h=0;ho&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=r)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=e[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=e[o+1],i=e[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=e[o+1],i=e[o+2],s=e[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(e){return e.__proto__=Buffer$2.prototype,e},Buffer$2.from=function(e,t,r){return from(null,e,t,r)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(e,t,r){return alloc(null,e,t,r)},Buffer$2.allocUnsafe=function(e){return allocUnsafe$1(null,e)},Buffer$2.allocUnsafeSlow=function(e){return allocUnsafe$1(null,e)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,a=Math.min(r,n);o0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer$2.prototype.compare=function(e,t,r,n,o){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(r>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=e.slice(t,r),c=0;co)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,e,t,r);case"utf8":case"utf-8":return utf8Write(this,e,t,r);case"ascii":return asciiWrite(this,e,t,r);case"latin1":case"binary":return latin1Write(this,e,t,r);case"base64":return base64Write(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,r,n,o,a){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function objectWriteUInt32(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function checkIEEE754(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function writeFloat(e,t,r,n,o){return o||checkIEEE754(e,t,r,4),write(e,t,r,n,23,4),r+4}function writeDouble(e,t,r,n,o){return o||checkIEEE754(e,t,r,8),write(e,t,r,n,52,8),r+8}Buffer$2.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},Buffer$2.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer$2.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer$2.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer$2.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer$2.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer$2.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=this[e],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||checkOffset(e,t,this.length);for(var n=t,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer$2.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Buffer$2.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer$2.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer$2.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer$2.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+r},Buffer$2.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer$2.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},Buffer$2.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);checkInt(this,e,t,r,o-1,-o)}var a=r-1,i=1,s=0;for(this[t+a]=255&e;--a>=0&&(i*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/i>>0)-s&255;return t+r},Buffer$2.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer$2.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(e,t,r){return writeFloat(this,e,t,!0,r)},Buffer$2.prototype.writeFloatBE=function(e,t,r){return writeFloat(this,e,t,!1,r)},Buffer$2.prototype.writeDoubleLE=function(e,t,r){return writeDouble(this,e,t,!0,r)},Buffer$2.prototype.writeDoubleBE=function(e,t,r){return writeDouble(this,e,t,!1,r)},Buffer$2.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=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),e.length-t=0;--o)e[o+t]=this[o+r];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function asciiToBytes(e){for(var t=[],r=0;r>8,o=r%256,a.push(o),a.push(n);return a}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function isnan(e){return e!=e}function isBuffer$1(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function buff(e,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(e)?e:new Buffer$2.from(e,t)}var replaceErrors=function(e,t){if(t instanceof Error){var r={};return Object.getOwnPropertyNames(t).forEach((function(e){r[e]=t[e]})),r}return t},printError=function(e){return JSON.stringify(e,replaceErrors)};function findFromContract(e,t,r){return!!(r[e]&&r[e][t]&&r[e][t].file&&fs.existsSync(r[e][t].file))&&r[e][t].file}var DOT=".",getDocLen=function(e){return Buffer$2.byteLength(e,"utf8")},headerParser=function(e,t){try{var r=e.headers.accept.split(",");return t?r.filter((function(e){return e===t})):r}catch(e){return[]}},isHeaderPresent=function(e,t){return!!headerParser(e,t).length},getPathToFn=function(e,t,r){var n=r.resolverDir,o=dasherize(e),a=[];r.contract&&r.contract[t]&&r.contract[t].path&&a.push(r.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;s { t.truthy(utilFns.groupByNamespace) t.truthy(utilFns.toArray) + + t.false(utilFns.isNotEmpty(' ')) }) -- Gitee From 912c7f2180a3847d633debae3662c7206025e399 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 8 Dec 2019 17:34:51 +0800 Subject: [PATCH 8/8] just add the key for testing --- packages/koa/keys/privateKey.pem | 15 +++++++++++++++ packages/koa/keys/publicKey.pem | 6 ++++++ packages/koa/package.json | 2 +- 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 packages/koa/keys/privateKey.pem create mode 100644 packages/koa/keys/publicKey.pem diff --git a/packages/koa/keys/privateKey.pem b/packages/koa/keys/privateKey.pem new file mode 100644 index 00000000..885aed98 --- /dev/null +++ b/packages/koa/keys/privateKey.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDISseWqVH7QTTuzQ/HQkRMRi3IPEsHJm8gT1RoxD/R3MpWYPFR +14fVE/IXxHZa74XSPxfMfBB8eh+CJu9K9mmgnGhHovgNUMsfshLmvY7dnkepiNE7 +sZsDR63+6BPgogMzHhMxUAcP3AiwPtQz8uKRwroqWMHI1pn2zqKRVLe4+QIDAQAB +AoGAe0OyU6F+5794oSKofDvnJn3mPR4GGq9nop3P1+43TKOyDrj4qyKW4Oa2jjQF +lu9kD0FvFxSfXMwXyhTGHf9Kf0oj0fuMz87EvHRMDAYfGzIz/skqqCcN49viejK8 +09mFtE+GYC8SVKj5qw9J2/pHsUSRTxkeb2hR8CSV8fOx8hUCQQD/dyfMmGsmnou+ +WEjQ4gdYixNzsP7TtmBkS4aBug8QHHsf1L5gQ6ikmuyLa507hAH3WmOx7MNeia2y +xXn8QYdrAkEAyLYR0g1t2qdJQiubZBO8MkGKUFk1NSQSAmatjk/6EAWrJSDuIDH4 +8GOnOKyNbFQ5nG1HTK+1nE9fl+/22BJuKwJAM6UiHaF+n/sTYzKz3c6kD4lmMFBK +5AANspj2I0m6+9XWKlQ2/H0RHd3YDkN+MOb6Ash6OSEVSgppXCfCBnY06wJBAICu +yuojlgUUMBHup2gYhxapkqZFK6nwgGNttWSCvk67c6kQXdvibjqhibr6VonXzkAO +iCIQnZ2j/iQJw/dwiZUCQQDln/vKEmEcnhU+OgmgNb7k8mRhS/2F6j4LCJQ5dMwY +Lnaxh2Zsl93vYSHHm6LG784zN3sPKdGgwGCN/ldWCxo6 +-----END RSA PRIVATE KEY----- diff --git a/packages/koa/keys/publicKey.pem b/packages/koa/keys/publicKey.pem new file mode 100644 index 00000000..30b9e94e --- /dev/null +++ b/packages/koa/keys/publicKey.pem @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDISseWqVH7QTTuzQ/HQkRMRi3I +PEsHJm8gT1RoxD/R3MpWYPFR14fVE/IXxHZa74XSPxfMfBB8eh+CJu9K9mmgnGhH +ovgNUMsfshLmvY7dnkepiNE7sZsDR63+6BPgogMzHhMxUAcP3AiwPtQz8uKRwroq +WMHI1pn2zqKRVLe4+QIDAQAB +-----END PUBLIC KEY----- diff --git a/packages/koa/package.json b/packages/koa/package.json index 34d212b8..59f900f1 100644 --- a/packages/koa/package.json +++ b/packages/koa/package.json @@ -81,7 +81,7 @@ "jsonql-node-client": "^1.2.5", "jsonql-params-validator": "^1.5.0", "jsonql-resolver": "^0.9.11", - "jsonql-utils": "^0.9.1", + "jsonql-utils": "^0.9.2", "jsonql-web-console": "^0.4.4", "koa-compose": "^4.1.0", "lodash": "^4.17.15" -- Gitee