diff --git a/packages/@jsonql/event/src/event-service.ts b/packages/@jsonql/event/src/event-service.ts index 4deb1e6e8db8d3408f15f9e59df24971c5df30c6..4d790a11702e57f9507f0bcc923cd39d2900d639 100644 --- a/packages/@jsonql/event/src/event-service.ts +++ b/packages/@jsonql/event/src/event-service.ts @@ -130,7 +130,7 @@ export default class JsonqlEvent extends JsonqlStoreService { /** * $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 adeed in v1.4.0 + * 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 @@ -274,6 +274,7 @@ export default class JsonqlEvent extends JsonqlStoreService { throw new Error(`${type} is not supported!`) } } + /** * Add $trigger args to the queue during suspend state * @param {array} args from the $trigger call parameters diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js b/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..6a7b7b6c9a58ca04eb822d462b0ebfda86741682 --- /dev/null +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js @@ -0,0 +1,2 @@ +"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var debug$3=_interopDefault(require("debug"));require("fs"),require("path");var WebSocket=_interopDefault(require("ws")),global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},DATA_KEY="data",ERROR_KEY="error",JSONQL_PATH="jsonql",DEFAULT_TYPE="any",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",QUERY_ARG_NAME="args",KEY_WORD="continue",TYPE_KEY="type",OPTIONAL_KEY="optional",ENUM_KEY="enumv",ARGS_KEY="args",CHECKER_KEY="checker",ALIAS_KEY="alias",LOGIN_NAME="login",ISSUER_NAME=LOGIN_NAME,LOGOUT_NAME="logout",OR_SEPERATOR="|",STRING_TYPE="string",BOOLEAN_TYPE="boolean",ARRAY_TYPE="array",OBJECT_TYPE="object",NUMBER_TYPE="number",ARRAY_TYPE_LFT="array.<",ARRAY_TYPE_RGT=">",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,LOGIN_EVENT_NAME="__login__",LOGOUT_EVENT_NAME="__logout__",WS_REPLY_TYPE="__reply__",WS_EVT_NAME="__event__",WS_DATA_NAME="__data__",EMIT_REPLY_TYPE="emit",ACKNOWLEDGE_REPLY_TYPE="acknowledge",ERROR_TYPE="error",NSP_SET="nspSet",PUBLIC_NAMESPACE="publicNamespace",JS_WS_SOCKET_IO_NAME="socket.io",JS_WS_NAME="ws",MESSAGE_PROP_NAME="onMessage",RESULT_PROP_NAME="onResult",ERROR_PROP_NAME="onError",READY_PROP_NAME="onReady",SEND_MSG_PROP_NAME="send",NOT_LOGIN_ERR_MSG="NOT LOGIN",TOKEN_PARAM_NAME="token",SOCKET_IO=JS_WS_SOCKET_IO_NAME,MISSING_PROP_ERR="Missing property in contract!",EXPECT_FUNC_ERR="Expect a function!",EMIT_EVT=EMIT_REPLY_TYPE,UNKNOWN_RESULT="UKNNOWN RESULT!",MY_NAMESPACE="myNamespace";function isNull(e){return null===e}var 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;function arrayMap(e,r){for(var t=-1,n=null==e?0:e.length,o=Array(n);++to?0:o+r),(t=t>o?o:t)<0&&(t+=o),o=r>t?0:t-r>>>0,r>>>=0;for(var a=Array(o);++n=n?e:baseSlice(e,r,t)}function baseFindIndex(e,r,t,n){for(var o=e.length,a=t+(n?1:-1);n?a--:++a-1;);return t}function charsStartIndex(e,r){for(var t=-1,n=e.length;++t-1;);return t}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,r,t){if((e=toString(e))&&(t||void 0===r))return e.replace(reTrim,"");if(!e||!(r=baseToString(r)))return e;var n=stringToArray(e),o=stringToArray(r);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}function isUndefined(e){return void 0===e}var boolTag="[object Boolean]";function isBoolean(e){return!0===e||!1===e||isObjectLike(e)&&baseGetTag(e)==boolTag}var numberTag="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag}function isNaN(e){return isNumber(e)&&e!=+e}var stringTag="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag}function overArg(e,r){return function(t){return e(r(t))}}var getPrototype=overArg(Object.getPrototypeOf,Object),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 r=getPrototype(e);if(null===r)return!0;var t=hasOwnProperty$1.call(r,"constructor")&&r.constructor;return"function"==typeof t&&t instanceof t&&funcToString.call(t)==objectCtorString}function arrayFilter(e,r){for(var t=-1,n=null==e?0:e.length,o=0,a=[];++t-1&&e%1==0&&e-1&&e%1==0&&e<=MAX_SAFE_INTEGER$1}var argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag$1="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag$1="[object Number]",objectTag$1="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag$1="[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(r){return e(r)}}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$1]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag$1]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag$1]=typedArrayTags[weakMapTag]=!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,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$1&&freeModule$1.require&&freeModule$1.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty;function arrayLikeKeys(e,r){var t=isArray(e),n=!t&&isArguments(e),o=!t&&!n&&isBuffer(e),a=!t&&!n&&!o&&isTypedArray(e),i=t||n||o||a,s=i?baseTimes(e.length,String):[],c=s.length;for(var u in e)!r&&!hasOwnProperty$3.call(e,u)||i&&("length"==u||o&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||isIndex(u,c))||s.push(u);return s}var objectProto$5=Object.prototype;function isPrototype(e){var r=e&&e.constructor;return e===("function"==typeof r&&r.prototype||objectProto$5)}var nativeKeys=overArg(Object.keys,Object),objectProto$6=Object.prototype,hasOwnProperty$4=objectProto$6.hasOwnProperty;function baseKeys(e){if(!isPrototype(e))return nativeKeys(e);var r=[];for(var t in Object(e))hasOwnProperty$4.call(e,t)&&"constructor"!=t&&r.push(t);return r}function isObject(e){var r=typeof e;return null!=e&&("object"==r||"function"==r)}var asyncTag="[object AsyncFunction]",funcTag$1="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(e){if(!isObject(e))return!1;var r=baseGetTag(e);return r==funcTag$1||r==genTag||r==asyncTag||r==proxyTag}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function keys(e){return isArrayLike(e)?arrayLikeKeys(e):baseKeys(e)}function baseForOwn(e,r){return e&&baseFor(e,r,keys)}function listCacheClear(){this.__data__=[],this.size=0}function eq(e,r){return e===r||e!=e&&r!=r}function assocIndexOf(e,r){for(var t=e.length;t--;)if(eq(e[t][0],r))return t;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(e){var r=this.__data__,t=assocIndexOf(r,e);return!(t<0)&&(t==r.length-1?r.pop():splice.call(r,t,1),--this.size,!0)}function listCacheGet(e){var r=this.__data__,t=assocIndexOf(r,e);return t<0?void 0:r[t][1]}function listCacheHas(e){return assocIndexOf(this.__data__,e)>-1}function listCacheSet(e,r){var t=this.__data__,n=assocIndexOf(t,e);return n<0?(++this.size,t.push([e,r])):t[n][1]=r,this}function ListCache(e){var r=-1,t=null==e?0:e.length;for(this.clear();++rs))return!1;var u=a.get(e);if(u&&a.get(r))return u==r;var l=-1,f=!0,p=t&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(a.set(e,r),a.set(r,e);++l0){if(++r>=HOT_COUNT)return arguments[0]}else r=0;return e.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(e,r){return setToString(overRest(e,r,identity),e+"")}function isIterateeCall(e,r,t){if(!isObject(t))return!1;var n=typeof r;return!!("number"==n?isArrayLike(t)&&isIndex(r,t.length):"string"==n&&r in t)&&eq(t[r],e)}function createAssigner(e){return baseRest((function(r,t){var n=-1,o=t.length,a=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(t[0],t[1],i)&&(a=o<3?void 0:a,o=1),r=Object(r);++n0))},isArrayLike$1=function(e){if(e.indexOf(ARRAY_TYPE_LFT$1)>-1&&e.indexOf(ARRAY_TYPE_RGT$1)>-1){var r=e.replace(ARRAY_TYPE_LFT$1,"").replace(ARRAY_TYPE_RGT$1,"");return r.indexOf(OR_SEPERATOR$1)?r.split(OR_SEPERATOR$1):[r]}return!1},arrayTypeHandler=function(e,r){var t=e.arg;return r.length>1?!t.filter((function(e){return!(r.length>r.filter((function(r){return!combineFn(r)(e)})).length)})).length:r.length>r.filter((function(e){return!checkIsArray(t,e)})).length},checkIsObject=function(e,r){if(void 0===r&&(r=null),isPlainObject(e)){if(!r)return!0;if(checkIsArray(r))return!r.filter((function(r){var t=e[r.name];return!(r.type.length>r.type.filter((function(e){var r;return!!isUndefined(t)||(!1!==(r=isArrayLike$1(e))?!arrayTypeHandler({arg:t},r):!combineFn(e)(t))})).length)})).length}return!1},objectTypeHandler=function(e){var r=e.arg,t=e.param,n=[r];return Array.isArray(t.keys)&&t.keys.length&&n.push(t.keys),checkIsObject.apply(null,n)},Jsonql406Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 406},t.name.get=function(){return"Jsonql406Error"},Object.defineProperties(r,t),r}(Error),Jsonql500Error=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"Jsonql500Error"},Object.defineProperties(r,t),r}(Error),JsonqlAuthorisationError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(r,t),r}(Error),JsonqlContractAuthError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(r,t),r}(Error),JsonqlResolverAppError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(r,t),r}(Error),isBrowser=function(){try{if(window||document)return!0}catch(e){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(e){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(e){function r(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];e.apply(this,r)}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r.where=function(){return whereAmI()},r}(Error),JsonqlResolverNotFoundError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,Error.captureStackTrace&&Error.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 404},t.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(r,t),r}(JsonqlBaseError),JsonqlEnumError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(r,t),r}(Error),JsonqlTypeError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(r,t),r}(Error),JsonqlCheckerError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,e.captureStackTrace&&e.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(r,t),r}(Error),JsonqlValidationError$1=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,Error.captureStackTrace&&Error.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(r,t),r}(JsonqlBaseError),JsonqlError=function(e){function r(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];e.apply(this,t),this.message=t[0],this.detail=t[1],this.className=r.name,Error.captureStackTrace&&Error.captureStackTrace(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(r,t),r}(JsonqlBaseError),JsonqlServerError=function(e){function r(t,n){e.call(this,n),this.statusCode=t,this.className=r.name}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlServerError"},Object.defineProperties(r,t),r}(Error);function finalCatch(e){if(Array.isArray(e))throw new JsonqlValidationError$1("",e);var r=e.message||NO_ERROR_MSG,t=e.detail||e;switch(!0){case e instanceof Jsonql406Error:throw new Jsonql406Error(r,t);case e instanceof Jsonql500Error:throw new Jsonql500Error(r,t);case e instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(r,t);case e instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(r,t);case e instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(r,t);case e instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(r,t);case e instanceof JsonqlEnumError:throw new JsonqlEnumError(r,t);case e instanceof JsonqlTypeError:throw new JsonqlTypeError(r,t);case e instanceof JsonqlCheckerError:throw new JsonqlCheckerError(r,t);case e instanceof JsonqlValidationError$1:throw new JsonqlValidationError$1(r,t);case e instanceof JsonqlServerError:throw new JsonqlServerError(r,t);default:throw new JsonqlError(r,t)}}function log(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];try{window&&window.console&&Reflect.apply(console.log,console,e)}catch(e){}}var optionalHandler=function(e){var r=e.arg,t=e.param;return!!notEmpty(r)&&!(t.type.length>t.type.filter((function(r){return validateHandler(r,e)})).length)},validateHandler=function(e,r){var t;switch(!0){case e===OBJECT_TYPE$1:return!objectTypeHandler(r);case e===ARRAY_TYPE$1:return!checkIsArray(r.arg);case!1!==(t=isArrayLike$1(e)):return!arrayTypeHandler(r,t);default:return!combineFn(e)(r.arg)}},getOptionalValue=function(e,r){return isUndefined(e)?!0!==r.optional||isUndefined(r.defaultvalue)?null:r.defaultvalue:e},normalizeArgs=function(e,r){if(!checkIsArray(r))throw new JsonqlError(PARAMS_NOT_ARRAY_ERR);if(0===r.length)return[];if(!checkIsArray(e))throw new JsonqlError(ARGS_NOT_ARRAY_ERR);switch(!0){case e.length==r.length:return log(1),e.map((function(e,t){return{arg:e,index:t,param:r[t]}}));case!0===r[0].variable:log(2);var t=r[0].type;return e.map((function(e,n){return{arg:e,index:n,param:r[n]||{type:t,name:"_"}}}));case e.lengthr.length:log(4);var n=r.length,o=[DEFAULT_TYPE$1];return e.map((function(e,t){var a=t>=n||!!r[t].optional,i=r[t]||{type:o,name:"_"+t};return{arg:a?getOptionalValue(e,i):e,index:t,param:i,optional:a}}));default:throw log(5),new JsonqlError(EXCEPTION_CASE_ERR,{args:e,params:r})}},processReturn=function(e){return e.map((function(e){return e.arg}))},validateSync=function(e,r,t){var n;void 0===t&&(t=!1);var o=normalizeArgs(e,r),a=o.filter((function(e){return!0===e.optional||!0===e.param.optional?optionalHandler(e):!(e.param.type.length>e.param.type.filter((function(r){return validateHandler(r,e)})).length)}));return t?((n={})[ERROR_KEY]=a,n[DATA_KEY]=processReturn(o),n):a},validateAsync=function(e,r,t){return void 0===t&&(t=!1),new Promise((function(n,o){var a=validateSync(e,r,t);return t?a[ERROR_KEY].length?o(a[ERROR_KEY]):n(a[DATA_KEY]):a.length?o(a):n([])}))},isInArray=function(e,r){return!!e.filter((function(e){return e===r})).length},isKeyInObject=function(e,r){var t=Object.keys(e);return isInArray(t,r)},isEmpty=function(e){return!notEmpty(e)};function mapAliasConfigKeys(e,r){var t=omitBy(r,(function(e,r){return!e[ALIAS_KEY$1]}));return isEqual(t,{})?e:mapKeys(e,(function(e,r){return findKey(t,(function(e){return e.alias===r}))||r}))}function preservePristineValues(e,r){var t=mapAliasConfigKeys(e,r);return{pristineValues:mapValues(omitBy(r,(function(e,r){return isKeyInObject(t,r)})),(function(e){return e.args})),checkAgainstAppProps:omitBy(r,(function(e,r){return!isKeyInObject(t,r)})),config:t}}function processConfigAction(e,r){return mapValues(r,(function(r,t){var n,o;return isUndefined(e[t])||!0===r[OPTIONAL_KEY$1]&&isEmpty(e[t])?merge({},r,((n={})[KEY_WORD$1]=!0,n)):((o={})[ARGS_KEY$1]=e[t],o[TYPE_KEY$1]=r[TYPE_KEY$1],o[OPTIONAL_KEY$1]=r[OPTIONAL_KEY$1]||!1,o[ENUM_KEY$1]=r[ENUM_KEY$1]||!1,o[CHECKER_KEY$1]=r[CHECKER_KEY$1]||!1,o)}))}function prepareArgsForValidation(e,r){var t=preservePristineValues(e,r),n=t.config,o=t.pristineValues;return[processConfigAction(n,t.checkAgainstAppProps),o]}var toArray=function(e){return checkIsArray(e)?e:[e]},inArray=function(e,r){return!!e.filter((function(e){return e===r})).length};function validateHandler$1(e,r){var t,n=[[e[ARGS_KEY$1]],[(t={},t[TYPE_KEY$1]=toArray(e[TYPE_KEY$1]),t[OPTIONAL_KEY$1]=e[OPTIONAL_KEY$1],t)]];return Reflect.apply(r,null,n)}var enumHandler=function(e,r){return!checkIsArray(r)||inArray(r,e)},checkerHandler=function(e,r){try{return!!isFunction(r)&&r.apply(null,[e])}catch(e){return!1}};function runValidationAction(e){return function(r,t){if(r[KEY_WORD$1])return r[ARGS_KEY$1];var n=validateHandler$1(r,e);if(n.length)throw log("runValidationAction",t,r),new JsonqlTypeError(t,n);if(!1!==r[ENUM_KEY$1]&&!enumHandler(r[ARGS_KEY$1],r[ENUM_KEY$1]))throw log(ENUM_KEY$1,r[ENUM_KEY$1]),new JsonqlEnumError(t);if(!1!==r[CHECKER_KEY$1]&&!checkerHandler(r[ARGS_KEY$1],r[CHECKER_KEY$1]))throw log(CHECKER_KEY$1,r[CHECKER_KEY$1]),new JsonqlCheckerError(t);return r[ARGS_KEY$1]}}function runValidation(e,r){var t=e[0],n=e[1],o=mapValues(t,runValidationAction(r));return merge(o,n)}var configToArgs=function(e,r){return Promise.resolve(prepareArgsForValidation(e,r))};function checkOptionsAsync(e,r,t,n){return void 0===e&&(e={}),configToArgs(e,r).then((function(e){return runValidation(e,n)})).then((function(e){return merge({},e,t)}))}function constructConfigFn(e,r,t,n,o,a){void 0===t&&(t=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=!1);var i={};return i[ARGS_KEY]=e,i[TYPE_KEY]=r,!0===t&&(i[OPTIONAL_KEY]=!0),checkIsArray(n)&&(i[ENUM_KEY]=n),isFunction(o)&&(i[CHECKER_KEY]=o),isString(a)&&(i[ALIAS_KEY]=a),i}var createConfig=function(e,r,t){void 0===t&&(t={});var n=t[OPTIONAL_KEY],o=t[ENUM_KEY],a=t[CHECKER_KEY],i=t[ALIAS_KEY];return constructConfigFn.apply(null,[e,r,n,o,a,i])},checkConfigAsync=function(e){return function(r,t,n){return void 0===n&&(n={}),checkOptionsAsync(r,t,n,e)}},isString$1=checkIsString,validateAsync$1=validateAsync,createConfig$1=createConfig,checkConfigAsync$1=checkConfigAsync(validateSync),isKeyInObject$1=isKeyInObject,inArray$1=function(e,r){return!!e.filter((function(e){return e===r})).length},toArray$1=function(e){return isArray(e)?e:[e]},isKeyInObject$2=function(e,r){var t=Object.keys(e);return inArray$1(t,r)},createEvt=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.join("_")},chainFns=function(e){for(var r=[],t=arguments.length-1;t-- >0;)r[t]=arguments[t+1];return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];return r.reduce((function(e,r){return Reflect.apply(r,null,toArray$1(e))}),Reflect.apply(e,null,t))}};function objDefineProps(e,r,t,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(e,r)&&Object.defineProperty(e,r,{set:t,get:null===n?function(){return null}:n}),e}function injectToFn(e,r,t,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(e,r);return!1===n&&void 0!==o?e:(Object.defineProperty(e,r,{value:t,writable:n}),e)}function checkIsContract(e){return isPlainObject(e)&&(isKeyInObject$2(e,QUERY_NAME)||isKeyInObject$2(e,MUTATION_NAME)||isKeyInObject$2(e,SOCKET_NAME))}function extractSocketPart(e){return!!isKeyInObject$2(e,"socket")&&e.socket}function groupByNamespace(e,r){void 0===r&&(r=!1);var t=extractSocketPart(e);if(!1===t){if(r)return e;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in t){var s=t[i],c=s.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=s,n||s.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(e,r){var t=[];for(var n in e)n===r?t[1]=n:t[0]=n;return t}var formatPayload=function(e){var r;return(r={})[QUERY_ARG_NAME]=e,r};function getNameFromPayload(e){return Object.keys(e)[0]}function createQuery(e,r,t){var n;if(void 0===r&&(r=[]),void 0===t&&(t=!1),isString(e)&&isArray(r)){var o=formatPayload(r);return!0===t?o:((n={})[e]=o,n)}throw new JsonqlValidationError$1("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:r})}function createQueryStr(e,r,t){return void 0===r&&(r=[]),void 0===t&&(t=!1),JSON.stringify(createQuery(e,r,t))}var isContract=checkIsContract,BASE_NAME="jsonql-ws-client",getDebug=function(e){try{if(window.debug)return window.debug(BASE_NAME).extend(e)}catch(e){}try{if(global$1.debug)return global$1.debug(BASE_NAME).extend(e)}catch(e){}return function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];console.info.apply(null,[BASE_NAME,e].concat(r))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",BASE_NAME+"*")}catch(e){}var NB_EVENT_SERVICE_PRIVATE_STORE=new WeakMap,NB_EVENT_SERVICE_PRIVATE_LAZY=new WeakMap;function hashCode(e){return e.split("").reduce((function(e,r){return(e=(e<<5)-e+r.charCodeAt(0))&e}),0)}var SuspendClass=function(){this.__suspend__=null,this.queueStore=new Set},prototypeAccessors={$suspend:{configurable:!0},$queues:{configurable:!0}};prototypeAccessors.$suspend.set=function(e){var r=this;if("boolean"!=typeof e)throw new Error("$suspend only accept Boolean value!");var t=this.__suspend__;this.__suspend__=e,this.logger("($suspend)","Change from "+t+" --\x3e "+e),!0===t&&!1===e&&setTimeout((function(){r.release()}),1)},SuspendClass.prototype.$queue=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",e),this.queueStore.add(e)),this.__suspend__},prototypeAccessors.$queues.get=function(){var e=this.queueStore.size;return this.logger("($queues)","size: "+e),e>0?Array.from(this.queueStore):[]},SuspendClass.prototype.release=function(){var e=this,r=this.queueStore.size;if(this.logger("(release)","Release was called "+r),r>0){var t=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",t),t.forEach((function(r){e.logger(r),Reflect.apply(e.$trigger,e,r)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(SuspendClass.prototype,prototypeAccessors);var NbEventServiceBase=function(e){function r(r){void 0===r&&(r={}),e.call(this),r.logger&&"function"==typeof r.logger&&(this.logger=r.logger),this.keep=r.keep,this.result=r.keep?[]:null,this.normalStore=new Map,this.lazyStore=new Map}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={normalStore:{configurable:!0},lazyStore:{configurable:!0}};return r.prototype.validateEvt=function(){for(var e=this,r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.forEach((function(r){if("string"!=typeof r)throw e.logger("(validateEvt)",r),new Error("event name must be string type!")})),!0},r.prototype.validate=function(e,r){if(this.validateEvt(e)&&"function"==typeof r)return!0;throw new Error("callback required to be function type!")},r.prototype.validateType=function(e){return!!["on","only","once","onlyOnce"].filter((function(r){return e===r})).length},r.prototype.run=function(e,r,t){this.logger("(run)",e,r,t),this.$done=Reflect.apply(e,t,this.toArray(r))},r.prototype.takeFromStore=function(e,r){void 0===r&&(r="lazyStore");var t=this[r];if(t){if(this.logger("(takeFromStore)",r,t),t.has(e)){var n=t.get(e);return this.logger("(takeFromStore)","has "+e,n),t.delete(e),n}return!1}throw new Error(r+" is not supported!")},r.prototype.addToStore=function(e,r){for(var t,n=[],o=arguments.length-2;o-- >0;)n[o]=arguments[o+2];if(e.has(r)?(this.logger("(addToStore)",r+" existed"),t=e.get(r)):(this.logger("(addToStore)","create new Set for "+r),t=new Set),n.length>2)if(Array.isArray(n[0])){var a=n[2];this.checkTypeInLazyStore(r,a)||t.add(n)}else this.checkContentExist(n,t)||(this.logger("(addToStore)","insert new",n),t.add(n));else t.add(n);return e.set(r,t),[e,t.size]},r.prototype.checkContentExist=function(e,r){return!!Array.from(r).filter((function(r){return r[0]===e[0]})).length},r.prototype.checkTypeInStore=function(e,r){this.validateEvt(e,r);var t=this.$get(e,!0);return!1===t||!t.filter((function(e){var t=e[3];return r!==t})).length},r.prototype.checkTypeInLazyStore=function(e,r){this.validateEvt(e,r);var t=this.lazyStore.get(e);return this.logger("(checkTypeInLazyStore)",t),!!t&&!!Array.from(t).filter((function(e){return e[2]!==r})).length},r.prototype.addToNormalStore=function(e,r,t,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",e,r,"try to add to normal store"),this.checkTypeInStore(e,r)){this.logger("(addToNormalStore)",r+" can add to "+e+" normal store");var o=this.hashFnToKey(t),a=[this.normalStore,e,o,t,n,r],i=Reflect.apply(this.addToStore,this,a),s=i[0],c=i[1];return this.normalStore=s,c}return!1},r.prototype.addToLazyStore=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1);var o=[this.lazyStore,e,this.toArray(r),t];n&&o.push(n);var a=Reflect.apply(this.addToStore,this,o),i=a[0],s=a[1];return this.lazyStore=i,s},r.prototype.toArray=function(e){return Array.isArray(e)?e:[e]},t.normalStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_STORE.set(this,e)},t.normalStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)},t.lazyStore.set=function(e){NB_EVENT_SERVICE_PRIVATE_LAZY.set(this,e)},t.lazyStore.get=function(){return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)},r.prototype.hashFnToKey=function(e){return hashCode(e.toString())+""},Object.defineProperties(r.prototype,t),r}(SuspendClass),EventService=function(e){function r(r){void 0===r&&(r={}),e.call(this,r)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var t={$done:{configurable:!0}};return r.prototype.logger=function(){},r.prototype.$on=function(e,r,t){var n=this;void 0===t&&(t=null);this.validate(e,r);var o=this.takeFromStore(e);if(!1===o)return this.logger("($on)",e+" callback is not in lazy store"),this.addToNormalStore(e,"on",r,t);this.logger("($on)",e+" found in lazy store");var a=0;return o.forEach((function(o){var i=o[0],s=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 "+e),n.run(r,i,t||s),a+=n.addToNormalStore(e,"on",r,t||s)})),a},r.prototype.$once=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=this.takeFromStore(e);this.normalStore;if(!1===n)return this.logger("($once)",e+" not in the lazy store"),this.addToNormalStore(e,"once",r,t);this.logger("($once)",n);var o=Array.from(n)[0],a=o[0],i=o[1],s=o[2];if(s&&"once"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);this.logger("($once)","call run for "+e),this.run(r,a,t||i),this.$off(e)},r.prototype.$only=function(e,r,t){var n=this;void 0===t&&(t=null),this.validate(e,r);var o=!1,a=this.takeFromStore(e);(this.normalStore.has(e)||(this.logger("($only)",e+" add to store"),o=this.addToNormalStore(e,"only",r,t)),!1!==a)&&(this.logger("($only)",e+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=o[1],s=o[2];if(s&&"only"!==s)throw new Error("You are trying to register an event already been taken by other type: "+s);n.logger("($only)","call run for "+e),n.run(r,a,t||i)})));return o},r.prototype.$onlyOnce=function(e,r,t){void 0===t&&(t=null),this.validate(e,r);var n=!1,o=this.takeFromStore(e);if(this.normalStore.has(e)||(this.logger("($onlyOnce)",e+" add to store"),n=this.addToNormalStore(e,"onlyOnce",r,t)),!1!==o){this.logger("($onlyOnce)",o);var a=Array.from(o)[0],i=a[0],s=a[1],c=a[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 "+e),this.run(r,i,t||s),this.$off(e)}return n},r.prototype.$replace=function(e,r,t,n){if(void 0===t&&(t=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(e);var o=this["$"+n];return this.logger("($replace)",e,r),Reflect.apply(o,this,[e,r,t])}throw new Error(n+" is not supported!")},r.prototype.$trigger=function(e,r,t,n){void 0===r&&(r=[]),void 0===t&&(t=null),void 0===n&&(n=!1),this.validateEvt(e);var o=0,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(e)){var i=this.$queue(e,r,t,n);if(this.logger("($trigger)",e,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",e,"not executed. Exit now."),!1;for(var s=Array.from(a.get(e)),c=s.length,u=!1,l=0;l-1?r.indexOf("https")>-1?r.replace("https","wss"):r.replace("http","ws"):r};function createWsClient(e,r){return void 0===r&&(r=!1),!1===r?function(r){return new e(fixWss$1(r))}:function(r,t){void 0===t&&(t=!1);var n=fixWss$1(r),o=t&&"string"==typeof t?n+"?"+TOKEN_PARAM_NAME+"="+t:n;try{return new e(o)}catch(e){return console.error("WebSocket Connection Error",e),!1}}}function createNspClient(e,r){var t=r.hostname,n=r.wssPath,o=r.wsOptions;return(0,r.nspClient)(e?[t,e].join("/"):n,o)}function createNspAuthClient(e,r){var t=r.hostname,n=r.wssPath,o=r.token,a=r.wsOptions,i=r.nspAuthClient,s=e?[t,e].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(s,o,a)}function triggerNamespacesOnError(e,r,t){r.forEach((function(r){e.$call(createEvt(r,ERROR_PROP_NAME),[{message:t,namespace:r}])}))}var debugFn$5=getDebug("client-event-handler"),notLoginWsHandler=function(e,r){r.$only(createEvt(e,EMIT_EVT),(function(t,n){debugFn$5("noLoginHandler hijack the ws call",e,t,n);var o={message:NOT_LOGIN_ERR_MSG};r.$call(createEvt(e,t,ERROR_PROP_NAME),[o]),r.$call(createEvt(e,t,RESULT_PROP_NAME),[{error:o}])}))};function clientEventHandler(e,r,t,n,o,a){o.forEach((function(o){if(a[o]){debugFn$5("call bindWsHandler",o);var i=[o,a[o],t];if(e.serverType===SOCKET_IO){var s=r.nspSet;i.push(s[o]),i.push(e)}Reflect.apply(n,null,i)}else notLoginWsHandler(o,t)})),t.$on(LOGOUT_EVENT_NAME,(function(){debugFn$5("LOGOUT_EVENT_NAME"),triggerNamespacesOnError(t,o,LOGOUT_EVENT_NAME),o.forEach((function(e){clearMainEmitEvt(t,e),a[e]=!1,notLoginWsHandler(e,t)}))}))}var keys$1=[WS_REPLY_TYPE,WS_EVT_NAME,WS_DATA_NAME],isWsReply=function(e){var r=e.data;return!!r&&(keys$1.filter((function(e){return isKeyInObject$1(r,e)})).length===keys$1.length&&r)},extractWsPayload=function(e){var r,t=e.data,n=isString$1(t)?JSON.parse(t):t;if(!1!==(r=isWsReply(n)))return{resolverName:r[WS_EVT_NAME],data:r[WS_DATA_NAME],type:r[WS_REPLY_TYPE]};throw new JsonqlError("payload can not be decoded",e)},debugFn$6=getDebug("ws-main-handler"),MESSAGE_PROP_NAME$1=MESSAGE_PROP_NAME,RESULT_PROP_NAME$1=RESULT_PROP_NAME,EMIT_EVT$1=EMIT_EVT,errorTypeHandler=function(e,r,t,n){var o=[r];t&&(debugFn$6("a global error on "+r),o.push(t)),o.push(ERROR_PROP_NAME);var a=Reflect.apply(createEvt,null,o),i=n.data||n;e.$trigger(a,[i])};function wsMainHandler(e,r,t){r.onopen=function(){debugFn$6("ws.onopen listened"),t.$call(READY_PROP_NAME,e),t.$only(createEvt(e,EMIT_EVT$1),(function(e,t){debugFn$6("calling server",e,t),r.send(createQueryStr(e,t))}))},r.onmessage=function(r){try{var n=extractWsPayload(r),o=n.resolverName,a=n.type;switch(debugFn$6("Hear from server",a,n),a){case EMIT_REPLY_TYPE:var i=createEvt(e,o,MESSAGE_PROP_NAME$1),s=t.$trigger(i,[n]);debugFn$6("EMIT_REPLY_TYPE",i,s);break;case ACKNOWLEDGE_REPLY_TYPE:var c=createEvt(e,o,RESULT_PROP_NAME$1);t.$trigger(c,[n]);debugFn$6("ACKNOWLEDGE_REPLY_TYPE",c,n);break;case ERROR_TYPE:debugFn$6("ERROR_TYPE"),errorTypeHandler(t,e,o,n);break;default:debugFn$6("Unhandled event!",n),errorTypeHandler(t,e,o,n)}}catch(r){debug("ws.onmessage error",r),errorTypeHandler(t,e,!1,r)}},r.onclose=function(){debugFn$6("ws.onclose callback")},t.$on(LOGOUT_EVENT_NAME,(function(){try{debugFn$6("terminate ws connection"),r.terminate()}catch(e){console.error("ws.terminate error",e)}}))}var debugFn$7=getDebug("ws-create-client"),createNsps=function(e,r,t){var n=r.nspSet,o=r.publicNamespace,a=!1,i=[],s={};if(e.enableAuth&&e.useJwt)a=!0,s=(i=getNamespaceInOrder(n,o)).map((function(r,n){var o,a,i;return 0===n?t?(e.token=t,(o={})[r]=createNspAuthClient(r,e),o):((a={})[r]=!1,a):((i={})[r]=createNspClient(r,e),i)})).reduce((function(e,r){return Object.assign(e,r)}),{});else{var c=getNameFromPayload(n);i.push(c),s[c]=createNspClient(!1,e)}return{nsps:s,namespaces:i,login:a}};function createClient(e,r,t){var n=[e,r,t,wsMainHandler],o=e.token,a=createNsps(e,r,o),i=a.nsps,s=a.namespaces,c=a.login;return Reflect.apply(clientEventHandler,null,n.concat([s,i])),c&&t.$only(LOGIN_EVENT_NAME,(function(o){clearMainEmitEvt(t,s);var a=createNsps(e,r,o);Reflect.apply(clientEventHandler,null,n.concat([a.namespaces,a.nsps]))})),{opts:e,nspMap:r,ee:t}}function createClientResolver(e){var r=createWsClient(e),t=createWsClient(e,!0);return function(e,n,o){return e.nspClient=r,e.nspAuthClient=t,createClient(e,n,o)}}var wsClientResolver=createClientResolver(WebSocket);global$1.debug=debug$3;var node=wsClient(wsClientResolver,constProps);module.exports=node; +//# sourceMappingURL=jsonql-ws-client.cjs.js.map diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js.map b/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9f5509fa8b00813d0f29f2c3be7ca9f6ae6c59ae --- /dev/null +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonql-ws-client.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..4f8378ffb24ebfc7db08644bb296c59d628d3586 --- /dev/null +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("fs"),require("path")):"function"==typeof define&&define.amd?define(["fs","path"],e):(t=t||self).jsonqlWsClient=e(t.fs,t.path)}(this,(function(t,e){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var r="data",n="error",o="jsonql",a="query",i="mutation",u="socket",c="type",s="optional",f="enumv",l="args",p="checker",h="alias",v="No message",d="__login__",g="__logout__",y="emit",b="acknowledge",_="error",m="nspSet",w="publicNamespace",j="onResult",O="onError",S="onReady",E="token",k="socket.io",$=y,T="UKNNOWN RESULT!";var A="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},P="object"==typeof A&&A&&A.Object===Object&&A,N="object"==typeof self&&self&&self.Object===Object&&self,z=P||N||Function("return this")(),x=z.Symbol;function q(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r=n?t:function(t,e,r){var n=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var a=Array(o);++n-1;);return r}(n,o),function(t,e){for(var r=t.length;r--&&tt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}function gt(t){return void 0===t}var yt="[object Boolean]";var bt="[object Number]";function _t(t){return function(t){return"number"==typeof t||V(t)&&D(t)==bt}(t)&&t!=+t}var mt="[object String]";function wt(t){return"string"==typeof t||!C(t)&&V(t)&&D(t)==mt}function jt(t,e){return function(r){return t(e(r))}}var Ot=jt(Object.getPrototypeOf,Object),St="[object Object]",Et=Function.prototype,kt=Object.prototype,$t=Et.toString,Tt=kt.hasOwnProperty,At=$t.call(Object);function Pt(t){if(!V(t)||D(t)!=St)return!1;var e=Ot(t);if(null===e)return!0;var r=Tt.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&$t.call(r)==At}var Nt,zt=function(t,e,r){for(var n=-1,o=Object(t),a=r(t),i=a.length;i--;){var u=a[Nt?i:++n];if(!1===e(o[u],u,o))break}return t};var xt="[object Arguments]";function qt(t){return V(t)&&D(t)==xt}var Ct=Object.prototype,Rt=Ct.hasOwnProperty,Mt=Ct.propertyIsEnumerable,Ft=qt(function(){return arguments}())?qt:function(t){return V(t)&&Rt.call(t,"callee")&&!Mt.call(t,"callee")};var Wt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Lt=Wt&&"object"==typeof module&&module&&!module.nodeType&&module,Jt=Lt&&Lt.exports===Wt?z.Buffer:void 0,It=(Jt?Jt.isBuffer:void 0)||function(){return!1},Ut=9007199254740991,Dt=/^(?:0|[1-9]\d*)$/;function Vt(t,e){var r=typeof t;return!!(e=null==e?Ut:e)&&("number"==r||"symbol"!=r&&Dt.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=Bt}var Yt={};Yt["[object Float32Array]"]=Yt["[object Float64Array]"]=Yt["[object Int8Array]"]=Yt["[object Int16Array]"]=Yt["[object Int32Array]"]=Yt["[object Uint8Array]"]=Yt["[object Uint8ClampedArray]"]=Yt["[object Uint16Array]"]=Yt["[object Uint32Array]"]=!0,Yt["[object Arguments]"]=Yt["[object Array]"]=Yt["[object ArrayBuffer]"]=Yt["[object Boolean]"]=Yt["[object DataView]"]=Yt["[object Date]"]=Yt["[object Error]"]=Yt["[object Function]"]=Yt["[object Map]"]=Yt["[object Number]"]=Yt["[object Object]"]=Yt["[object RegExp]"]=Yt["[object Set]"]=Yt["[object String]"]=Yt["[object WeakMap]"]=!1;var Gt,Kt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Qt=Kt&&"object"==typeof module&&module&&!module.nodeType&&module,Xt=Qt&&Qt.exports===Kt&&P.process,Zt=function(){try{var t=Qt&&Qt.require&&Qt.require("util").types;return t||Xt&&Xt.binding&&Xt.binding("util")}catch(t){}}(),te=Zt&&Zt.isTypedArray,ee=te?(Gt=te,function(t){return Gt(t)}):function(t){return V(t)&&Ht(t.length)&&!!Yt[D(t)]},re=Object.prototype.hasOwnProperty;function ne(t,e){var r=C(t),n=!r&&Ft(t),o=!r&&!n&&It(t),a=!r&&!n&&!o&&ee(t),i=r||n||o||a,u=i?function(t,e){for(var r=-1,n=Array(t);++r-1},me.prototype.set=function(t,e){var r=this.__data__,n=be(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var we,je=z["__core-js_shared__"],Oe=(we=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||""))?"Symbol(src)_1."+we:"";var Se=Function.prototype.toString;function Ee(t){if(null!=t){try{return Se.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var ke=/^\[object .+?Constructor\]$/,$e=Function.prototype,Te=Object.prototype,Ae=$e.toString,Pe=Te.hasOwnProperty,Ne=RegExp("^"+Ae.call(Pe).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ze(t){return!(!ce(t)||function(t){return!!Oe&&Oe in t}(t))&&(he(t)?Ne:ke).test(Ee(t))}function xe(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return ze(r)?r:void 0}var qe=xe(z,"Map"),Ce=xe(Object,"create");var Re="__lodash_hash_undefined__",Me=Object.prototype.hasOwnProperty;var Fe=Object.prototype.hasOwnProperty;var We="__lodash_hash_undefined__";function Le(t){var e=-1,r=null==t?0:t.length;for(this.clear();++eu))return!1;var s=a.get(t);if(s&&a.get(e))return s==e;var f=-1,l=!0,p=r&Ge?new Be:void 0;for(a.set(t,e),a.set(e,t);++f0){if(++e>=Mn)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Rn);function Jn(t,e){return Ln(function(t,e,r){return e=Cn(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,a=Cn(n.length-e,0),i=Array(a);++o1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(o=In.length>3&&"function"==typeof o?(n--,o):void 0,a&&function(t,e,r){if(!ce(r))return!1;var n=typeof e;return!!("number"==n?ve(r)&&Vt(e,r.length):"string"==n&&e in r)&&ye(r[e],t)}(e[0],e[1],a)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0))},fo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},lo=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!co(e)(t)})).length)})).length:e.length>e.filter((function(t){return!so(r,t)})).length},po=function(t,e){if(void 0===e&&(e=null),Pt(t)){if(!e)return!0;if(so(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return!!gt(r)||(!1!==(e=fo(t))?!lo({arg:r},e):!co(t)(r))})).length)})).length}return!1},ho=function(t){var e=t.arg,r=t.param,n=[e];return Array.isArray(r.keys)&&r.keys.length&&n.push(r.keys),po.apply(null,n)},vo=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 406},r.name.get=function(){return"Jsonql406Error"},Object.defineProperties(e,r),e}(Error),go=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"Jsonql500Error"},Object.defineProperties(e,r),e}(Error),yo=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),bo=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 401},r.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(e,r),e}(Error),_o=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 500},r.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(e,r),e}(Error),mo=function(){try{if(window||document)return!0}catch(t){}return!1},wo=function(){try{if(!mo()&&A)return!0}catch(t){}return!1};var jo=function(t){function e(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.where=function(){return mo()?"browser":wo()?"node":"unknown"},e}(Error),Oo=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,Error.captureStackTrace&&Error.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={statusCode:{configurable:!0},name:{configurable:!0}};return r.statusCode.get=function(){return 404},r.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(e,r),e}(jo),So=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,r),e}(Error),Eo=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,r),e}(Error),ko=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,t.captureStackTrace&&t.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,r),e}(Error),$o=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,Error.captureStackTrace&&Error.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,r),e}(jo),To=function(t){function e(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];t.apply(this,r),this.message=r[0],this.detail=r[1],this.className=e.name,Error.captureStackTrace&&Error.captureStackTrace(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0},statusCode:{configurable:!0}};return r.name.get=function(){return"JsonqlError"},r.statusCode.get=function(){return-1},Object.defineProperties(e,r),e}(jo),Ao=function(t){function e(r,n){t.call(this,n),this.statusCode=r,this.className=e.name}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"JsonqlServerError"},Object.defineProperties(e,r),e}(Error);function Po(t){if(Array.isArray(t))throw new $o("",t);var e=t.message||v,r=t.detail||t;switch(!0){case t instanceof vo:throw new vo(e,r);case t instanceof go:throw new go(e,r);case t instanceof yo:throw new yo(e,r);case t instanceof bo:throw new bo(e,r);case t instanceof _o:throw new _o(e,r);case t instanceof Oo:throw new Oo(e,r);case t instanceof So:throw new So(e,r);case t instanceof Eo:throw new Eo(e,r);case t instanceof ko:throw new ko(e,r);case t instanceof $o:throw new $o(e,r);case t instanceof Ao:throw new Ao(e,r);default:throw new To(e,r)}}function No(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];try{window&&window.console&&Reflect.apply(console.log,console,t)}catch(t){}}var zo=function(t,e){var r;switch(!0){case"object"===t:return!ho(e);case"array"===t:return!so(e.arg);case!1!==(r=fo(t)):return!lo(e,r);default:return!co(t)(e.arg)}},xo=function(t,e){return gt(t)?!0!==e.optional||gt(e.defaultvalue)?null:e.defaultvalue:t},qo=function(t,e,o){var a;void 0===o&&(o=!1);var i=function(t,e){if(!so(e))throw new To("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!so(t))throw new To("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case t.length==e.length:return No(1),t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:No(2);var r=e[0].type;return t.map((function(t,n){return{arg:t,index:n,param:e[n]||{type:r,name:"_"}}}));case t.lengthe.length:No(4);var n=e.length,o=["any"];return t.map((function(t,r){var a=r>=n||!!e[r].optional,i=e[r]||{type:o,name:"_"+r};return{arg:a?xo(t,i):t,index:r,param:i,optional:a}}));default:throw No(5),new To("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),u=i.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!Kn(e)&&!(r.type.length>r.type.filter((function(e){return zo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return zo(e,t)})).length)}));return o?((a={})[n]=u,a[r]=i.map((function(t){return t.arg})),a):u},Co=function(t,e){var r,n=Object.keys(t);return r=e,!!n.filter((function(t){return t===r})).length},Ro=function(t){return!Kn(t)};function Mo(t,e){var r=Gn(e,(function(t,e){return!t[io]}));return Jr(r,{})?t:function(t,e){var r={};return e=vn(e),ge(t,(function(t,n,o){gn(r,e(t,n,o),t)})),r}(t,(function(t,e){return function(t,e,r){var n;return r(t,(function(t,r,o){if(e(t,r,o))return n=r,!1})),n}(r,vn((function(t){return t.alias===e})),ge)||e}))}function Fo(t,e){return Dn(e,(function(e,r){var n,o;return gt(t[r])||!0===e[ro]&&Ro(t[r])?Un({},e,((n={})[uo]=!0,n)):((o={})[oo]=t[r],o[eo]=e[eo],o[ro]=e[ro]||!1,o[no]=e[no]||!1,o[ao]=e[ao]||!1,o)}))}function Wo(t,e){var r=function(t,e){var r=Mo(t,e);return{pristineValues:Dn(Gn(e,(function(t,e){return Co(r,e)})),(function(t){return t.args})),checkAgainstAppProps:Gn(e,(function(t,e){return!Co(r,e)})),config:r}}(t,e),n=r.config,o=r.pristineValues;return[Fo(n,r.checkAgainstAppProps),o]}var Lo=function(t){return so(t)?t:[t]};var Jo=function(t,e){return!so(e)||function(t,e){return!!t.filter((function(t){return t===e})).length}(e,t)},Io=function(t,e){try{return!!he(e)&&e.apply(null,[t])}catch(t){return!1}};function Uo(t){return function(e,r){if(e[uo])return e[oo];var n=function(t,e){var r,n=[[t[oo]],[(r={},r[eo]=Lo(t[eo]),r[ro]=t[ro],r)]];return Reflect.apply(e,null,n)}(e,t);if(n.length)throw No("runValidationAction",r,e),new Eo(r,n);if(!1!==e[no]&&!Jo(e[oo],e[no]))throw No(no,e[no]),new So(r);if(!1!==e[ao]&&!Io(e[oo],e[ao]))throw No(ao,e[ao]),new ko(r);return e[oo]}}var Do=function(t,e){return Promise.resolve(Wo(t,e))};function Vo(t,e,r,n){return void 0===t&&(t={}),Do(t,e).then((function(t){return function(t,e){var r=t[0],n=t[1],o=Dn(r,Uo(e));return Un(o,n)}(t,n)})).then((function(t){return Un({},t,r)}))}function Bo(t,e,r,n,o,a){void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=!1);var i={};return i[l]=t,i[c]=e,!0===r&&(i[s]=!0),so(n)&&(i[f]=n),he(o)&&(i[p]=o),wt(a)&&(i[h]=a),i}var Ho=Xn,Yo=function(t,e,o){return void 0===o&&(o=!1),new Promise((function(a,i){var u=qo(t,e,o);return o?u[n].length?i(u[n]):a(u[r]):u.length?i(u):a([])}))},Go=function(t,e,r){void 0===r&&(r={});var n=r[s],o=r[f],a=r[p],i=r[h];return Bo.apply(null,[t,e,n,o,a,i])},Ko=function(t){return function(e,r,n){return void 0===n&&(n={}),Vo(e,r,n,t)}}(qo),Qo=Co,Xo=function(t){return C(t)?t:[t]},Zo=function(t,e){var r,n=Object.keys(t);return r=e,!!n.filter((function(t){return t===r})).length},ta=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},ea=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];return function(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];return e.reduce((function(t,e){return Reflect.apply(e,null,Xo(t))}),Reflect.apply(t,null,r))}};function ra(t,e,r,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,e)&&Object.defineProperty(t,e,{set:r,get:null===n?function(){return null}:n}),t}function na(t,e,r,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(t,e);return!1===n&&void 0!==o?t:(Object.defineProperty(t,e,{value:r,writable:n}),t)}function oa(t){return!!Zo(t,"socket")&&t.socket}var aa=function(t){var e;return(e={}).args=t,e};function ia(t,e,r){return void 0===e&&(e=[]),void 0===r&&(r=!1),JSON.stringify(function(t,e,r){var n;if(void 0===e&&(e=[]),void 0===r&&(r=!1),wt(t)&&C(e)){var o=aa(e);return!0===r?o:((n={})[t]=o,n)}throw new $o("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e,r))}var ua=function(t){return Pt(t)&&(Zo(t,a)||Zo(t,i)||Zo(t,u))},ca="jsonql-ws-client",sa=function(t){try{if(window.debug)return window.debug(ca).extend(t)}catch(t){}try{if(A.debug)return A.debug(ca).extend(t)}catch(t){}return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];console.info.apply(null,[ca,t].concat(e))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",ca+"*")}catch(t){}var fa=new WeakMap,la=new WeakMap;var pa=function(){this.__suspend__=null,this.queueStore=new Set},ha={$suspend:{configurable:!0},$queues:{configurable:!0}};ha.$suspend.set=function(t){var e=this;if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value!");var r=this.__suspend__;this.__suspend__=t,this.logger("($suspend)","Change from "+r+" --\x3e "+t),!0===r&&!1===t&&setTimeout((function(){e.release()}),1)},pa.prototype.$queue=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return!0===this.__suspend__&&(this.logger("($queue)","added to $queue",t),this.queueStore.add(t)),this.__suspend__},ha.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},pa.prototype.release=function(){var t=this,e=this.queueStore.size;if(this.logger("(release)","Release was called "+e),e>0){var r=Array.from(this.queueStore);this.queueStore.clear(),this.logger("queue",r),r.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}},Object.defineProperties(pa.prototype,ha);var va=function(t){function e(){t.call(this,{logger:sa("nb-event-service")})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={name:{configurable:!0}};return r.name.get=function(){return"jsonql-ws-client"},Object.defineProperties(e.prototype,r),e}(function(t){function e(e){void 0===e&&(e={}),t.call(this,e)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$done:{configurable:!0}};return e.prototype.logger=function(){},e.prototype.$on=function(t,e,r){var n=this;void 0===r&&(r=null);this.validate(t,e);var o=this.takeFromStore(t);if(!1===o)return this.logger("($on)",t+" callback is not in lazy store"),this.addToNormalStore(t,"on",e,r);this.logger("($on)",t+" found in lazy store");var a=0;return o.forEach((function(o){var i=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(e,i,r||u),a+=n.addToNormalStore(t,"on",e,r||u)})),a},e.prototype.$once=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=this.takeFromStore(t);this.normalStore;if(!1===n)return this.logger("($once)",t+" not in the lazy store"),this.addToNormalStore(t,"once",e,r);this.logger("($once)",n);var o=Array.from(n)[0],a=o[0],i=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(e,a,r||i),this.$off(t)},e.prototype.$only=function(t,e,r){var n=this;void 0===r&&(r=null),this.validate(t,e);var o=!1,a=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger("($only)",t+" add to store"),o=this.addToNormalStore(t,"only",e,r)),!1!==a)&&(this.logger("($only)",t+" found data in lazy store to execute"),Array.from(a).forEach((function(o){var a=o[0],i=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(e,a,r||i)})));return o},e.prototype.$onlyOnce=function(t,e,r){void 0===r&&(r=null),this.validate(t,e);var n=!1,o=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger("($onlyOnce)",t+" add to store"),n=this.addToNormalStore(t,"onlyOnce",e,r)),!1!==o){this.logger("($onlyOnce)",o);var a=Array.from(o)[0],i=a[0],u=a[1],c=a[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(e,i,r||u),this.$off(t)}return n},e.prototype.$replace=function(t,e,r,n){if(void 0===r&&(r=null),void 0===n&&(n="on"),this.validateType(n)){this.$off(t);var o=this["$"+n];return this.logger("($replace)",t,e),Reflect.apply(o,this,[t,e,r])}throw new Error(n+" is not supported!")},e.prototype.$trigger=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1),this.validateEvt(t);var o=0,a=this.normalStore;if(this.logger("($trigger)","normalStore",a),a.has(t)){var i=this.$queue(t,e,r,n);if(this.logger("($trigger)",t,"found; add to queue: ",i),!0===i)return this.logger("($trigger)",t,"not executed. Exit now."),!1;for(var u=Array.from(a.get(t)),c=u.length,s=!1,f=0;f0;)n[o]=arguments[o+2];if(t.has(e)?(this.logger("(addToStore)",e+" existed"),r=t.get(e)):(this.logger("(addToStore)","create new Set for "+e),r=new Set),n.length>2)if(Array.isArray(n[0])){var a=n[2];this.checkTypeInLazyStore(e,a)||r.add(n)}else this.checkContentExist(n,r)||(this.logger("(addToStore)","insert new",n),r.add(n));else r.add(n);return t.set(e,r),[t,r.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,n){if(void 0===n&&(n=null),this.logger("(addToNormalStore)",t,e,"try to add to normal store"),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",e+" can add to "+t+" normal store");var o=this.hashFnToKey(r),a=[this.normalStore,t,o,r,n,e],i=Reflect.apply(this.addToStore,this,a),u=i[0],c=i[1];return this.normalStore=u,c}return!1},e.prototype.addToLazyStore=function(t,e,r,n){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===n&&(n=!1);var o=[this.lazyStore,t,this.toArray(e),r];n&&o.push(n);var a=Reflect.apply(this.addToStore,this,o),i=a[0],u=a[1];return this.lazyStore=i,u},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){fa.set(this,t)},r.normalStore.get=function(){return fa.get(this)},r.lazyStore.set=function(t){la.set(this,t)},r.lazyStore.get=function(){return la.get(this)},e.prototype.hashFnToKey=function(t){return t.toString().split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)+""},Object.defineProperties(e.prototype,r),e}(pa))),da=(sa("process-contract"),function(t){var e=oa(t);if(!1!==e)return e;throw new Oo("Missing property in contract!")});function ga(t){var e,r,n=t.contract;return t.enableAuth?function(t,e){void 0===e&&(e=!1);var r=oa(t);if(!1===r){if(e)return t;throw new To("socket not found in contract!")}var n,o={},a=0;for(var i in r){var u=r[i],c=u.namespace;c&&(o[c]||(++a,o[c]={}),o[c][i]=u,n||u.public&&(n=c))}return{size:a,nspSet:o,publicNamespace:n}}(n):((r={})[m]=((e={})[o]=da(n),e),r[w]=o,r)}var ya=function(t,e){return"ws"===e?t.replace("http://","ws://"):t},ba=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}},_a=function(t,e){Xo(e).forEach((function(e){t.$off(ta(e,y))}))},ma=function(t){if("function"==typeof t)return!0;console.error("Expect a function!")},wa=sa("respondHandler");function ja(t,e,o){Zo(t,n)?(wa("-- rejecter called --",t[n]),o(t[n])):Zo(t,r)?(wa("-- resolver called --",t[r]),e(t[r])):(wa("-- UNKNOWN_RESULT --",t),o({message:T,error:t}))}var Oa=sa("action-call");function Sa(t,e,r,n){void 0===n&&(n=[]);var o=ta(e,y);return Oa("actionCall: "+o+" --\x3e "+r,n),t.$trigger(o,[r,Xo(n)]),new Promise((function(n,o){t.$on(ta(e,r,j),(function(t){Oa("got the first result",t),ja(t,n,o)}))}))}var Ea=sa("setup-resolver"),ka=function(t,e,r,n,o){return[na(t,"myNamespace",r),e,r,n,o]},$a=function(t,e,r,n,o){return[ra(t,j,(function(t){ma(t)&&e.$on(ta(r,n,j),(function(o){ja(o,t,(function(t){e.$trigger(ta(r,n,O),t)}))}))})),e,r,n,o]},Ta=function(t,e,r,n,o){return[ra(t,"onMessage",(function(t){if(ma(t)){e.$only(ta(r,n,"onMessage"),(function(o){ja(o,t,(function(t){e.$trigger(ta(r,n,O),t)}))}))}})),e,r,n,o]},Aa=function(t,e,r,n,o){return[ra(t,O,(function(t){ma(t)&&e.$only(ta(r,n,O),t)})),e,r,n,o]},Pa=function(t,e,r,o,a){return ra(t,"send",(function(t){Ea("got payload for",t),Yo(Xo(t),a.params,!0).then((function(a){a[n]&&a[n].length?(Ea("got ERROR_KEY",a[n]),e.$call(ta(r,o,O),[JsonqlValidationError(o,a[n])])):Sa(e,r,o,t)})).catch((function(t){Ea("error after validateAsync",t),e.$call(ta(r,o,O),[JsonqlValidationError(o,t)])}))}))};function Na(t,e,r,n,o){var a=[n,o,t,e,r],i=ea(ka,$a,Ta,Aa,Pa);return Reflect.apply(i,null,a)}var za=sa("resolver-methods");function xa(t,e,r,n){return function(){for(var o=[],a=arguments.length;a--;)o[a]=arguments[a];return Yo(o,n.params,!0).then((function(n){return Sa(t,e,r,n)})).catch(Po)}}var qa;sa("generator");function Ca(t,e,r){var n=e.nspSet;return function(t,e,r){var n={},o=e.nspSet;for(var a in o){var i=o[a];for(var u in i){var c=i[u],s=xa(r,a,u,c);n[u]=Na(a,u,c,s,r)}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}(t,e,r).then((function(t){return function(t,e,r){return ra(t,O,(function(t){if(ma(t))for(var n in r)e.$on(ta(n,O),t)}))}(t,r,n)})).then((function(t){return function(t,e,r){return ra(t,S,(function(t){ma(t)&&e.$on(S,t)}))}(t,r)})).then((function(e){return function(t,e,r){return r.enableAuth&&(t[r.loginHandlerName]=function(t){if(za(r.loginHandlerName,t),t&&Ho(t))return e.$trigger(d,[t]);throw new $o(r.loginHandlerName)},t[r.logoutHandlerName]=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.$trigger(g,t)}),t}(e,r,t)}))}var Ra={loginHandlerName:Go("login",["string"]),logoutHandlerName:Go("logout",["string"]),useJwt:Go(!0,["boolean","string"]),hostname:Go(!1,["string"]),namespace:Go(o,["string"]),wsOptions:Go({},["object"]),contract:Go({},["object"],(qa={},qa[p]=ua,qa)),enableAuth:Go(!1,["boolean"]),token:Go(!1,["string"])},Ma=sa("check-options"),Fa={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""};var Wa={version:"version: 0.4.0 module: umd",serverType:"ws"},La=null;"undefined"!=typeof WebSocket?La=WebSocket:"undefined"!=typeof MozWebSocket?La=MozWebSocket:void 0!==A?La=A.WebSocket||A.MozWebSocket:"undefined"!=typeof window?La=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(La=self.WebSocket||self.MozWebSocket);var Ja=La,Ia=function(t){var e=t.toLowerCase();return e.indexOf("http")>-1?e.indexOf("https")>-1?e.replace("https","wss"):e.replace("http","ws"):e};function Ua(t,e){return void 0===e&&(e=!1),!1===e?function(e){return new t(Ia(e))}:function(e,r){void 0===r&&(r=!1);var n=Ia(e),o=r&&"string"==typeof r?n+"?"+E+"="+r:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}function Da(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions;return(0,e.nspClient)(t?[r,t].join("/"):n,o)}var Va=sa("client-event-handler"),Ba=function(t,e){e.$only(ta(t,$),(function(r,n){Va("noLoginHandler hijack the ws call",t,r,n);var o={message:"NOT LOGIN"};e.$call(ta(t,r,O),[o]),e.$call(ta(t,r,j),[{error:o}])}))};function Ha(t,e,r,n,o,a){o.forEach((function(o){if(a[o]){Va("call bindWsHandler",o);var i=[o,a[o],r];if(t.serverType===k){var u=e.nspSet;i.push(u[o]),i.push(t)}Reflect.apply(n,null,i)}else Ba(o,r)})),r.$on(g,(function(){Va("LOGOUT_EVENT_NAME"),function(t,e,r){e.forEach((function(e){t.$call(ta(e,O),[{message:r,namespace:e}])}))}(r,o,g),o.forEach((function(t){_a(r,t),a[t]=!1,Ba(t,r)}))}))}var Ya=["__reply__","__event__","__data__"],Ga=function(t){var e,r=t.data;if(!1!==(e=function(t){var e=t.data;return!!e&&(Ya.filter((function(t){return Qo(e,t)})).length===Ya.length&&e)}(Ho(r)?JSON.parse(r):r)))return{resolverName:e.__event__,data:e.__data__,type:e.__reply__};throw new To("payload can not be decoded",t)},Ka=sa("ws-main-handler"),Qa="onMessage",Xa=j,Za=$,ti=function(t,e,r,n){var o=[e];r&&(Ka("a global error on "+e),o.push(r)),o.push(O);var a=Reflect.apply(ta,null,o),i=n.data||n;t.$trigger(a,[i])};function ei(t,e,r){e.onopen=function(){Ka("ws.onopen listened"),r.$call(S,t),r.$only(ta(t,Za),(function(t,r){Ka("calling server",t,r),e.send(ia(t,r))}))},e.onmessage=function(e){try{var n=Ga(e),o=n.resolverName,a=n.type;switch(Ka("Hear from server",a,n),a){case y:var i=ta(t,o,Qa),u=r.$trigger(i,[n]);Ka("EMIT_REPLY_TYPE",i,u);break;case b:var c=ta(t,o,Xa);r.$trigger(c,[n]);Ka("ACKNOWLEDGE_REPLY_TYPE",c,n);break;case _:Ka("ERROR_TYPE"),ti(r,t,o,n);break;default:Ka("Unhandled event!",n),ti(r,t,o,n)}}catch(e){debug("ws.onmessage error",e),ti(r,t,!1,e)}},e.onclose=function(){Ka("ws.onclose callback")},r.$on(g,(function(){try{Ka("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}sa("ws-create-client");var ri=function(t,e,r){var n,o=e.nspSet,a=e.publicNamespace,i=!1,u=[],c={};if(t.enableAuth&&t.useJwt)i=!0,c=(u=function(t,e){var r=[];for(var n in t)n===e?r[1]=n:r[0]=n;return r}(o,a)).map((function(e,n){var o,a,i;return 0===n?r?(t.token=r,(o={})[e]=function(t,e){var r=e.hostname,n=e.wssPath,o=e.token,a=e.wsOptions,i=e.nspAuthClient,u=t?[r,t].join("/"):n;if(o&&"string"!=typeof o)throw new Error("Expect token to be string, but got "+o);return i(u,o,a)}(e,t),o):((a={})[e]=!1,a):((i={})[e]=Da(e,t),i)})).reduce((function(t,e){return Object.assign(t,e)}),{});else{var s=(n=o,Object.keys(n)[0]);u.push(s),c[s]=Da(!1,t)}return{nsps:c,namespaces:u,login:i}};return function(t,e){return void 0===e&&(e={}),function(r){var n=r.eventEmitter;return function(t,e){return Ko(t,Ra,Object.assign(Fa,e)).then((function(t){return t.hostname||(t.hostname=ba()),t.wssPath=ya([t.hostname,t.namespace].join("/"),t.serverType),Ma("CONFIGURATION OPTIONS",t),t}))}(r,e).then((function(t){return{opts:t,nspMap:ga(t),ee:n||new va}})).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return Ca(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var e=Ua(t),r=Ua(t,!0);return function(t,n,o){return t.nspClient=e,t.nspAuthClient=r,function(t,e,r){var n=[t,e,r,ei],o=t.token,a=ri(t,e,o),i=a.nsps,u=a.namespaces,c=a.login;return Reflect.apply(Ha,null,n.concat([u,i])),c&&r.$only(d,(function(o){_a(r,u);var a=ri(t,e,o);Reflect.apply(Ha,null,n.concat([a.namespaces,a.nsps]))})),{opts:t,nspMap:e,ee:r}}(t,n,o)}}(Ja),Wa)})); +//# sourceMappingURL=jsonql-ws-client.umd.js.map diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fa3cdb5480f77df620a5aacc62a7bb7cd8935cde --- /dev/null +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonql-ws-client.umd.js","sources":[],"sourcesContent":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/@jsonql/ws/index.js b/packages/@jsonql/ws/index.js index 35ee6a2ac0c4dbbfc7d4b79ce72f389c5d3c86ac..68c405701d3d119481085e80f0776b6bb2fe85b6 100644 --- a/packages/@jsonql/ws/index.js +++ b/packages/@jsonql/ws/index.js @@ -1,2 +1,9 @@ // this is the module entry point for ES6 for client // the main will point to the node.js server side setup +import { jsonqlWsClient } from 'jsonql-ws-client' + +import { constProps } from './src/options' +import wsClientResolver from './src/ws-client-resolver' + +// export back the function and that's it +export default jsonqlWsClient(wsClientResolver, constProps) diff --git a/packages/@jsonql/ws/node.js b/packages/@jsonql/ws/node.js new file mode 100644 index 0000000000000000000000000000000000000000..55eb07439a2a186573e49f5ef6c060f2fb865c89 --- /dev/null +++ b/packages/@jsonql/ws/node.js @@ -0,0 +1,12 @@ +// this is the module entry point for ES6 for client +// Node.js version +import debug from 'debug' +global.debug = debug + +import { jsonqlWsClient } from 'jsonql-ws-client' + +import { constProps } from './src/options' +import wsClientResolver from './src/node-ws-client-resolver' + +// export back the function and that's it +export default jsonqlWsClient(wsClientResolver, constProps) diff --git a/packages/@jsonql/ws/src/client/auth-client.js b/packages/@jsonql/ws/old/client/auth-client.js similarity index 100% rename from packages/@jsonql/ws/src/client/auth-client.js rename to packages/@jsonql/ws/old/client/auth-client.js diff --git a/packages/@jsonql/ws/src/client/ws.js b/packages/@jsonql/ws/old/client/ws.js similarity index 100% rename from packages/@jsonql/ws/src/client/ws.js rename to packages/@jsonql/ws/old/client/ws.js diff --git a/packages/@jsonql/ws/src/server/get-userdata.js b/packages/@jsonql/ws/old/server/get-userdata.js similarity index 100% rename from packages/@jsonql/ws/src/server/get-userdata.js rename to packages/@jsonql/ws/old/server/get-userdata.js diff --git a/packages/@jsonql/ws/src/server/verify-client.js b/packages/@jsonql/ws/old/server/verify-client.js similarity index 100% rename from packages/@jsonql/ws/src/server/verify-client.js rename to packages/@jsonql/ws/old/server/verify-client.js diff --git a/packages/@jsonql/ws/src/ws-client.js b/packages/@jsonql/ws/old/ws-client.js similarity index 100% rename from packages/@jsonql/ws/src/ws-client.js rename to packages/@jsonql/ws/old/ws-client.js diff --git a/packages/@jsonql/ws/src/ws/create-client.js b/packages/@jsonql/ws/old/ws/create-client.js similarity index 100% rename from packages/@jsonql/ws/src/ws/create-client.js rename to packages/@jsonql/ws/old/ws/create-client.js diff --git a/packages/@jsonql/ws/src/ws/extract-ws-payload.js b/packages/@jsonql/ws/old/ws/extract-ws-payload.js similarity index 100% rename from packages/@jsonql/ws/src/ws/extract-ws-payload.js rename to packages/@jsonql/ws/old/ws/extract-ws-payload.js diff --git a/packages/@jsonql/ws/src/ws/index.js b/packages/@jsonql/ws/old/ws/index.js similarity index 100% rename from packages/@jsonql/ws/src/ws/index.js rename to packages/@jsonql/ws/old/ws/index.js diff --git a/packages/@jsonql/ws/src/ws/ws-main-handler.js b/packages/@jsonql/ws/old/ws/ws-main-handler.js similarity index 100% rename from packages/@jsonql/ws/src/ws/ws-main-handler.js rename to packages/@jsonql/ws/old/ws/ws-main-handler.js diff --git a/packages/@jsonql/ws/src/ws/ws.js b/packages/@jsonql/ws/old/ws/ws.js similarity index 100% rename from packages/@jsonql/ws/src/ws/ws.js rename to packages/@jsonql/ws/old/ws/ws.js diff --git a/packages/@jsonql/ws/package.json b/packages/@jsonql/ws/package.json index 5e8577fab72fea2d6ed16e57e5c25d1154082122..afcb4dc9bfce778d2ca338ba1563b6debd3fdcb1 100644 --- a/packages/@jsonql/ws/package.json +++ b/packages/@jsonql/ws/package.json @@ -1,21 +1,28 @@ { "name": "@jsonql/ws", - "version": "0.0.1", - "description": "WS (WebSocket) client / server module for jsonql", - "main": "server.js", - "module": "index.js", + "version": "0.4.0", + "description": "WS (WebSocket) jsonql client module for browser / node", + "main": "dist/jsonql-ws.cjs.js", "browser": "dist/jsonql-ws.umd.js", + "module": "index.js", + "files": [ + "dist", + "src", + "index.js", + "node.js" + ], "scripts": { "test": "ava --verbose", - "test:browser": "DEBUG=jsonql-ws-client*,server-io-core* node ./tests/browser/run-qunit.js", - "test:browser:ws:auth": "DEBUG=jsonql-ws-client* NODE_ENV=ws-auth node ./tests/browser/run-qunit.js", - - "test:jwt:ws": "DEBUG=jsonql-jwt* ava ./tests/ws-handshake.test.js", - - "test:ws": "npm run build:cjs && DEBUG=jsonql-ws-client* ava ./tests/ws-client.test.js", - "test:ws:auth": "npm run build:cjs && DEBUG=jsonql-ws-client*,-jsonql-ws-client:nb-event-service ava ./tests/ws-client-auth.test.js", - "test:ws:login": "npm run build:cjs && DEBUG=jsonql-ws-client*,-jsonql-ws-client:nb-event-service ava ./tests/ws-client-auth-login.test.js", - "test:ws:chain": "npm run build:cjs && DEBUG=jsonql-ws-client*,-jsonql-ws-client:nb-event-service ava --verbose ./tests/ws-client-chain.test.js" + "prepare": "npm run build", + "build:cjs": "TARGET=cjs rollup -c", + "build:umd": "TARGET=umd rollup -c", + "build": "NODE_ENV=production npm run build:cjs && NODE_ENV=production npm run build:umd", + "test:browser:basic": "npm run build:umd && DEBUG=jsonql-ws-client*,server-io-core* node ./tests/browser/run-qunit.js", + "test:browser:auth": "npm run build:umd && DEBUG=jsonql-ws-* NODE_ENV=ws-auth node ./tests/browser/run-qunit.js", + "test:basic": "npm run build:cjs && DEBUG=jsonql-ws-client* ava ./tests/ws-client-basic.test.js", + "test:auth": "npm run build:cjs && DEBUG=jsonql-ws-client*,-jsonql-ws-client:nb-event-service ava ./tests/ws-client-auth.test.js", + "test:login": "npm run build:cjs && DEBUG=jsonql-ws*,-jsonql-ws-client:nb-event-service ava ./tests/ws-client-auth-login.test.js", + "test:chain": "npm run build:cjs && DEBUG=jsonql-ws-client*,-jsonql-ws-client:nb-event-service ava --verbose ./tests/ws-client-chain.test.js" }, "keywords": [ "jsonql", @@ -28,22 +35,33 @@ ], "author": "Joel Chu ", "license": "ISC", - "homepage": "jsonql.js.org", + "homepage": "jsonql.org", + "dependencies": { + "jsonql-constants": "^1.8.5", + "jsonql-errors": "^1.1.3", + "jsonql-jwt": "^1.3.3", + "jsonql-params-validator": "^1.4.11", + "jsonql-utils": "^0.7.8", + "jsonql-ws-client": "^1.0.13", + "ws": "^7.2.0" + }, "devDependencies": { - "ava": "^2.2.0", + "ava": "^2.4.0", + "esm": "^3.2.25", "fs-extra": "^8.1.0", - "glob": "^7.1.4", - "jsonql-contract": "^1.7.7", - "jsonql-koa": "^1.3.7", - "jsonql-ws-server": "^1.2.0", - "koa": "^2.7.0", + "glob": "^7.1.5", + "jsonql-contract": "^1.7.21", + "jsonql-koa": "^1.3.10", + "jsonql-ws-server": "^1.3.4", + "kefir": "^3.8.6", + "koa": "^2.10.0", "koa-bodyparser": "^4.2.1", - "rollup": "^1.19.4", - "rollup-plugin-alias": "^1.5.2", + "rollup": "^1.25.2", + "rollup-plugin-alias": "^2.2.0", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", "rollup-plugin-bundle-size": "^1.0.3", - "rollup-plugin-commonjs": "^10.0.2", + "rollup-plugin-commonjs": "^10.1.0", "rollup-plugin-copy": "^3.1.0", "rollup-plugin-json": "^4.0.0", "rollup-plugin-node-builtins": "^2.1.2", @@ -51,12 +69,9 @@ "rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-replace": "^2.2.0", "rollup-plugin-serve": "^1.0.1", - "rollup-plugin-terser": "^5.1.1", - "rollup-pluginutils": "^2.8.1", - "server-io-core": "^1.2.0", - "sorcery": "^0.10.0", - "ws": "^7.1.2", - "kefir": "^3.8.6" + "rollup-plugin-terser": "^5.1.2", + "rollup-pluginutils": "^2.8.2", + "server-io-core": "^1.2.0" }, "ava": { "files": [ @@ -78,7 +93,6 @@ "engine": { "node": ">=8" }, - "homepage": "jsonql.org", "repository": { "type": "git", "url": "git+ssh://git@gitee.com:to1source/jsonql.git" diff --git a/packages/@jsonql/ws/rollup.config.js b/packages/@jsonql/ws/rollup.config.js index e6d3778e4548c0563e43214e308d055e0a5f7aa2..e41b737c7dc3affa0e0b257038b582c237eab533 100644 --- a/packages/@jsonql/ws/rollup.config.js +++ b/packages/@jsonql/ws/rollup.config.js @@ -21,6 +21,7 @@ import async from 'rollup-plugin-async' import { version } from './package.json' const env = process.env.NODE_ENV +const target = process.env.TARGET let plugins = [ json({ @@ -31,7 +32,7 @@ let plugins = [ transforms: { dangerousForOf: true } }), nodeResolve({ - preferBuiltins: false + }), commonjs({ include: 'node_modules/**' @@ -41,7 +42,7 @@ let plugins = [ async(), replace({ 'process.env.NODE_ENV': JSON.stringify('production'), - '__PLACEHOLDER__': `version: ${version} module: umd` + '__PLACEHOLDER__': `version: ${version} module: ${target}` }) ] @@ -50,14 +51,19 @@ if (process.env.NODE_ENV === 'production') { } plugins.push( size() ) + +const inFile = target === 'cjs' ? 'node.js' : 'index.js' + let config = { - input: join(__dirname, 'index.js'), + input: join(__dirname, inFile), output: { name: 'jsonqlWsClient', - file: join(__dirname, 'dist', 'jsonql-ws-client.js'), - format: 'umd', + file: join(__dirname, 'dist', `jsonql-ws-client.${target}.js`), + format: target, sourcemap: true, globals: { + 'path': 'path', + 'fs': 'fs', 'WebSocket': 'ws', 'socket.io-client': 'io', 'promise-polyfill': 'Promise', @@ -65,6 +71,9 @@ let config = { } }, external: [ + 'path', + 'fs', + 'ws', 'WebSocket', 'socket.io-client', 'io', diff --git a/packages/@jsonql/ws/rollup.config.node.js b/packages/@jsonql/ws/rollup.config.node.js deleted file mode 100644 index d6c593b758db019b29c1b5dbe9de7f6dd7e3c23e..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/rollup.config.node.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Rollup config this will build the main in cjs version - * then we have another interface to import that and pass the createWsClient call to it - */ -import { join } from 'path' -import buble from 'rollup-plugin-buble' - -// import { terser } from "rollup-plugin-terser"; -import replace from 'rollup-plugin-replace' -import commonjs from 'rollup-plugin-commonjs' - -import json from 'rollup-plugin-json' - -import nodeResolve from 'rollup-plugin-node-resolve' -import nodeGlobals from 'rollup-plugin-node-globals' -import builtins from 'rollup-plugin-node-builtins' -import size from 'rollup-plugin-bundle-size' -// support async functions -import async from 'rollup-plugin-async' -// get the version info -import { version } from './package.json' - -const env = process.env.NODE_ENV; - -let plugins = [ - json({ - preferConst: true - }), - buble({ - objectAssign: 'Object.assign', - transforms: { dangerousForOf: true } - }), - nodeResolve({ - preferBuiltins: false - }), - commonjs({ - include: 'node_modules/**' - }), - nodeGlobals(), - builtins(), - async(), - replace({ - 'process.env.NODE_ENV': JSON.stringify('production'), - '__PLACEHOLDER__': `version: ${version} module: cjs` - }), - size() -] - -const basedir = join(__dirname, 'src') -const mainFile = join(basedir, 'main.js') -const testFile = join(__dirname, 'tests', 'fixtures', 'node', 'test.js') -const mainOutFile = join(basedir, 'node', 'main.cjs.js') -const testOutFile = join(__dirname, 'tests', 'fixtures', 'node', 'test.cjs.js') - -const inputFile = env === 'test' ? testFile : mainFile; -const outputFile = env === 'test' ? testOutFile : mainOutFile; - -console.info(`Input: ${inputFile}\r\noutput: ${outputFile}`) - -let config = { - input: inputFile, - output: { - name: 'jsonqlWsNodeClient', - file: outputFile, - format: 'cjs', - sourcemap: false, - globals: { - 'WebSocket': "ws", - 'socket.io-client': 'io', - 'promise-polyfill': 'Promise', - 'debug': 'debug' - } - }, - external: [ - 'WebSocket', - 'socket.io-client', - 'io', - 'debug', - 'Promise', - 'promise-polyfill' - ], - plugins: plugins -} - -export default config; diff --git a/packages/@jsonql/ws/src/core/create-client-resolver.js b/packages/@jsonql/ws/src/core/create-client-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..faa00c634cd207fc4d4edc0571293ed1d82814a3 --- /dev/null +++ b/packages/@jsonql/ws/src/core/create-client-resolver.js @@ -0,0 +1,29 @@ +// share method to create the wsClientResolver + +import { createWsClient } from './create-ws-client' +import { createClient } from './create-client' + +/** + * combine the create client resolver + * @param {object} ws the different WebSocket module + * @return {function} the wsClientResolver + */ +export default function createClientResolver(ws) { + const client = createWsClient(ws) + const authClient = createWsClient(ws, true) + /** + * wsClientResolver + * @param {object} opts configuration + * @param {object} nspMap from the contract + * @param {object} ee instance of the eventEmitter + * @return {object} passing the same 3 input out with additional in the opts + */ + return function(opts, nspMap, ee) { + opts.nspClient = client; + opts.nspAuthClient = authClient; + + // console.log(`contract`, opts.contract) + + return createClient(opts, nspMap, ee) + } +} diff --git a/packages/@jsonql/ws/src/core/create-client.js b/packages/@jsonql/ws/src/core/create-client.js new file mode 100644 index 0000000000000000000000000000000000000000..b354dc4f0e3b71020c1753e7d89fc34b14b96840 --- /dev/null +++ b/packages/@jsonql/ws/src/core/create-client.js @@ -0,0 +1,101 @@ +// actually binding the event client to the socket client +import { getNameFromPayload, getNamespaceInOrder } from 'jsonql-utils/module' +import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants' +import { + createNspClient, + createNspAuthClient, + clientEventHandler, + triggerNamespacesOnError, + clearMainEmitEvt, + disconnect, + getDebug +} from 'jsonql-ws-client/share' +import { wsMainHandler } from './ws-main-handler' + +const debugFn = getDebug('ws-create-client') + +/* +import { + createNspClient, + createNspAuthClient +} from '../../tests/fixtures/create-login-clients' +*/ +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +const createNsps = function(opts, nspMap, token) { + let { nspSet, publicNamespace } = nspMap; + let login = false; + let namespaces = []; + let nsps = {}; + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + login = true; // just saying we need to listen to login event + namespaces = getNamespaceInOrder(nspSet, publicNamespace) + nsps = namespaces.map((namespace, i) => { + if (i === 0) { + if (token) { + opts.token = token; + // console.log('create createNspAuthClient at run time', opts) + return {[namespace]: createNspAuthClient(namespace, opts)} + } + return {[namespace]: false} + } + return {[namespace]: createNspClient(namespace, opts)} + }).reduce((first, next) => Object.assign(first, next), {}) + } else { + let namespace = getNameFromPayload(nspSet) + namespaces.push(namespace) + // standard without login + // the stock version should not have a namespace + nsps[namespace] = createNspClient(false, opts) + } + // return + return { nsps, namespaces, login } +} + +/** + * create a ws client + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +export function createClient(opts, nspMap, ee) { + // arguments that don't change + const args = [opts, nspMap, ee, wsMainHandler] + // now create the nsps + const { token } = opts; + const { nsps, namespaces, login } = createNsps(opts, nspMap, token) + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])) + // setup listener + if (login) { + ee.$only(LOGIN_EVENT_NAME, function loginEventHandler(tokenLater) { + // @BUG this keep causing an "Disconnect call failed TypeError: Cannot read property 'readyState' of null" + // I think that is because it's not login then it can not be disconnect + // how do we track this state globally + // disconnect(nsps, JS_WS_NAME) + + // @TODO should we trigger error on this one? + // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME) + clearMainEmitEvt(ee, namespaces) + // console.log('LOGIN_EVENT_NAME', token) + const newNsps = createNsps(opts, nspMap, tokenLater) + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ) + }) + } + // return what input + return { opts, nspMap, ee } +} diff --git a/packages/@jsonql/ws/src/core/create-ws-client.js b/packages/@jsonql/ws/src/core/create-ws-client.js new file mode 100644 index 0000000000000000000000000000000000000000..a804a0f3ac023620bdb6c2ba2cebbbb0b9f28b8a --- /dev/null +++ b/packages/@jsonql/ws/src/core/create-ws-client.js @@ -0,0 +1,48 @@ +// pass the different type of ws to generate the client +import { TOKEN_PARAM_NAME } from 'jsonql-constants' +/** + * WebSocket is strict about the path, therefore we need to make sure before it goes in + * @param {string} url input url + * @return {string} url with correct path name + */ +const fixWss = url => { + const uri = url.toLowerCase() + if (uri.indexOf('http') > -1) { + if (uri.indexOf('https') > -1) { + return uri.replace('https', 'wss') + } + return uri.replace('http', 'ws') + } + return uri; +} + +/** + * The bug was in the wsOptions where ws doesn't need it but socket.io do + * therefore the object was pass as second parameter! + * @param {object} WebSocket the client or node version of ws + * @param {boolean} auth if it's auth then 3 param or just one + */ +export function createWsClient(WebSocket, auth = false) { + if (auth === false) { + return function createWsClientHandler(url) { + return new WebSocket(fixWss(url)) + } + } + + /** + * Create a client with auth token + * @param {string} url start with ws:// @TODO check this? + * @param {string} [token = false] the jwt token + * @return {object} ws instance + */ + return function createWsAuthClientHandler(url, token = false) { + const ws_url = fixWss(url) + const uri = token && typeof token === 'string' ? `${ws_url}?${TOKEN_PARAM_NAME}=${token}` : ws_url; + try { + return new WebSocket(uri) + } catch(e) { + console.error('WebSocket Connection Error', e) + return false; + } + } +} diff --git a/packages/@jsonql/ws/src/core/extract-ws-payload.js b/packages/@jsonql/ws/src/core/extract-ws-payload.js new file mode 100644 index 0000000000000000000000000000000000000000..e223ed47244aa29080f506f534ecca856f518709 --- /dev/null +++ b/packages/@jsonql/ws/src/core/extract-ws-payload.js @@ -0,0 +1,40 @@ +// take the ws reply data for use +import { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants' +import { isString, isKeyInObject } from 'jsonql-params-validator' +import { JsonqlError, clientErrorsHandler } from 'jsonql-errors' + +const keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ] + +/** + * @param {object} payload should be string when reply but could be transformed + * @return {boolean} true is OK + */ +const isWsReply = payload => { + const { data } = payload; + if (data) { + let result = keys.filter(key => isKeyInObject(data, key)) + return (result.length === keys.length) ? data : false; + } + return false; +} + +/** + * @param {object} payload This is the entire ws Event Object + * @return {object} false on failed + */ +const extractWsPayload = payload => { + const { data } = payload; + let json = isString(data) ? JSON.parse(data) : data; + // debugFn('extractWsPayload', json) + let fdata; + if ((fdata = isWsReply(json)) !== false) { + return { + resolverName: fdata[WS_EVT_NAME], + data: fdata[WS_DATA_NAME], + type: fdata[WS_REPLY_TYPE] + }; + } + throw new JsonqlError('payload can not be decoded', payload) +} +// export it +export default extractWsPayload diff --git a/packages/@jsonql/ws/src/core/ws-main-handler.js b/packages/@jsonql/ws/src/core/ws-main-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..896c679edc987f8ad5439db5a679d17da9aad9b4 --- /dev/null +++ b/packages/@jsonql/ws/src/core/ws-main-handler.js @@ -0,0 +1,120 @@ +// the WebSocket main handler +import { constants, getDebug } from 'jsonql-ws-client/share' +import { + ERROR_PROP_NAME, + LOGIN_EVENT_NAME, + LOGOUT_EVENT_NAME, + ACKNOWLEDGE_REPLY_TYPE, + EMIT_REPLY_TYPE, + ERROR_TYPE, + READY_PROP_NAME +} from 'jsonql-constants' +import { createQueryStr, createEvt } from 'jsonql-utils/module' +import extractWsPayload from './extract-ws-payload' + +const debugFn = getDebug('ws-main-handler') + +const { + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + EMIT_EVT +} = constants + +/** + * under extremely circumstances we might not even have a resolverName, then + * we issue a global error for the developer to catch it + * @param {object} ee event emitter + * @param {string} namespace nsp + * @param {string} resolverName resolver + * @param {object} json decoded payload or error object + */ +const errorTypeHandler = (ee, namespace, resolverName, json) => { + let evt = [namespace] + if (resolverName) { + debugFn(`a global error on ${namespace}`) + evt.push(resolverName) + } + evt.push(ERROR_PROP_NAME) + let evtName = Reflect.apply(createEvt, null, evt) + // test if there is a data field + let payload = json.data || json; + ee.$trigger(evtName, [payload]) +} + +/** + * Binding the even to socket normally + * @param {string} namespace + * @param {object} ws the nsp + * @param {object} ee EventEmitter + * @return {object} promise resolve after the onopen event + */ +export function wsMainHandler(namespace, ws, ee) { + // send + ws.onopen = function onOpenCallback() { + debugFn('ws.onopen listened') + // we just call the onReady + ee.$call(READY_PROP_NAME, namespace) + // add listener only after the open is called + ee.$only( + createEvt(namespace, EMIT_EVT), + function wsMainOnEvtHandler(resolverName, args) { + debugFn('calling server', resolverName, args) + ws.send( + createQueryStr(resolverName, args) + ) + } + ) + } + + // reply + ws.onmessage = function onMessageCallback(payload) { + try { + const json = extractWsPayload(payload) + const { resolverName, type } = json; + debugFn('Hear from server', type, json) + switch (type) { + case EMIT_REPLY_TYPE: + let e1 = createEvt(namespace, resolverName, MESSAGE_PROP_NAME) + let r = ee.$trigger(e1, [json]) + debugFn(`EMIT_REPLY_TYPE`, e1, r) + break; + case ACKNOWLEDGE_REPLY_TYPE: + let e2 = createEvt(namespace, resolverName, RESULT_PROP_NAME) + let x = ee.$trigger(e2, [json]) + debugFn(`ACKNOWLEDGE_REPLY_TYPE`, e2, json) + break; + case ERROR_TYPE: + // this is handled error and we won't throw it + // we need to extract the error from json + debugFn(`ERROR_TYPE`) + errorTypeHandler(ee, namespace, resolverName, json) + break; + // @TODO there should be an error type instead of roll into the other two types? TBC + default: + // if this happen then we should throw it and halt the operation all together + debugFn('Unhandled event!', json) + errorTypeHandler(ee, namespace, resolverName, json) + // let error = {error: {'message': 'Unhandled event!', type}}; + // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) + } + } catch(e) { + debug(`ws.onmessage error`, e) + errorTypeHandler(ee, namespace, false, e) + } + } + // when the server close the connection + ws.onclose = function onCloseCallback() { + debugFn('ws.onclose callback') + // @TODO what to do with this + // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) + } + // listen to the LOGOUT_EVENT_NAME + ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() { + try { + debugFn('terminate ws connection') + ws.terminate() + } catch(e) { + console.error('ws.terminate error', e) + } + }) +} diff --git a/packages/@jsonql/ws/src/core/ws.js b/packages/@jsonql/ws/src/core/ws.js new file mode 100644 index 0000000000000000000000000000000000000000..e3e940897e71e0dfa3d224bd45ee93e0e04b7481 --- /dev/null +++ b/packages/@jsonql/ws/src/core/ws.js @@ -0,0 +1,16 @@ +// this is all the isormophic-ws is +var ws = null + +if (typeof WebSocket !== 'undefined') { + ws = WebSocket +} else if (typeof MozWebSocket !== 'undefined') { + ws = MozWebSocket +} else if (typeof global !== 'undefined') { + ws = global.WebSocket || global.MozWebSocket +} else if (typeof window !== 'undefined') { + ws = window.WebSocket || window.MozWebSocket +} else if (typeof self !== 'undefined') { + ws = self.WebSocket || self.MozWebSocket +} + +export default ws; diff --git a/packages/@jsonql/ws/src/node-ws-client-resolver.js b/packages/@jsonql/ws/src/node-ws-client-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..bda2108d43d7758a4be99b96fa51c240dac00fb3 --- /dev/null +++ b/packages/@jsonql/ws/src/node-ws-client-resolver.js @@ -0,0 +1,13 @@ +// this will be the news style interface that will pass to the jsonql-ws-client +// then return a function for accepting an opts to generate the final +// client api +import WebSocket from 'ws' +import createClientResolver from './core/create-client-resolver' + +/** + * @param {object} opts configuration + * @param {object} nspMap from the contract + * @param {object} ee instance of the eventEmitter + * @return {object} passing the same 3 input out with additional in the opts + */ +export default createClientResolver(WebSocket) diff --git a/packages/@jsonql/ws/src/options/index.js b/packages/@jsonql/ws/src/options/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7df13abc8eccac8eb153cad29ca0f4895d7c2c1a --- /dev/null +++ b/packages/@jsonql/ws/src/options/index.js @@ -0,0 +1,10 @@ +// where all the base options are +// create options +import { JS_WS_NAME } from 'jsonql-constants' +// constant props +const constProps = { + version: '__PLACEHOLDER__', // will get replace + serverType: JS_WS_NAME +} + +export { constProps } diff --git a/packages/@jsonql/ws/src/ws-client-resolver.js b/packages/@jsonql/ws/src/ws-client-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..f41dc96cd0bfa0596ab4d1b81c5e7fc7a5e24ef3 --- /dev/null +++ b/packages/@jsonql/ws/src/ws-client-resolver.js @@ -0,0 +1,13 @@ +// this will be the news style interface that will pass to the jsonql-ws-client +// then return a function for accepting an opts to generate the final +// client api +import WebSocket from './core/ws' +import createClientResolver from './core/create-client-resolver' + +/** + * @param {object} opts configuration + * @param {object} nspMap from the contract + * @param {object} ee instance of the eventEmitter + * @return {object} passing the same 3 input out with additional in the opts + */ +export default createClientResolver(WebSocket) diff --git a/packages/@jsonql/ws/tests/browser/files/auth-test.js b/packages/@jsonql/ws/tests/browser/files/auth-test.js new file mode 100644 index 0000000000000000000000000000000000000000..8a0b41776f75203daeb5bb0dd4374fbc16634f7e --- /dev/null +++ b/packages/@jsonql/ws/tests/browser/files/auth-test.js @@ -0,0 +1,38 @@ +QUnit.test('It should able to connect to the auth enabled server', function(assert) { + var done1 = assert.async() + var token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9lbCIsImlhdCI6MTU3MTkwODg5N30.Cp53a29nuFCKjEqUT8MmO2pAKsUVOHogBLuiGg-WOYetqgW48HvEudpO1KdBnZMzJPQcbdqVHVQlhv720GaYfE33ZOgC6o37LTTrPPKzXgynJ9kTfWI-Mct28teKN7SMKl2rACHn5OBogFkUE1zDB4wADoF77ClgnhehXkv-XlM" + var jclient = jsonqlWsClient({ + hostname: 'http://localhost:8002', + enableAuth: true, + token: token, + contract: authContract + }) + + jclient.then(function(client) { + + client.simple(1) + + client.simple.onResult = function(result) { + console.log('result', 2) + assert.equal(2, result, "Hello world test done") + done1() + } + + client.onReady = function(namespace) { + + console.info('myNamespace', client.simple.myNamespace) + console.info('namespace', namespace) + + if (client.simple.myNamespace === namespace) { + console.info('Logged in') + + assert.equal('jsonql/private', namespace, "Expect the private namespace") + done1() + } + } + }) + .catch(function(error) { + console.error('init error', error) + }) + +}) diff --git a/packages/@jsonql/ws/tests/browser/files/simple-test.js b/packages/@jsonql/ws/tests/browser/files/simple-test.js index 24f733c387a6ff83783c2fb67d9c38b6a73f6c20..f8e1b695a48f4c1dd8d3c3dc4ad0aa44c9c514f2 100644 --- a/packages/@jsonql/ws/tests/browser/files/simple-test.js +++ b/packages/@jsonql/ws/tests/browser/files/simple-test.js @@ -4,7 +4,6 @@ QUnit.test('It should able to use the client to contact the server with static c var jclient = jsonqlWsClient({ hostname: 'http://localhost:8001', - serverType: 'socket.io', contract: contract }).catch(function(error) { console.error('init error', error) diff --git a/packages/@jsonql/ws/tests/browser/run-qunit.js b/packages/@jsonql/ws/tests/browser/run-qunit.js index 5fe81471f349b012c48085df49b24be0f8608879..ebdf925e17efd6988ad58c94b1279035063b430f 100644 --- a/packages/@jsonql/ws/tests/browser/run-qunit.js +++ b/packages/@jsonql/ws/tests/browser/run-qunit.js @@ -4,15 +4,18 @@ const glob = require('glob') const { join, resolve } = require('path') const wsServer = require('jsonql-ws-server') const serverIoCore = require('server-io-core') - +const debug = require('debug')('jsonql-ws-client:test:browser') const baseDir = join(__dirname, 'files') + const appBaseDir = resolve(join(__dirname, '..', 'fixtures')) + const contractDir = join(appBaseDir, 'contract') const resolverDir = join(appBaseDir, 'resolvers') const contractAuthDir = join(contractDir, 'auth') const keysDir = join(appBaseDir, 'keys') -const port = 8001; +const nodeEnv = process.env.NODE_ENV +const port = nodeEnv === 'ws-auth' ? 8002 : 8001 const getConfig = (env) => { let opts = { @@ -21,9 +24,8 @@ const getConfig = (env) => { keysDir, hostname: `ws://localhost:${port}`, } - - let envOpts = {} switch (env) { + /* will use again in socket.io version case 'io': envOpts.serverType = 'socket.io'; break; @@ -37,24 +39,39 @@ const getConfig = (env) => { envOpts.enableAuth = true; envOpts.useJwt = '12345678'; break; + */ case 'ws-auth': - envOpts.enableAuth = true; - envOpts.useJwt = true; - envOpts.serverType = 'ws'; + opts.enableAuth = true; + opts.serverType = 'ws'; break; + case 'ws': default: - envOpts.serverType = 'ws' + opts.serverType = 'ws' break; } - return Object.assign(opts, envOpts) + return opts; } const wsServerSetup = (server) => { - const wss = wsServer(getConfig(process.env.NODE_ENV), server) + const wss = wsServer(getConfig(nodeEnv), server) return wss; // not in use } +/* +files + .map(file => file.replace(__dirname, '')) + .filter(file => { + debug(file) + const f = nodeEnv === 'ws' ? 'simple-test.js' : 'auth-test.js' + return file.indexOf(f) > -1 + }) +*/ +// just hardcode the file +const getInjectFile = (e) => { + return e === 'ws-auth' ? 'auth-test.js' : 'simple-test.js' +} + const runQunit = (open = true) => { return new Promise((resolver, rejecter) => { glob(join(baseDir, '*-test.js'), function(err, files) { @@ -75,13 +92,15 @@ const runQunit = (open = true) => { ], // open: open, // this will interface with jsonql-ws-server - socket:false, + socket: false, reload: false, debugger: false, inject: { insertBefore: false, target: { - body: files.map( file => file.replace(__dirname, '') ) + body: [ + join('files', getInjectFile(nodeEnv)) + ] } } }) diff --git a/packages/@jsonql/ws/tests/browser/webroot/index.html b/packages/@jsonql/ws/tests/browser/webroot/index.html index 4f4f45ecfb89dc744b7ba036db1cc75fec5d9ec8..657ad8382bc3c186339aa83382498f1b4a49416e 100644 --- a/packages/@jsonql/ws/tests/browser/webroot/index.html +++ b/packages/@jsonql/ws/tests/browser/webroot/index.html @@ -3,9 +3,127 @@ - QUnit testing for jsonql-client + QUnit testing for @jsonql/ws + + + - - - + + + diff --git a/packages/@jsonql/ws/tests/fixtures/create-login-clients.js b/packages/@jsonql/ws/tests/fixtures/create-login-clients.js new file mode 100644 index 0000000000000000000000000000000000000000..36fe24ae5acc67090328bebda4b6f2d7e7607876 --- /dev/null +++ b/packages/@jsonql/ws/tests/fixtures/create-login-clients.js @@ -0,0 +1,33 @@ +// just for debugging purposes + +// since both the ws and io version are +// pre-defined in the client-generator +// and this one will have the same parameters +// and the callback is identical +const debugFn = console.info +/** + * wrapper method to create a nsp without login + * @param {string|boolean} namespace namespace url could be false + * @param {object} opts configuration + * @return {object} ws client instance + */ +export function createNspClient(namespace, opts) { + const { wssPath, wsOptions, hostname } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + debugFn('nspClient url', url) + // the wsOptions is the BUG! + return opts.nspClient(url, wsOptions) +} + +/** + * wrapper method to create a nsp with token auth + * @param {string} namespace namespace url + * @param {object} opts configuration + * @return {object} ws client instance + */ +export function createNspAuthClient(namespace, opts) { + const { wssPath, token, wsOptions, hostname } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + debugFn('nspAuthClient url', url) + return opts.nspAuthClient(url, token, wsOptions) +} diff --git a/packages/@jsonql/ws/tests/ws-client-auth-login.test.js b/packages/@jsonql/ws/tests/ws-client-auth-login.test.js index 833dfc4d5f782a0f80944b8157b821cd828a3b6f..e4435b83bccb150e684ed4054b265ca3153e1019 100644 --- a/packages/@jsonql/ws/tests/ws-client-auth-login.test.js +++ b/packages/@jsonql/ws/tests/ws-client-auth-login.test.js @@ -2,8 +2,8 @@ const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') - -const wsClient = require('../main') +// +const wsClient = require('../dist/jsonql-ws-client.cjs') const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') @@ -13,7 +13,9 @@ const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json' const { NOT_LOGIN_ERR_MSG } = require('jsonql-constants') const payload = {name: 'Joel'}; -const debug = require('debug')('jsonql-ws-client:test:ws-auth-login') +const _debug = require('debug') +const debug = _debug('jsonql-ws-client:test:login') +global.debug = _debug; const port = 8003; @@ -23,20 +25,16 @@ test.before(async t => { contract, contractDir, resolverDir: join(__dirname, 'fixtures', 'resolvers'), - serverType: 'ws', enableAuth: true, keysDir: join(__dirname, 'fixtures', 'keys') }) t.context.server = app.listen(port) // without the token t.context.client = await wsClient({ - serverType: 'ws', hostname: `ws://localhost:${port}`, contract: publicContract, - enableAuth: true, - useJwt: true + enableAuth: true }) - }) test.after(t => { @@ -52,22 +50,26 @@ test.after(t => { test.serial.cb('It should able to connect to the ws server public namespace', t => { let ctn = 0; - t.plan(2) + t.plan(3) let client = t.context.client; + client.pinging('Hello') + .then(promiseResult => { + t.is(promiseResult, 'connection established') + }) - client.pinging.onResult= (res) => { + client.pinging.onResult= function testOneOnResultCallback(res) { debug('res', res) t.is(res, 'connection established') client.pinging.send = 'ping'; } // the send is happen after the result return on the server side - client.pinging.onMessage = function(msg) { + client.pinging.onMessage = function testOneOnMessageCallback(msg) { if (msg==='pong') { client.pinging.send = 'pong'; } else { client.pinging.send = 'giving up'; - debug('TEST SHOULD HALT HERE') + debug('TEST ONE SHOULD HALT HERE') t.pass() t.end() } @@ -79,25 +81,44 @@ test.serial.cb('It should trigger the login call here', t => { let client = t.context.client; let ctn = 0; // add onReady and wait for the login to happen - client.onReady = function(namespace) { + client.onReady = function testTwoOnReadyCallback(namespace) { debug('onReady -->', namespace, client.simple.myNamespace) if (namespace === client.simple.myNamespace) { + client.simple(200) - client.simple.onResult = (result) => { - debug('simple onResult pass (3)', result) + /* + .then(result => { + debug(`simple 200 result, TEST SHOULD END HERE!`, result) + t.pass() + t.end() + }) + */ + client.simple.onResult = function simpleOnResultCallback(result) { + debug('simple onResult pass (3) TEST SHOULD END HERE!', result) t.pass() t.end() } } } - + // this will fail because it's not login yet client.simple(100) - client.simple.onError = (error) => { - if (!ctn) { - t.is(NOT_LOGIN_ERR_MSG, error.message, 'pass (2)') - const token = genToken(payload) - client.login(token) - ++ctn; - } + .then(result => { + debug('simple 100 result', result) + }) + .catch(err => { + // @NOTE this is where the Unhandled error happened! + console.error(`client.simple catch`, err) + }) + // catch the error from above then call the login + client.simple.onError = function testTwoOnErrorCallback(error) { + + if (!ctn) { + t.is(NOT_LOGIN_ERR_MSG, error.message, 'pass (2)') + const token = genToken(payload) + debug(`---------------- Try to login with token ---------------------`) + debug(token) + client.login(token) + ++ctn; + } } }) diff --git a/packages/@jsonql/ws/tests/ws-client-auth.test.js b/packages/@jsonql/ws/tests/ws-client-auth.test.js index f7961b2567367108cf5fbf974363b5050d4810e7..211af27e3656ad8e19d2e0f55ced19d56c25f7f9 100644 --- a/packages/@jsonql/ws/tests/ws-client-auth.test.js +++ b/packages/@jsonql/ws/tests/ws-client-auth.test.js @@ -1,7 +1,7 @@ // standard ws client test without auth const test = require('ava') -const wsClient = require('../main') +const wsClient = require('../dist/jsonql-ws-client.cjs') const serverSetup = require('./fixtures/server-setup') const { join } = require('path') @@ -34,11 +34,9 @@ test.before(async t => { t.context.client = await wsClient({ token, - serverType: 'ws', hostname: `ws://localhost:${port}`, contract: publicContract, - enableAuth: true, - useJwt: true + enableAuth: true }) }) diff --git a/packages/@jsonql/ws/tests/ws-client.test.js b/packages/@jsonql/ws/tests/ws-client-basic.test.js similarity index 76% rename from packages/@jsonql/ws/tests/ws-client.test.js rename to packages/@jsonql/ws/tests/ws-client-basic.test.js index 9edcd56c953eb42462cce282219a7d56e5e349a2..92122024203895f74a956e2ed8ca553ff173f1a1 100644 --- a/packages/@jsonql/ws/tests/ws-client.test.js +++ b/packages/@jsonql/ws/tests/ws-client-basic.test.js @@ -1,19 +1,20 @@ // standard ws client test without auth const test = require('ava') -const { JS_WS_NAME } = require('jsonql-constants') -const wsClient = require('../main') -const serverSetup = require('./fixtures/server-setup') - const { join } = require('path') const fsx = require('fs-extra') +const { JS_WS_NAME } = require('jsonql-constants') -const publicContract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract', 'public-contract.json')) -const contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract', 'contract.json')) +const wsClient = require('../dist/jsonql-ws-client.cjs') +const serverSetup = require('./fixtures/server-setup') -const debug = require('debug')('jsonql-ws-client:test:ws') +const contractDir = join(__dirname, 'fixtures', 'contract') +const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) +const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) -const port = 8001; +const debug = require('debug')('jsonql-ws-client:test:basic') +const port = 8001; +// prepare test.before(async t => { const { io, app } = await serverSetup({ contract @@ -22,21 +23,25 @@ test.before(async t => { t.context.client = await wsClient({ hostname: `ws://localhost:${port}`, - serverType: JS_WS_NAME, contract: publicContract }) - }) - +// finish test.after(t => { t.context.server.close() }) - +// start test test.cb('It should able to connect to the ws server', t => { t.plan(2) let client = t.context.client - t.truthy(wsClient.CLIENT_TYPE_INFO) + debug(client) + + let ver = client.devHelpers.getVer() + + debug('version', ver) + + t.truthy(ver) client.simple(100) client.simple.onResult = (result) => { diff --git a/packages/@jsonql/ws/tests/ws-client-chain.test.js b/packages/@jsonql/ws/tests/ws-client-chain.test.js index 612acecc123d9dbd9a76852f33f55adf7726cbaa..252e536b6bdfd4b35bbac6c015d2424cee7b033e 100644 --- a/packages/@jsonql/ws/tests/ws-client-chain.test.js +++ b/packages/@jsonql/ws/tests/ws-client-chain.test.js @@ -2,13 +2,12 @@ const test = require('ava') const { join } = require('path') const fsx = require('fs-extra') +const { chainPromises } = require('jsonql-utils') +const { createWsClient } = require('../src/core/create-ws-client') +const WebSocket = require('ws') -const { - chainPromises, - wsNodeClient, - wsNodeAuthClient -} = require('jsonql-jwt') - +const wsNodeAuthClient = createWsClient(WebSocket, true) +const wsNodeClient = createWsClient(WebSocket) const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') @@ -24,7 +23,7 @@ const token = genToken(payload) const debug = require('debug')('jsonql-ws-client:test:ws-client-chain') -const port = 8009; +const port = 8004; test.before(async t => { const { io, app } = await serverSetup({ @@ -35,6 +34,7 @@ test.before(async t => { enableAuth: true, keysDir: join(__dirname, 'fixtures', 'keys') }) + t.context.server = app.listen(port) let baseUrl = `ws://localhost:${port}`; @@ -60,18 +60,21 @@ test.serial.cb('First test the connection individually', t => { }) // @BUG whenever I wrap this code in the promise the ws just hang up +// @TODO The bug still here after we port it over test.serial.cb.skip('Try to create a promise based ws client and using the chainPromises method to login', t => { t.plan(1) let p1 = () => ( new Promise((resolver, rejecter) => { let ws1 = wsNodeAuthClient(nsp1url, token) + /* let timer; setTimeout(() => { rejecter() }, 5000) + */ ws1.onopen = () => { - clearTimeout(timer) + // clearTimeout(timer) resolver(ws1) } }) @@ -79,12 +82,13 @@ test.serial.cb.skip('Try to create a promise based ws client and using the chain let p2 = () => ( new Promise((resolver, rejecter) => { let ws2 = wsNodeClient(nsp2url) + /* let timer; setTimeout(() => { rejecter() - }, 5000) + }, 5000) */ ws2.onopen = () => { - clearTimeout(timer) + // clearTimeout(timer) resolver(ws2) } }) diff --git a/packages/constants/README.md b/packages/constants/README.md index a057240a5d7649c85104853d31b3c431c94f63c4..0b97a829779bd22fef518f6be1cafcc921484536 100755 --- a/packages/constants/README.md +++ b/packages/constants/README.md @@ -107,6 +107,7 @@ non-javascript to develop your tool. You can also use the included `constants.js - RESULT_PROP_NAME - ERROR_PROP_NAME - READY_PROP_NAME +- LOGGIN_PROP_NAME - SEND_MSG_PROP_NAME - CLIENT_PROP_NAME - USERDATA_PROP_NAME diff --git a/packages/constants/constants.json b/packages/constants/constants.json index 0b7ec2cc3e2c17f1b4d6bfb21fe252321fc6b28b..69fdc21804e8ce1fdcfe7a62c4ea73aa1bd17dc4 100644 --- a/packages/constants/constants.json +++ b/packages/constants/constants.json @@ -139,6 +139,7 @@ "RESULT_PROP_NAME": "onResult", "ERROR_PROP_NAME": "onError", "READY_PROP_NAME": "onReady", + "LOGGIN_PROP_NAME": "onLogin", "SEND_MSG_PROP_NAME": "send", "CLIENT_PROP_NAME": "client", "USERDATA_PROP_NAME": "userdata", diff --git a/packages/constants/main.js b/packages/constants/main.js index 80870bf69a541afe6af9457432b1e819bb483777..eab245df056ae3eede843c1c354a30f4bf88d6ca 100644 --- a/packages/constants/main.js +++ b/packages/constants/main.js @@ -139,6 +139,7 @@ module.exports = { "RESULT_PROP_NAME": "onResult", "ERROR_PROP_NAME": "onError", "READY_PROP_NAME": "onReady", + "LOGGIN_PROP_NAME": "onLogin", "SEND_MSG_PROP_NAME": "send", "CLIENT_PROP_NAME": "client", "USERDATA_PROP_NAME": "userdata", diff --git a/packages/constants/module.js b/packages/constants/module.js index eec341bc15467aa6ad9c7b001c46221c24e8b993..9d0a26658da4d0ef0bc4e42fd0825801e08d7c61 100644 --- a/packages/constants/module.js +++ b/packages/constants/module.js @@ -144,6 +144,7 @@ export const MESSAGE_PROP_NAME = 'onMessage'; export const RESULT_PROP_NAME = 'onResult'; export const ERROR_PROP_NAME = 'onError'; export const READY_PROP_NAME = 'onReady'; +export const LOGGIN_PROP_NAME = 'onLogin'; // new @1.8.6 export const SEND_MSG_PROP_NAME = 'send'; // this one is for nodeClient inject into the resolver export const CLIENT_PROP_NAME = 'client'; diff --git a/packages/constants/package.json b/packages/constants/package.json index 97722c909d04faa8c99a90bf49c946efd59a6c0d..3670bd1d92db37ee2c1a02982ea8e573e236e2fe 100755 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-constants", - "version": "1.8.5", + "version": "1.8.6", "description": "All the share constants for json:ql tools", "main": "main.js", "module": "module.js", diff --git a/packages/utils/browser.js b/packages/utils/browser.js index 1594f3085fa33c8c29f504a88261aa764d1eea25..853012b365048b8a6f1eaf2d70de337c4a85175b 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,b,g=(h=Object.getPrototypeOf,b=Object,function(t){return h(b(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=g(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 E=1/0,k=i?i.prototype:void 0,z=k?k.toString:void 0;function F(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="[object String]";function W(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==K}function Z(t,r){return t===r||t!=t&&r!=r}function X(t,r){for(var e=t.length;e--;)if(Z(t[e][0],r))return e;return-1}var Y=Array.prototype.splice;function tt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},tt.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 et="[object AsyncFunction]",nt="[object Function]",ot="[object GeneratorFunction]",ut="[object Proxy]";function it(t){if(!rt(t))return!1;var r=y(t);return r==nt||r==ot||r==et||r==ut}var at,ct=u["__core-js_shared__"],ft=(at=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var st=Function.prototype.toString;var lt=/^\[object .+?Constructor\]$/,pt=Function.prototype,vt=Object.prototype,dt=pt.toString,yt=vt.hasOwnProperty,ht=RegExp("^"+dt.call(yt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function bt(t){return!(!rt(t)||function(t){return!!ft&&ft in t}(t))&&(it(t)?ht:lt).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function gt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return bt(e)?e:void 0}var _t=gt(u,"Map"),jt=gt(Object,"create");var mt="__lodash_hash_undefined__",Ot=Object.prototype.hasOwnProperty;var wt=Object.prototype.hasOwnProperty;var Pt="__lodash_hash_undefined__";function St(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Zt}function Yt(t){return null!=t&&Xt(t.length)&&!it(t)}var tr="object"==typeof t&&t&&!t.nodeType&&t,rr=tr&&"object"==typeof module&&module&&!module.nodeType&&module,er=rr&&rr.exports===tr?u.Buffer:void 0,nr=(er?er.isBuffer:void 0)||function(){return!1},or={};or["[object Float32Array]"]=or["[object Float64Array]"]=or["[object Int8Array]"]=or["[object Int16Array]"]=or["[object Int32Array]"]=or["[object Uint8Array]"]=or["[object Uint8ClampedArray]"]=or["[object Uint16Array]"]=or["[object Uint32Array]"]=!0,or["[object Arguments]"]=or["[object Array]"]=or["[object ArrayBuffer]"]=or["[object Boolean]"]=or["[object DataView]"]=or["[object Date]"]=or["[object Error]"]=or["[object Function]"]=or["[object Map]"]=or["[object Number]"]=or["[object Object]"]=or["[object RegExp]"]=or["[object Set]"]=or["[object String]"]=or["[object WeakMap]"]=!1;var ur="object"==typeof t&&t&&!t.nodeType&&t,ir=ur&&"object"==typeof module&&module&&!module.nodeType&&module,ar=ir&&ir.exports===ur&&n.process,cr=function(){try{var t=ir&&ir.require&&ir.require("util").types;return t||ar&&ar.binding&&ar.binding("util")}catch(t){}}(),fr=cr&&cr.isTypedArray,sr=fr?function(t){return function(r){return t(r)}}(fr):function(t){return _(t)&&Xt(t.length)&&!!or[y(t)]};function lr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var pr=Object.prototype.hasOwnProperty;function vr(t,r,e){var n=t[r];pr.call(t,r)&&Z(n,e)&&(void 0!==e||r in t)||Ft(t,r,e)}var dr=9007199254740991,yr=/^(?:0|[1-9]\d*)$/;function hr(t,r){var e=typeof t;return!!(r=null==r?dr:r)&&("number"==e||"symbol"!=e&&yr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=kr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Er);function Tr(t,r){return xr(function(t,r,e){return r=Nr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Nr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Cr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!rt(e))return!1;var n=typeof r;return!!("number"==n?Yt(e)&&hr(r,e.length):"string"==n&&r in e)&&Z(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 Reflect.apply(r,null,[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]):Jr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.checkIsContract=re,t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=ae,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(ae(t,r,e,n))},t.createQuery=ie,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(ie(t,r,e))},t.dasherize=function(t){return H(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case $r:return t[Gr];case Br:return[t[Qr],t[Vr]];default:throw new te("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Xr(e,r);return n}catch(t){throw new Xr(e,t)}},t.extractSocketPart=ee,t.formatPayload=oe,t.getCallMethod=function(t){switch(!0){case t===Hr[0]:return $r;case t===Hr[1]:return Br;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=se,t.getMutationFromPayload=function(t){var r=fe(t,se);if(!1!==r)return r;throw new Yr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ue,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=ce,t.getQueryFromPayload=function(t){var r=fe(t,ce);if(!1!==r)return r;throw new Yr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=ee(t);if(!1===e){if(r)return t;throw new te("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=Mr,t.injectToFn=function(t,r,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)},t.isContract=pe,t.isJsonqlErrorObj=le,t.isKeyInObject=Rr,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==H(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.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=le(t)||u,o))},t.packResult=function(t){var r;return JSON.stringify(((r={}).data=t,r))},t.resultHandler=function(t){return Rr(t,"data")&&!Rr(t,"error")?t.data:t},t.timestamp=Ur,t.toArray=function(t){return r(t)?t:[t]},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=ne,t.urlParams=qr,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,b,g=(h=Object.getPrototypeOf,b=Object,function(t){return h(b(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=g(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 E=1/0,k=i?i.prototype:void 0,z=k?k.toString:void 0;function F(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){var e=Object.keys(t);return K(e,r)},X=function(t){void 0===t&&(t=!1);var r=Date.now();return t?Math.floor(r/1e3):r},Y=function(t,r){var e=[];for(var n in r)e.push([n,r[n]].join("="));return[t,e.join("&")].join("?")},tt=function(){return{_cb:X()}};function rt(t,r){return t===r||t!=t&&r!=r}function et(t,r){for(var e=t.length;e--;)if(rt(t[e][0],r))return e;return-1}var nt=Array.prototype.splice;function ot(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},ot.prototype.set=function(t,r){var e=this.__data__,n=et(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var it="[object AsyncFunction]",at="[object Function]",ct="[object GeneratorFunction]",ft="[object Proxy]";function st(t){if(!ut(t))return!1;var r=y(t);return r==at||r==ct||r==it||r==ft}var lt,pt=u["__core-js_shared__"],vt=(lt=/[^.]+$/.exec(pt&&pt.keys&&pt.keys.IE_PROTO||""))?"Symbol(src)_1."+lt:"";var dt=Function.prototype.toString;var yt=/^\[object .+?Constructor\]$/,ht=Function.prototype,bt=Object.prototype,gt=ht.toString,_t=bt.hasOwnProperty,jt=RegExp("^"+gt.call(_t).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function mt(t){return!(!ut(t)||function(t){return!!vt&&vt in t}(t))&&(st(t)?jt:yt).test(function(t){if(null!=t){try{return dt.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function Ot(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return mt(e)?e:void 0}var wt=Ot(u,"Map"),Pt=Ot(Object,"create");var St="__lodash_hash_undefined__",At=Object.prototype.hasOwnProperty;var Nt=Object.prototype.hasOwnProperty;var Et="__lodash_hash_undefined__";function kt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=rr}function nr(t){return null!=t&&er(t.length)&&!st(t)}var or="object"==typeof t&&t&&!t.nodeType&&t,ur=or&&"object"==typeof module&&module&&!module.nodeType&&module,ir=ur&&ur.exports===or?u.Buffer:void 0,ar=(ir?ir.isBuffer:void 0)||function(){return!1},cr={};cr["[object Float32Array]"]=cr["[object Float64Array]"]=cr["[object Int8Array]"]=cr["[object Int16Array]"]=cr["[object Int32Array]"]=cr["[object Uint8Array]"]=cr["[object Uint8ClampedArray]"]=cr["[object Uint16Array]"]=cr["[object Uint32Array]"]=!0,cr["[object Arguments]"]=cr["[object Array]"]=cr["[object ArrayBuffer]"]=cr["[object Boolean]"]=cr["[object DataView]"]=cr["[object Date]"]=cr["[object Error]"]=cr["[object Function]"]=cr["[object Map]"]=cr["[object Number]"]=cr["[object Object]"]=cr["[object RegExp]"]=cr["[object Set]"]=cr["[object String]"]=cr["[object WeakMap]"]=!1;var fr="object"==typeof t&&t&&!t.nodeType&&t,sr=fr&&"object"==typeof module&&module&&!module.nodeType&&module,lr=sr&&sr.exports===fr&&n.process,pr=function(){try{var t=sr&&sr.require&&sr.require("util").types;return t||lr&&lr.binding&&lr.binding("util")}catch(t){}}(),vr=pr&&pr.isTypedArray,dr=vr?function(t){return function(r){return t(r)}}(vr):function(t){return _(t)&&er(t.length)&&!!cr[y(t)]};function yr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var hr=Object.prototype.hasOwnProperty;function br(t,r,e){var n=t[r];hr.call(t,r)&&rt(n,e)&&(void 0!==e||r in t)||Jt(t,r,e)}var gr=9007199254740991,_r=/^(?:0|[1-9]\d*)$/;function jr(t,r){var e=typeof t;return!!(r=null==r?gr:r)&&("number"==e||"symbol"!=e&&_r.test(t))&&t>-1&&t%1==0&&t0){if(++r>=Tr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(xr);function Rr(t,r){return Mr(function(t,r,e){return r=Fr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Fr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Ur.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!ut(e))return!1;var n=typeof r;return!!("number"==n?nr(e)&&jr(r,e.length):"string"==n&&r in e)&&rt(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 Reflect.apply(r,null,W(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]):qr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.checkIsContract=te,t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=ce,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(ce(t,r,e,n))},t.createQuery=ae,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(ae(t,r,e))},t.dasherize=function(t){return H(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case Ir:return t[Lr];case $r:return[t[Dr],t[Qr]];default:throw new Yr("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Zr(e,r);return n}catch(t){throw new Zr(e,t)}},t.extractSocketPart=re,t.formatPayload=ue,t.getCallMethod=function(t){switch(!0){case t===Gr[0]:return Ir;case t===Gr[1]:return $r;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=le,t.getMutationFromPayload=function(t){var r=se(t,le);if(!1!==r)return r;throw new Xr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ie,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=fe,t.getQueryFromPayload=function(t){var r=se(t,fe);if(!1!==r)return r;throw new Xr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=re(t);if(!1===e){if(r)return t;throw new Yr("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=function(t,r,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)},t.isContract=ve,t.isJsonqlErrorObj=pe,t.isKeyInObject=Z,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==H(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.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=pe(t)||u,o))},t.packResult=function(t){var r;return JSON.stringify(((r={}).data=t,r))},t.resultHandler=function(t){return Z(t,"data")&&!Z(t,"error")?t.data:t},t.timestamp=X,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=oe,t.urlParams=Y,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/main.js b/packages/utils/main.js index ce542001e55b8ac03d958c2551dc362fb692975c..72e60a33f72c2e00285318262648c1f4da01f714 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}function arrayMap(r,t){for(var e=-1,n=null==r?0:r.length,o=Array(n);++eo?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(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 stringTag="[object String]";function isString(r){return"string"==typeof r||!isArray(r)&&isObjectLike(r)&&baseGetTag(r)==stringTag}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$1="[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$1]=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);++n0;)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,[r])}),Reflect.apply(r,null,e))}};function chainPromises(r,t){return void 0===t&&(t=!1),r.reduce((function(r,e){return r.then((function(r){return e.then((function(e){return!1===t?r.concat([e]):merge(r,e)}))}))}),Promise.resolve(!1===t?[]:isPlainObject(t)?t:{}))}function objDefineProps(r,t,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(r,t)&&Object.defineProperty(r,t,{set:e,get:null===n?function(){return null}:n}),r}function injectToFn(r,t,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(r,t);return!1===n&&void 0!==o?r:(Object.defineProperty(r,t,{value:e,writable:n}),r)}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}},isKeyInObject=function(r,t){var e=Object.keys(r);return inArray(e,t)},createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},timestamp=function(r){void 0===r&&(r=!1);var t=Date.now();return r?Math.floor(t/1e3):t},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()}},dasherize=function(r){return trim(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},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)},EXT="js",DATA_KEY="data",ERROR_KEY="error",CONTENT_TYPE="application/vnd.api+json",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",PAYLOAD_PARAM_NAME="payload",CONDITION_PARAM_NAME="condition",RESOLVER_PARAM_NAME="resolverName",QUERY_ARG_NAME="args",API_REQUEST_METHODS=["POST","PUT"],INDEX_KEY="index",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,BASE64_FORMAT="base64",SUCCESS_STATUS=200,FORBIDDEN_STATUS=403;function getErrorByStatus(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}var Jsonql406Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),Jsonql500Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),JsonqlAuthorisationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),JsonqlContractAuthError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),JsonqlResolverAppError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),isBrowser=function(){try{if(window||document)return!0}catch(r){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(r){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(r){function t(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t)}return r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t,t.where=function(){return whereAmI()},t}(Error),JsonqlResolverNotFoundError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlEnumError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),JsonqlTypeError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),JsonqlCheckerError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),JsonqlValidationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlServerError=function(r){function t(e,n){r.call(this,n),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),errors=Object.freeze({__proto__:null,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError}),JsonqlError$1=JsonqlError,isKeyInObject$1=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};function clientErrorsHandler(r){if(isKeyInObject$1(r,"error")){var t=r.error,e=t.className,n=t.name,o=e||n,a=t.message||NO_ERROR_MSG,i=t.detail||t;if(o&&errors[o])throw new errors[e](a,i);throw new JsonqlError$1(a,i)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}function getErrorNameByInstance(r,t){var e=mapErrToName(r,t);return e.length?e[0]:UNKNOWN_ERROR}function getErrorNameByInstanceWithDefault(r,t){var e=getErrorNameByInstance(r,t);return e===UNKNOWN_ERROR?"JsonqlError":e}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var t=r.message||NO_ERROR_MSG,e=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(t,e);case r instanceof Jsonql500Error:throw new Jsonql500Error(t,e);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(t,e);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(t,e);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(t,e);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(t,e);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(t,e);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(t,e);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(t,e);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(t,e);case r instanceof JsonqlServerError:throw new JsonqlServerError(t,e);default:throw new JsonqlError(t,e)}}var JSONQL_ERRORS_INFO="__PLACEHOLDER__",jsonqlErrors=Object.freeze({__proto__:null,JSONQL_ERRORS_INFO:JSONQL_ERRORS_INFO,UNKNOWN_ERROR:UNKNOWN_ERROR,getErrorByStatus:getErrorByStatus,clientErrorsHandler:clientErrorsHandler,finalCatch:finalCatch,getErrorNameByInstance:getErrorNameByInstance,getErrorNameByInstanceWithDefault:getErrorNameByInstanceWithDefault,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError});function checkIsContract(r){return isPlainObject(r)&&(isKeyInObject(r,QUERY_NAME)||isKeyInObject(r,MUTATION_NAME)||isKeyInObject(r,SOCKET_NAME))}function extractSocketPart(r){return!!isKeyInObject(r,"socket")&&r.socket}function groupByNamespace(r,t){void 0===t&&(t=!1);var e=extractSocketPart(r);if(!1===e){if(t)return r;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in e){var s=e[i],u=s.namespace;u&&(o[u]||(++a,o[u]={}),o[u][i]=s,n||s.public&&(n=u))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(r,t){var e=[];for(var n in r)n===t?e[1]=n:e[0]=n;return e}function extractArgsFromPayload(r,t){switch(t){case QUERY_NAME:return r[QUERY_ARG_NAME];case MUTATION_NAME:return[r[PAYLOAD_PARAM_NAME],r[CONDITION_PARAM_NAME]];default:throw new JsonqlError("Unknown "+t+" to extract argument from!")}}function extractParamsFromContract(r,t,e){try{var n=r[t][e];if(!n)throw new JsonqlResolverNotFoundError(e,t);return n}catch(r){throw new JsonqlResolverNotFoundError(e,r)}}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 createQuery(r,t,e){var n;if(void 0===t&&(t=[]),void 0===e&&(e=!1),isString(r)&&isArray(t)){var o=formatPayload(t);return!0===e?o:((n={})[r]=o,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){var o;void 0===e&&(e={}),void 0===n&&(n=!1);var a={};if(a[PAYLOAD_PARAM_NAME]=t,a[CONDITION_PARAM_NAME]=e,!0===n)return a;if(isString(r))return(o={})[r]=a,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}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}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){var t;return JSON.stringify(((t={})[DATA_KEY]=r,t))},isJsonqlErrorObj=function(r){return!!["detail","className"].filter((function(t){return isKeyInObject(r,t)})).length&&["className","message","statusCode"].filter((function(t){return isKeyInObject(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))},resultHandler=function(r){return isKeyInObject(r,DATA_KEY)&&!isKeyInObject(r,ERROR_KEY)?r[DATA_KEY]:r},isContract=checkIsContract,VERSION="0.7.6",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;so?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(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 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}},isKeyInObject=function(r,t){var e=Object.keys(r);return inArray(e,t)},createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},timestamp=function(r){void 0===r&&(r=!1);var t=Date.now();return r?Math.floor(t/1e3):t},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()}},dasherize=function(r){return trim(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},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);++n0)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;s e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n"],"names":["const"],"mappings":"8y4BAAAA,yrQCAA"} \ No newline at end of file +{"version":3,"file":"main.js","sources":["node_modules/jsonql-errors/src/get-error-name-by-instance.js","node_modules/buffer-es6/isArray.js"],"sourcesContent":["const UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n"],"names":["const"],"mappings":"+q4BAAAA,m0QCAA"} \ No newline at end of file diff --git a/packages/utils/module.js b/packages/utils/module.js index eb75d5f8685577d62939c882763b97bdbe956f59..9e181843c793314c443c55954626177765d662c3 100644 --- a/packages/utils/module.js +++ b/packages/utils/module.js @@ -1,6 +1,7 @@ // exportfor ES modules // ported from jsonql-params-validator -import { chainFns, chainPromises } from './src/chain-fns' +import { chainFns } from './src/chain-fns' +import { chainPromises } from './src/chain-promises' import { injectToFn, objDefineProps } from './src/obj-define-props' import { checkIsContract, diff --git a/packages/utils/package.json b/packages/utils/package.json index 92c14aaa01bc49afe76a8d095cbfac9b2d008cc2..62709ff89fc985f55bd74dc4bec2bb9bdecff316 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-utils", - "version": "0.7.6", + "version": "0.7.8", "description": "This is a jsonql dependency module, not for generate use.", "main": "main.js", "module": "index.js", @@ -8,9 +8,11 @@ "files": [ "src", "browser.js", + "browser.js.map", "debug.js", "index.js", "main.js", + "main.js.map", "module.js" ], "scripts": { @@ -59,7 +61,7 @@ "compileEnhancements": false }, "dependencies": { - "jsonql-constants": "^1.8.4", + "jsonql-constants": "^1.8.5", "jsonql-errors": "^1.1.3", "lodash-es": "^4.17.15" }, @@ -68,8 +70,8 @@ "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "rollup": "^1.23.1", - "rollup-plugin-alias": "^2.0.1", + "rollup": "^1.25.1", + "rollup-plugin-alias": "^2.2.0", "rollup-plugin-analyzer": "^3.2.1", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", diff --git a/packages/utils/src/chain-fns.js b/packages/utils/src/chain-fns.js index 101a70731d82b6da4ce4bd114492f62bf9a72e45..2867ec27ff8b23c54edd24995ace17bb36982b21 100644 --- a/packages/utils/src/chain-fns.js +++ b/packages/utils/src/chain-fns.js @@ -1,7 +1,4 @@ -// break it out on its own because -// it's building from the lodash-es from scratch -// according to this discussion https://github.com/lodash/lodash/issues/3298 -import { merge, isPlainObject } from './lodash' +import { toArray } from './generic' /** * using just the map reduce to chain multiple functions together * @param {function} mainFn the init function @@ -11,26 +8,8 @@ import { merge, isPlainObject } from './lodash' export const chainFns = (mainFn, ...moreFns) => ( (...args) => ( moreFns.reduce((value, nextFn) => ( - Reflect.apply(nextFn, null, [value]) + // 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)) ) ) - -/** - * previously we already make sure the order of the namespaces - * and attach the auth client to it - * @param {array} promises array of unresolved promises - * @param {boolean} asObject if true then merge the result object - * @return {object} promise resolved with the array of promises resolved results - */ -export function chainPromises(promises, asObject = false) { - return promises.reduce((promiseChain, currentTask) => ( - promiseChain.then(chainResults => ( - currentTask.then(currentResult => ( - asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult) - )) - )) - ), Promise.resolve( - asObject === false ? [] : (isPlainObject(asObject) ? asObject : {}) - )) -} diff --git a/packages/utils/src/chain-promises.js b/packages/utils/src/chain-promises.js new file mode 100644 index 0000000000000000000000000000000000000000..30889daef2f9425d42fcf23dd49a9c3271dc59e8 --- /dev/null +++ b/packages/utils/src/chain-promises.js @@ -0,0 +1,23 @@ +// break it out on its own because +// it's building from the lodash-es from scratch +// according to this discussion https://github.com/lodash/lodash/issues/3298 +import isPlainObject from 'lodash-es/isPlainObject' +import merge from 'lodash-es/merge' +/** + * previously we already make sure the order of the namespaces + * and attach the auth client to it + * @param {array} promises array of unresolved promises + * @param {boolean} asObject if true then merge the result object + * @return {object} promise resolved with the array of promises resolved results + */ +export function chainPromises(promises, asObject = false) { + return promises.reduce((promiseChain, currentTask) => ( + promiseChain.then(chainResults => ( + currentTask.then(currentResult => ( + asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult) + )) + )) + ), Promise.resolve( + asObject === false ? [] : (isPlainObject(asObject) ? asObject : {}) + )) +} diff --git a/packages/utils/src/contract.js b/packages/utils/src/contract.js index 90cc6cd73dbafec9bc1e34c21295355dabaf4442..1a61d47439f5e50aef93f30085c0499394f6eae6 100644 --- a/packages/utils/src/contract.js +++ b/packages/utils/src/contract.js @@ -1,6 +1,6 @@ // split the contract into the node side and the generic side import { isKeyInObject } from './generic' -import { isPlainObject } from './lodash' +import isPlainObject from 'lodash-es/isPlainObject' import { QUERY_NAME, MUTATION_NAME, diff --git a/packages/utils/src/generic.js b/packages/utils/src/generic.js index 0b28f01d0c416caa1e251c3f9914caaa39cf3f78..bea579b09f39f0853fb6a74b354f1b5eb4ad6473 100644 --- a/packages/utils/src/generic.js +++ b/packages/utils/src/generic.js @@ -1,5 +1,8 @@ // bunch of generic helpers -import { isArray, isPlainObject, trim } from './lodash' + +import isArray from 'lodash-es/isArray' +import isPlainObject from 'lodash-es/isPlainObject' +import trim from 'lodash-es/trim' /** * DIY in Array @@ -12,7 +15,11 @@ export const inArray = (arr, value) => !!arr.filter(a => a === value).length; // quick and dirty to turn non array to array export const toArray = (arg) => isArray(arg) ? arg : [arg]; - +/** + * parse string to json or just return the original value if error happened + * @param {*} n input + * @return {*} json object on success + */ const parse = function(n) { try { return JSON.parse(n) diff --git a/packages/utils/src/lodash.js b/packages/utils/src/lodash.js deleted file mode 100644 index 63361bd9891495c518799a3b081c4f335aa13572..0000000000000000000000000000000000000000 --- a/packages/utils/src/lodash.js +++ /dev/null @@ -1,15 +0,0 @@ -// first import all the required lodash module then re-export it -// that will reduce the change rollup get it wrong and ended up with the entire lodash -import isArray from 'lodash-es/isArray' -import isPlainObject from 'lodash-es/isPlainObject' -import trim from 'lodash-es/trim' -import isString from 'lodash-es/isString' -import merge from 'lodash-es/merge' - -export { - isArray, - isPlainObject, - isString, - trim, - merge -} diff --git a/packages/utils/src/params-api.js b/packages/utils/src/params-api.js index 8762a7f63299f80dc891931722e363ac59b7a0fe..a7ab054234ac214308276136879430df57d64f49 100644 --- a/packages/utils/src/params-api.js +++ b/packages/utils/src/params-api.js @@ -8,13 +8,10 @@ import { QUERY_ARG_NAME } from 'jsonql-constants' import { JsonqlValidationError } from 'jsonql-errors' -/* -use lodash-es instead -import isString from './string' -import { isArray } from './array' -import { checkIsObject } from './object' -*/ -import { isString, isArray, isPlainObject } from './lodash' + +import isArray from 'lodash-es/isArray' +import isPlainObject from 'lodash-es/isPlainObject' +import isString from 'lodash-es/isString' /** * make sure it's an object (it was call formatPayload but it doesn't make sense) @@ -57,7 +54,10 @@ export function createQuery(resolverName, args = [], jsonp = false) { throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args }) } -// string version of the above +/** + * string version of the createQuery + * @return {string} + */ export function createQueryStr(resolverName, args = [], jsonp = false) { return JSON.stringify(createQuery(resolverName, args, jsonp)) } @@ -83,7 +83,10 @@ export function createMutation(resolverName, payload, condition = {}, jsonp = fa throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition }) } -// string version of above +/** + * string version of createMutation + * @return {string} + */ export function createMutationStr(resolverName, payload, condition = {}, jsonp = false) { return JSON.stringify(createMutation(resolverName, payload, condition, jsonp)) } diff --git a/packages/utils/src/results.js b/packages/utils/src/results.js index d57bc1d4138beab824c1463dde71293b1f318afc..1e5021ec6d8b981a3cb702002b23dbf1cb822198 100644 --- a/packages/utils/src/results.js +++ b/packages/utils/src/results.js @@ -13,7 +13,7 @@ import { EXT } from 'jsonql-constants' import { isKeyInObject } from './generic' -import { merge } from './lodash' +import merge from 'lodash-es/merge' /** * getting what is calling after the above check * @param {string} method of call diff --git a/packages/utils/tests/chain-fn.test.js b/packages/utils/tests/chain-fn.test.js index e0d55c39117aa7365b17bc810d1ec68309323b88..7161e761a16032e8af67ff6bfe628c5a48cb8428 100644 --- a/packages/utils/tests/chain-fn.test.js +++ b/packages/utils/tests/chain-fn.test.js @@ -1,6 +1,7 @@ // need to test the chain-fns because of the way we change the lodash import const test = require('ava') -const { chainFns, chainPromises } = require('../src/chain-fns') +const { chainFns } = require('../src/chain-fns') +const { chainPromises } = require('../src/chain-promises') const debug = require('debug')('jsonql-utils:test:chain-fn') test('It should able to accept more than one functions after the first one', t => { @@ -13,6 +14,25 @@ test('It should able to accept more than one functions after the first one', t = t.is(103, result) }) +test(`It should able to accept the last array return as spread input`, t => { + const baseFn = (num, base) => { + return [num + base, base] + } + const add1 = (num, base) => { + debug(num, base) + return [num*base, base] + } + const add2 = (num, base) => { + debug(num, base) + return num - base; + } + const fn = chainFns(baseFn, add1, add2) + const result = fn(1, 10) + t.is(result, 100) + +}) + + test(`It should able to merge the promise result together as one object`, async t => { let ps = [] for (let i = 0; i < 3; ++i) { diff --git a/packages/ws-client/README.md b/packages/ws-client/README.md index eb41bc4911b5bb55d6ead1478e720f6d8ab7f177..3911262ef0854764965b809b8a265b3613a89b6d 100644 --- a/packages/ws-client/README.md +++ b/packages/ws-client/README.md @@ -9,6 +9,11 @@ Please check the following - [@jsonql/socketio](https://npmjs.com/package/@jsonql/socketio) for [Socket.io](https://npmjs.com/package/socketio) client / server - ~~@jsonql/primus for Primus client / server~~ (planning stage) +## Share methods + +This module also export several share methods via `jsonql-ws-client/share` but this is mainly for the +down stream client to use. + Please check [jsonql.org](https://jsonql.org) for further information diff --git a/packages/ws-client/index.js b/packages/ws-client/index.js index ca4dec95d8350e293aaa18e26a96a5dcaeee6696..90aa2a9e3b33c20f3606f1a8e48eff0fefdc017d 100644 --- a/packages/ws-client/index.js +++ b/packages/ws-client/index.js @@ -1,6 +1,5 @@ // This is the module entry point -import clientGenerator from './src/utils/client-generator' -import main from './src/main' -// as of beta.3 this has been cut down to only the core function -// without the actual socket client / server implementation and -// serve as a support library for the socket implementation for jsonql +import jsonqlWsClient from './src/api' + +// export with name interface +export { jsonqlWsClient } diff --git a/packages/ws-client/main.js b/packages/ws-client/main.js index fbb9234093e5afa791b49fbec8f84fec24fe5cc4..1d2c7a1ec5b14d95767c67546ec00dd91430cbcf 100644 --- a/packages/ws-client/main.js +++ b/packages/ws-client/main.js @@ -1,2 +1,2 @@ require = require("esm")(module/*, options*/) -module.exports = require("./module.js") +module.exports = require("./index.js") diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index ca86ccd59a2dad6da0e8a1637e0cae2628ec7a0e..b96d6bb22ea19c5b552ee201157128cff74687d2 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -1,21 +1,23 @@ { "name": "jsonql-ws-client", - "version": "1.0.0", + "version": "1.0.13", "description": "This is the Web Socket client for Node and Browser", "main": "main.js", "module": "index.js", - "browser": "dist/jsonql-ws-client.js", "files": [ - "dist", "src", "index.js", - "main.js" + "main.js", + "share.js" ], "scripts": { "test": "ava --verbose", + "prepare": "npm run test", "test:node": "DEBUG=jsonql-ws-* ava --verbose ./tests/test-node.test.js", + "test:opt": "DEBUG=jsonql-ws-* ava --verbose ./tests/options.test.js", "contract": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config.js", - "contract:auth": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config-auth.js" + "contract:auth": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config-auth.js", + "test:evt": "DEBUG=jsonql-ws-* ava ./tests/event.test.js" }, "keywords": [ "jsonql", @@ -51,8 +53,8 @@ "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.3", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.7.6", - "nb-event-service": "^1.8.3" + "jsonql-utils": "^0.7.8", + "nb-event-service": "^1.8.5" }, "devDependencies": { "ava": "^2.4.0", @@ -61,7 +63,7 @@ "jsonql-contract": "^1.7.21", "jsonql-ws-server": "^1.3.2", "kefir": "^3.8.6", - "ws": "^7.1.2" + "ws": "^7.2.0" }, "repository": { "type": "git", diff --git a/packages/ws-client/share.js b/packages/ws-client/share.js new file mode 100644 index 0000000000000000000000000000000000000000..d36edaccd5dd6573ad644d290e3cee5102433396 --- /dev/null +++ b/packages/ws-client/share.js @@ -0,0 +1,22 @@ +// new interface to export some of the method for other module to use +// jsonql-ws-client/share +// import export the constants +import * as constants from './src/options/constants' +// import the share methods +import { createNspClient, createNspAuthClient } from './src/share/create-nsp-client' +import { triggerNamespacesOnError } from './src/share/trigger-namespaces-on-error' +import { clientEventHandler } from './src/share/client-event-handler' +// also export some of the util methods +import { clearMainEmitEvt, disconnect, getDebug, ee } from './src/utils' +// export it +export { + constants, + createNspClient, + createNspAuthClient, + triggerNamespacesOnError, + clientEventHandler, + clearMainEmitEvt, + disconnect, + getDebug, + ee +} diff --git a/packages/ws-client/src/api.js b/packages/ws-client/src/api.js index fae45ca0f9f23506119def8efd59bb34dc16cb2d..0bb0ae7f54e9f1131bc2c98a41327c6737d74a28 100644 --- a/packages/ws-client/src/api.js +++ b/packages/ws-client/src/api.js @@ -2,20 +2,22 @@ // The goal is to create a generic method that will able to handle // any kind of clients // import { injectToFn } from 'jsonql-utils' -import generator from './core/generator' +import { generator } from './core' import checkOptions from './options' import { ee, processContract } from './utils' /** - * @param {object} socketClientResolver we normalize the auth and non auth client from now on + * The main interface which will generate the socket clients and map all events + * @param {object} socketClientResolver this is the one method export by various clients + * @param {object} [constProps={}] add this to supply the constProps from the downstream client * @return {object} the wsClient instance with all the available API */ -export default function wsClient(socketClientResolver) { +export default function wsClient(socketClientResolver, constProps = {}) { // we need to inject property to this client later // therefore we need to do it this way return (opts) => { const { eventEmitter } = opts; - return checkOptions(opts) + return checkOptions(opts, constProps) .then(opts => ({ opts, nspMap: processContract(opts), @@ -31,5 +33,4 @@ export default function wsClient(socketClientResolver) { console.error(`jsonql-ws-client init error`, err) }) } - // return injectToFn(_wsClient, 'CLIENT_TYPE_INFO', opts.serverType) } diff --git a/packages/ws-client/src/core/action-call.js b/packages/ws-client/src/core/action-call.js new file mode 100644 index 0000000000000000000000000000000000000000..59291b568b49e7580c93f0f487f9333d37e86479 --- /dev/null +++ b/packages/ws-client/src/core/action-call.js @@ -0,0 +1,32 @@ +// the actual trigger call method +import { RESULT_PROP_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants' +import { createEvt, toArray } from 'jsonql-utils/module' +import { respondHandler } from './respond-handler' +import { getDebug } from '../utils' +const debugFn = getDebug(`action-call`) + +/** + * just wrapper + * @param {object} ee EventEmitter + * @param {string} namespace where this belongs + * @param {string} resolverName resolver + * @param {array} args arguments + * @return {void} nothing + */ +export function actionCall(ee, namespace, resolverName, args = []) { + const eventName = createEvt(namespace, EMIT_REPLY_TYPE) + debugFn(`actionCall: ${eventName} --> ${resolverName}`, args) + ee.$trigger(eventName, [resolverName, toArray(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 + return new Promise((resolver, rejecter) => { + ee.$on( + createEvt(namespace, resolverName, RESULT_PROP_NAME), + function actionCallResultHandler(result) { + debugFn(`got the first result`, result) + respondHandler(result, resolver, rejecter) + } + ) + }) +} diff --git a/packages/ws-client/src/core/generator.js b/packages/ws-client/src/core/generator.js index 3ceb0ddaf7de7f82366168d782b2757cfbad829d..2bd322beb66f3be68839b381accd62ec4e3677d6 100644 --- a/packages/ws-client/src/core/generator.js +++ b/packages/ws-client/src/core/generator.js @@ -1,54 +1,25 @@ -// generator resolvers -// this will be a mini client server architect -// The reason is when the enableAuth setup - the private route -// might not be validated, but we need the callable point is ready -// therefore this part will always take the contract and generate -// callable api for the developer to setup their front end -// the only thing is - when they call they might get an error or -// NOT_LOGIN_IN and they can react to this error accordingly +// resolvers generator +// we change the interface to return promise from v1.0.3 +// this way we make sure the obj return is correct and timely +import { setupResolver } from './setup-resolver' import { - JsonqlResolverNotFoundError, - JsonqlValidationError, - JsonqlError, - finalCatch -} from 'jsonql-errors' -import { - validateAsync, - isKeyInObject, - isString -} from 'jsonql-params-validator' -import { - ERROR_TYPE, - DATA_KEY, - ERROR_KEY, - ERROR_PROP_NAME, - MESSAGE_PROP_NAME, - RESULT_PROP_NAME, - SEND_MSG_PROP_NAME, - LOGIN_EVENT_NAME, - READY_PROP_NAME, - LOGOUT_EVENT_NAME -} from 'jsonql-constants' - -import { getDebug, createEvt, toArray, injectToFn, objDefineProps } from '../utils' -import { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } from '../options/constants' - -// const debugFn = getDebug('[generator]') - -import debug from 'debug' -const debugFn = debug('jsonql-ws-client:generator') - + createResolver, + createNamespaceErrorHandler, + createOnReadyhandler, + createAuthMethods +} from './resolver-methods' +import { getDebug } from '../utils' +const debugFn = getDebug('generator') /** - * prepare the methods + * step one get the obj map with the namespace * @param {object} opts configuration * @param {object} nspMap resolvers index by their namespace * @param {object} ee EventEmitter - * @return {object} of resolvers - * @public + * @return {promise} resolve the obj mapped, and start the chain */ -export default function generator(opts, nspMap, ee) { - const obj = {}; +function getMappedObj(opts, nspMap, ee) { + let obj = {}; const { nspSet } = nspMap; for (let namespace in nspSet) { let list = nspSet[namespace] @@ -58,221 +29,32 @@ export default function generator(opts, nspMap, ee) { obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee) } } - // add error handler - createNamespaceErrorHandler(obj, ee, nspSet) - // add onReady handler - createOnReadyhandler(obj, ee, nspSet) - // Auth related methods - createAuthMethods(obj, ee, opts) - // this is a helper method for the developer to know the namespace inside - obj.getNsp = () => { - return Object.keys(nspSet) + // move this two method down to helpers + obj.devHelpers = { + // this is a helper method for the developer to know the namespace inside + getNsp: () => Object.keys(nspSet), + // simple get version trick + getVer: () => opts.version || 'NOT SET' } - // output - return obj; + // resolve the obj to start the chain + return Promise.resolve(obj) } /** - * create the actual function to send message to server - * @param {object} ee EventEmitter instance - * @param {string} namespace this resolver end point - * @param {string} resolverName name of resolver as event name - * @param {object} params from contract - * @return {function} resolver - */ -function createResolver(ee, namespace, resolverName, params) { - // note we pass the new withResult=true option - return function(...args) { - return validateAsync(args, params.params, true) - .then(_args => actionCall(ee, namespace, resolverName, _args)) - .catch(finalCatch) - } -} - -/** - * just wrapper - * @param {object} ee EventEmitter - * @param {string} namespace where this belongs - * @param {string} resolverName resolver - * @param {array} args arguments - * @return {void} nothing - */ -function actionCall(ee, namespace, resolverName, args = []) { - const eventName = createEvt(namespace, EMIT_EVT) - debugFn(`actionCall: ${eventName} --> ${resolverName}`, args) - ee.$trigger(eventName, [resolverName, toArray(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 - return new Promise((resolver, rejecter) => { - ee.$on( - createEvt(namespace, resolverName, RESULT_PROP_NAME), - result => { - debugFn(`got the first result`, result) - respondHandler(result, resolver, rejecter) - } - ) - }) -} - -/** - * break out to use in different places to handle the return from server - * @param {object} data from server - * @param {function} resolver NOT from promise - * @param {function} rejecter NOT from promise - * @return {void} nothing - */ -function respondHandler(data, resolver, rejecter) { - if (isKeyInObject(data, ERROR_KEY)) { - debugFn('-- rejecter called --', data[ERROR_KEY]) - rejecter(data[ERROR_KEY]) - } else if (isKeyInObject(data, DATA_KEY)) { - debugFn('-- resolver called --', data[DATA_KEY]) - resolver(data[DATA_KEY]) - } else { - debugFn('-- UNKNOWN_RESULT --', data) - rejecter({message: UNKNOWN_RESULT, error: data}) - } -} - -/** - * Add extra property to the resolver - * @param {string} namespace where this belongs - * @param {string} resolverName name as event name - * @param {object} params from contract - * @param {function} fn resolver function - * @param {object} ee EventEmitter - * @return {function} resolver - */ -const setupResolver = (namespace, resolverName, params, fn, ee) => { - // also need to setup a getter to get back the namespace of this resolver - let _fn = injectToFn(fn, MY_NAMESPACE, namespace) - // onResult handler - _fn = objDefineProps(_fn, RESULT_PROP_NAME, function(resultCallback) { - if (typeof resultCallback === 'function') { - ee.$on( - createEvt(namespace, resolverName, RESULT_PROP_NAME), - function resultHandler(result) { - respondHandler(result, resultCallback, (error) => { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) - }) - } - ) - } - }) - // we do need to add the send prop back because it's the only way to deal with - // bi-directional data stream - _fn = objDefineProps(_fn, MESSAGE_PROP_NAME, function(messageCallback) { - // we expect this to be a function - if (typeof messageCallback === 'function') { - // did that add to the callback - let onMessageCallback = (args) => { - respondHandler(args, messageCallback, (error) => { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) - }) - } - // register the handler for this message event - ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback) - } - }) - // add an ERROR_PROP_NAME handler - _fn = objDefineProps(_fn, ERROR_PROP_NAME, function(resolverErrorHandler) { - if (typeof resolverErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler) - } - }) - // pairing with the server vesrion SEND_MSG_PROP_NAME - _fn = objDefineProps(_fn, SEND_MSG_PROP_NAME, function(messagePayload) { - debugFn('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(toArray(messagePayload), params.params, true) - .then(result => { - // here is the different we don't throw error instead we trigger onError - if (result[ERROR_KEY] && result[ERROR_KEY].length) { - debugFn(`got ERROR_KEY`, result[ERROR_KEY]) - ee.$call( - createEvt(namespace, resolverName, ERROR_PROP_NAME), - [JsonqlValidationError(resolverName, result[ERROR_KEY])] - ) - } else { - // there is no return only an action call - actionCall(ee, namespace, resolverName, messagePayload) - } - }) - .catch(err => { - debugFn(`error after validateAsync`, err) - ee.$call( - createEvt(namespace, resolverName, ERROR_PROP_NAME), - [JsonqlValidationError(resolverName, err)] - ) - }) - }) - return _fn; -} - -/** - * The problem is the namespace can have more than one - * and we only have on onError message - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ -const createNamespaceErrorHandler = (obj, ee, nspSet) => { - // using the onError as name - // @TODO we should follow the convention earlier - // make this a setter for the obj itself - objDefineProps(obj, ERROR_PROP_NAME, function(namespaceErrorHandler) { - if (typeof namespaceErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - for (let namespace in nspSet) { - // this one is very tricky, we need to make sure the trigger is calling - // with the namespace as well as the error - ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler) - } - } - }) -} - -/** - * This event will fire when the socket.io.on('connection') and ws.onopen - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ -const createOnReadyhandler = (obj, ee, nspSet) => { - objDefineProps(obj, READY_PROP_NAME, function(onReadyCallback) { - if (typeof onReadyCallback === 'function') { - // reduce it down to just one flat level - let result = ee.$on(READY_PROP_NAME, onReadyCallback) - } - }) -} - -/** - * Create auth related methods - * @param {object} obj the client itself - * @param {object} ee Event Emitter + * prepare the methods * @param {object} opts configuration - * @return {void} + * @param {object} nspMap resolvers index by their namespace + * @param {object} ee EventEmitter + * @return {object} of resolvers + * @public */ -const createAuthMethods = (obj, ee, opts) => { - if (opts.enableAuth) { - // create an additonal login handler - // we require the token - obj[opts.loginHandlerName] = (token) => { - debugFn(opts.loginHandlerName, token) - if (token && isString(token)) { - return ee.$trigger(LOGIN_EVENT_NAME, [token]) - } - throw new JsonqlValidationError(opts.loginHandlerName) - } - // logout event handler - obj[opts.logoutHandlerName] = (...args) => { - ee.$trigger(LOGOUT_EVENT_NAME, args) - } - } +export function generator(opts, nspMap, ee) { + const { nspSet } = nspMap + return getMappedObj(opts, nspMap, ee) + // add error handler + .then(obj1 => createNamespaceErrorHandler(obj1, ee, nspSet)) + // add onReady handler + .then(obj2 => createOnReadyhandler(obj2, ee, nspSet)) + // Auth related methods + .then(obj3 => createAuthMethods(obj3, ee, opts)) } diff --git a/packages/ws-client/src/core/index.js b/packages/ws-client/src/core/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a6faf947d2b9a86673e90c38bffbe66ef8a72549 --- /dev/null +++ b/packages/ws-client/src/core/index.js @@ -0,0 +1,5 @@ +// just doing the import export thing here + +import { generator } from './generator' + +export { generator } diff --git a/packages/ws-client/src/core/resolver-methods.js b/packages/ws-client/src/core/resolver-methods.js new file mode 100644 index 0000000000000000000000000000000000000000..61afc6e733400621abee20df4d336e4c2d4eafb6 --- /dev/null +++ b/packages/ws-client/src/core/resolver-methods.js @@ -0,0 +1,132 @@ +// put all the resolver related methods here to make it more clear + +// this will be a mini client server architect +// The reason is when the enableAuth setup - the private route +// might not be validated, but we need the callable point is ready +// therefore this part will always take the contract and generate +// callable api for the developer to setup their front end +// the only thing is - when they call they might get an error or +// NOT_LOGIN_IN and they can react to this error accordingly +import { + JsonqlResolverNotFoundError, + JsonqlValidationError, + JsonqlError, + finalCatch +} from 'jsonql-errors' +import { + validateAsync, + isKeyInObject, + isString +} from 'jsonql-params-validator' +import { + ERROR_TYPE, + DATA_KEY, + ERROR_KEY, + ERROR_PROP_NAME, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + SEND_MSG_PROP_NAME, + LOGIN_EVENT_NAME, + READY_PROP_NAME, + LOGOUT_EVENT_NAME +} from 'jsonql-constants' +import { + EMIT_EVT, + NOT_ALLOW_OP, + UNKNOWN_RESULT, + MY_NAMESPACE, + EXPECT_FUNC_ERR +} from '../options/constants' +import { actionCall } from './action-call' +import { + getDebug, + createEvt, + toArray, + injectToFn, + objDefineProps, + isFunc +} from '../utils' +const debugFn = getDebug('resolver-methods') + +/** + * create the actual function to send message to server + * @param {object} ee EventEmitter instance + * @param {string} namespace this resolver end point + * @param {string} resolverName name of resolver as event name + * @param {object} params from contract + * @return {function} resolver + */ +export function createResolver(ee, namespace, resolverName, params) { + // note we pass the new withResult=true option + return function(...args) { + return validateAsync(args, params.params, true) + .then(_args => actionCall(ee, namespace, resolverName, _args)) + .catch(finalCatch) + } +} + +/** + * The problem is the namespace can have more than one + * and we only have on onError message + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {object} obj with onError prop + */ +export function createNamespaceErrorHandler(obj, ee, nspSet) { + // using the onError as name + // @TODO we should follow the convention earlier + // make this a setter for the obj itself + return objDefineProps(obj, ERROR_PROP_NAME, function(namespaceErrorHandler) { + if (isFunc(namespaceErrorHandler)) { + // please note ERROR_PROP_NAME can add multiple listners + for (let namespace in nspSet) { + // this one is very tricky, we need to make sure the trigger is calling + // with the namespace as well as the error + ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler) + } + } + }) +} + +/** + * This event will fire when the socket.io.on('connection') and ws.onopen + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {object} obj with onReady prop + */ +export function createOnReadyhandler(obj, ee, nspSet) { + return objDefineProps(obj, READY_PROP_NAME, function(onReadyCallback) { + if (isFunc(onReadyCallback)) { + // reduce it down to just one flat level + ee.$on(READY_PROP_NAME, onReadyCallback) + } + }) +} + +/** + * Create auth related methods + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} opts configuration + * @return {object} obj with auth methods if any + */ +export function createAuthMethods(obj, ee, opts) { + if (opts.enableAuth) { + // create an additonal login handler + // we require the token + obj[opts.loginHandlerName] = (token) => { + debugFn(opts.loginHandlerName, token) + if (token && isString(token)) { + return ee.$trigger(LOGIN_EVENT_NAME, [token]) + } + throw new JsonqlValidationError(opts.loginHandlerName) + } + // logout event handler + obj[opts.logoutHandlerName] = (...args) => { + ee.$trigger(LOGOUT_EVENT_NAME, args) + } + } + return obj; +} diff --git a/packages/ws-client/src/core/respond-handler.js b/packages/ws-client/src/core/respond-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..4b793285b3b3957d3c38bbdb5fc3de96368e2ff3 --- /dev/null +++ b/packages/ws-client/src/core/respond-handler.js @@ -0,0 +1,25 @@ +// breaking it up further to share between methods +import { DATA_KEY, ERROR_KEY } from 'jsonql-constants' +import { UNKNOWN_RESULT } from '../options/constants' +import { isKeyInObject } from 'jsonql-utils/module' +import { getDebug } from '../utils' +const debugFn = getDebug('respondHandler') +/** + * break out to use in different places to handle the return from server + * @param {object} data from server + * @param {function} resolver NOT from promise + * @param {function} rejecter NOT from promise + * @return {void} nothing + */ +export function respondHandler(data, resolver, rejecter) { + if (isKeyInObject(data, ERROR_KEY)) { + debugFn('-- rejecter called --', data[ERROR_KEY]) + rejecter(data[ERROR_KEY]) + } else if (isKeyInObject(data, DATA_KEY)) { + debugFn('-- resolver called --', data[DATA_KEY]) + resolver(data[DATA_KEY]) + } else { + debugFn('-- UNKNOWN_RESULT --', data) + rejecter({message: UNKNOWN_RESULT, error: data}) + } +} diff --git a/packages/ws-client/src/core/setup-resolver.js b/packages/ws-client/src/core/setup-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..6620aa18073b8d7485f759430348d51d9d98417e --- /dev/null +++ b/packages/ws-client/src/core/setup-resolver.js @@ -0,0 +1,142 @@ +// break up the original setup resolver method here +import { + ERROR_TYPE, + DATA_KEY, + ERROR_KEY, + ERROR_PROP_NAME, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + SEND_MSG_PROP_NAME, + LOGIN_EVENT_NAME, + READY_PROP_NAME, + LOGOUT_EVENT_NAME +} from 'jsonql-constants' +import { + EMIT_EVT, + NOT_ALLOW_OP, + UNKNOWN_RESULT, + MY_NAMESPACE, + EXPECT_FUNC_ERR +} from '../options/constants' +import { validateAsync } from 'jsonql-params-validator' +import { chainFns, objDefineProps, injectToFn, createEvt, toArray } from 'jsonql-utils/module' +import { actionCall } from './action-call' +import { respondHandler } from './respond-handler' +import { getDebug, isFunc } from '../utils' +const debugFn = getDebug('setup-resolver') + +/** + * The first one in the chain + * @return {array} + */ +const setupNamespace = (fn, ee, namespace, resolverName, params) => [ + injectToFn(fn, MY_NAMESPACE, namespace), + ee, + namespace, + resolverName, + params +] + +// onResult handler +const setupOnResult = (fn, ee, namespace, resolverName, params) => [ + objDefineProps(fn, RESULT_PROP_NAME, function(resultCallback) { + if (isFunc(resultCallback)) { + ee.$on( + createEvt(namespace, resolverName, RESULT_PROP_NAME), + function resultHandler(result) { + respondHandler(result, resultCallback, (error) => { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) + }) + } + ) + } + }), + ee, + namespace, + resolverName, + params +] + +// we do need to add the send prop back because it's the only way to deal with +// bi-directional data stream +const setupOnMessage = (fn, ee, namespace, resolverName, params) => [ + objDefineProps(fn, MESSAGE_PROP_NAME, function(messageCallback) { + // we expect this to be a function + if (isFunc(messageCallback)) { + // did that add to the callback + let onMessageCallback = (args) => { + respondHandler(args, messageCallback, (error) => { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) + }) + } + // register the handler for this message event + ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback) + } + }), + ee, + namespace, + resolverName, + params +] + +// add an ERROR_PROP_NAME handler +const setupOnError = (fn, ee, namespace, resolverName, params) => [ + objDefineProps(fn, ERROR_PROP_NAME, function(resolverErrorHandler) { + if (isFunc(resolverErrorHandler)) { + // please note ERROR_PROP_NAME can add multiple listners + ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler) + } + }), + ee, + namespace, + resolverName, + params +] + +// pairing with the server vesrion SEND_MSG_PROP_NAME +// last of the chain so only return the resolver (fn) +const setupSend = (fn, ee, namespace, resolverName, params) => ( + objDefineProps(fn, SEND_MSG_PROP_NAME, function(messagePayload) { + debugFn('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(toArray(messagePayload), params.params, true) + .then(result => { + // here is the different we don't throw error instead we trigger onError + if (result[ERROR_KEY] && result[ERROR_KEY].length) { + debugFn(`got ERROR_KEY`, result[ERROR_KEY]) + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, result[ERROR_KEY])] + ) + } else { + // there is no return only an action call + actionCall(ee, namespace, resolverName, messagePayload) + } + }) + .catch(err => { + debugFn(`error after validateAsync`, err) + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, err)] + ) + }) + }) +) + +/** + * Add extra property to the resolver + * @param {string} namespace where this belongs + * @param {string} resolverName name as event name + * @param {object} params from contract + * @param {function} fn resolver function + * @param {object} ee EventEmitter + * @return {function} resolver + */ +export function setupResolver(namespace, resolverName, params, fn, ee) { + // also need to setup a getter to get back the namespace of this resolver + const args = [fn, ee, namespace, resolverName, params] + const exe = chainFns(setupNamespace, setupOnResult, setupOnMessage, setupOnError, setupSend) + // debug(exe) + return Reflect.apply(exe, null, args) +} diff --git a/packages/ws-client/src/options/constants.js b/packages/ws-client/src/options/constants.js index 928a430444d7902b9b759bc525a3cf2ed6bac2c7..bbc935c94ab1481e4f18aa7a8f4ffa9540d82733 100644 --- a/packages/ws-client/src/options/constants.js +++ b/packages/ws-client/src/options/constants.js @@ -21,6 +21,8 @@ const MISSING_PROP_ERR = 'Missing property in contract!'; const UNKNOWN_CLIENT_ERR = 'Unknown client type!'; +const EXPECT_FUNC_ERR = `Expect a function!` + const EMIT_EVT = EMIT_REPLY_TYPE; const NAMESPACE_KEY = 'namespaceMap'; @@ -45,5 +47,6 @@ export { NAMESPACE_KEY, UNKNOWN_RESULT, NOT_ALLOW_OP, - MY_NAMESPACE + MY_NAMESPACE, + EXPECT_FUNC_ERR } diff --git a/packages/ws-client/src/options/defaults.js b/packages/ws-client/src/options/defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..66f78f0d77027050c7a4e592178453ad63d28412 --- /dev/null +++ b/packages/ws-client/src/options/defaults.js @@ -0,0 +1,33 @@ +// take the sharable default options out and put here +// then we can export it and re-use on the downstream clients +import { createConfig } from 'jsonql-params-validator' +import { isContract } from 'jsonql-utils' +import { + STRING_TYPE, + BOOLEAN_TYPE, + OBJECT_TYPE, + ENUM_KEY, + CHECKER_KEY, + JSONQL_PATH, + ISSUER_NAME, + LOGOUT_NAME +} from 'jsonql-constants' +import { AVAILABLE_SERVERS } from './constants' + +const defaultOptions = { + loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), + // we will use this for determine the socket.io client type as well + useJwt: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), + hostname: createConfig(false, [STRING_TYPE]), + namespace: createConfig(JSONQL_PATH, [STRING_TYPE]), + wsOptions: createConfig({}, [OBJECT_TYPE]), + // 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({}, [OBJECT_TYPE], {[CHECKER_KEY]: isContract}), + enableAuth: createConfig(false, [BOOLEAN_TYPE]), + token: createConfig(false, [STRING_TYPE]) +} + +export { defaultOptions } diff --git a/packages/ws-client/src/options/index.js b/packages/ws-client/src/options/index.js index b1ca0834b9fa581193d08449e4b032c19cdc7d6e..a85940d0c0d10fac76f7b75ba898c5d40a71c798 100644 --- a/packages/ws-client/src/options/index.js +++ b/packages/ws-client/src/options/index.js @@ -1,48 +1,29 @@ // create options -import { createConfig, checkConfigAsync, isNotEmpty } from 'jsonql-params-validator' -import { isContract } from 'jsonql-utils' -import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors' -import { - STRING_TYPE, - BOOLEAN_TYPE, - OBJECT_TYPE, - ENUM_KEY, - CHECKER_KEY, - JSONQL_PATH, - ISSUER_NAME, - LOGOUT_NAME -} from 'jsonql-constants' +import { checkConfigAsync, isNotEmpty } from 'jsonql-params-validator' +// import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors' // this should be remove - we have to make it generic -import { SOCKET_IO, WS, AVAILABLE_SERVERS } from './constants' +import { defaultOptions } from './defaults' import { fixWss, getHostName, getDebug } from '../utils' const debug = getDebug('check-options') // constant props -const constProps = { +const defaultConstProps = { eventEmitter: null, // we unify the two different client into one now // only expect different parameter nspClient: null, + nspAuthClient: null, // contructed path wssPath: '' } -const defaultOptions = { - loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), - // we will use this for determine the socket.io client type as well - useJwt: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), - hostname: createConfig(false, [STRING_TYPE]), - namespace: createConfig(JSONQL_PATH, [STRING_TYPE]), - wsOptions: createConfig({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), - serverType: createConfig(SOCKET_IO, [STRING_TYPE], {[ENUM_KEY]: AVAILABLE_SERVERS}), - // we require the contract already generated and pass here - contract: createConfig({}, [OBJECT_TYPE], {[CHECKER_KEY]: isContract}), - enableAuth: createConfig(false, [BOOLEAN_TYPE]), - token: createConfig(false, [STRING_TYPE]) -} -// export -export default function checkOptions(config) { - return checkConfigAsync(config, defaultOptions, constProps) +/** + * check the configuration + * @param {object} config user supplied configuration + * @param {object} constProps developer supplied configuration + * @return {object} after checked + */ +export default function checkOptions(config, constProps) { + return checkConfigAsync(config, defaultOptions, Object.assign(defaultConstProps, constProps)) .then(opts => { if (!opts.hostname) { opts.hostname = getHostName() @@ -50,8 +31,7 @@ export default function checkOptions(config) { // @TODO the contract now will supply the namespace information // and we need to use that to group the namespace call opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType) - - debug('opts', opts) + debug('CONFIGURATION OPTIONS', opts) return opts; }) } diff --git a/packages/ws-client/src/share/client-event-handler.js b/packages/ws-client/src/share/client-event-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..9b6516ddbc5165b8ed8903d344c367a0f9b711fd --- /dev/null +++ b/packages/ws-client/src/share/client-event-handler.js @@ -0,0 +1,94 @@ +// This is share between different clients so we export it + + +// @TODO port what is in the ws-main-handler +// because all the client side call are via the ee +// and that makes it re-usable between different client setup +import { + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + EMIT_EVT, + SOCKET_IO, + WS +} from '../options/constants' +import { + LOGIN_EVENT_NAME, + LOGOUT_EVENT_NAME, + NOT_LOGIN_ERR_MSG, + ERROR_PROP_NAME +} from 'jsonql-constants' + +import { getDebug, createEvt, clearMainEmitEvt } from '../utils' +import { triggerNamespacesOnError } from './trigger-namespaces-on-error' +const debugFn = getDebug('client-event-handler') + +/** + * A fake ee handler + * @param {string} namespace nsp + * @param {object} ee EventEmitter + * @return {void} + */ +const notLoginWsHandler = (namespace, ee) => { + ee.$only( + createEvt(namespace, EMIT_EVT), + function notLoginHandlerCallback(resolverName, args) { + debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args) + let error = { + message: NOT_LOGIN_ERR_MSG + } + // It should just throw error here and should not call the result + // because that's channel for handling normal event not the fake one + ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error]) + // also trigger the result handler, but wrap inside the error key + ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error }]) + } + ) +} + +/** + * centralize all the comm in one place + * @param {object} opts configuration + * @param {array} namespaces namespace(s) + * @param {object} ee Event Emitter instance + * @param {function} bindWsHandler binding the ee to ws --> this is the core bit + * @param {array} namespaces array of namespace available + * @param {object} nsps namespaced nsp + * @return {void} nothing + */ +export function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) { + // loop + // @BUG for io this has to be in order the one with auth need to get call first + // The order of login is very import we need to run a waterfall here to make sure + // one is execute then the other + namespaces.forEach(namespace => { + if (nsps[namespace]) { + debugFn('call bindWsHandler', namespace) + let args = [namespace, nsps[namespace], ee] + if (opts.serverType === SOCKET_IO) { + let { nspSet } = nspMap; + args.push(nspSet[namespace]) + args.push(opts) + } + Reflect.apply(bindWsHandler, null, args) + } else { + // a dummy placeholder + notLoginWsHandler(namespace, ee) + } + }) + // this will be available regardless enableAuth + // because the server can log the client out + ee.$on(LOGOUT_EVENT_NAME, function logoutEvtHandler() { + debugFn('LOGOUT_EVENT_NAME') + // disconnect(nsps, opts.serverType) + // we need to issue error to all the namespace onError handler + triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME) + // rebind all of the handler to the fake one + namespaces.forEach( namespace => { + clearMainEmitEvt(ee, namespace) + // clear out the nsp + nsps[namespace] = false; + // add a NOT LOGIN error if call + notLoginWsHandler(namespace, ee) + }) + }) +} diff --git a/packages/ws-client/src/share/create-nsp-client.js b/packages/ws-client/src/share/create-nsp-client.js new file mode 100644 index 0000000000000000000000000000000000000000..5e732410fcd941f025f76d0b4da6579d4dccf802 --- /dev/null +++ b/packages/ws-client/src/share/create-nsp-client.js @@ -0,0 +1,36 @@ +// since both the ws and io version are +// pre-defined in the client-generator +// and this one will have the same parameters +// and the callback is identical + +/** + * wrapper method to create a nsp without login + * @param {string|boolean} namespace namespace url could be false + * @param {object} opts configuration + * @return {object} ws client instance + */ +function createNspClient(namespace, opts) { + const { hostname, wssPath, wsOptions, nspClient } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + return nspClient(url, wsOptions) +} + +/** + * wrapper method to create a nsp with token auth + * @param {string} namespace namespace url + * @param {object} opts configuration + * @return {object} ws client instance + */ +function createNspAuthClient(namespace, opts) { + const { hostname, wssPath, token, wsOptions, nspAuthClient } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + if (token && typeof token !== 'string') { + throw new Error(`Expect token to be string, but got ${token}`) + } + return nspAuthClient(url, token, wsOptions) +} + +export { + createNspClient, + createNspAuthClient +} diff --git a/packages/ws-client/src/share/trigger-namespaces-on-error.js b/packages/ws-client/src/share/trigger-namespaces-on-error.js new file mode 100644 index 0000000000000000000000000000000000000000..1496f6601baf855aab78f8ea470e75b82b74ce69 --- /dev/null +++ b/packages/ws-client/src/share/trigger-namespaces-on-error.js @@ -0,0 +1,15 @@ +// this use by client-event-handler +import { ERROR_PROP_NAME } from 'jsonql-constants' +import { createEvt } from 'jsonql-utils' +/** + * trigger errors on all the namespace onError handler + * @param {object} ee Event Emitter + * @param {array} namespaces nsps string + * @param {string} message optional + * @return {void} + */ +export function triggerNamespacesOnError(ee, namespaces, message) { + namespaces.forEach( namespace => { + ee.$call(createEvt(namespace, ERROR_PROP_NAME), [{ message, namespace }]) + }) +} diff --git a/packages/ws-client/src/utils/ee.js b/packages/ws-client/src/utils/ee.js index d16626e55b7459b98e82ca70853e76f25c070e79..2cb6caf77d8d05827969cfb4a05ff8f2490b142c 100644 --- a/packages/ws-client/src/utils/ee.js +++ b/packages/ws-client/src/utils/ee.js @@ -5,8 +5,10 @@ import NBEventService from 'nb-event-service' export default class JsonqlWsEvt extends NBEventService { constructor() { + // this ee will always come with the logger + // because we should take the ee from the configuration super({ - // logger: getDebug('nb-event-service') + logger: getDebug('nb-event-service') }) } diff --git a/packages/ws-client/src/utils/get-debug.js b/packages/ws-client/src/utils/get-debug.js index 7ef63c8b772fe1ca37abc8639339fa8283f13eaa..d962e154083b983451e75e48756e7e6e019dc4ed 100644 --- a/packages/ws-client/src/utils/get-debug.js +++ b/packages/ws-client/src/utils/get-debug.js @@ -25,8 +25,8 @@ const getDebug = (name) => { } } try { - if (window && window.localStorage) { - localStorage.setItem('DEBUG', 'jsonql-ws-client*') + if (window && window.localStorage && window.DEBUG) { + localStorage.setItem('DEBUG', `${BASE_NAME}*`) } } catch(e) {} // export it diff --git a/packages/ws-client/src/utils/helpers.js b/packages/ws-client/src/utils/helpers.js index b9afa2fa483325fa49d476c073b9125b1798ec25..2f35ec67baa04cdbb8d362b626de95b03b0e34da 100644 --- a/packages/ws-client/src/utils/helpers.js +++ b/packages/ws-client/src/utils/helpers.js @@ -1,5 +1,9 @@ // group all the small functions here -import { JS_WS_SOCKET_IO_NAME, JS_WS_NAME} from 'jsonql-constants' +import { JS_WS_SOCKET_IO_NAME, JS_WS_NAME, EMIT_REPLY_TYPE } from 'jsonql-constants' +import { EXPECT_FUNC_ERR } from '../options/constants' +import { toArray, createEvt } from 'jsonql-utils/module' +// import { getDebug } from './get-debug'; +// const debug = getDebug('helpers') // we shouldn't do this anymore export const fixWss = (url, serverType) => { @@ -28,9 +32,9 @@ export const getHostName = () => { * @return {void} */ export const clearMainEmitEvt = (ee, namespace) => { - let nsps = isArray(namespace) ? namespace : [namespace] + let nsps = toArray(namespace) nsps.forEach(n => { - ee.$off(createEvt(n, constants.EMIT_EVT)) + ee.$off(createEvt(n, EMIT_REPLY_TYPE)) }) } @@ -59,4 +63,9 @@ export const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => { * @param {*} prop input * @return {boolean} true on success */ -export const isFunc = prop => typeof prop === 'function'; +export const isFunc = prop => { + if (typeof prop === 'function') { + return true; + } + console.error(EXPECT_FUNC_ERR) +} diff --git a/packages/ws-client/src/utils/index.js b/packages/ws-client/src/utils/index.js index f6a8c74cc3903e6c3ab919864464561f1b318e57..a2e829f240a74790451aa1842f1b30521df45b7e 100644 --- a/packages/ws-client/src/utils/index.js +++ b/packages/ws-client/src/utils/index.js @@ -1,7 +1,7 @@ // export the util methods import { isArray } from 'jsonql-params-validator' // moved to jsonql-utils -import { toArray, createEvt, injectToFn, objDefineProps } from 'jsonql-utils' +import { toArray, createEvt, injectToFn, objDefineProps } from 'jsonql-utils/module' import ee from './ee' import getDebug from './get-debug' @@ -10,7 +10,8 @@ import { fixWss, getHostName, clearMainEmitEvt, - disconnect + disconnect, + isFunc } from './helpers' // export @@ -29,5 +30,6 @@ export { fixWss, getHostName, clearMainEmitEvt, - disconnect + disconnect, + isFunc } diff --git a/packages/ws-client/src/utils/process-contract.js b/packages/ws-client/src/utils/process-contract.js index 43f6a1726d00f540599f7d4fd8c8883c0d61e3f1..67360d5e8dc960c5003a7ab8158694b538922aca 100644 --- a/packages/ws-client/src/utils/process-contract.js +++ b/packages/ws-client/src/utils/process-contract.js @@ -1,6 +1,6 @@ // mapping the resolver to their respective nsp import { JSONQL_PATH, NSP_SET, PUBLIC_NAMESPACE } from 'jsonql-constants' -import { groupByNamespace, extractSocketPart } from 'jsonql-utils' +import { groupByNamespace, extractSocketPart } from 'jsonql-utils/module' import { JsonqlResolverNotFoundError } from 'jsonql-errors' import { MISSING_PROP_ERR } from '../options/constants' diff --git a/packages/ws-client/tests/event.test.js b/packages/ws-client/tests/event.test.js new file mode 100644 index 0000000000000000000000000000000000000000..5d72ded9fc7f5f9156e0514426525cc7c0df988f --- /dev/null +++ b/packages/ws-client/tests/event.test.js @@ -0,0 +1,31 @@ +// retest the nb-event-service here to try to figure out why some of the event not fired +const test = require('ava') +const NbEventService = require('nb-event-service') +const debug = require('debug')('jsonql-ws-client:test:event') + +test.before(t => { + t.context.evt = new NbEventService({logger: debug}) +}) + +test.cb(`It should able to trigger multiple callback`, t => { + t.plan(3) + let ctn = 0; + const evt = t.context.evt + evt.$on('something', function somethingOneHandler(value) { + t.is(value, 1) + debug(++ctn) + }) + evt.$on('something', function somethingTwoHandler(value) { + t.is(value, 1) + debug(++ctn) + }) + evt.$on('something', function somethingLastHandler(value) { + debug(++ctn) + t.is(value, 1) + t.end() + + }) + + evt.$trigger('something', 1) + +}) diff --git a/packages/ws-client/tests/fixtures/jsonql-ws-client.js b/packages/ws-client/tests/fixtures/beta/jsonql-ws-client.js similarity index 56% rename from packages/ws-client/tests/fixtures/jsonql-ws-client.js rename to packages/ws-client/tests/fixtures/beta/jsonql-ws-client.js index 6b0303258d6b3d483b30a89c4e1b821fa47f57c3..3f4d4b2ba0792bc916b66a700aab8cd2ba3051b3 100644 --- a/packages/ws-client/tests/fixtures/jsonql-ws-client.js +++ b/packages/ws-client/tests/fixtures/beta/jsonql-ws-client.js @@ -1,6 +1,6 @@ // this will create the final client -import wsClientResolver from './beta/ws-client-resolver' -import jsonqlWsClient from '../../src/api' +import wsClientResolver from './ws-client-resolver' +import { jsonqlWsClient } from '../../../index' // export back the function and that's it export default jsonqlWsClient(wsClientResolver) diff --git a/packages/ws-client/tests/fixtures/beta/src/client-event-handler.js b/packages/ws-client/tests/fixtures/beta/src/client-event-handler.js index ef3ede423ea3db8e519f40fa338d7f2f6d2feebd..634ddf4c4e4ffe5a4b7bc0c48ac59cda3b1827cb 100644 --- a/packages/ws-client/tests/fixtures/beta/src/client-event-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/client-event-handler.js @@ -1,3 +1,4 @@ + // @TODO port what is in the ws-main-handler // because all the client side call are via the ee // and that makes it re-usable between different client setup diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js index dbd12eb8e303c8b84d90f0d59246a1a8601818d8..3b9a7f958ac65e1e594776e349dfcc64dacafa53 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js @@ -12,6 +12,7 @@ import debug from 'debug' const debugFn = debug('jsonql-ws-client:ws-create-client') + /** * Because the nsps can be throw away so it doesn't matter the scope * this will get reuse again diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js index b52d32b0feb2a03b8b8821acf6b79742f3d826a4..2bf16b6cae6f10e68f01f84ddd9212fa7c01e401 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js @@ -13,14 +13,12 @@ import { ERROR_TYPE, READY_PROP_NAME } from 'jsonql-constants' - -import extractWsPayload from './extract-ws-payload' import { createQueryStr } from 'jsonql-utils' +import extractWsPayload from './extract-ws-payload' import { getDebug, createEvt } from '../utils' -import debug from 'debug' -const debugFn = debug('jsonql-ws-client:ws-main-handler') +const debugFn = getDebug('ws-main-handler') /** * under extremely circumstances we might not even have a resolverName, then @@ -59,7 +57,7 @@ export default function wsMainHandlerAction(namespace, ws, ee) { // add listener ee.$only( createEvt(namespace, EMIT_EVT), - function(resolverName, args) { + function onopenEmitEvtCallback(resolverName, args) { debugFn('calling server', resolverName, args) ws.send( createQueryStr(resolverName, args) @@ -72,15 +70,15 @@ export default function wsMainHandlerAction(namespace, ws, ee) { ws.onmessage = function(payload) { try { const json = extractWsPayload(payload) - debugFn('Hear from server', json) const { resolverName, type } = json; + debugFn('Hear from server', type, json) switch (type) { case EMIT_REPLY_TYPE: let r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json]) - debugFn(MESSAGE_PROP_NAME, r) + debugFn(`MESSAGE_PROP_NAME`, r) break; case ACKNOWLEDGE_REPLY_TYPE: - debugFn(RESULT_PROP_NAME, json) + debugFn(`RESULT_PROP_NAME`, json) let x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json]) debugFn('onResult add to event?', x) break; @@ -109,7 +107,7 @@ export default function wsMainHandlerAction(namespace, ws, ee) { // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) } // listen to the LOGOUT_EVENT_NAME - ee.$on(LOGOUT_EVENT_NAME, function close() { + ee.$on(LOGOUT_EVENT_NAME, function closeEvtHandler() { try { debugFn('terminate ws connection') ws.terminate() diff --git a/packages/ws-client/src/core/client-event-handler.js b/packages/ws-client/tests/fixtures/old-ws-client/client-event-handler.js similarity index 100% rename from packages/ws-client/src/core/client-event-handler.js rename to packages/ws-client/tests/fixtures/old-ws-client/client-event-handler.js diff --git a/packages/ws-client/src/core/create-nsp-client.js b/packages/ws-client/tests/fixtures/old-ws-client/create-nsp-client.js similarity index 100% rename from packages/ws-client/src/core/create-nsp-client.js rename to packages/ws-client/tests/fixtures/old-ws-client/create-nsp-client.js diff --git a/packages/ws-client/src/core/map-event-to-client.js b/packages/ws-client/tests/fixtures/old-ws-client/map-event-to-client.js similarity index 100% rename from packages/ws-client/src/core/map-event-to-client.js rename to packages/ws-client/tests/fixtures/old-ws-client/map-event-to-client.js diff --git a/packages/ws-client/src/core/trigger-namespaces-on-error.js b/packages/ws-client/tests/fixtures/old-ws-client/trigger-namespaces-on-error.js similarity index 100% rename from packages/ws-client/src/core/trigger-namespaces-on-error.js rename to packages/ws-client/tests/fixtures/old-ws-client/trigger-namespaces-on-error.js index 59409c8162602f2f507413873e96707f65512cea..5dc3fa81850fa6083a1fb9cfc1a65ae9772b6a57 100644 --- a/packages/ws-client/src/core/trigger-namespaces-on-error.js +++ b/packages/ws-client/tests/fixtures/old-ws-client/trigger-namespaces-on-error.js @@ -1,6 +1,6 @@ - import { ERROR_PROP_NAME } from 'jsonql-constants' import { createEvt } from './index' + /** * trigger errors on all the namespace onError handler * @param {object} ee Event Emitter diff --git a/packages/ws-client/tests/options.test.js b/packages/ws-client/tests/options.test.js new file mode 100644 index 0000000000000000000000000000000000000000..65f00912b40945351093f1c9809a083d842b6306 --- /dev/null +++ b/packages/ws-client/tests/options.test.js @@ -0,0 +1,37 @@ +// just testing if the options are export correctly + +const test = require('ava') +const debug = require('debug')('jsonql-ws-client:test:options') +const { constants, triggerNamespacesOnError } = require('../share') +const { objDefineProps, injectToFn, chainFns } = require('jsonql-utils')//require('../../utils/main') + +test(`Should have the constants in options`, t => { + + t.truthy(constants.MY_NAMESPACE) + + t.is(typeof triggerNamespacesOnError, 'function') +}) + +test(`test the objDefineProps if it return a new prop`, t => { + const prop0 = 'prop zero' + const prop1 = 'prop from fn1' + const fn1 = (fn, name, prop) => { + return [ + injectToFn(fn, name, prop), + 'prop1', + prop1 + ] + } + const fn2 = (fn, name, prop) => { + debug(name, prop, fn) + return injectToFn(fn, name, prop) + } + const exe = chainFns(fn1, fn2) + const obj = {} + + const fnFinal = exe(obj, 'prop0', prop0) + + t.is(obj.prop0, prop0) + t.is(obj.prop1, prop1) + +}) diff --git a/packages/@jsonql/ws/tests/test-node.test.js b/packages/ws-client/tests/test-node-parts.test.js similarity index 87% rename from packages/@jsonql/ws/tests/test-node.test.js rename to packages/ws-client/tests/test-node-parts.test.js index af83dde7f3e942ea4f36d31fa8187fd21326f00d..db249925fde20ddd976f9e9d6516f65417aec384 100644 --- a/packages/@jsonql/ws/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node-parts.test.js @@ -14,14 +14,8 @@ const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json' const { NOT_LOGIN_ERR_MSG, JS_WS_SOCKET_IO_NAME, JS_WS_NAME } = require('jsonql-constants') const payload = {name: 'Joel'}; const token = genToken(payload) -const port = 8010; +const port = 8888; const url = `ws://localhost:${port}` -//////////////////// -const { - chainCreateNsps, - clientGenerator, - es -} = require('./fixtures/node') /// PREPARE TEST /// test.before(async t => { @@ -37,14 +31,11 @@ test.before(async t => { t.context.server = app.listen(port) - let config = { opts: { serverType: JS_WS_SOCKET_IO_NAME }, nspMap: {}, ee: es }; - let { opts, ee } = clientGenerator(config) - t.context.opts = opts; - t.context.ee = ee; + }) // real test start here -test.serial.cb('It should able to replace the same event with new method', t => { +test.serial.cb.skip('It should able to replace the same event with new method', t => { t.plan(3) // try a sequence with swapping out the event handler @@ -73,7 +64,7 @@ test.serial.cb('It should able to replace the same event with new method', t => ee.$call(evtName, [fnName, 3]) }) -test.serial.cb.only('It should able to resolve the promise one after the other', t => { +test.serial.cb.skip('It should able to resolve the promise one after the other', t => { t.plan(1) let opts = t.context.opts; let p1 = () => opts.nspAuthClient([url, 'jsonql/private'].join('/'), token) @@ -95,7 +86,7 @@ test.serial.cb.only('It should able to resolve the promise one after the other', }) }) -test.serial.cb('Just test with the ws client can connect to the server normally', t => { +test.serial.cb.skip('Just test with the ws client can connect to the server normally', t => { t.plan(2) let opts = t.context.opts; @@ -131,7 +122,7 @@ test.serial.cb('Just test with the ws client can connect to the server normally' }) -test.serial.cb('It should able to use the chainCreateNsps to run connection in sequence', t => { +test.serial.cb.skip('It should able to use the chainCreateNsps to run connection in sequence', t => { t.plan(1) let opts = t.context.opts; diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index a11a539ae9dcf9e85a4d798ef7e611a8b5a2a82e..03ea693ead49fd32125a62548af4a6fe52ab676a 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -1,6 +1,7 @@ /// breaking things apart and try to figure out what went wrong at the last step const test = require('ava') const debug = require('debug')('jsonql-ws-client:test:node') +global.debug = debug; /// SERVER SETUP /// const { join } = require('path') const fsx = require('fs-extra') @@ -8,8 +9,8 @@ const fsx = require('fs-extra') const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') -const jsonqlWsClient = require('./fixtures/jsonql-ws-client') -const wsClient = jsonqlWsClient.default +const jsonqlWsClient = require('./fixtures/beta/jsonql-ws-client') +const wsClient = jsonqlWsClient.default || jsonqlWsClient const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) @@ -54,17 +55,29 @@ test.before(async t => { t.context.client = await wsClient({ contract, hostname: url, - serverType: JS_WS_NAME, enableAuth: true }) +}) +test.after( t => { + t.context.server.close() }) // real test start here test.serial('It should able to create the WebSocket client object', t => { const client = t.context.client; + t.truthy(client) + t.true(typeof client.pinging === 'function') + /// test individual properties + t.truthy( Object.getOwnPropertyDescriptor(client.pinging, ERROR_PROP_NAME), `has ${ERROR_PROP_NAME} prop`) + t.truthy( Object.getOwnPropertyDescriptor(client.pinging, MESSAGE_PROP_NAME), `has ${MESSAGE_PROP_NAME} prop`) + t.truthy( Object.getOwnPropertyDescriptor(client.pinging, RESULT_PROP_NAME), `has ${RESULT_PROP_NAME} prop`) + t.truthy( Object.getOwnPropertyDescriptor(client.pinging, SEND_MSG_PROP_NAME), `has ${SEND_MSG_PROP_NAME} prop`) + + t.truthy( Object.getOwnPropertyDescriptor(client, READY_PROP_NAME), `the client object should have ${READY_PROP_NAME} prop`) + }) test.serial.cb('The ws client can connect to the WebSocket server public interface', t => { @@ -72,21 +85,26 @@ test.serial.cb('The ws client can connect to the WebSocket server public interfa let ctn = 0; const client = t.context.client; - client.pinging.onResult = function(result) { + client.onReady = function testOnReadyCallback() { + debug(`onReady executed`) + } + + client.pinging.onResult = function testonResultCallback(result) { ++ctn - debug(`${ctn} result`, result) + debug(`[${ctn}] result`, result) t.pass() } - client.pinging.onError = function(err) { + client.pinging.onError = function testOnErrorCallback(err) { ++ctn; debug(`[got error]`, err.error.detail[0]) t.pass() } - client.pinging.onMessage = function(msg) { + debug(`${MESSAGE_PROP_NAME}`) + client.pinging.onMessage = function testOnMessageCallback(msg) { ++ctn; - debug(`${ctn} ${MESSAGE_PROP_NAME}`, msg) + debug(`[${ctn}] ${MESSAGE_PROP_NAME}`, msg) t.pass() t.end() } @@ -108,6 +126,4 @@ test.serial.cb('The ws client can connect to the WebSocket server public interfa t.pass() // t.end() }) - - }) diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 3c3cfc395cf7634f904638fc500c12a5054cf420..86b507e8264097521e23f73fc257dc8a8138bbf8 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server", - "version": "1.3.2", + "version": "1.3.4", "description": "Setup WebSocket server for the jsonql to run on the same host, automatic generate public / private channel using contract", "main": "index.js", "files": [ @@ -36,9 +36,9 @@ "jsonql-jwt": "^1.3.3", "jsonql-params-validator": "^1.4.11", "jsonql-resolver": "^0.9.4", - "jsonql-utils": "^0.7.6", + "jsonql-utils": "^0.7.8", "lodash": "^4.17.15", - "ws": "^7.1.2" + "ws": "^7.2.0" }, "devDependencies": { "ava": "^2.4.0", diff --git a/packages/ws-server/src/core/verify-client.js b/packages/ws-server/src/core/verify-client.js index 80334caceb4270ce7b3388c34e771caf504778be..6ad441451c4fb62fe1debb45712ff9554ad906d3 100644 --- a/packages/ws-server/src/core/verify-client.js +++ b/packages/ws-server/src/core/verify-client.js @@ -35,11 +35,12 @@ function createVerifyClient(publicKey, jwtOptions = {}, failCallback = false) { * @param {function} done a callback to pass or fail the login */ return function verifyClient(info, done) { - let token = getTokenFromQuery(info.req.url) + const uri = info.req.url + const token = getTokenFromQuery(uri) if (token) { try { - let payload = jwtDecode(token, publicKey, jwtOptions) - debug(`calling verifyClient`, payload) + const payload = jwtDecode(token, publicKey, jwtOptions) + debug(`verifyClient decoded with result:`, payload) if (!info.req.state) { info.req.state = {}; } @@ -48,7 +49,7 @@ function createVerifyClient(publicKey, jwtOptions = {}, failCallback = false) { return done(payload) } catch(e) { done(false) - cb(e) + cb({e, token, uri}) } } cb('no token!')