diff --git a/packages/@jsonql/ws/old/client/auth-client.js b/archived/ws/old/client/auth-client.js similarity index 100% rename from packages/@jsonql/ws/old/client/auth-client.js rename to archived/ws/old/client/auth-client.js diff --git a/packages/@jsonql/ws/old/client/ws.js b/archived/ws/old/client/ws.js similarity index 100% rename from packages/@jsonql/ws/old/client/ws.js rename to archived/ws/old/client/ws.js diff --git a/packages/@jsonql/ws/old/server/get-userdata.js b/archived/ws/old/server/get-userdata.js similarity index 100% rename from packages/@jsonql/ws/old/server/get-userdata.js rename to archived/ws/old/server/get-userdata.js diff --git a/packages/@jsonql/ws/old/server/verify-client.js b/archived/ws/old/server/verify-client.js similarity index 100% rename from packages/@jsonql/ws/old/server/verify-client.js rename to archived/ws/old/server/verify-client.js diff --git a/packages/@jsonql/ws/old/ws-client.js b/archived/ws/old/ws-client.js similarity index 100% rename from packages/@jsonql/ws/old/ws-client.js rename to archived/ws/old/ws-client.js diff --git a/packages/@jsonql/ws/old/ws/create-client.js b/archived/ws/old/ws/create-client.js similarity index 100% rename from packages/@jsonql/ws/old/ws/create-client.js rename to archived/ws/old/ws/create-client.js diff --git a/packages/@jsonql/ws/old/ws/extract-ws-payload.js b/archived/ws/old/ws/extract-ws-payload.js similarity index 100% rename from packages/@jsonql/ws/old/ws/extract-ws-payload.js rename to archived/ws/old/ws/extract-ws-payload.js diff --git a/packages/@jsonql/ws/old/ws/index.js b/archived/ws/old/ws/index.js similarity index 100% rename from packages/@jsonql/ws/old/ws/index.js rename to archived/ws/old/ws/index.js diff --git a/packages/@jsonql/ws/old/ws/ws-main-handler.js b/archived/ws/old/ws/ws-main-handler.js similarity index 100% rename from packages/@jsonql/ws/old/ws/ws-main-handler.js rename to archived/ws/old/ws/ws-main-handler.js diff --git a/packages/@jsonql/ws/old/ws/ws.js b/archived/ws/old/ws/ws.js similarity index 100% rename from packages/@jsonql/ws/old/ws/ws.js rename to archived/ws/old/ws/ws.js diff --git a/packages/@jsonql/koa/index.js b/packages/@jsonql/koa/index.js index a6160945fcc0279e029c0896d934ee681cf19f5c..82633699765e8d8f1e2028256e711180b2e54d9a 100644 --- a/packages/@jsonql/koa/index.js +++ b/packages/@jsonql/koa/index.js @@ -1,20 +1,31 @@ // main const debug = require('debug')('jsonql-koa:main') +const checkOptions = require('./src/options') +const { initServer } = require('./src') +const { version } = require('./package.json') /** * @param {object} config options * @return {object} with several method to control the server */ -module.exports = function(config, middlewares = []) { +module.exports = function createKoaServer(config = {}, middlewares = []) { + // keep a copy of the original config + const originalConfig = Object.assign({}, config) + const opts = checkOptions(config) - debug('config', config) + const { server, app, ws } = initServer(config, middlewares) - return { - start: () => { - - }, - stop: () => { + const start = () => { + debug(`Server version: ${version} start on ${opts.port}`) + server.listen(opts.port) + } + const stop = () => { + server.close() + } - } + if (opts.autoStart) { + start() } + // export + return { start, stop, app, ws } } diff --git a/packages/@jsonql/koa/package.json b/packages/@jsonql/koa/package.json index b10456fe0fb204c07c812ebc6fa899ff7df0bb9d..545b09bb5ac952d7e7679f20d04745e102f5de87 100644 --- a/packages/@jsonql/koa/package.json +++ b/packages/@jsonql/koa/package.json @@ -5,6 +5,7 @@ "main": "index.js", "scripts": { "test": "ava --verbose", + "test:basic": "DEBUG=jsonql-koa* ava --verbose ./tests/basic.test.js", "test:cli": "DEBUG=jsonql-koa* node ./cli.js" }, "keywords": [ @@ -22,7 +23,6 @@ "license": "MIT", "devDependencies": { "ava": "^2.4.0", - "debug": "^4.1.1", "nyc": "^14.1.1", "superkoa": "^1.0.3" }, @@ -47,9 +47,11 @@ "node": ">=8" }, "dependencies": { + "debug": "^4.1.1", "fs-extra": "^8.1.0", "jsonql-constants": "^1.8.9", - "jsonql-koa": "^1.3.10", + "jsonql-koa": "^1.3.11", + "jsonql-params-validator": "^1.4.11", "koa": "^2.11.0", "koa-bodyparser": "^4.2.1", "koa-cors": "0.0.16", diff --git a/packages/@jsonql/koa/src/get-socket-server.js b/packages/@jsonql/koa/src/get-socket-server.js index 160ea8cee4b2011708e745e855d88b8e168b75d4..7327db79dcbe780f02de79b4e8d1a002161d1ec4 100644 --- a/packages/@jsonql/koa/src/get-socket-server.js +++ b/packages/@jsonql/koa/src/get-socket-server.js @@ -15,7 +15,8 @@ function getSocketServer(config, server) { case JS_WS_SOCKET_IO_NAME: case JS_PRIMUS_NAME: default: - throw new Error(`Not support ${config.serverType} at the moment!`) + console.error(`Not support ${config.serverType} at the moment!`) + return false; } return wsServer(config) } diff --git a/packages/@jsonql/koa/src/index.js b/packages/@jsonql/koa/src/index.js index 56def75e9f5cdcb2246b649f57f2f7f3d9567e41..b75a198b7d72fbb99af5a88ba86776df2197953a 100644 --- a/packages/@jsonql/koa/src/index.js +++ b/packages/@jsonql/koa/src/index.js @@ -3,9 +3,9 @@ const http = require('http') const Koa = require('koa') const bodyparser = require('koa-bodyparser') const cors = require('koa-cors') -const contractApi = require('jsonql-koa/contract') -const jsonqlKoa = require('jsonql-koa') -const getSocketServer = require('./get-socket-server') +// const contractApi = require('jsonql-koa/contract') +const { jsonqlKoa } = require('jsonql-koa') +const { getSocketServer } = require('./get-socket-server') /** * @param {object} config configuration @@ -25,13 +25,10 @@ function initServer(config, middlewares) { }) const server = http.createServer(app.callback()) - + const ws = getSocketServer(config, server) // return it - return { - ws, - server - } + return { server, app, ws } } module.exports = { initServer } diff --git a/packages/@jsonql/koa/src/options/index.js b/packages/@jsonql/koa/src/options/index.js index a69bf15f8fa407cd433806f4620f422b05e9c03b..c619037a4b6285edfd5395ca455552c4103b603b 100644 --- a/packages/@jsonql/koa/src/options/index.js +++ b/packages/@jsonql/koa/src/options/index.js @@ -1,6 +1,6 @@ -const { checkOptions } = require('jsonql-params-valiator') +const { checkConfig } = require('jsonql-params-validator') const { options } = require('./options') module.exports = function(config) { - return checkOptions(config, options) + return checkConfig(config, options) } diff --git a/packages/@jsonql/koa/src/options/options.js b/packages/@jsonql/koa/src/options/options.js index f59cff0031b7d2db63641cd950e6414a92bc1969..42a171716dd5653f8050fa722bf4fa763e68ac3f 100644 --- a/packages/@jsonql/koa/src/options/options.js +++ b/packages/@jsonql/koa/src/options/options.js @@ -2,12 +2,20 @@ const { createConfig } = require('jsonql-params-validator') const { BOOLEAN_TYPE, NUMBER_TYPE, - DEFAULT_PORT_NUM + DEFAULT_PORT_NUM, + JS_WS_NAME, + JS_WS_SOCKET_IO_NAME, + JS_PRIMUS_NAME } = require('jsonql-constants') const options = { autoStart: createConfig(true, [BOOLEAN_TYPE]), - port: createConfig(DEFAULT_PORT_NUM, [NUMBER_TYPE]) + port: createConfig(DEFAULT_PORT_NUM, [NUMBER_TYPE]), + // new prop for socket client + serverType: createConfig(null, [STRING_TYPE], { + [ENUM_KEY]: [JS_WS_NAME, JS_WS_SOCKET_IO_NAME, JS_PRIMUS_NAME], + [ALIAS_KEY]: 'socketServerType' + }) } module.exports = { diff --git a/packages/@jsonql/koa/tests/auth.test.js b/packages/@jsonql/koa/tests/auth.test.js new file mode 100644 index 0000000000000000000000000000000000000000..186fdea9ec46779ccdf67d883f1f07311a3af3d1 --- /dev/null +++ b/packages/@jsonql/koa/tests/auth.test.js @@ -0,0 +1,22 @@ +const test = require('ava') +const { JS_WS_NAME } = require('jsonql-constants') +const initServer = require('./fixtures/test-server') + +test.before(t => { + const { stop } = initServer({ + port: 8082, + autoStart: true, + enableAuth: true, + socketType: JS_WS_NAME + }) + + t.context.stop = stop; + +}) + +test.after( t => { + t.context.stop() +}) + + +test.todo(`It should able to setup a auth server`) diff --git a/packages/@jsonql/koa/tests/basic.test.js b/packages/@jsonql/koa/tests/basic.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6e0509f09061ce89646eceb068da72ff2ace421a --- /dev/null +++ b/packages/@jsonql/koa/tests/basic.test.js @@ -0,0 +1,27 @@ +const test = require('ava') +const debug = require('debug')('jsonql-koa:test:basic') +const { JS_WS_NAME } = require('jsonql-constants') + +const initServer = require('./fixtures/test-server') + +test.before(t => { + const { stop } = initServer({ + port: 8001, + autoStart: true + }) + + t.context.stop = stop; +}) + +test.after(t => { + t.context.stop() +}) + + +test(`Just take a look at the option`, t => { + + const config = {someOption: 'xyz'} + + t.pass() + +}) diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/mutation/update-list.js b/packages/@jsonql/koa/tests/fixtures/resolvers/mutation/update-list.js new file mode 100644 index 0000000000000000000000000000000000000000..bac225811b6ba84ae297b6b6afb3b57728eebcc9 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/mutation/update-list.js @@ -0,0 +1,12 @@ +const debug = require('debug')('jsonql-koa:resolver:mutation:updateList'); +/** + * @param {object} payload + * @param {number} payload.user + * @param {object} condition + * @return {object} with user as key + */ +module.exports = function(payload, condition) { + debug('calling updateList with', payload, condition); + let p = payload.user + 1; + return {user: p}; +}; diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/query/cause-error.js b/packages/@jsonql/koa/tests/fixtures/resolvers/query/cause-error.js new file mode 100644 index 0000000000000000000000000000000000000000..0a5eb534437227da7fdbb3b7c264b69a6ff879b5 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/query/cause-error.js @@ -0,0 +1,10 @@ + +// this method will cause an error to throw +/** + * @param {*} x param + * @return {*} unknown + */ +module.exports = function(x) { + // none of the variable exists certainly will cause an error + return x ? y : z; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/query/get-user.js b/packages/@jsonql/koa/tests/fixtures/resolvers/query/get-user.js new file mode 100644 index 0000000000000000000000000000000000000000..49b836f2159a20004a78aae04ff12700b98eaaa1 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/query/get-user.js @@ -0,0 +1,12 @@ +// This is a new query method to test out if we actually get the userData props at the end of call +/** + * This use a spread as parameter + * @param {...string} args passing unknown number of param + * @return {any} extract from last of the args + */ +module.exports = function getUser(...args) { + const ctn = args.length; + const lastProp = args[ctn - 1]; + // also test with the assigned property + return getUser.userdata || {userId: 'dummy bear'}; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/query/private/get-secret-msg.js b/packages/@jsonql/koa/tests/fixtures/resolvers/query/private/get-secret-msg.js new file mode 100644 index 0000000000000000000000000000000000000000..b655360dbeb227fc6a50c0405f83dc5fab07161b --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/query/private/get-secret-msg.js @@ -0,0 +1,9 @@ +// this resolver will not be include if the privateMethodDir is not set + +/** + * a hidden private method + * @return {string} a secret message + */ +module.exports = function getSecretMsg() { + return 'Let me tell ya a secret ...'; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/query/public/always-available.js b/packages/@jsonql/koa/tests/fixtures/resolvers/query/public/always-available.js new file mode 100644 index 0000000000000000000000000000000000000000..0a08679841738e3b27e20b7a9553771869704a97 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/query/public/always-available.js @@ -0,0 +1,7 @@ +/** + * This is a public method that is always available + * @return {string} a message + */ +module.exports = function() { + return 'Hello there'; +}; diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/query/test-list.js b/packages/@jsonql/koa/tests/fixtures/resolvers/query/test-list.js new file mode 100644 index 0000000000000000000000000000000000000000..c1359fc2054d1fe3f1623ba920a5727730edd91b --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/query/test-list.js @@ -0,0 +1,13 @@ +const debug = require('debug')('jsonql-koa:resolver:query:testList'); +/** + * @param {number} num a number + * @return {object} @TODO need to figure out how to give keys to the returns + */ +module.exports = function testList(num) { + debug('Call testList with this params', num); + return { + modified: Date.now(), + text: testList.userdata && testList.userdata.dummy ? testList.userdata.dummy : 'nope', + num: num ? --num : -1 + } +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/cause-error.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/cause-error.js new file mode 100644 index 0000000000000000000000000000000000000000..6b9278c314ead5b4072cc81b76f0b502dee07e12 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/cause-error.js @@ -0,0 +1,9 @@ +// this method will throw an error + +/** + * @param {string} msg a message + * @return {string} a message but here we throw an error + */ +module.exports = function(msg) { + throw new Error(msg) +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/chatroom.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/chatroom.js new file mode 100644 index 0000000000000000000000000000000000000000..0b57676e1e3a1cd3ee583eaaf249a9accea26ce6 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/chatroom.js @@ -0,0 +1,12 @@ +// a private method + +/** + * + * @param {string} msg message + * @param {number} timestamp for checking the time + * @return {string} reply + */ +module.exports = function(msg, timestamp) { + const d = Date.now() - timestamp; + return msg + ` took ${d} ms`; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/delay-fn.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/delay-fn.js new file mode 100644 index 0000000000000000000000000000000000000000..523ed5c1640af604a093213806dcdad5da0f1422 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/delay-fn.js @@ -0,0 +1,15 @@ +// test this with a Promise return result +/** + * @param {string} msg a message + * @param {number} timestamp a timestamp + */ +module.exports = function delayFn(msg, timestamp) { + // also test the global socket instance + delayFn.send = 'I am calling from delayFn'; + + return new Promise(resolver => { + setTimeout(() => { + resolver(msg + (Date.now() - timestamp)) + }, 1000) + }) +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/private/secret-chatroom.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/private/secret-chatroom.js new file mode 100644 index 0000000000000000000000000000000000000000..a8dfc2f66546046675d85f67bf0877e557d9d8e9 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/private/secret-chatroom.js @@ -0,0 +1,12 @@ + +/** + * @param {string} room room name + * @param {*} msg message to that room + * @return {*} depends + */ +module.exports = function secretChatroom(room, msg) { + + let userdata = secretChatroom.userdata; + // @TODO + return `send ${msg+''} to ${room} room from ${userdata.name}`; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/public/available-to-everyone/index.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/public/available-to-everyone/index.js new file mode 100644 index 0000000000000000000000000000000000000000..16b326f970dc769884dda13e36b4df9f3f924166 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/public/available-to-everyone/index.js @@ -0,0 +1,9 @@ +// This method for testing the public call + +/** + * There is no parameter require for this call + * @return {string} a message + */ +module.exports = function availableToEveryone() { + return 'You get a public message'; +} diff --git a/packages/@jsonql/koa/tests/fixtures/resolvers/socket/ws-handler.js b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/ws-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..0a6a10e0c4b96c40a363157e05e6b26622d325ff --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/resolvers/socket/ws-handler.js @@ -0,0 +1,18 @@ +// will test this one with the send property + +/** + * method just for testing the ws + * @param {string} msg message + * @param {number} timestamp timestamp + * @return {string} msg + time lapsed + */ +module.exports = function wsHandler(msg, timestamp) { + + wsHandler.send = 'I am sending a message back from ws'; + + return new Promise(resolver => { + setTimeout(() => { + resolver(msg + ' - ' +(Date.now() - timestamp)) + }, 1000) + }) +} diff --git a/packages/@jsonql/koa/tests/fixtures/test-server.js b/packages/@jsonql/koa/tests/fixtures/test-server.js new file mode 100644 index 0000000000000000000000000000000000000000..3673afee4ef6f1e0418f945502cedbc09b3cf9f3 --- /dev/null +++ b/packages/@jsonql/koa/tests/fixtures/test-server.js @@ -0,0 +1,26 @@ +// create server for testing +const initServer = require('../../index') +const { join } = require('path') +const resolverDir = join(__dirname, 'resolvers') +const contractBaseDir = join(__dirname, 'contract') +const keysDir = join(__dirname, 'keys') + + +module.exports = function(config = {}) { + let { enableAuth, serverType } = config; + let contractDir; + switch (true) { + case enableAuth && serverType: + contractDir = join(contractBaseDir, 'auth') + break; + default: + contractDir = join(contractBaseDir, 'basic') + } + + const baseConfig = { + resolverDir, + contractDir, + keysDir + } + return initServer(Object.assign(baseConfig, config)) +} diff --git a/packages/@jsonql/koa/tests/socket.test.js b/packages/@jsonql/koa/tests/socket.test.js new file mode 100644 index 0000000000000000000000000000000000000000..79506a143b6b9ba093502a8dd28dbc57a8e3efac --- /dev/null +++ b/packages/@jsonql/koa/tests/socket.test.js @@ -0,0 +1,20 @@ +const test = require('ava') + +test.before(t => { + const { stop } = initServer({ + port: 8082, + autoStart: true, + enableAuth: true, + socketType: JS_WS_NAME + }) + + t.context.stop = stop; + +}) + +test.after( t => { + t.context.stop() +}) + + +test.todo(`It should able to have a server with socket server enabled`) diff --git a/packages/@jsonql/ws/README.md b/packages/@jsonql/ws/README.md index ead066d29c5cd4ab0dd642250dc60e7f4c258223..b5b504318df4bfeb46688ededf60361eaa7ed2c6 100644 --- a/packages/@jsonql/ws/README.md +++ b/packages/@jsonql/ws/README.md @@ -2,12 +2,11 @@ The socket client for jsonql, [ws](https://www.npmjs.com/package/ws) on node, and [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) on browser -You don't usually use this directly. This is part of the optional dependencies for @jsonql/client +You don't usually use this directly. This is part of the optional dependencies for [@jsonql/client](https://www.npmjs.com/package/@jsonql/client) and [jsonql-node-client](https://www.npmjs.com/package/jsonql-node-client) ## Example -Coming soon - +Coming soon --- diff --git a/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js b/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js deleted file mode 100644 index 5599426f05ef3a7d3455d30ad5a8a948d06a3048..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var debug$2=_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:{},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),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",ON_MESSAGE_PROP_NAME$1="onMessage",ON_RESULT_PROP_NAME$1="onResult",ON_ERROR_PROP_NAME$1="onError",ON_READY_PROP_NAME="onReady",ON_LOGIN_PROP_NAME="onLogin",SEND_MSG_PROP_NAME="send",MESSAGE_PROP_NAME="message",RESULT_PROP_NAME="result",ERROR_PROP_NAME="error",READY_PROP_NAME$1="ready",LOGIN_PROP_NAME="login",NOT_LOGIN_ERR_MSG="NOT LOGIN",TOKEN_PARAM_NAME="token",IO_ROUNDTRIP_LOGIN="roundtip",IO_HANDSHAKE_LOGIN="handshake",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)}}var SOCKET_IO=JS_WS_SOCKET_IO_NAME,MISSING_PROP_ERR="Missing property in contract!",EMIT_EVT=EMIT_REPLY_TYPE,UNKNOWN_RESULT="UKNNOWN RESULT!",MY_NAMESPACE="myNamespace",CB_FN_NAME="on",isArray=Array.isArray,freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(e){var r=hasOwnProperty.call(e,symToStringTag),t=e[symToStringTag];try{e[symToStringTag]=void 0;var n=!0}catch(e){}var o=nativeObjectToString.call(e);return n&&(r?e[symToStringTag]=t:delete e[symToStringTag]),o}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function overArg(e,r){return function(t){return e(r(t))}}var getPrototype=overArg(Object.getPrototypeOf,Object);function isObjectLike(e){return null!=e&&"object"==typeof e}var objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag)return!1;var 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 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("")}var inArray=function(e,r){return!!e.filter((function(e){return e===r})).length},toArray=function(e){return isArray(e)?e:[e]},isObjectHasKey=function(e,r){var t=Object.keys(e);return inArray(t,r)},createEvt=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.join("_")},isFunc=function(e){if("function"==typeof e)return!0;console.error("Expect to be Function type!")},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(e))}),Reflect.apply(e,null,t))}};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();++r-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag$1="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(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]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(e,r){if(("constructor"!==r||"function"!=typeof e[r])&&"__proto__"!=r)return e[r]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(e,r,t){var n=e[r];hasOwnProperty$6.call(e,r)&&eq(n,t)&&(void 0!==t||r in e)||baseAssignValue(e,r,t)}function copyObject(e,r,t,n){var o=!t;t||(t={});for(var a=-1,i=r.length;++a-1&&e%1==0&&e0){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;)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 e.then((function(e){return r(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)&&(isObjectHasKey(e,QUERY_NAME)||isObjectHasKey(e,MUTATION_NAME)||isObjectHasKey(e,SOCKET_NAME))}function extractSocketPart(e){return!!isObjectHasKey(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 stringTag$1="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag$1}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;function isNull(e){return null===e}function isUndefined(e){return void 0===e}var boolTag$1="[object Boolean]";function isBoolean(e){return!0===e||!1===e||isObjectLike(e)&&baseGetTag(e)==boolTag$1}var numberTag$1="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag$1}function isNaN(e){return isNumber(e)&&e!=+e}function arrayFilter(e,r){for(var t=-1,n=null==e?0:e.length,o=0,a=[];++ts))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))},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)};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$1=function(e){return checkIsArray(e)?e:[e]},inArray$1=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$1(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$1(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),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){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,n){void 0===n&&(n={});var o=n.useCallbackStyle?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.forEach((function(r){e.$call(createEvt(r,o),[{message:t,namespace:r}])}))}var debugFn$7=getDebug("client-event-handler"),notLoginWsHandler=function(e,r,t){var n=t.useCallbackStyle,o=n?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1,a=n?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1;r.$only(createEvt(e,EMIT_EVT),(function(t,n){debugFn$7("noLoginHandler hijack the ws call",e,t,n);var i={message:NOT_LOGIN_ERR_MSG};r.$call(createEvt(e,t,o),[i]),r.$call(createEvt(e,t,a),[{error:i}])}))},getPrivateNamespace=function(e){return e.length>1&&e[0]};function clientEventHandler(e,r,t,n,o,a){var i=getPrivateNamespace(o),s=!1;o.forEach((function(o){if(s=i===o,a[o]){debugFn$7("call bindWsHandler",s,o);var c=[o,a[o],t,s,e];if(e.serverType===SOCKET_IO){var u=r.nspSet;c.push(u[o])}Reflect.apply(n,null,c)}else notLoginWsHandler(o,t,e)})),t.$on(LOGOUT_EVENT_NAME,(function(){debugFn$7("LOGOUT_EVENT_NAME"),triggerNamespacesOnError(t,o,LOGOUT_EVENT_NAME),o.forEach((function(r){clearMainEmitEvt(t,r),a[r]=!1,notLoginWsHandler(r,t,e)}))}))}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 isObjectHasKey(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$8=getDebug("ws-main-handler"),errorTypeHandler=function(e,r,t,n,o){var a=[r];t&&(debugFn$8("a global error on "+r),a.push(t)),a.push(o);var i=Reflect.apply(createEvt,null,a),s=n.data||n;e.$trigger(i,[s])};function wsMainHandler(e,r,t,n,o){var a=o.useCallbackStyle,i=a?READY_PROP_NAME$1:ON_READY_PROP_NAME,s=a?LOGIN_PROP_NAME:ON_LOGIN_PROP_NAME,c=a?MESSAGE_PROP_NAME:ON_MESSAGE_PROP_NAME$1,u=a?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1,l=a?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.onopen=function(){debugFn$8("ws.onopen listened"),t.$call(i,e),n&&(console.log("isPrivate and fire the "+s),t.$call(s,e)),t.$only(createEvt(e,EMIT_REPLY_TYPE),(function(e,t){debugFn$8("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$8("Hear from server",a,n),a){case EMIT_REPLY_TYPE:var i=createEvt(e,o,c),s=t.$trigger(i,[n]);debugFn$8("EMIT_REPLY_TYPE",i,s);break;case ACKNOWLEDGE_REPLY_TYPE:var f=createEvt(e,o,u);t.$trigger(f,[n]);debugFn$8("ACKNOWLEDGE_REPLY_TYPE",f,n);break;case ERROR_TYPE:debugFn$8("ERROR_TYPE"),errorTypeHandler(t,e,o,n,l);break;default:debugFn$8("Unhandled event!",n),errorTypeHandler(t,e,o,n,l)}}catch(r){console.error("ws.onmessage error",r),errorTypeHandler(t,e,!1,r,l)}},r.onclose=function(){debugFn$8("ws.onclose callback")},t.$on(LOGOUT_EVENT_NAME,(function(){try{debugFn$8("terminate ws connection"),r.terminate()}catch(e){console.error("ws.terminate error",e)}}))}var debugFn$9=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$2;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 deleted file mode 100644 index 9f5509fa8b00813d0f29f2c3be7ca9f6ae6c59ae..0000000000000000000000000000000000000000 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.cjs.js.map +++ /dev/null @@ -1 +0,0 @@ -{"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 index 105260e0cf155f6a700f53e9a35dcebc65860f0a..8a66d3cb275ced9b66bf35d0db0f13dddb51224c 100644 --- a/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js +++ b/packages/@jsonql/ws/dist/jsonql-ws-client.umd.js @@ -1,2 +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=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),n=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),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 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),a=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),i=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),u="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c=function(){try{if(window||document)return!0}catch(t){}return!1},f=function(){try{if(!c()&&u)return!0}catch(t){}return!1};var s=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 c()?"browser":f()?"node":"unknown"},e}(Error),l=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}(s),p=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),h=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),v=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),d=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}(s),g="data",y="error",b="jsonql",_="query",m="mutation",w="socket",j="type",O="optional",S="enumv",k="args",E="checker",$="alias",A="No message",T="__login__",P="__logout__",N="emit",R="acknowledge",z="error",x="nspSet",C="publicNamespace",q="onMessage",M="onResult",F="onError",L="onReady",W="onLogin",U="message",I="result",J="error",D="ready",B="login",V="token",Y=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}(s),H=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 G(t){if(Array.isArray(t))throw new d("",t);var e=t.message||A,u=t.detail||t;switch(!0){case t instanceof r:throw new r(e,u);case t instanceof n:throw new n(e,u);case t instanceof o:throw new o(e,u);case t instanceof a:throw new a(e,u);case t instanceof i:throw new i(e,u);case t instanceof l:throw new l(e,u);case t instanceof p:throw new p(e,u);case t instanceof h:throw new h(e,u);case t instanceof v:throw new v(e,u);case t instanceof d:throw new d(e,u);case t instanceof H:throw new H(e,u);default:throw new Y(e,u)}}var K="socket.io",Q=N,X="UKNNOWN RESULT!",Z="on",tt=Array.isArray,et="object"==typeof u&&u&&u.Object===Object&&u,rt="object"==typeof self&&self&&self.Object===Object&&self,nt=et||rt||Function("return this")(),ot=nt.Symbol,at=Object.prototype,it=at.hasOwnProperty,ut=at.toString,ct=ot?ot.toStringTag:void 0;var ft=Object.prototype.toString;var st="[object Null]",lt="[object Undefined]",pt=ot?ot.toStringTag:void 0;function ht(t){return null==t?void 0===t?lt:st:pt&&pt in Object(t)?function(t){var e=it.call(t,ct),r=t[ct];try{t[ct]=void 0;var n=!0}catch(t){}var o=ut.call(t);return n&&(e?t[ct]=r:delete t[ct]),o}(t):function(t){return ft.call(t)}(t)}function vt(t,e){return function(r){return t(e(r))}}var dt=vt(Object.getPrototypeOf,Object);function gt(t){return null!=t&&"object"==typeof t}var yt="[object Object]",bt=Function.prototype,_t=Object.prototype,mt=bt.toString,wt=_t.hasOwnProperty,jt=mt.call(Object);function Ot(t){if(!gt(t)||ht(t)!=yt)return!1;var e=dt(t);if(null===e)return!0;var r=wt.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&mt.call(r)==jt}function St(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--&&zt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Gt=function(t){return tt(t)?t:[t]},Kt=function(t,e){var r,n=Object.keys(t);return r=e,!!n.filter((function(t){return t===r})).length},Qt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Xt=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type!")},Zt=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,Gt(t))}),Reflect.apply(t,null,r))}};function te(t,e){return t===e||t!=t&&e!=e}function ee(t,e){for(var r=t.length;r--;)if(te(t[r][0],e))return r;return-1}var re=Array.prototype.splice;function ne(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ne.prototype.set=function(t,e){var r=this.__data__,n=ee(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ae="[object AsyncFunction]",ie="[object Function]",ue="[object GeneratorFunction]",ce="[object Proxy]";function fe(t){if(!oe(t))return!1;var e=ht(t);return e==ie||e==ue||e==ae||e==ce}var se,le=nt["__core-js_shared__"],pe=(se=/[^.]+$/.exec(le&&le.keys&&le.keys.IE_PROTO||""))?"Symbol(src)_1."+se:"";var he=Function.prototype.toString;function ve(t){if(null!=t){try{return he.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var de=/^\[object .+?Constructor\]$/,ge=Function.prototype,ye=Object.prototype,be=ge.toString,_e=ye.hasOwnProperty,me=RegExp("^"+be.call(_e).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function we(t){return!(!oe(t)||(e=t,pe&&pe in e))&&(fe(t)?me:de).test(ve(t));var e}function je(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return we(r)?r:void 0}var Oe=je(nt,"Map"),Se=je(Object,"create");var ke="__lodash_hash_undefined__",Ee=Object.prototype.hasOwnProperty;var $e=Object.prototype.hasOwnProperty;var Ae="__lodash_hash_undefined__";function Te(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=er}function nr(t){return null!=t&&rr(t.length)&&!fe(t)}var or="object"==typeof exports&&exports&&!exports.nodeType&&exports,ar=or&&"object"==typeof module&&module&&!module.nodeType&&module,ir=ar&&ar.exports===or?nt.Buffer:void 0,ur=(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,sr="object"==typeof exports&&exports&&!exports.nodeType&&exports,lr=sr&&"object"==typeof module&&module&&!module.nodeType&&module,pr=lr&&lr.exports===sr&&et.process,hr=function(){try{var t=lr&&lr.require&&lr.require("util").types;return t||pr&&pr.binding&&pr.binding("util")}catch(t){}}(),vr=hr&&hr.isTypedArray,dr=vr?(fr=vr,function(t){return fr(t)}):function(t){return gt(t)&&rr(t.length)&&!!cr[ht(t)]};function gr(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var yr=Object.prototype.hasOwnProperty;function br(t,e,r){var n=t[e];yr.call(t,e)&&te(n,r)&&(void 0!==r||e in t)||Ce(t,e,r)}var _r=9007199254740991,mr=/^(?:0|[1-9]\d*)$/;function wr(t,e){var r=typeof t;return!!(e=null==e?_r:e)&&("number"==r||"symbol"!=r&&mr.test(t))&&t>-1&&t%1==0&&t0){if(++e>=xr)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(zr);function Fr(t,e){return Mr(function(t,e,r){return e=Rr(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,a=Rr(n.length-e,0),i=Array(a);++o1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(o=Lr.length>3&&"function"==typeof o?(n--,o):void 0,a&&function(t,e,r){if(!oe(r))return!1;var n=typeof e;return!!("number"==n?nr(r)&&wr(e,r.length):"string"==n&&e in r)&&te(r[e],t)}(e[0],e[1],a)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)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 t.then((function(t){return e(t)}))}),Reflect.apply(t,null,r))}}function Ir(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 Jr(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 Dr(t){return!!Kt(t,"socket")&&t.socket}var Br="[object String]";function Vr(t){return"string"==typeof t||!tt(t)&>(t)&&ht(t)==Br}var Yr=function(t){var e;return(e={}).args=t,e};function Hr(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),Vr(t)&&tt(e)){var o=Yr(e);return!0===r?o:((n={})[t]=o,n)}throw new d("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e,r))}var Gr=function(t){return Ot(t)&&(Kt(t,_)||Kt(t,m)||Kt(t,w))};function Kr(t){return void 0===t}var Qr="[object Boolean]";var Xr="[object Number]";function Zr(t){return function(t){return"number"==typeof t||gt(t)&&ht(t)==Xr}(t)&&t!=+t}var tn=vt(Object.keys,Object),en=Object.prototype.hasOwnProperty;function rn(t){return nr(t)?Or(t):function(t){if(!He(t))return tn(t);var e=[];for(var r in Object(t))en.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function nn(t,e){return t&&Fe(t,e,rn)}var on="__lodash_hash_undefined__";function an(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new Ne;++eu))return!1;var f=a.get(t);if(f&&a.get(e))return f==e;var s=-1,l=!0,p=r&fn?new an:void 0;for(a.set(t,e),a.set(e,t);++s0))},Yo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},Ho=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Bo(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Vo(r,t)})).length},Go=function(t,e){if(void 0===e&&(e=null),Ot(t)){if(!e)return!0;if(Vo(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return!!Kr(r)||(!1!==(e=Yo(t))?!Ho({arg:r},e):!Bo(t)(r))})).length)})).length}return!1},Ko=function(t){var e=t.arg,r=t.param,n=[e];return Array.isArray(r.keys)&&r.keys.length&&n.push(r.keys),Go.apply(null,n)};function Qo(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];try{window&&window.console&&Reflect.apply(console.log,console,t)}catch(t){}}var Xo=function(t,e){var r;switch(!0){case"object"===t:return!Ko(e);case"array"===t:return!Vo(e.arg);case!1!==(r=Yo(t)):return!Ho(e,r);default:return!Bo(t)(e.arg)}},Zo=function(t,e){return Kr(t)?!0!==e.optional||Kr(e.defaultvalue)?null:e.defaultvalue:t},ta=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Vo(e))throw new Y("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Vo(t))throw new Y("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 Qo(1),t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:Qo(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:Qo(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?Zo(t,i):t,index:r,param:i,optional:a}}));default:throw Qo(5),new Y("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),a=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!zo(e)&&!(r.type.length>r.type.filter((function(e){return Xo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Xo(e,t)})).length)}));return r?((n={})[y]=a,n[g]=o.map((function(t){return t.arg})),n):a},ea=function(t,e){var r,n=Object.keys(t);return r=e,!!n.filter((function(t){return t===r})).length},ra=function(t){return!zo(t)};function na(t,e){var r=Ro(e,(function(t,e){return!t[Jo]}));return to(r,{})?t:function(t,e){var r={};return e=Eo(e),nn(t,(function(t,n,o){Ce(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,Eo((function(t){return t.alias===e})),nn)||e}))}function oa(t,e){return $o(e,(function(e,r){var n,o;return Kr(t[r])||!0===e[Lo]&&ra(t[r])?Wr({},e,((n={})[Do]=!0,n)):((o={})[Uo]=t[r],o[Fo]=e[Fo],o[Lo]=e[Lo]||!1,o[Wo]=e[Wo]||!1,o[Io]=e[Io]||!1,o)}))}function aa(t,e){var r=function(t,e){var r=na(t,e);return{pristineValues:$o(Ro(e,(function(t,e){return ea(r,e)})),(function(t){return t.args})),checkAgainstAppProps:Ro(e,(function(t,e){return!ea(r,e)})),config:r}}(t,e),n=r.config,o=r.pristineValues;return[oa(n,r.checkAgainstAppProps),o]}var ia=function(t){return Vo(t)?t:[t]};var ua=function(t,e){return!Vo(e)||function(t,e){return!!t.filter((function(t){return t===e})).length}(e,t)},ca=function(t,e){try{return!!fe(e)&&e.apply(null,[t])}catch(t){return!1}};function fa(t){return function(e,r){if(e[Do])return e[Uo];var n=function(t,e){var r,n=[[t[Uo]],[(r={},r[Fo]=ia(t[Fo]),r[Lo]=t[Lo],r)]];return Reflect.apply(e,null,n)}(e,t);if(n.length)throw Qo("runValidationAction",r,e),new h(r,n);if(!1!==e[Wo]&&!ua(e[Uo],e[Wo]))throw Qo(Wo,e[Wo]),new p(r);if(!1!==e[Io]&&!ca(e[Uo],e[Io]))throw Qo(Io,e[Io]),new v(r);return e[Uo]}}var sa=function(t,e){return Promise.resolve(aa(t,e))};function la(t,e,r,n){return void 0===t&&(t={}),sa(t,e).then((function(t){return function(t,e){var r=t[0],n=t[1],o=$o(r,fa(e));return Wr(o,n)}(t,n)})).then((function(t){return Wr({},t,r)}))}function pa(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[k]=t,i[j]=e,!0===r&&(i[O]=!0),Vo(n)&&(i[S]=n),fe(o)&&(i[E]=o),Vr(a)&&(i[$]=a),i}var ha=Co,va=function(t,e,r){return void 0===r&&(r=!1),new Promise((function(n,o){var a=ta(t,e,r);return r?a[y].length?o(a[y]):n(a[g]):a.length?o(a):n([])}))},da=function(t,e,r){void 0===r&&(r={});var n=r[O],o=r[S],a=r[E],i=r[$];return pa.apply(null,[t,e,n,o,a,i])},ga=function(t){return function(e,r,n){return void 0===n&&(n={}),la(e,r,n,t)}}(ta),ya="jsonql-ws-client",ba=function(t){try{if(window.debug)return window.debug(ya).extend(t)}catch(t){}try{if(u.debug)return u.debug(ya).extend(t)}catch(t){}return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];console.info.apply(null,[ya,t].concat(e))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",ya+"*")}catch(t){}var _a=new WeakMap,ma=new WeakMap;var wa=function(){this.__suspend__=null,this.queueStore=new Set},ja={$suspend:{configurable:!0},$queues:{configurable:!0}};ja.$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)},wa.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__},ja.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},wa.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(wa.prototype,ja);var Oa=function(t){function e(){t.call(this,{logger:ba("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,f=!1,s=0;s0;)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){_a.set(this,t)},r.normalStore.get=function(){return _a.get(this)},r.lazyStore.set=function(t){ma.set(this,t)},r.lazyStore.get=function(){return ma.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}(wa))),Sa=(ba("process-contract"),function(t){var e=Dr(t);if(!1!==e)return e;throw new l("Missing property in contract!")});function ka(t){var e,r,n=t.contract;return t.enableAuth?function(t,e){void 0===e&&(e=!1);var r=Dr(t);if(!1===r){if(e)return t;throw new Y("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={})[x]=((e={})[b]=Sa(n),e),r[C]=b,r)}var Ea=function(t,e){return"ws"===e?t.replace("http://","ws://"):t},$a=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}},Aa=function(t,e){Gt(e).forEach((function(e){t.$off(Qt(e,N))}))},Ta=ba("respondHandler");function Pa(t,e,r){Kt(t,y)?(Ta("-- rejecter called --",t[y]),r(t[y])):Kt(t,g)?(Ta("-- resolver called --",t[g]),e(t[g])):(Ta("-- UNKNOWN_RESULT --",t),r({message:X,error:t}))}var Na=ba("action-call");function Ra(t,e,r,n,o){void 0===o&&(o=[]);var a=Qt(e,N),i=n?I:M;return Na("actionCall: "+a+" --\x3e "+r,o),t.$trigger(a,[r,Gt(o)]),new Promise((function(n,o){t.$on(Qt(e,r,i),(function(t){Na("got the first result",t),Pa(t,n,o)}))}))}var za=ba("setup-send"),xa=function(t,e,r,n,o,a){return Ir(t,"send",(function(t){var i=a?J:F;za("got payload for",t),va(Gt(t),o.params,!0).then((function(o){if(!o[y]||!o[y].length)return Ra(e,r,n,a,t);za("got ERROR_KEY",o[y]),e.$call(Qt(r,n,i),[new d(n,o[y])])})).catch((function(t){za("error after validateAsync",t),e.$call(Qt(r,n,i),[new d(n,t)])}))}),(function(){return function(){for(var t=[],i=arguments.length;i--;)t[i]=arguments[i];return va(t,o.params,!0).then((function(t){return Ra(e,r,n,a,t)})).catch(G)}}))};ba("setup-resolver");function Ca(t,e,r,n,o){return[Jr(t,Z,(function(t,o){if(ha(t)&&Xt(o))switch(t){case I:e.$on(Qt(r,n,ON_RESULT_PROP_NAME),(function(t){Pa(t,o,(function(t){e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case U:e.$only(Qt(r,n,ON_MESSAGE_PROP_NAME),(function(t){Pa(t,o,(function(t){e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case READY_PROP_NAME:e.$only(Qt(r,n,ON_ERROR_PROP_NAME),o);break;default:e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),new Y(n,"Unknown event name "+t+"!"))}})),e,r,n,o]}ba("setup-resolver");var qa=function(t,e,r,n,o,a){return[Jr(t,"myNamespace",r),e,r,n,o,a]},Ma=function(t,e,r,n,o,a){return[Ir(t,M,(function(t){Xt(t)&&e.$on(Qt(r,n,M),(function(o){Pa(o,t,(function(t){e.$trigger(Qt(r,n,F),t)}))}))})),e,r,n,o,a]},Fa=function(t,e,r,n,o,a){return[Ir(t,q,(function(t){if(Xt(t)){e.$only(Qt(r,n,q),(function(o){Pa(o,t,(function(t){e.$trigger(Qt(r,n,F),t)}))}))}})),e,r,n,o,a]},La=function(t,e,r,n,o,a){return[Ir(t,F,(function(t){Xt(t)&&e.$only(Qt(r,n,F),t)})),e,r,n,o,a]};function Wa(t,e,r,n,o,a){var i=[qa];a?i.push(Ca):i.push(Ma,Fa,La),i.push(xa);var u=Reflect.apply(Zt,null,i);return Reflect.apply(u,null,[n,o,t,e,r,a])}ba("resolver-methods");function Ua(t,e,r,n,o){return function(){for(var a=[],i=arguments.length;i--;)a[i]=arguments[i];return va(a,n.params,!0).then((function(n){return Ra(t,e,r,o,n)})).catch(G)}}var Ia=function(t,e,r){return[Jr(t,r.loginHandlerName,(function(t){if(t&&ha(t))return e.$trigger(T,[t]);throw new d(r.loginHandlerName,"Unexpected token "+t)})),e,r]},Ja=function(t,e,r){return Jr(t,r.logoutHandlerName,(function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.$trigger(P,t)}))};var Da,Ba;ba("generator");function Va(t,e,r){var n={},o=e.nspSet,a=t.useCallbackStyle;for(var i in o){var u=o[i];for(var c in u){var f=u[c];n=Jr(n,c,Wa(i,c,f,Ua(r,i,c,f,a),r,a))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function Ya(t,e,r){var n=e.nspSet,o=[Va];return t.useCallbackStyle?o.push((function(t){return function(t,e,r,n){return Jr(t,Z,(function(t,n){if(ha(t)&&Xt(n))switch(t){case J:for(var o in r)e.$on(Qt(o,J),n);break;case B:e.$only(B,n);break;case D:e.$on(D,n);break;default:e.$trigger(J,new Y(Z,"Unknown event name "+t+"!"))}}))}(t,r,n)})):o.push((function(t){return function(t,e,r){return Ir(t,F,(function(t){if(Xt(t))for(var n in r)e.$on(Qt(n,F),t)}))}(t,r,n)}),(function(t){return function(t,e,r){return Ir(t,L,(function(t){Xt(t)&&e.$on(L,t)}))}(t,r)}),(function(e){return function(t,e,r){return r.enableAuth?Ir(t,W,(function(t){Xt(t)&&e.$only(W,t)})):t}(e,r,t)})),o.push((function(e){return function(t,e,r){return r.enableAuth?Zt(Ia,Ja)(t,e,r):t}(e,r,t)})),Reflect.apply(Ur,null,o)(t,e,r)}var Ha=["roundtip","handshake"],Ga={useCallbackStyle:da(!1,["boolean"]),loginHandlerName:da("login",["string"]),logoutHandlerName:da("logout",["string"]),loginMethod:da("handshake",["string"],(Da={},Da[S]=Ha,Da)),useJwt:da(!0,["boolean","string"]),hostname:da(!1,["string"]),namespace:da(b,["string"]),wsOptions:da({},["object"]),contract:da({},["object"],(Ba={},Ba[E]=Gr,Ba)),enableAuth:da(!1,["boolean"]),token:da(!1,["string"])},Ka=ba("check-options"),Qa={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""};var Xa={version:"version: 0.8.0 module: umd",serverType:"ws"},Za=null;"undefined"!=typeof WebSocket?Za=WebSocket:"undefined"!=typeof MozWebSocket?Za=MozWebSocket:void 0!==u?Za=u.WebSocket||u.MozWebSocket:"undefined"!=typeof window?Za=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(Za=self.WebSocket||self.MozWebSocket);var ti=Za,ei=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 ri(t,e){return void 0===e&&(e=!1),!1===e?function(e){return new t(ei(e))}:function(e,r){var n=ei(e),o=r&&"string"==typeof r?n+"?"+V+"="+r:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}function ni(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions;return(0,e.nspClient)(t?[r,t].join("/"):n,o)}var oi=ba("client-event-handler"),ai=function(t,e,r){var n=r.useCallbackStyle,o=n?J:F,a=n?I:M;e.$only(Qt(t,Q),(function(r,n){oi("noLoginHandler hijack the ws call",t,r,n);var i={message:"NOT LOGIN"};e.$call(Qt(t,r,o),[i]),e.$call(Qt(t,r,a),[{error:i}])}))},ii=function(t){return t.length>1&&t[0]};function ui(t,e,r,n,o,a){var i=ii(o),u=!1;o.forEach((function(o){if(u=i===o,a[o]){oi("call bindWsHandler",u,o);var c=[o,a[o],r,u,t];if(t.serverType===K){var f=e.nspSet;c.push(f[o])}Reflect.apply(n,null,c)}else ai(o,r,t)})),r.$on(P,(function(){oi("LOGOUT_EVENT_NAME"),function(t,e,r,n){void 0===n&&(n={});var o=n.useCallbackStyle?J:F;e.forEach((function(e){t.$call(Qt(e,o),[{message:r,namespace:e}])}))}(r,o,P),o.forEach((function(e){Aa(r,e),a[e]=!1,ai(e,r,t)}))}))}var ci=["__reply__","__event__","__data__"],fi=function(t){var e,r=t.data;if(!1!==(e=function(t){var e=t.data;return!!e&&(ci.filter((function(t){return Kt(e,t)})).length===ci.length&&e)}(ha(r)?JSON.parse(r):r)))return{resolverName:e.__event__,data:e.__data__,type:e.__reply__};throw new Y("payload can not be decoded",t)},si=ba("ws-main-handler"),li=function(t,e,r,n,o){var a=[e];r&&(si("a global error on "+e),a.push(r)),a.push(o);var i=Reflect.apply(Qt,null,a),u=n.data||n;t.$trigger(i,[u])};function pi(t,e,r,n,o){var a=o.useCallbackStyle,i=a?D:L,u=a?B:W,c=a?U:q,f=a?I:M,s=a?J:F;e.onopen=function(){si("ws.onopen listened"),r.$call(i,t),n&&(console.log("isPrivate and fire the "+u),r.$call(u,t)),r.$only(Qt(t,N),(function(t,r){si("calling server",t,r),e.send(Hr(t,r))}))},e.onmessage=function(e){try{var n=fi(e),o=n.resolverName,a=n.type;switch(si("Hear from server",a,n),a){case N:var i=Qt(t,o,c),u=r.$trigger(i,[n]);si("EMIT_REPLY_TYPE",i,u);break;case R:var l=Qt(t,o,f);r.$trigger(l,[n]);si("ACKNOWLEDGE_REPLY_TYPE",l,n);break;case z:si("ERROR_TYPE"),li(r,t,o,n,s);break;default:si("Unhandled event!",n),li(r,t,o,n,s)}}catch(e){console.error("ws.onmessage error",e),li(r,t,!1,e,s)}},e.onclose=function(){si("ws.onclose callback")},r.$on(P,(function(){try{si("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}ba("ws-create-client");var hi=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]=ni(e,t),i)})).reduce((function(t,e){return Object.assign(t,e)}),{});else{var f=(n=o,Object.keys(n)[0]);u.push(f),c[f]=ni(!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 ga(t,Ga,Object.assign(Qa,e)).then((function(t){return t.hostname||(t.hostname=$a()),t.wssPath=Ea([t.hostname,t.namespace].join("/"),t.serverType),Ka("CONFIGURATION OPTIONS",t),t}))}(r,e).then((function(t){return{opts:t,nspMap:ka(t),ee:n||new Oa}})).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return Ya(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var e=ri(t),r=ri(t,!0);return function(t,n,o){return t.nspClient=e,t.nspAuthClient=r,function(t,e,r){var n=[t,e,r,pi],o=t.token,a=hi(t,e,o),i=a.nsps,u=a.namespaces,c=a.login;return Reflect.apply(ui,null,n.concat([u,i])),c&&r.$only(T,(function(o){Aa(r,u);var a=hi(t,e,o);Reflect.apply(ui,null,n.concat([a.namespaces,a.nsps]))})),{opts:t,nspMap:e,ee:r}}(t,n,o)}}(ti),Xa)})); +!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=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),n=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),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 401},r.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(e,r),e}(Error),a=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),i=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),u="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c=function(){try{if(window||document)return!0}catch(t){}return!1},f=function(){try{if(!c()&&u)return!0}catch(t){}return!1};var s=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 c()?"browser":f()?"node":"unknown"},e}(Error),l=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}(s),p=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),h=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),v=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),d=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}(s),g="data",y="error",b="jsonql",_="query",m="mutation",w="socket",j="type",O="optional",S="enumv",k="args",E="checker",$="alias",A="No message",T="__login__",P="__logout__",N="emit",R="acknowledge",z="error",x="nspSet",C="publicNamespace",q="onMessage",M="onResult",F="onError",L="onReady",W="onLogin",U="message",I="result",J="error",D="ready",B="login",V="token",Y=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}(s),H=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 G(t){if(Array.isArray(t))throw new d("",t);var e=t.message||A,u=t.detail||t;switch(!0){case t instanceof r:throw new r(e,u);case t instanceof n:throw new n(e,u);case t instanceof o:throw new o(e,u);case t instanceof a:throw new a(e,u);case t instanceof i:throw new i(e,u);case t instanceof l:throw new l(e,u);case t instanceof p:throw new p(e,u);case t instanceof h:throw new h(e,u);case t instanceof v:throw new v(e,u);case t instanceof d:throw new d(e,u);case t instanceof H:throw new H(e,u);default:throw new Y(e,u)}}var K="socket.io",Q=N,X="UKNNOWN RESULT!",Z="on",tt=Array.isArray,et="object"==typeof u&&u&&u.Object===Object&&u,rt="object"==typeof self&&self&&self.Object===Object&&self,nt=et||rt||Function("return this")(),ot=nt.Symbol,at=Object.prototype,it=at.hasOwnProperty,ut=at.toString,ct=ot?ot.toStringTag:void 0;var ft=Object.prototype.toString;var st="[object Null]",lt="[object Undefined]",pt=ot?ot.toStringTag:void 0;function ht(t){return null==t?void 0===t?lt:st:pt&&pt in Object(t)?function(t){var e=it.call(t,ct),r=t[ct];try{t[ct]=void 0;var n=!0}catch(t){}var o=ut.call(t);return n&&(e?t[ct]=r:delete t[ct]),o}(t):function(t){return ft.call(t)}(t)}function vt(t,e){return function(r){return t(e(r))}}var dt=vt(Object.getPrototypeOf,Object);function gt(t){return null!=t&&"object"==typeof t}var yt="[object Object]",bt=Function.prototype,_t=Object.prototype,mt=bt.toString,wt=_t.hasOwnProperty,jt=mt.call(Object);function Ot(t){if(!gt(t)||ht(t)!=yt)return!1;var e=dt(t);if(null===e)return!0;var r=wt.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&mt.call(r)==jt}function St(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--&&zt(e,t[r],0)>-1;);return r}(n,o)+1).join("")}var Gt=function(t){return tt(t)?t:[t]},Kt=function(t,e){try{var r=Object.keys(t);return n=e,!!r.filter((function(t){return t===n})).length}catch(t){return!1}var n},Qt=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.join("_")},Xt=function(t){if("function"==typeof t)return!0;console.error("Expect to be Function type!")},Zt=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,Gt(t))}),Reflect.apply(t,null,r))}};function te(t,e){return t===e||t!=t&&e!=e}function ee(t,e){for(var r=t.length;r--;)if(te(t[r][0],e))return r;return-1}var re=Array.prototype.splice;function ne(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1},ne.prototype.set=function(t,e){var r=this.__data__,n=ee(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this};var ae="[object AsyncFunction]",ie="[object Function]",ue="[object GeneratorFunction]",ce="[object Proxy]";function fe(t){if(!oe(t))return!1;var e=ht(t);return e==ie||e==ue||e==ae||e==ce}var se,le=nt["__core-js_shared__"],pe=(se=/[^.]+$/.exec(le&&le.keys&&le.keys.IE_PROTO||""))?"Symbol(src)_1."+se:"";var he=Function.prototype.toString;function ve(t){if(null!=t){try{return he.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var de=/^\[object .+?Constructor\]$/,ge=Function.prototype,ye=Object.prototype,be=ge.toString,_e=ye.hasOwnProperty,me=RegExp("^"+be.call(_e).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function we(t){return!(!oe(t)||(e=t,pe&&pe in e))&&(fe(t)?me:de).test(ve(t));var e}function je(t,e){var r=function(t,e){return null==t?void 0:t[e]}(t,e);return we(r)?r:void 0}var Oe=je(nt,"Map"),Se=je(Object,"create");var ke="__lodash_hash_undefined__",Ee=Object.prototype.hasOwnProperty;var $e=Object.prototype.hasOwnProperty;var Ae="__lodash_hash_undefined__";function Te(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t<=er}function nr(t){return null!=t&&rr(t.length)&&!fe(t)}var or="object"==typeof exports&&exports&&!exports.nodeType&&exports,ar=or&&"object"==typeof module&&module&&!module.nodeType&&module,ir=ar&&ar.exports===or?nt.Buffer:void 0,ur=(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,sr="object"==typeof exports&&exports&&!exports.nodeType&&exports,lr=sr&&"object"==typeof module&&module&&!module.nodeType&&module,pr=lr&&lr.exports===sr&&et.process,hr=function(){try{var t=lr&&lr.require&&lr.require("util").types;return t||pr&&pr.binding&&pr.binding("util")}catch(t){}}(),vr=hr&&hr.isTypedArray,dr=vr?(fr=vr,function(t){return fr(t)}):function(t){return gt(t)&&rr(t.length)&&!!cr[ht(t)]};function gr(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var yr=Object.prototype.hasOwnProperty;function br(t,e,r){var n=t[e];yr.call(t,e)&&te(n,r)&&(void 0!==r||e in t)||Ce(t,e,r)}var _r=9007199254740991,mr=/^(?:0|[1-9]\d*)$/;function wr(t,e){var r=typeof t;return!!(e=null==e?_r:e)&&("number"==r||"symbol"!=r&&mr.test(t))&&t>-1&&t%1==0&&t0){if(++e>=xr)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(zr);function Fr(t,e){return Mr(function(t,e,r){return e=Rr(void 0===e?t.length-1:e,0),function(){for(var n=arguments,o=-1,a=Rr(n.length-e,0),i=Array(a);++o1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(o=Lr.length>3&&"function"==typeof o?(n--,o):void 0,a&&function(t,e,r){if(!oe(r))return!1;var n=typeof e;return!!("number"==n?nr(r)&&wr(e,r.length):"string"==n&&e in r)&&te(r[e],t)}(e[0],e[1],a)&&(o=n<3?void 0:o,n=1),t=Object(t);++r0;)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 t.then((function(t){return e(t)}))}),Reflect.apply(t,null,r))}}function Ir(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 Jr(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 Dr(t){return!!Kt(t,"socket")&&t.socket}var Br="[object String]";function Vr(t){return"string"==typeof t||!tt(t)&>(t)&&ht(t)==Br}var Yr=function(t){var e;return(e={}).args=t,e};function Hr(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),Vr(t)&&tt(e)){var o=Yr(e);return!0===r?o:((n={})[t]=o,n)}throw new d("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:e})}(t,e,r))}var Gr=function(t){return Ot(t)&&(Kt(t,_)||Kt(t,m)||Kt(t,w))};function Kr(t){return void 0===t}var Qr="[object Boolean]";var Xr="[object Number]";function Zr(t){return function(t){return"number"==typeof t||gt(t)&&ht(t)==Xr}(t)&&t!=+t}var tn=vt(Object.keys,Object),en=Object.prototype.hasOwnProperty;function rn(t){return nr(t)?Or(t):function(t){if(!He(t))return tn(t);var e=[];for(var r in Object(t))en.call(t,r)&&"constructor"!=r&&e.push(r);return e}(t)}function nn(t,e){return t&&Fe(t,e,rn)}var on="__lodash_hash_undefined__";function an(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new Ne;++eu))return!1;var f=a.get(t);if(f&&a.get(e))return f==e;var s=-1,l=!0,p=r&fn?new an:void 0;for(a.set(t,e),a.set(e,t);++s0))},Yo=function(t){if(t.indexOf("array.<")>-1&&t.indexOf(">")>-1){var e=t.replace("array.<","").replace(">","");return e.indexOf("|")?e.split("|"):[e]}return!1},Ho=function(t,e){var r=t.arg;return e.length>1?!r.filter((function(t){return!(e.length>e.filter((function(e){return!Bo(e)(t)})).length)})).length:e.length>e.filter((function(t){return!Vo(r,t)})).length},Go=function(t,e){if(void 0===e&&(e=null),Ot(t)){if(!e)return!0;if(Vo(e))return!e.filter((function(e){var r=t[e.name];return!(e.type.length>e.type.filter((function(t){var e;return!!Kr(r)||(!1!==(e=Yo(t))?!Ho({arg:r},e):!Bo(t)(r))})).length)})).length}return!1},Ko=function(t){var e=t.arg,r=t.param,n=[e];return Array.isArray(r.keys)&&r.keys.length&&n.push(r.keys),Go.apply(null,n)};function Qo(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];try{window&&window.console&&Reflect.apply(console.log,console,t)}catch(t){}}var Xo=function(t,e){var r;switch(!0){case"object"===t:return!Ko(e);case"array"===t:return!Vo(e.arg);case!1!==(r=Yo(t)):return!Ho(e,r);default:return!Bo(t)(e.arg)}},Zo=function(t,e){return Kr(t)?!0!==e.optional||Kr(e.defaultvalue)?null:e.defaultvalue:t},ta=function(t,e,r){var n;void 0===r&&(r=!1);var o=function(t,e){if(!Vo(e))throw new Y("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Vo(t))throw new Y("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 Qo(1),t.map((function(t,r){return{arg:t,index:r,param:e[r]}}));case!0===e[0].variable:Qo(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:Qo(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?Zo(t,i):t,index:r,param:i,optional:a}}));default:throw Qo(5),new Y("Could not understand your arguments and parameter structure!",{args:t,params:e})}}(t,e),a=o.filter((function(t){return!0===t.optional||!0===t.param.optional?function(t){var e=t.arg,r=t.param;return!!zo(e)&&!(r.type.length>r.type.filter((function(e){return Xo(e,t)})).length)}(t):!(t.param.type.length>t.param.type.filter((function(e){return Xo(e,t)})).length)}));return r?((n={})[y]=a,n[g]=o.map((function(t){return t.arg})),n):a},ea=function(t,e){var r,n=Object.keys(t);return r=e,!!n.filter((function(t){return t===r})).length},ra=function(t){return!zo(t)};function na(t,e){var r=Ro(e,(function(t,e){return!t[Jo]}));return to(r,{})?t:function(t,e){var r={};return e=Eo(e),nn(t,(function(t,n,o){Ce(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,Eo((function(t){return t.alias===e})),nn)||e}))}function oa(t,e){return $o(e,(function(e,r){var n,o;return Kr(t[r])||!0===e[Lo]&&ra(t[r])?Wr({},e,((n={})[Do]=!0,n)):((o={})[Uo]=t[r],o[Fo]=e[Fo],o[Lo]=e[Lo]||!1,o[Wo]=e[Wo]||!1,o[Io]=e[Io]||!1,o)}))}function aa(t,e){var r=function(t,e){var r=na(t,e);return{pristineValues:$o(Ro(e,(function(t,e){return ea(r,e)})),(function(t){return t.args})),checkAgainstAppProps:Ro(e,(function(t,e){return!ea(r,e)})),config:r}}(t,e),n=r.config,o=r.pristineValues;return[oa(n,r.checkAgainstAppProps),o]}var ia=function(t){return Vo(t)?t:[t]};var ua=function(t,e){return!Vo(e)||function(t,e){return!!t.filter((function(t){return t===e})).length}(e,t)},ca=function(t,e){try{return!!fe(e)&&e.apply(null,[t])}catch(t){return!1}};function fa(t){return function(e,r){if(e[Do])return e[Uo];var n=function(t,e){var r,n=[[t[Uo]],[(r={},r[Fo]=ia(t[Fo]),r[Lo]=t[Lo],r)]];return Reflect.apply(e,null,n)}(e,t);if(n.length)throw Qo("runValidationAction",r,e),new h(r,n);if(!1!==e[Wo]&&!ua(e[Uo],e[Wo]))throw Qo(Wo,e[Wo]),new p(r);if(!1!==e[Io]&&!ca(e[Uo],e[Io]))throw Qo(Io,e[Io]),new v(r);return e[Uo]}}var sa=function(t,e){return Promise.resolve(aa(t,e))};function la(t,e,r,n){return void 0===t&&(t={}),sa(t,e).then((function(t){return function(t,e){var r=t[0],n=t[1],o=$o(r,fa(e));return Wr(o,n)}(t,n)})).then((function(t){return Wr({},t,r)}))}function pa(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[k]=t,i[j]=e,!0===r&&(i[O]=!0),Vo(n)&&(i[S]=n),fe(o)&&(i[E]=o),Vr(a)&&(i[$]=a),i}var ha=Co,va=function(t,e,r){return void 0===r&&(r=!1),new Promise((function(n,o){var a=ta(t,e,r);return r?a[y].length?o(a[y]):n(a[g]):a.length?o(a):n([])}))},da=function(t,e,r){void 0===r&&(r={});var n=r[O],o=r[S],a=r[E],i=r[$];return pa.apply(null,[t,e,n,o,a,i])},ga=function(t){return function(e,r,n){return void 0===n&&(n={}),la(e,r,n,t)}}(ta),ya="jsonql-ws-client",ba=function(t){try{if(window.debug)return window.debug(ya).extend(t)}catch(t){}try{if(u.debug)return u.debug(ya).extend(t)}catch(t){}return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];console.info.apply(null,[ya,t].concat(e))}};try{window&&window.localStorage&&window.DEBUG&&localStorage.setItem("DEBUG",ya+"*")}catch(t){}var _a=new WeakMap,ma=new WeakMap;var wa=function(){this.__suspend__=null,this.queueStore=new Set},ja={$suspend:{configurable:!0},$queues:{configurable:!0}};ja.$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)},wa.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__},ja.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},wa.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(wa.prototype,ja);var Oa=function(t){function e(){t.call(this,{logger:ba("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,f=!1,s=0;s0;)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){_a.set(this,t)},r.normalStore.get=function(){return _a.get(this)},r.lazyStore.set=function(t){ma.set(this,t)},r.lazyStore.get=function(){return ma.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}(wa))),Sa=(ba("process-contract"),function(t){var e=Dr(t);if(!1!==e)return e;throw new l("Missing property in contract!")});function ka(t){var e,r,n=t.contract;return t.enableAuth?function(t,e){void 0===e&&(e=!1);var r=Dr(t);if(!1===r){if(e)return t;throw new Y("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={})[x]=((e={})[b]=Sa(n),e),r[C]=b,r)}var Ea=function(t,e){return"ws"===e?t.replace("http://","ws://"):t},$a=function(){try{return[window.location.protocol,window.location.host].join("//")}catch(t){throw new JsonqlValidationError(t)}},Aa=function(t,e){Gt(e).forEach((function(e){t.$off(Qt(e,N))}))},Ta=ba("respondHandler");function Pa(t,e,r){Kt(t,y)?(Ta("-- rejecter called --",t[y]),r(t[y])):Kt(t,g)?(Ta("-- resolver called --",t[g]),e(t[g])):(Ta("-- UNKNOWN_RESULT --",t),r({message:X,error:t}))}var Na=ba("action-call");function Ra(t,e,r,n,o){void 0===o&&(o=[]);var a=Qt(e,N),i=n?I:M;return Na("actionCall: "+a+" --\x3e "+r,o),t.$trigger(a,[r,Gt(o)]),new Promise((function(n,o){t.$on(Qt(e,r,i),(function(t){Na("got the first result",t),Pa(t,n,o)}))}))}var za=ba("setup-send"),xa=function(t,e,r,n,o,a){return Ir(t,"send",(function(t){var i=a?J:F;za("got payload for",t),va(Gt(t),o.params,!0).then((function(o){if(!o[y]||!o[y].length)return Ra(e,r,n,a,t);za("got ERROR_KEY",o[y]),e.$call(Qt(r,n,i),[new d(n,o[y])])})).catch((function(t){za("error after validateAsync",t),e.$call(Qt(r,n,i),[new d(n,t)])}))}),(function(){return function(){for(var t=[],i=arguments.length;i--;)t[i]=arguments[i];return va(t,o.params,!0).then((function(t){return Ra(e,r,n,a,t)})).catch(G)}}))};ba("setup-resolver");function Ca(t,e,r,n,o){return[Jr(t,Z,(function(t,o){if(ha(t)&&Xt(o))switch(t){case I:e.$on(Qt(r,n,ON_RESULT_PROP_NAME),(function(t){Pa(t,o,(function(t){e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case U:e.$only(Qt(r,n,ON_MESSAGE_PROP_NAME),(function(t){Pa(t,o,(function(t){e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),t)}))}));break;case READY_PROP_NAME:e.$only(Qt(r,n,ON_ERROR_PROP_NAME),o);break;default:e.$trigger(Qt(r,n,ON_ERROR_PROP_NAME),new Y(n,"Unknown event name "+t+"!"))}})),e,r,n,o]}ba("setup-resolver");var qa=function(t,e,r,n,o,a){return[Jr(t,"myNamespace",r),e,r,n,o,a]},Ma=function(t,e,r,n,o,a){return[Ir(t,M,(function(t){Xt(t)&&e.$on(Qt(r,n,M),(function(o){Pa(o,t,(function(t){e.$trigger(Qt(r,n,F),t)}))}))})),e,r,n,o,a]},Fa=function(t,e,r,n,o,a){return[Ir(t,q,(function(t){if(Xt(t)){e.$only(Qt(r,n,q),(function(o){Pa(o,t,(function(t){e.$trigger(Qt(r,n,F),t)}))}))}})),e,r,n,o,a]},La=function(t,e,r,n,o,a){return[Ir(t,F,(function(t){Xt(t)&&e.$only(Qt(r,n,F),t)})),e,r,n,o,a]};function Wa(t,e,r,n,o,a){var i=[qa];a?i.push(Ca):i.push(Ma,Fa,La),i.push(xa);var u=Reflect.apply(Zt,null,i);return Reflect.apply(u,null,[n,o,t,e,r,a])}ba("resolver-methods");function Ua(t,e,r,n,o){return function(){for(var a=[],i=arguments.length;i--;)a[i]=arguments[i];return va(a,n.params,!0).then((function(n){return Ra(t,e,r,o,n)})).catch(G)}}var Ia=function(t,e,r){return[Jr(t,r.loginHandlerName,(function(t){if(t&&ha(t))return e.$trigger(T,[t]);throw new d(r.loginHandlerName,"Unexpected token "+t)})),e,r]},Ja=function(t,e,r){return Jr(t,r.logoutHandlerName,(function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.$trigger(P,t)}))};var Da,Ba;ba("generator");function Va(t,e,r){var n={},o=e.nspSet,a=t.useCallbackStyle;for(var i in o){var u=o[i];for(var c in u){var f=u[c];n=Jr(n,c,Wa(i,c,f,Ua(r,i,c,f,a),r,a))}}return n.devHelpers={getNsp:function(){return Object.keys(o)},getVer:function(){return t.version||"NOT SET"}},Promise.resolve(n)}function Ya(t,e,r){var n=e.nspSet,o=[Va];return t.useCallbackStyle?o.push((function(t){return function(t,e,r,n){return Jr(t,Z,(function(t,n){if(ha(t)&&Xt(n))switch(t){case J:for(var o in r)e.$on(Qt(o,J),n);break;case B:e.$only(B,n);break;case D:e.$on(D,n);break;default:e.$trigger(J,new Y(Z,"Unknown event name "+t+"!"))}}))}(t,r,n)})):o.push((function(t){return function(t,e,r){return Ir(t,F,(function(t){if(Xt(t))for(var n in r)e.$on(Qt(n,F),t)}))}(t,r,n)}),(function(t){return function(t,e,r){return Ir(t,L,(function(t){Xt(t)&&e.$on(L,t)}))}(t,r)}),(function(e){return function(t,e,r){return r.enableAuth?Ir(t,W,(function(t){Xt(t)&&e.$only(W,t)})):t}(e,r,t)})),o.push((function(e){return function(t,e,r){return r.enableAuth?Zt(Ia,Ja)(t,e,r):t}(e,r,t)})),Reflect.apply(Ur,null,o)(t,e,r)}var Ha=["roundtip","handshake"],Ga={useCallbackStyle:da(!1,["boolean"]),loginHandlerName:da("login",["string"]),logoutHandlerName:da("logout",["string"]),loginMethod:da("handshake",["string"],(Da={},Da[S]=Ha,Da)),useJwt:da(!0,["boolean","string"]),hostname:da(!1,["string"]),namespace:da(b,["string"]),wsOptions:da({},["object"]),contract:da({},["object"],(Ba={},Ba[E]=Gr,Ba)),enableAuth:da(!1,["boolean"]),token:da(!1,["string"])},Ka=ba("check-options"),Qa={eventEmitter:null,nspClient:null,nspAuthClient:null,wssPath:""};var Xa={version:"version: 0.8.2 module: umd",serverType:"ws"},Za=null;"undefined"!=typeof WebSocket?Za=WebSocket:"undefined"!=typeof MozWebSocket?Za=MozWebSocket:void 0!==u?Za=u.WebSocket||u.MozWebSocket:"undefined"!=typeof window?Za=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(Za=self.WebSocket||self.MozWebSocket);var ti=Za,ei=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 ri(t,e){return void 0===e&&(e=!1),!1===e?function(e){return new t(ei(e))}:function(e,r){var n=ei(e),o=r&&"string"==typeof r?n+"?"+V+"="+r:n;try{return new t(o)}catch(t){return console.error("WebSocket Connection Error",t),!1}}}function ni(t,e){var r=e.hostname,n=e.wssPath,o=e.wsOptions;return(0,e.nspClient)(t?[r,t].join("/"):n,o)}var oi=ba("client-event-handler"),ai=function(t,e,r){var n=r.useCallbackStyle,o=n?J:F,a=n?I:M;e.$only(Qt(t,Q),(function(r,n){oi("noLoginHandler hijack the ws call",t,r,n);var i={message:"NOT LOGIN"};e.$call(Qt(t,r,o),[i]),e.$call(Qt(t,r,a),[{error:i}])}))},ii=function(t){return t.length>1&&t[0]};function ui(t,e,r,n,o,a){var i=ii(o),u=!1;o.forEach((function(o){if(u=i===o,a[o]){oi("call bindWsHandler",u,o);var c=[o,a[o],r,u,t];if(t.serverType===K){var f=e.nspSet;c.push(f[o])}Reflect.apply(n,null,c)}else ai(o,r,t)})),r.$on(P,(function(){oi("LOGOUT_EVENT_NAME"),function(t,e,r,n){void 0===n&&(n={});var o=n.useCallbackStyle?J:F;e.forEach((function(e){t.$call(Qt(e,o),[{message:r,namespace:e}])}))}(r,o,P),o.forEach((function(e){Aa(r,e),a[e]=!1,ai(e,r,t)}))}))}var ci=["__reply__","__event__","__data__"],fi=function(t){var e,r=t.data;if(!1!==(e=function(t){var e=t.data;return!!e&&(ci.filter((function(t){return Kt(e,t)})).length===ci.length&&e)}(ha(r)?JSON.parse(r):r)))return{resolverName:e.__event__,data:e.__data__,type:e.__reply__};throw new Y("payload can not be decoded",t)},si=ba("ws-main-handler"),li=function(t,e,r,n,o){var a=[e];r&&(si("a global error on "+e),a.push(r)),a.push(o);var i=Reflect.apply(Qt,null,a),u=n.data||n;t.$trigger(i,[u])};function pi(t,e,r,n,o){var a=o.useCallbackStyle,i=a?D:L,u=a?B:W,c=a?U:q,f=a?I:M,s=a?J:F;e.onopen=function(){si("ws.onopen listened"),r.$call(i,t),n&&(console.log("isPrivate and fire the "+u),r.$call(u,t)),r.$only(Qt(t,N),(function(t,r){si("calling server",t,r),e.send(Hr(t,r))}))},e.onmessage=function(e){try{var n=fi(e),o=n.resolverName,a=n.type;switch(si("Hear from server",a,n),a){case N:var i=Qt(t,o,c),u=r.$trigger(i,[n]);si("EMIT_REPLY_TYPE",i,u);break;case R:var l=Qt(t,o,f);r.$trigger(l,[n]);si("ACKNOWLEDGE_REPLY_TYPE",l,n);break;case z:si("ERROR_TYPE"),li(r,t,o,n,s);break;default:si("Unhandled event!",n),li(r,t,o,n,s)}}catch(e){console.error("ws.onmessage error",e),li(r,t,!1,e,s)}},e.onclose=function(){si("ws.onclose callback")},r.$on(P,(function(){try{si("terminate ws connection"),e.terminate()}catch(t){console.error("ws.terminate error",t)}}))}ba("ws-create-client");var hi=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]=ni(e,t),i)})).reduce((function(t,e){return Object.assign(t,e)}),{});else{var f=(n=o,Object.keys(n)[0]);u.push(f),c[f]=ni(!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 ga(t,Ga,Object.assign(Qa,e)).then((function(t){return t.hostname||(t.hostname=$a()),t.wssPath=Ea([t.hostname,t.namespace].join("/"),t.serverType),Ka("CONFIGURATION OPTIONS",t),t}))}(r,e).then((function(t){return{opts:t,nspMap:ka(t),ee:n||new Oa}})).then((function(e){var r=e.opts,n=e.nspMap,o=e.ee;return t(r,n,o)})).then((function(t){return Ya(t.opts,t.nspMap,t.ee)})).catch((function(t){console.error("jsonql-ws-client init error",t)}))}}(function(t){var e=ri(t),r=ri(t,!0);return function(t,n,o){return t.nspClient=e,t.nspAuthClient=r,function(t,e,r){var n=[t,e,r,pi],o=t.token,a=hi(t,e,o),i=a.nsps,u=a.namespaces,c=a.login;return Reflect.apply(ui,null,n.concat([u,i])),c&&r.$only(T,(function(o){Aa(r,u);var a=hi(t,e,o);Reflect.apply(ui,null,n.concat([a.namespaces,a.nsps]))})),{opts:t,nspMap:e,ee:r}}(t,n,o)}}(ti),Xa)})); //# sourceMappingURL=jsonql-ws-client.umd.js.map diff --git a/packages/@jsonql/ws/node.js b/packages/@jsonql/ws/node.js index 55eb07439a2a186573e49f5ef6c060f2fb865c89..9bf63d80e1f5a5c17c2e1a9d6b947642bd400606 100644 --- a/packages/@jsonql/ws/node.js +++ b/packages/@jsonql/ws/node.js @@ -1,12 +1,2 @@ -// 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) +"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}require("fs"),require("path");var WebSocket=_interopDefault(require("ws")),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),global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},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),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",ON_MESSAGE_PROP_NAME$1="onMessage",ON_RESULT_PROP_NAME$1="onResult",ON_ERROR_PROP_NAME$1="onError",ON_READY_PROP_NAME="onReady",ON_LOGIN_PROP_NAME="onLogin",SEND_MSG_PROP_NAME="send",MESSAGE_PROP_NAME="message",RESULT_PROP_NAME="result",ERROR_PROP_NAME="error",READY_PROP_NAME$1="ready",LOGIN_PROP_NAME="login",NOT_LOGIN_ERR_MSG="NOT LOGIN",TOKEN_PARAM_NAME="token",IO_ROUNDTRIP_LOGIN="roundtip",IO_HANDSHAKE_LOGIN="handshake",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)}}var SOCKET_IO=JS_WS_SOCKET_IO_NAME,MISSING_PROP_ERR="Missing property in contract!",EMIT_EVT=EMIT_REPLY_TYPE,UNKNOWN_RESULT="UKNNOWN RESULT!",MY_NAMESPACE="myNamespace",CB_FN_NAME="on",isArray=Array.isArray,freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(e){var r=hasOwnProperty.call(e,symToStringTag),t=e[symToStringTag];try{e[symToStringTag]=void 0;var n=!0}catch(e){}var o=nativeObjectToString.call(e);return n&&(r?e[symToStringTag]=t:delete e[symToStringTag]),o}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function overArg(e,r){return function(t){return e(r(t))}}var getPrototype=overArg(Object.getPrototypeOf,Object);function isObjectLike(e){return null!=e&&"object"==typeof e}var objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(e){if(!isObjectLike(e)||baseGetTag(e)!=objectTag)return!1;var 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 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("")}var inArray=function(e,r){return!!e.filter((function(e){return e===r})).length},toArray=function(e){return isArray(e)?e:[e]},isObjectHasKey=function(e,r){try{var t=Object.keys(e);return inArray(t,r)}catch(e){return!1}},createEvt=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.join("_")},isFunc=function(e){if("function"==typeof e)return!0;console.error("Expect to be Function type!")},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(e))}),Reflect.apply(e,null,t))}};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();++r-1&&e%1==0&&e<=MAX_SAFE_INTEGER}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag$1="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(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]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var e=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return e||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(e,r){if(("constructor"!==r||"function"!=typeof e[r])&&"__proto__"!=r)return e[r]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(e,r,t){var n=e[r];hasOwnProperty$6.call(e,r)&&eq(n,t)&&(void 0!==t||r in e)||baseAssignValue(e,r,t)}function copyObject(e,r,t,n){var o=!t;t||(t={});for(var a=-1,i=r.length;++a-1&&e%1==0&&e0){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;)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 e.then((function(e){return r(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)&&(isObjectHasKey(e,QUERY_NAME)||isObjectHasKey(e,MUTATION_NAME)||isObjectHasKey(e,SOCKET_NAME))}function extractSocketPart(e){return!!isObjectHasKey(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 stringTag$1="[object String]";function isString(e){return"string"==typeof e||!isArray(e)&&isObjectLike(e)&&baseGetTag(e)==stringTag$1}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;function isNull(e){return null===e}function isUndefined(e){return void 0===e}var boolTag$1="[object Boolean]";function isBoolean(e){return!0===e||!1===e||isObjectLike(e)&&baseGetTag(e)==boolTag$1}var numberTag$1="[object Number]";function isNumber(e){return"number"==typeof e||isObjectLike(e)&&baseGetTag(e)==numberTag$1}function isNaN(e){return isNumber(e)&&e!=+e}function arrayFilter(e,r){for(var t=-1,n=null==e?0:e.length,o=0,a=[];++ts))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))},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)};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$1=function(e){return checkIsArray(e)?e:[e]},inArray$1=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$1(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$1(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),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){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,n){void 0===n&&(n={});var o=n.useCallbackStyle?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.forEach((function(r){e.$call(createEvt(r,o),[{message:t,namespace:r}])}))}var debugFn$7=getDebug("client-event-handler"),notLoginWsHandler=function(e,r,t){var n=t.useCallbackStyle,o=n?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1,a=n?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1;r.$only(createEvt(e,EMIT_EVT),(function(t,n){debugFn$7("noLoginHandler hijack the ws call",e,t,n);var i={message:NOT_LOGIN_ERR_MSG};r.$call(createEvt(e,t,o),[i]),r.$call(createEvt(e,t,a),[{error:i}])}))},getPrivateNamespace=function(e){return e.length>1&&e[0]};function clientEventHandler(e,r,t,n,o,a){var i=getPrivateNamespace(o),s=!1;o.forEach((function(o){if(s=i===o,a[o]){debugFn$7("call bindWsHandler",s,o);var c=[o,a[o],t,s,e];if(e.serverType===SOCKET_IO){var u=r.nspSet;c.push(u[o])}Reflect.apply(n,null,c)}else notLoginWsHandler(o,t,e)})),t.$on(LOGOUT_EVENT_NAME,(function(){debugFn$7("LOGOUT_EVENT_NAME"),triggerNamespacesOnError(t,o,LOGOUT_EVENT_NAME),o.forEach((function(r){clearMainEmitEvt(t,r),a[r]=!1,notLoginWsHandler(r,t,e)}))}))}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 isObjectHasKey(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$8=getDebug("ws-main-handler"),errorTypeHandler=function(e,r,t,n,o){var a=[r];t&&(debugFn$8("a global error on "+r),a.push(t)),a.push(o);var i=Reflect.apply(createEvt,null,a),s=n.data||n;e.$trigger(i,[s])};function wsMainHandler(e,r,t,n,o){var a=o.useCallbackStyle,i=a?READY_PROP_NAME$1:ON_READY_PROP_NAME,s=a?LOGIN_PROP_NAME:ON_LOGIN_PROP_NAME,c=a?MESSAGE_PROP_NAME:ON_MESSAGE_PROP_NAME$1,u=a?RESULT_PROP_NAME:ON_RESULT_PROP_NAME$1,l=a?ERROR_PROP_NAME:ON_ERROR_PROP_NAME$1;r.onopen=function(){debugFn$8("ws.onopen listened"),t.$call(i,e),n&&(console.log("isPrivate and fire the "+s),t.$call(s,e)),t.$only(createEvt(e,EMIT_REPLY_TYPE),(function(e,t){debugFn$8("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$8("Hear from server",a,n),a){case EMIT_REPLY_TYPE:var i=createEvt(e,o,c),s=t.$trigger(i,[n]);debugFn$8("EMIT_REPLY_TYPE",i,s);break;case ACKNOWLEDGE_REPLY_TYPE:var f=createEvt(e,o,u);t.$trigger(f,[n]);debugFn$8("ACKNOWLEDGE_REPLY_TYPE",f,n);break;case ERROR_TYPE:debugFn$8("ERROR_TYPE"),errorTypeHandler(t,e,o,n,l);break;default:debugFn$8("Unhandled event!",n),errorTypeHandler(t,e,o,n,l)}}catch(r){console.error("ws.onmessage error",r),errorTypeHandler(t,e,!1,r,l)}},r.onclose=function(){debugFn$8("ws.onclose callback")},t.$on(LOGOUT_EVENT_NAME,(function(){try{debugFn$8("terminate ws connection"),r.terminate()}catch(e){console.error("ws.terminate error",e)}}))}var debugFn$9=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),node=wsClient(wsClientResolver,constProps);module.exports=node; +//# sourceMappingURL=node.js.map diff --git a/packages/@jsonql/ws/node.js.map b/packages/@jsonql/ws/node.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dec3b7b64329f9ce75db7b225711278b144506a7 --- /dev/null +++ b/packages/@jsonql/ws/node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node.js","sources":[],"sourcesContent":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/@jsonql/ws/package.json b/packages/@jsonql/ws/package.json index ab8ac2d33927ac7909f779f8f10201db02454733..f70cc93b9280397db62ae97e6e90e07b79f63679 100644 --- a/packages/@jsonql/ws/package.json +++ b/packages/@jsonql/ws/package.json @@ -1,15 +1,16 @@ { "name": "@jsonql/ws", - "version": "0.8.0", + "version": "0.8.2", "description": "WS (WebSocket) jsonql client module for browser / node", - "main": "dist/jsonql-ws.cjs.js", + "main": "node.js", "browser": "dist/jsonql-ws.umd.js", "module": "index.js", "files": [ "dist", "src", "index.js", - "node.js" + "node.js", + "node.js.map" ], "scripts": { "test": "ava --verbose", @@ -37,11 +38,11 @@ "license": "ISC", "homepage": "jsonql.org", "dependencies": { - "jsonql-constants": "^1.8.8", + "jsonql-constants": "^1.8.9", "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.3", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.8.1", + "jsonql-utils": "^0.8.3", "jsonql-ws-client": "^1.3.3", "ws": "^7.2.0" }, @@ -50,13 +51,13 @@ "esm": "^3.2.25", "fs-extra": "^8.1.0", "glob": "^7.1.5", - "jsonql-contract": "^1.7.21", - "jsonql-koa": "^1.3.10", - "jsonql-ws-server": "^1.3.4", + "jsonql-contract": "^1.7.22", + "jsonql-koa": "^1.3.11", + "jsonql-ws-server": "^1.3.5", "kefir": "^3.8.6", - "koa": "^2.10.0", + "koa": "^2.11.0", "koa-bodyparser": "^4.2.1", - "rollup": "^1.25.2", + "rollup": "^1.26.3", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-async": "^1.2.0", "rollup-plugin-buble": "^0.19.8", diff --git a/packages/@jsonql/ws/rollup.config.js b/packages/@jsonql/ws/rollup.config.js index e41b737c7dc3affa0e0b257038b582c237eab533..713988029c8ae7276319f6293b059bdbf0496f1c 100644 --- a/packages/@jsonql/ws/rollup.config.js +++ b/packages/@jsonql/ws/rollup.config.js @@ -32,7 +32,7 @@ let plugins = [ transforms: { dangerousForOf: true } }), nodeResolve({ - + }), commonjs({ include: 'node_modules/**' @@ -52,13 +52,14 @@ if (process.env.NODE_ENV === 'production') { plugins.push( size() ) -const inFile = target === 'cjs' ? 'node.js' : 'index.js' +const inFile = target === 'cjs' ? 'src/node.js' : 'index.js' +const outFile = target === 'cjs' ? join(__dirname, 'node.js') : join(__dirname, 'dist', `jsonql-ws-client.${target}.js`) let config = { input: join(__dirname, inFile), output: { name: 'jsonqlWsClient', - file: join(__dirname, 'dist', `jsonql-ws-client.${target}.js`), + file: outFile, format: target, sourcemap: true, globals: { diff --git a/packages/@jsonql/ws/src/node.js b/packages/@jsonql/ws/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..54753117059a16e43baea2322c32eac968c302c0 --- /dev/null +++ b/packages/@jsonql/ws/src/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 './options' +import wsClientResolver from './node-ws-client-resolver' + +// export back the function and that's it +export default jsonqlWsClient(wsClientResolver, constProps) 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 93eeb517c480427572dc621ce9d481ed8918f76d..834ef7dda84a3fa2b035e7dfdbc24436aac64a75 100644 --- a/packages/@jsonql/ws/tests/ws-client-auth-login.test.js +++ b/packages/@jsonql/ws/tests/ws-client-auth-login.test.js @@ -116,7 +116,6 @@ test.serial.cb('It should trigger the login call here', t => { }) // 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) diff --git a/packages/contract-cli/package.json b/packages/contract-cli/package.json index 9aab45834ee7bbb101f4ee2a8e8147c326132cb4..666aafda6e4a64589fc548423e848c8e99f091ae 100755 --- a/packages/contract-cli/package.json +++ b/packages/contract-cli/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-contract", - "version": "1.7.22", + "version": "1.8.0", "description": "JS API / command line tool to generate the contract.json for jsonql", "main": "index.js", "files": [ @@ -15,8 +15,8 @@ "prepare": "ava --verbose", "cli": "DEBUG=jsonql-contract* node ./cli.js", "cli:watch": "DEBUG=jsonql-contract* node ./watch.js", - "test:cli": "npm run cli configFile ./tests/fixtures/cmd-config-test.js", "test": "ava --verbose", + "test:cli": "npm run cli configFile ./tests/fixtures/cmd-config-test.js", "test:doc": "DEBUG=jsonql-contract:* ava ./tests/contract-with-doc.test.js", "test:gen": "DEBUG=jsonql-contract:* ava ./tests/generator.test.js", "test:path": "DEBUG=jsonql-contract:* ava tests/paths.test.js", @@ -43,18 +43,19 @@ }, "dependencies": { "acorn": "^7.1.0", - "debug": "^4.1.1", - "chokidar": "^3.2.3", + "chokidar": "^3.3.0", "colors": "^1.4.0", + "debug": "^4.1.1", "fs-extra": "^8.1.0", "glob": "^7.1.5", "jsdoc-api": "^5.0.4", "jsonql-constants": "^1.8.9", - "jsonql-errors": "^1.1.3", + "jsonql-errors": "^1.1.5", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.8.2", + "jsonql-utils": "^0.8.3", "kefir": "^3.8.6", "lodash": "^4.17.15", + "nb-split-tasks": "^0.5.1", "yargs": "^14.2.0" }, "devDependencies": { diff --git a/packages/contract-cli/src/ast/jsdoc.js b/packages/contract-cli/src/ast/jsdoc.js index 1b0e07df192b96a354eec756e6d2e7dfc0c3638f..cda2b9fcd78e0cdd7121db818d84313d0369d7d7 100644 --- a/packages/contract-cli/src/ast/jsdoc.js +++ b/packages/contract-cli/src/ast/jsdoc.js @@ -199,7 +199,6 @@ const search = function(output, name = '') { */ const searchForParams = function(output) { const result = search(output) - // debug('searchForParams', result) if (result.name && !result.params) { debug(`params is no defined?`, detailOut(result)) debug(`output`, detailOut(output)) @@ -217,12 +216,12 @@ const clearForOutput = function(result, name) { if (Array.isArray(result)) { const res = searchForParams(result) if (!res.params) { - debug(detailOut(res)) + debug(`res.params it not defined?`, detailOut(res)) throw new Error(`Could not parse the jsdoc for ${name}!`) } return res; } else { - debug('jsdoc return result result', detailOut(result)) + debug('jsdoc return result', detailOut(result)) throw new JsonqlError(`${name} jsdoc parsing result is unexpected, did the programmer wrote comment correctly?`, result) } } diff --git a/packages/contract-cli/src/generator/hamsters/explain-resolver.js b/packages/contract-cli/src/generator/hamsters/explain-resolver.js deleted file mode 100644 index 5effde7c9e5294565864af0894a3c607b594b2e3..0000000000000000000000000000000000000000 --- a/packages/contract-cli/src/generator/hamsters/explain-resolver.js +++ /dev/null @@ -1,18 +0,0 @@ -// this will take the last preprocess output then pass to the jsdoc acron to -// get the part for the contract -const { getJsdoc } = require('../ast/jsdoc') - -/** - * The process listener - * @param {object} payload the complete payload - * @param {number} payload.idx the index of this process - * @param {string} payload.processor the name of the processor - * @param {array} payload.args the argument pass to the processor - * @return {void} just use process.send back the idx, processor and result - */ -process.on('message', ({ idx, processor, args }) => { - Reflect.apply(fn[processor], null, args) - .then(result => { - process.send({ idx, processor, result}) - }) -}) diff --git a/packages/contract-cli/src/generator/import.template.js b/packages/contract-cli/src/generator/import.template.js deleted file mode 100644 index 6601f782c3497ae953db86928e4e6e922da04a10..0000000000000000000000000000000000000000 --- a/packages/contract-cli/src/generator/import.template.js +++ /dev/null @@ -1,2 +0,0 @@ -require = require("esm")(module/*, options*/) -module.exports = require("./resolver.js") diff --git a/packages/contract-cli/src/generator/index.js b/packages/contract-cli/src/generator/index.js index 6d6afb0dcc011d95155967b9ccbcf31f6b1b6599..b56a246402be41c8e40fe027c3b7c01646f46999 100644 --- a/packages/contract-cli/src/generator/index.js +++ b/packages/contract-cli/src/generator/index.js @@ -73,7 +73,7 @@ const generateNewContract = (config) => { // @BUG the async cause no end of problem for the client downstream // so I take it down and only return promise instead // main -module.exports = function(config) { +module.exports = function generator(config) { banner(config) // first we need to check if this is a public! // then try to read the contract.json file diff --git a/packages/contract-cli/src/generator/process-file.js b/packages/contract-cli/src/generator/process-file.js index 71af7531eeb1c77559448211fd37603854493958..0c85a4165163d7cc7890b25a903a88521a4d4405 100644 --- a/packages/contract-cli/src/generator/process-file.js +++ b/packages/contract-cli/src/generator/process-file.js @@ -7,35 +7,45 @@ const { getContractBase, processResolverToContract } = require('./get-resolver') +const { splitTask } = require('./split-task') +const { NOT_ENOUGH_CPU } = require('nb-split-tasks/constants') +const { EXT } = require('jsonql-constants') +const { JsonqlError } = require('jsonql-errors') + const { getDebug } = require('../utils') const debug = getDebug('process-file') -// this was lost when using as api using let /** + * @NOTE this should be replace with the split task * Take the map filter out to get the clean resolver objects * @param {array} _files files to process * @param {function} preprocessor for capture the resolver * @return {array} resolver objects */ -function processFilesAction(inDir, fileType, files, config) { - const preprocessor = getResolver(config, fileType) - return Promise.resolve( - files.map( preprocessor ) - .filter( obj => obj.ok ) - ) - // .reduce( (n, m) => [...n, m], []) +function processFilesAction(files, fileType, config) { + const payload = { fileType, files, config } + return splitTask('pre', payload) + .catch(err => { + if (err === NOT_ENOUGH_CPU) { + const preprocessor = getResolver(config, fileType) + return Promise.resolve( + files.map( preprocessor ) + .filter( obj => obj.ok ) + ) + } + throw new JsonqlError(err) + }) } /** * This is the step one to parallel process the resolver file * @param {array} files to process - * @param {string} inDir where the resolverDir is * @param {string} fileType extension to expect * @param {object} config options * @return {array} of preprocessed filtered resolver */ -function preprocessResolverFile(files, inDir, fileType, config) { - return processFilesAction(inDir, fileType, files, config) +function preprocessResolverFile(files, fileType, config) { + return processFilesAction(files, fileType, config) .then(objs => [ getSourceType(objs), objs @@ -51,13 +61,19 @@ function preprocessResolverFile(files, inDir, fileType, config) { * @return {object} promise that resolve all the files key query / mutation */ function processResolverFile(sourceType, files, config) { - return Promise.resolve( - files - .map(({ type, name, file, public, namespace }) => ( - processResolverToContract(type, name, file, public, namespace, resourceType) - )) - .reduce(merge, getContractBase(sourceType)) - ) + const contractBase = getContractBase(sourceType) + const payload = { sourceType, files, config } + return splitTask('process', payload, contractBase) + .catch(err => { + if (err === NOT_ENOUGH_CPU) { + return files + .map(({ type, name, file, public, namespace }) => ( + processResolverToContract(type, name, file, public, namespace, sourceType) + )) + .reduce(merge, contractBase) + } + throw new JsonqlError(err) + }) } /** diff --git a/packages/contract-cli/src/generator/read-files-out-contract.js b/packages/contract-cli/src/generator/read-files-out-contract.js index 4423f702f496aaa70291e7ba5dcb1f7878220f6b..3335c3f3e5fe5298c81485ef6e37f04934da2f26 100644 --- a/packages/contract-cli/src/generator/read-files-out-contract.js +++ b/packages/contract-cli/src/generator/read-files-out-contract.js @@ -43,14 +43,13 @@ function readFilesOutContract(config) { let timestart = Date.now() return getResolverFiles(resolverDir, fileType) - .then(_files => { - return preprocessResolverFile(_files, resolverDir, fileType, config) + .then(files => preprocessResolverFile(files, fileType, config) .then(result => { const [sourceType, files] = result; return processResolverFile(sourceType, files, config) .then(contract => [sourceType, contract]) }) - }) + ) .then(result => { let timeend = Date.now() - timestart debug('Time it took:', colors.yellow(timeend)) diff --git a/packages/contract-cli/src/generator/split-task.js b/packages/contract-cli/src/generator/split-task.js index 07deeeb812cc288c71f4b37640753d83ffc590ec..373837248869ffddcc9b4cf90935d3a20df4d750 100644 --- a/packages/contract-cli/src/generator/split-task.js +++ b/packages/contract-cli/src/generator/split-task.js @@ -1,71 +1,11 @@ // this will be responsible to split the task and run parallel computing to speed the task -const os = require('os') -const { fork } = require('child_process') const { join } = require('path') -const { chainPromises } = require('jsonql-utils') +const nbSplitTasks = require('nb-split-tasks') const { getDebug } = require('../utils') - const debug = getDebug('split-task') -const basePath = join(__dirname, 'hamsters') -/** - * test if we have enough cpu slots - * @return {int} available cpu slots - */ -function getSlots() { - return os.cpus().length - 1; -} - -/** - * actually calling the task and return a promise that resolve result - * @param {string} taskPath file name of the method - * @param {*} payload to send to the task - * @return {promise} resolve the result or reject with error - */ -function executeTask(taskPath, payload) { - const ps = fork(join(basePath, `${taskPath}.js`)) - - debug(payload.idx, payload) - - return new Promise((resolver, rejecter) => { - ps.send( payload ) - ps.on('message', result => { - resolver(result) - }) - ps.on('error', err => { - rejecter(err) - }) - }) -} - -/** - * create the task matrix - * @param {int} slots cpu slots - * @param {string} taskPath file name of the method - * @param {array} payloads array - * @param {boolean} returnType arry of object - * @return {promise} resolve the final result - */ -function createTask(slots, taskPath, payloads, returnType = true) { - let taskCtn = payloads.length; - let matrix = [] - let ctn = Math.ceil(taskCtn/slots) - for (let i=0; i= taskCtn) { - end = taskCtn; - } - matrix.push( - chainPromises(payloads.slice(begin, end).map(payload => ( - executeTask(taskPath, payload) - )), returnType) - ) - } - // now futher process the final matrix - return chainPromises(matrix, returnType) -} +const basePath = join(__dirname, 'sub') /** * The top level export method to get the task to do and array of payload @@ -73,49 +13,36 @@ function createTask(slots, taskPath, payloads, returnType = true) { * @param {array} payload array of payload * @return {promise} resolve the final result */ -function splitTask(config, payload) { - - return Promise.resolve(false) - - const slots = getSlots() - if ((slots > 0) === false) { - console.error(`Sorry your system does NOT support multi processing!`) - return Promise.resolve(false) - } - let returnType = true; +function splitTask(taskName, payload, returnType = 'array') { let scriptName, postProcessor; let payloads = [] // prepare payload switch (taskName) { case 'process': - - return Promise.resolve(false) // stop it for testing - - scriptName = 'explain-resolver' - let { sourceType, config } = payload; - payloads = payload.files.map(file => ({ sourceType, file, config })) + scriptName = join(basePath, 'explain.js') + let { sourceType } = payload; + payloads = payload.files.map( + ({ type, name, file, public, namespace }) => ({ type, name, file, public, namespace, sourceType }) + ) postProcessor = result => result; break; case 'pre': - returnType = false; // default is array - scriptName = 'preprocess-resolver'; + // 'prep.js' + scriptName = join(basePath, 'prep.js') // here we need to get a preprocessor, then we don't need to keep calling it // can not send a function as arument to the fork fn - let { inDir, fileType, files } = payload; + let { fileType, files } = payload; // debug(preprocessor, files) - payloads = files.map((file, idx) => ({ file, inDir, fileType, idx, config: payload.config })) - postProcessor = result => { - // should be running the fitler here - debug('postProcessor', result) - return result.filter(obj => obj.ok) - } + payloads = files.map((file, idx) => ({ idx, file, fileType, config: payload.config })) + // run the filter at this point + postProcessor = result => result.filter(obj => obj.ok) break; default: throw new Error(`Unknown task ${taskName}`) } + // debug(scriptName, payloads, returnType) // finally return - // return chainFns(createTask, postProcessor)(slots, scriptName, payloads) - return createTask(slots, scriptName, payloads, returnType) - .then(postProcessor) + return nbSplitTasks(scriptName, payloads, returnType) + .then(postProcessor) } // export diff --git a/packages/contract-cli/src/generator/sub/explain.js b/packages/contract-cli/src/generator/sub/explain.js new file mode 100644 index 0000000000000000000000000000000000000000..0d5a9562b7ade7010e33f80b94e42ff429e3b54c --- /dev/null +++ b/packages/contract-cli/src/generator/sub/explain.js @@ -0,0 +1,11 @@ +// this will take the last preprocess output then pass to the jsdoc acron to +// get the part for the contract +const { processResolverToContract } = require('../get-resolver') + +/** + * see processResolverToContract desc + * @return {object} the process result + */ +module.exports = function processResolverFile({ type, name, file, public, namespace, sourceType }) { + return processResolverToContract(type, name, file, public, namespace, sourceType) +} diff --git a/packages/contract-cli/src/generator/hamsters/preprocess-resolver.js b/packages/contract-cli/src/generator/sub/prep.js similarity index 72% rename from packages/contract-cli/src/generator/hamsters/preprocess-resolver.js rename to packages/contract-cli/src/generator/sub/prep.js index 8ecb8f8740b1db6b0e3e792d82948e6b991a6143..bbe8520ea058d593495101ec9d7224c52599a12c 100644 --- a/packages/contract-cli/src/generator/hamsters/preprocess-resolver.js +++ b/packages/contract-cli/src/generator/sub/prep.js @@ -1,5 +1,6 @@ // this will take the input files list then check if this is a resolver const { getResolver } = require('../get-resolver') + /** * The process listener * @param {object} payload the complete payload @@ -7,11 +8,7 @@ const { getResolver } = require('../get-resolver') * @param {string} payload.file the argument pass to the processor * @return {void} just use process.send back the idx, processor and result */ -process.on('message', ({file, config, fileType}) => { +module.exports = function preprocessResolver({file, config, fileType}) { const fn = getResolver(config, fileType) - fn(file) - .then(result => { - // send the result straight back - process.send(result) - }) -}) + return Reflect.apply(fn, null, [file]) +} diff --git a/packages/contract-cli/tests/cmd.test.js b/packages/contract-cli/tests/cmd.test.js index cd5fd870332e824df95cb2924e9e115e83b8c55b..56a71ff2d7bd377d05a15f26099c440e09dd2753 100644 --- a/packages/contract-cli/tests/cmd.test.js +++ b/packages/contract-cli/tests/cmd.test.js @@ -20,31 +20,42 @@ test.after(t => { }) test.cb('It should able to call the cmd and have correct output', t => { - t.context.ps = spawn('node', [ + + t.plan(1) + + const ps = spawn('node', [ cliFile, 'create', inDir, outDir ]) - t.plan(1) - - t.context.ps.stdout.on('data', data => { - debug('stdout: ', data.toString()) + ps.stdout.on('data', data => { + let msg = data.toString() + debug('stdout: ', msg) + // @BUG the ps.on('close') never fired??? + if (msg.indexOf('Your contract file generated in') > -1) { + t.pass() + t.end() + } }) - t.context.ps.stderr.on('data', data => { + ps.stderr.on('data', data => { debug('stderr: ', data.toString()) }) - t.context.ps.on('close', code => { + ps.on('close', code => { debug(`(1) Exited with ${code}`) t.true(fsx.existsSync(join(outDir, DEFAULT_CONTRACT_FILE_NAME))) t.end() }) + }) test.cb("It should able to pick up the config file", t => { + + t.plan(1) + const ps = spawn('node', [ cliFile, 'config', @@ -52,7 +63,13 @@ test.cb("It should able to pick up the config file", t => { ]) ps.stdout.on('data', data => { - debug('stdout: ', data.toString()) + let msg = data.toString() + debug('stdout: ', msg) + // @BUG the ps.on('close') never fired??? + if (msg.indexOf('Your contract file generated in') > -1) { + t.pass() + t.end() + } }) ps.stderr.on('data', data => { @@ -60,6 +77,12 @@ test.cb("It should able to pick up the config file", t => { }) ps.on('close', code => { + debug(`(2) Closed with ${code}`) + t.truthy(fsx.existsSync(configTestFile)) + t.end() + }) + + ps.on('exit', code => { debug(`(2) Exited with ${code}`) t.truthy(fsx.existsSync(configTestFile)) t.end() diff --git a/packages/contract-cli/tests/split-task.test.js b/packages/contract-cli/tests/split-task.test.js index ee69038eace72ec449c6cada6d0909a369c97fe7..4678a1735a344a436babc23486de6e83632b6aef 100644 --- a/packages/contract-cli/tests/split-task.test.js +++ b/packages/contract-cli/tests/split-task.test.js @@ -2,11 +2,9 @@ // array of promises const test = require('ava') const { join } = require('path') -const { chainPromises } = require('jsonql-utils') -const os = require('os') const debug = require('debug')('jsonql-contract:test:split') const { EXT } = require('jsonql-constants') - +const nbSplitTasks = require('nb-split-tasks') // import method frr testing const { getResolverFiles } = require('../src/generator/read-files-out-contract') const { splitTask } = require('../src/generator/split-task') @@ -19,78 +17,41 @@ const { const resolverDir = join(__dirname, 'fixtures', 'koa-resolvers') -function randomIntFromInterval(min, max) { // min and max included - return Math.floor(Math.random() * (max - min + 1) + min); -} - test.before(t => { - const ctn = os.cpus().length - 1; - t.context.ctn = ctn; - // create 100 fake taskes - let taskes = [] - for (let i = 0; i < 100; ++i) { - taskes.push(() => { - let seed = randomIntFromInterval(1, 10) - return new Promise(resolver => { - setTimeout(() => { - resolver({ - ['msg' + i]: `This is task #${i} with random num ${seed}` - }) - }, 100*seed) - }) - }) - } - t.context.taskes = taskes + }) -test.cb(`Should able to create multiple array based on the cpu available`, t => { +test.cb.skip(`First test the splitTask in a different environment`, t => { t.plan(1) - - debug(`available task slot is ${t.context.ctn}`) - - let ctn = t.context.ctn; - let taskes = t.context.taskes; - let taskCtn = taskes.length; - - let matrix = []; - let slots = Math.ceil(taskCtn / ctn) - - debug(`Total slot is ${slots}`) - - let i = 0; - for (let j = 0; j < slots; ++j) { - let begin = j * ctn; - let end = begin + ctn; - if (end >= taskCtn) { - end = taskCtn; - } - matrix.push( - chainPromises(taskes.slice(begin, end).map(fn => fn()), {}) - ) + const pathToFn = join(__dirname, '..', 'src', 'generator', 'sub', 'test.js') + let args = []; + for (let i=0; i<10; ++i) { + args.push([{idx: i+1}]) } - chainPromises(matrix) + + nbSplitTasks(pathToFn, args, 'array') .then(result => { - debug(result) - t.truthy( Array.isArray(result) ) + t.true(Array.isArray(result)) t.end() }) }) -test.cb.skip(`It should able to split the task and return an array`, t => { +test.cb(`It should able to split the task and return an array`, t => { t.plan(2) applyDefaultOptions({ resolverDir }) .then(config => { - return getResolverFiles(resolverDir) + return getResolverFiles(resolverDir, EXT) .then(files => { // prepare the payloads t.truthy(files.length) + // create payload for task const payload = { files, config, - inDir: resolverDir, // we should take this option out later + resolverDir, // we should take this option out later fileType: EXT // this also should be taken out } return splitTask('pre', payload) @@ -101,7 +62,4 @@ test.cb.skip(`It should able to split the task and return an array`, t => { t.end() }) }) - - - }) diff --git a/packages/errors/README.md b/packages/errors/README.md index 6358964d38627e65f5418fe0be38ebd379081db0..7d137b1ae3a5d62d6d2d1f3699c79664171ae307 100644 --- a/packages/errors/README.md +++ b/packages/errors/README.md @@ -1,6 +1,6 @@ # jsonql-errors -These will export a bunch of custom Error class for developer to use. +This module exports a bunch of custom Error class for developer to use. When the server side throw error, the client side will try to throw exactly the same error and as developer you can clearly understand what is happening. @@ -101,4 +101,4 @@ There are two constants export from this module as well --- -MIT (c) 2019 NEWBRAN LTD / TO1SOURCE.CN +ISC (c) 2019 NEWBRAN LTD / TO1SOURCE.CN diff --git a/packages/errors/dist/jsonql-errors.cjs.js b/packages/errors/dist/jsonql-errors.cjs.js index adcfd7b2962805fe313a1c1f8689bdc201d57ffb..14e2ae517f75472ba7cc5b799db15d831fdfc518 100644 --- a/packages/errors/dist/jsonql-errors.cjs.js +++ b/packages/errors/dist/jsonql-errors.cjs.js @@ -1,2 +1,2 @@ -"use strict";function getErrorByStatus(r,o){switch(void 0===o&&(o=!1),r){case 401:return o?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}Object.defineProperty(exports,"__esModule",{value:!0});var Jsonql406Error=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(o,e),o}(Error),Jsonql500Error=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(o,e),o}(Error),JsonqlAuthorisationError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(o,e),o}(Error),JsonqlContractAuthError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(o,e),o}(Error),JsonqlResolverAppError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(o,e),o}(Error),global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},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 o(){for(var o=[],e=arguments.length;e--;)o[e]=arguments[e];r.apply(this,o)}return r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o,o.where=function(){return whereAmI()},o}(Error),JsonqlResolverNotFoundError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(o,e),o}(JsonqlBaseError),JsonqlEnumError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(o,e),o}(Error),JsonqlTypeError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(o,e),o}(Error),JsonqlCheckerError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(o,e),o}(Error),JsonqlValidationError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(o,e),o}(JsonqlBaseError),NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,JsonqlError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;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(o,e),o}(JsonqlBaseError),JsonqlServerError=function(r){function o(e,t){r.call(this,t),this.statusCode=e,this.className=o.name}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(o,e),o}(Error),errors=Object.freeze({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,isObjectHasKey=function(r,o){return!!Object.keys(r).filter(function(r){return o===r}).length};function clientErrorsHandler(r){if(isObjectHasKey(r,"error")){var o=r.error,e=o.className,t=o.name,n=e||t,s=o.message||NO_ERROR_MSG,a=o.detail||o;if(n&&errors[n])throw new errors[e](s,a);throw new JsonqlError$1(s,a)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,o){return r.filter(function(r){return o instanceof r}).map(function(r){return r.name})}function getErrorNameByInstance(r,o){var e=mapErrToName(r,o);return e.length?e[0]:UNKNOWN_ERROR}function getErrorNameByInstanceWithDefault(r,o){var e=getErrorNameByInstance(r,o);return e===UNKNOWN_ERROR?"JsonqlError":e}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var o=r.message||NO_ERROR_MSG,e=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(o,e);case r instanceof Jsonql500Error:throw new Jsonql500Error(o,e);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(o,e);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(o,e);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(o,e);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(o,e);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(o,e);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(o,e);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(o,e);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(o,e);case r instanceof JsonqlServerError:throw new JsonqlServerError(o,e);default:throw new JsonqlError(o,e)}}var JSONQL_ERRORS_INFO="version: 1.1.3 module: cjs";exports.JSONQL_ERRORS_INFO=JSONQL_ERRORS_INFO,exports.Jsonql406Error=Jsonql406Error,exports.Jsonql500Error=Jsonql500Error,exports.JsonqlAuthorisationError=JsonqlAuthorisationError,exports.JsonqlCheckerError=JsonqlCheckerError,exports.JsonqlContractAuthError=JsonqlContractAuthError,exports.JsonqlEnumError=JsonqlEnumError,exports.JsonqlError=JsonqlError,exports.JsonqlResolverAppError=JsonqlResolverAppError,exports.JsonqlResolverNotFoundError=JsonqlResolverNotFoundError,exports.JsonqlServerError=JsonqlServerError,exports.JsonqlTypeError=JsonqlTypeError,exports.JsonqlValidationError=JsonqlValidationError,exports.UNKNOWN_ERROR=UNKNOWN_ERROR,exports.clientErrorsHandler=clientErrorsHandler,exports.finalCatch=finalCatch,exports.getErrorByStatus=getErrorByStatus,exports.getErrorNameByInstance=getErrorNameByInstance,exports.getErrorNameByInstanceWithDefault=getErrorNameByInstanceWithDefault; +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),c="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},s=function(){try{if(window||document)return!0}catch(r){}return!1},i=function(){try{if(!s()&&c)return!0}catch(r){}return!1};var u=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 s()?"browser":i()?"node":"unknown"},t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),m=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),d="No message",g=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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-1},Object.defineProperties(t,e),t}(u),E=function(r){function t(e,o){r.call(this,o),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),y=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:p,JsonqlEnumError:l,JsonqlTypeError:f,JsonqlCheckerError:h,JsonqlValidationError:m,JsonqlError:g,JsonqlServerError:E}),_=g,b=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var q="unknown";function J(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:q}r.JSONQL_ERRORS_INFO="version: 1.1.5 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=h,r.JsonqlContractAuthError=n,r.JsonqlEnumError=l,r.JsonqlError=g,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=p,r.JsonqlServerError=E,r.JsonqlTypeError=f,r.JsonqlValidationError=m,r.UNKNOWN_ERROR=q,r.clientErrorsHandler=function(r){if(b(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||d,c=t.detail||t;if(n&&y[n])throw new y[e](a,c);throw new _(a,c)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new m("",r);var c=r.message||d,s=r.detail||r;switch(!0){case r instanceof t:throw new t(c,s);case r instanceof e:throw new e(c,s);case r instanceof o:throw new o(c,s);case r instanceof n:throw new n(c,s);case r instanceof a:throw new a(c,s);case r instanceof p:throw new p(c,s);case r instanceof l:throw new l(c,s);case r instanceof f:throw new f(c,s);case r instanceof h:throw new h(c,s);case r instanceof m:throw new m(c,s);case r instanceof E:throw new E(c,s);default:throw new g(c,s)}},r.getErrorByStatus=function(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"}},r.getErrorNameByInstance=J,r.getErrorNameByInstanceWithDefault=function(r,t){var e=J(r,t);return e===q?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.cjs.js.map diff --git a/packages/errors/dist/jsonql-errors.umd.js b/packages/errors/dist/jsonql-errors.umd.js index a40b26a370950bca7926ec7baaef7d9b75fe72c5..984a4b69b086db8e5d4050062989aceed178ebef 100644 --- a/packages/errors/dist/jsonql-errors.umd.js +++ b/packages/errors/dist/jsonql-errors.umd.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),c="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},s=function(){try{if(window||document)return!0}catch(r){}return!1},i=function(){try{if(!s()&&c)return!0}catch(r){}return!1};var u=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 s()?"browser":i()?"node":"unknown"},t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),m=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),d="No message",g=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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-1},Object.defineProperties(t,e),t}(u),E=function(r){function t(e,o){r.call(this,o),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),y=Object.freeze({Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:p,JsonqlEnumError:l,JsonqlTypeError:f,JsonqlCheckerError:h,JsonqlValidationError:m,JsonqlError:g,JsonqlServerError:E}),_=g,b=function(r,t){return!!Object.keys(r).filter(function(r){return t===r}).length};var q="unknown";function J(r,t){var e=function(r,t){return r.filter(function(r){return t instanceof r}).map(function(r){return r.name})}(r,t);return e.length?e[0]:q}r.JSONQL_ERRORS_INFO="version: 1.1.3 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=h,r.JsonqlContractAuthError=n,r.JsonqlEnumError=l,r.JsonqlError=g,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=p,r.JsonqlServerError=E,r.JsonqlTypeError=f,r.JsonqlValidationError=m,r.UNKNOWN_ERROR=q,r.clientErrorsHandler=function(r){if(b(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||d,c=t.detail||t;if(n&&y[n])throw new y[e](a,c);throw new _(a,c)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new m("",r);var c=r.message||d,s=r.detail||r;switch(!0){case r instanceof t:throw new t(c,s);case r instanceof e:throw new e(c,s);case r instanceof o:throw new o(c,s);case r instanceof n:throw new n(c,s);case r instanceof a:throw new a(c,s);case r instanceof p:throw new p(c,s);case r instanceof l:throw new l(c,s);case r instanceof f:throw new f(c,s);case r instanceof h:throw new h(c,s);case r instanceof m:throw new m(c,s);case r instanceof E:throw new E(c,s);default:throw new g(c,s)}},r.getErrorByStatus=function(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"}},r.getErrorNameByInstance=J,r.getErrorNameByInstanceWithDefault=function(r,t){var e=J(r,t);return e===q?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})}); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,(function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),c="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},s=function(){try{if(window||document)return!0}catch(r){}return!1},i=function(){try{if(!s()&&c)return!0}catch(r){}return!1};var u=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 s()?"browser":i()?"node":"unknown"},t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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),m=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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}(u),d="No message",g=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];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-1},Object.defineProperties(t,e),t}(u),E=function(r){function t(e,o){r.call(this,o),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),y=Object.freeze({__proto__:null,Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:p,JsonqlEnumError:l,JsonqlTypeError:f,JsonqlCheckerError:h,JsonqlValidationError:m,JsonqlError:g,JsonqlServerError:E}),_=g,b=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};var q="unknown";function J(r,t){var e=function(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}(r,t);return e.length?e[0]:q}r.JSONQL_ERRORS_INFO="version: 1.1.5 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=h,r.JsonqlContractAuthError=n,r.JsonqlEnumError=l,r.JsonqlError=g,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=p,r.JsonqlServerError=E,r.JsonqlTypeError=f,r.JsonqlValidationError=m,r.UNKNOWN_ERROR=q,r.clientErrorsHandler=function(r){if(b(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||d,c=t.detail||t;if(n&&y[n])throw new y[e](a,c);throw new _(a,c)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new m("",r);var c=r.message||d,s=r.detail||r;switch(!0){case r instanceof t:throw new t(c,s);case r instanceof e:throw new e(c,s);case r instanceof o:throw new o(c,s);case r instanceof n:throw new n(c,s);case r instanceof a:throw new a(c,s);case r instanceof p:throw new p(c,s);case r instanceof l:throw new l(c,s);case r instanceof f:throw new f(c,s);case r instanceof h:throw new h(c,s);case r instanceof m:throw new m(c,s);case r instanceof E:throw new E(c,s);default:throw new g(c,s)}},r.getErrorByStatus=function(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"}},r.getErrorNameByInstance=J,r.getErrorNameByInstanceWithDefault=function(r,t){var e=J(r,t);return e===q?"JsonqlError":e},Object.defineProperty(r,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-errors.umd.js.map diff --git a/packages/errors/general.js b/packages/errors/general.js new file mode 100644 index 0000000000000000000000000000000000000000..5fd26515f951ecc21e1004c8b8d4eeb06d600b58 --- /dev/null +++ b/packages/errors/general.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).jsonqlErrors=t()}(this,(function(){"use strict";var e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t=function(){try{if(window||document)return!0}catch(e){}return!1},r=function(){try{if(!t()&&e)return!0}catch(e){}return!1};return function(e){function t(){for(var r=[],n=arguments.length;n--;)r[n]=arguments[n];e.apply(this,r),this.message=r[0],this.detail=r[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={name:{configurable:!0}};return r.name.get=function(){return"GeneralError"},Object.defineProperties(t,r),t}(function(e){function n(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.apply(this,t)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.where=function(){return t()?"browser":r()?"node":"unknown"},n}(Error))})); +//# sourceMappingURL=general.js.map diff --git a/packages/errors/general.js.map b/packages/errors/general.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2d75f79681198e3414ecda8c78aec86114c3969d --- /dev/null +++ b/packages/errors/general.js.map @@ -0,0 +1 @@ +{"version":3,"file":"general.js","sources":[],"sourcesContent":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/errors/main.js b/packages/errors/main.js deleted file mode 100644 index 29125d457481324fe227949f6edc51e7c525d78c..0000000000000000000000000000000000000000 --- a/packages/errors/main.js +++ /dev/null @@ -1,2 +0,0 @@ -require = require('esm')(module); -module.exports = require('./index.js'); diff --git a/packages/errors/package.json b/packages/errors/package.json index bc6e40930d5a0bce102489b0dfaa1b19fd1c3039..6822c0c373bbae47c37dc57351cfb2d143799c3b 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-errors", - "version": "1.1.3", + "version": "1.1.5", "description": "Jsonql js error classes use across the projects", "main": "dist/jsonql-errors.cjs.js", "module": "index.js", @@ -11,28 +11,30 @@ "test:server": "ava ./tests/server.test.js", "test:run": "node ./tests/helpers/run.js", "test:fn": "ava ./tests/fn.test.js", - "build:prod": "NODE_ENV=prod rollup -c", - "build:umd": "NODE_ENV=umd rollup -c", + "build:prod": "TARGET=cjs rollup -c", + "build:umd": "TARGET=umd rollup -c", + "build:gen": "TARGET=general rollup -c", "build": "npm run build:prod && npm run build:umd" }, "files": [ "dist", "src", - "index.js" + "index.js", + "general.js" ], "keywords": [ "jsonql", "Error" ], "devDependencies": { - "ava": "^2.3.0", + "ava": "^2.4.0", "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "koa": "^2.8.1", + "koa": "^2.11.0", "koa-bodyparser": "^4.2.1", - "rollup": "^1.20.3", - "rollup-plugin-alias": "^2.0.0", + "rollup": "^1.26.3", + "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", @@ -44,7 +46,7 @@ "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-plugin-terser": "^5.1.2", "superkoa": "^1.0.3" }, "repository": { @@ -71,9 +73,9 @@ "node": ">=8" }, "homepage": "jsonql.org", - "author": "Joel Chu ", + "author": "Joel Chu ", "license": "ISC", "dependencies": { - "jsonql-constants": "^1.8.3" + "jsonql-constants": "^1.8.9" } } diff --git a/packages/errors/rollup.config.js b/packages/errors/rollup.config.js index e62a6dd1dfbc0dbfc0798a3f61e9b53c7df113dc..7da55bd8364c9d71f099d0fd100936d10af246f0 100644 --- a/packages/errors/rollup.config.js +++ b/packages/errors/rollup.config.js @@ -20,6 +20,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({ @@ -43,17 +44,30 @@ let plugins = [ }), terser(), size() -]; +] +let file; +let inFile = join(__dirname, 'index.js') +switch (target) { + case 'cjs': + file = join(__dirname, 'dist', 'jsonql-errors.cjs.js') + break; + case 'umd': + file = join(__dirname, 'dist', 'jsonql-errors.umd.js') + break; + default: -const file = env === 'prod' ? 'jsonql-errors.cjs.js' : 'jsonql-errors.umd.js'; + inFile = join(__dirname, 'src', 'general.js') + file = join(__dirname, 'general.js') -console.log('Output file is %s', file); +} + +console.log('Output file is %s', file) let config = { - input: join(__dirname, 'index.js'), + input: inFile, output: { name: 'jsonqlErrors', - file: join(__dirname, 'dist', file), + file: file, format: env === 'prod' ? 'cjs' : 'umd', sourcemap: true, globals: { diff --git a/packages/errors/src/error.js b/packages/errors/src/error.js index 179834378c22219179edfb779f80ee53cd5a5beb..12a0531d34507cea4bb3c0ca82c3dbc4a7429268 100644 --- a/packages/errors/src/error.js +++ b/packages/errors/src/error.js @@ -1,4 +1,4 @@ -import { NO_STATUS_CODE } from 'jsonql-constants'; +import { NO_STATUS_CODE } from 'jsonql-constants' import JsonqlBaseError from './error-base' /** * This is a custom error to throw whenever a error happen inside the jsonql diff --git a/packages/errors/src/general.js b/packages/errors/src/general.js new file mode 100644 index 0000000000000000000000000000000000000000..faff2e3f8ad9525a6fd5dd030fe3263f917202af --- /dev/null +++ b/packages/errors/src/general.js @@ -0,0 +1,24 @@ +// this is a new Error class that is not part of the Jsonql +// but we will use it in other external modules +import JsonqlBaseError from './error-base' + +export default class GeneralError extends JsonqlBaseError { + + constructor(...args) { + super(...args); + + this.message = args[0] + this.detail = args[1] + + this.className = GeneralError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, GeneralError) + } + } + + static get name() { + return 'GeneralError'; + } + +} diff --git a/packages/errors/tests/fn.test.js b/packages/errors/tests/fn.test.js index b76a0adb41ae60381a1e8cf7a7be2f06ce8b820e..8f25d7d19a637a526771e52715a446db6423cf31 100644 --- a/packages/errors/tests/fn.test.js +++ b/packages/errors/tests/fn.test.js @@ -8,7 +8,7 @@ const { JsonqlResolverAppError, JsonqlResolverNotFoundError, getErrorNameByInstance -} = require('../main') +} = require('../index') test(`It should able to grab the error and return its name`, t => { diff --git a/packages/http-client/src/base/http-cls.js b/packages/http-client/src/base/http-cls.js index ed632a7d5c956bce27e732e40b0c4f75cf17f24c..46fa3c3088e77084dd74f3104871ffc71ba0950b 100644 --- a/packages/http-client/src/base/http-cls.js +++ b/packages/http-client/src/base/http-cls.js @@ -91,11 +91,11 @@ export default class HttpClass { reqInterceptor() { this.fly.interceptors.request.use( req => { - const headers = this.getHeaders(); + const headers = this.getHeaders() this.log('request interceptor call', headers) for (let key in headers) { - req.headers[key] = headers[key]; + req.headers[key] = headers[key] } return req; } diff --git a/packages/node-client/index.js b/packages/node-client/index.js index f33951ecfb7dc3e601d6cbc57a68607ec9ad6193..0f374bd8fb8ce3929c13b8e17741eca5dabd6958 100755 --- a/packages/node-client/index.js +++ b/packages/node-client/index.js @@ -3,9 +3,11 @@ const { JsonqlRequestClient, getContract, generator, - checkOptions + checkOptions, + createSocketClient } = require('./src') const debug = require('debug')('jsonql-node-client:main') + // finally /** * The config takes two things @@ -15,22 +17,36 @@ const debug = require('debug')('jsonql-node-client:main') * @return {object} promise to resolve the jsonql node client */ module.exports = function(config) { + // make a copy + const rawConfig = Object.assign({}, config) + // start the generator return checkOptions(config) + // @TODO remove once the socket client checked .then(opts => { debug('[jsonql-node-client] init opts', opts) return opts; }) + // start the init sequence .then(opts => ( { jsonqlInstance: new JsonqlRequestClient(opts), opts: opts } )) + // create the client .then( ({jsonqlInstance, opts}) => ( getContract(jsonqlInstance, opts.contract) - .then( - contract => generator(jsonqlInstance, opts, contract) + .then(contract => { + opts.contract = contract; + return { + opts, + contract, + client: generator(jsonqlInstance, opts, contract) + } + } ) ) ) + // create the node client if any + .then(({opts, contract, client}) => createSocketClient(client, opts, contract, rawConfig)) } diff --git a/packages/node-client/package.json b/packages/node-client/package.json index cc2363ca1039910d05c71c8b12308a614f9e7561..5f083a298c3ffb74ada52bbe2457aab441fdb622 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -1,17 +1,19 @@ { "name": "jsonql-node-client", - "version": "1.1.11", + "version": "1.2.0", "description": "jsonql node.js client", "main": "index.js", "scripts": { - "test": "ava --verbose", "prepare": "npm run test", - "test:nyc": "DEBUG=jsonql-node-client* nyc ava", + "test": "ava --verbose", + "test:debug": "DEBUG=jsonql-node-client*,jsonql-contract* ava --verbose", + "test:nyc": "nyc ava --verbose", "test:main": "DEBUG=jsonql-node-client* ava tests/main.test.js", "test:auth": "DEBUG=jsonql-* ava tests/auth.test.js", "test:valid": "DEBUG=jsonql-node-client* ava tests/validation.test.js", "test:config": "DEBUG=jsonql-node-client* ava tests/config.test.js", "test:jwt": "DEBUG=jsonql-node-client* ava tests/jwt.test.js", + "test:socket": "DEBUG=jsonql-node-client* ava tests/socket.test.js", "test:contract": "DEBUG=jsonql-node-client:main,jsonql-koa:process-contract ava --verbose tests/contract.test.js" }, "homepage": "jsonql.org", @@ -25,7 +27,9 @@ "client", "json", "ql", - "js" + "js", + "socket", + "WebSocket" ], "files": [ "src", @@ -37,21 +41,23 @@ ], "license": "MIT", "dependencies": { + "@jsonql/ws": "^0.8.2", "debug": "^4.1.1", "fs-extra": "^8.1.0", - "jsonql-constants": "^1.8.3", + "jsonql-constants": "^1.8.9", "jsonql-errors": "^1.1.3", - "jsonql-jwt": "^1.3.2", + "jsonql-jwt": "^1.3.3", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.6.12", + "jsonql-utils": "^0.8.3", "lodash.merge": "^4.6.2", - "node-cache": "^4.2.1", + "node-cache": "^5.0.1", "request": "^2.88.0" }, "devDependencies": { "ava": "^2.4.0", - "jsonql-contract": "^1.7.21", - "jsonql-koa": "^1.3.9", + "jsonql-contract": "^1.7.22", + "jsonql-koa": "^1.3.11", + "jsonql-ws-server": "^1.3.5", "nyc": "^14.1.1", "server-io-core": "^1.2.0", "superkoa": "^1.0.3" diff --git a/packages/node-client/src/base/index.js b/packages/node-client/src/base/index.js index f019612b9ad1168ad24901cfa732d02a80372109..f0ffe7a2e5e49db50210a51bef88815af1ec6c82 100644 --- a/packages/node-client/src/base/index.js +++ b/packages/node-client/src/base/index.js @@ -1,5 +1,5 @@ // export interface -const JsonqlClientCls = require('./request-client') +const JsonqlClientCls = require('./jsonql-auth-cls') module.exports = JsonqlClientCls; diff --git a/packages/node-client/src/base/jsonql-auth-cls.js b/packages/node-client/src/base/jsonql-auth-cls.js new file mode 100644 index 0000000000000000000000000000000000000000..ff88c7c8b5df0ec593118fc70e40b4f9a218c986 --- /dev/null +++ b/packages/node-client/src/base/jsonql-auth-cls.js @@ -0,0 +1,118 @@ +// this part is focus on the login / logout / validate metthod only +const nbEventService = require('nb-event-service') +const { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, AUTH_HEADER , BEARER } = require('jsonql-constants') +const { isFunc } = require('jsonql-utils') +const JsonqlRequestClient = require('./request-client') +const { display, getDebug, resultHandler } = require('../utils') +const debug = getDebug('jsonql-auth-cls') +// just a placeholder for overwrite +let jsonqlClassLogger = () => {} + +class JsonqlAuthClient extends JsonqlRequestClient { + + constructor(config) { + super(config) + this.eventEmitter = new nbEventService({logger: this.logger}) + } + + /** + * setter for the issuer method to use + * @param {string} token to store + * @return {string} on success + */ + set token(token) { + return this.__storeAuthToken(token) + } + + /** + * setter to pass a logger for the event emitter + * @param {function} fn mostly just the debug + * @return {void} + */ + set logger(fn) { + if (isFunc(fn)) { + jsonqlClassLogger = fn; + } + } + + /** + * getter to get the logger for event emitter + * @return {function} logger or just the placeholder + */ + get logger() { + return jsonqlClassLogger; + } + + /** + * We first call the user / built in method then use this + * callback method to trigger the success login (token) + * @param {string} token the valid token + * @return {string} the token + */ + loginCallback(token) { + this.token = token; + this.eventEmitter.$trigger(LOGIN_EVENT_NAME, token) + return token; + } + + /** + * this is the same as above also trigger the logout event + * @param {*} args when using the custom logout method might have this + * @return {array} return what comes in as an array + */ + logoutCallback(...args) { + this.token = false; // calling the setter + this.eventEmitter.$trigger(LOGOUT_EVENT_NAME, args) + return args; + } + + + /** + * Store the auth token into session storage + * @return {string} token + */ + __storeAuthToken(token) { + // the setter doesn't produce a return! + this.setter('token', token) + debug('store token --> ', token) + return token; + } + + /** + * Get the authorization header + * @return {object} Auth header + */ + __getAuthHeader() { + let t = this.__getAuthToken() + debug(`[getAuthHeader] ${t}`) + return t ? { [AUTH_HEADER]: `${BEARER} ${t}` } : {}; + } + + /** + * Get the stored auth token from session storage + * @return {string} auth token + */ + __getAuthToken() { + let v = this.getter('token') + debug('get token from node-cache', v) + return v; + } + + /** + * When we have the contractKey setup then we need to include this into heading + * @return {object} combine object + */ + __getAuth() { + const extraParams = this.__cacheBurst() + if (this.opts.contractKey === false) { + return extraParams; + } + const contractAuth = { + [this.opts.contractKeyName]: this.opts.contractKey + } + // debug('let see the contract key value pair', contractAuth); + return merge({}, contractAuth, extraParams); + } +} + +module.exports = JsonqlAuthClient diff --git a/packages/node-client/src/base/jsonql-base-cls.js b/packages/node-client/src/base/jsonql-base-cls.js index 497f23233c9e6c73e4e9f4d8e5ff21a38c7355f5..c01f57647c9eaaa147a9edd1d0a10bc3ead632b2 100755 --- a/packages/node-client/src/base/jsonql-base-cls.js +++ b/packages/node-client/src/base/jsonql-base-cls.js @@ -50,24 +50,7 @@ class JsonqlClient extends JsonqlCacheClass { return { 'Accept': contentType, 'Content-Type': contentType - }; - } - - /** - * setter for the issuer method to use - * @param {string} token to store - * @return {string} on success - */ - set token(token) { - return this.__storeAuthToken(token) - } - - /** - * Built-in logout method even if the server doens't have it - * - */ - logout() { - this.token = false; + } } /** @@ -78,6 +61,9 @@ class JsonqlClient extends JsonqlCacheClass { __interceptor(payload, body) { const result = typeof body === 'string' ? JSON.parse(body) : body; const resolverName = Object.keys(payload)[0]; + // this could create a potential bug when some idiot name their + // resolver similar to their auth methods! + /* const { loginHandlerName, logoutHandlerName } = this.opts; switch (true) { case loginHandlerName === resolverName: @@ -91,6 +77,7 @@ class JsonqlClient extends JsonqlCacheClass { this.logout() break; } + */ return result; } @@ -117,10 +104,13 @@ class JsonqlClient extends JsonqlCacheClass { /** * Check if the contract is expired or not + * @TODO this is not enable until we know if we need it * @param {object} contract what it said * @return {boolean} false on OK */ __isContractExpired(contract) { + return false; + /* if (contract) { const { expired } = contract; if (!expired) { @@ -132,6 +122,7 @@ class JsonqlClient extends JsonqlCacheClass { } } return false; + */ } /** @@ -163,10 +154,11 @@ class JsonqlClient extends JsonqlCacheClass { // check if there is a contract store locally const file = join(this.opts.contractDir, this.opts.contractFileName) if (fsx.existsSync(file)) { + let fc = fsx.readJsonSync(file) debug('return contract from file: ', file) - if (!this.__isContractExpired(contract)) { - this.setter('contract', contract) // cache it - return Promise.resolve(fsx.readJsonSync(file)) + if (!this.__isContractExpired(fc)) { + this.setter('contract', fc) // cache it + return Promise.resolve(fc) } } // now grab it from remote @@ -183,51 +175,6 @@ class JsonqlClient extends JsonqlCacheClass { this.setter('contract', contract) }) } - - /** - * Store the auth token into session storage - * @return {string} token - */ - __storeAuthToken(token) { - // the setter doesn't produce a return! - this.setter('token', token) - debug('store token --> ', token) - return token; - } - - /** - * Get the authorization header - * @return {object} Auth header - */ - __getAuthHeader() { - let t = this.__getAuthToken() - debug(`[getAuthHeader] ${t}`) - return t ? { [AUTH_HEADER]: `${BEARER} ${t}` } : {}; - } - - /** - * Get the stored auth token from session storage - * @return {string} auth token - */ - __getAuthToken() { - let v = this.getter('token') - debug('get token from node-cache', v) - return v; - } - - /** - * When we have the contractKey setup then we need to include this into heading - * @return {object} combine object - */ - __getAuth() { - const extraParams = this.__cacheBurst(); - if (this.opts.contractKey === false) { - return extraParams; - } - const contractAuth = {[this.opts.contractKeyName]: this.opts.contractKey}; - // debug('let see the contract key value pair', contractAuth); - return merge({}, contractAuth, extraParams); - } } // export diff --git a/packages/node-client/src/base/jsonql-cache-class.js b/packages/node-client/src/base/jsonql-cache-class.js index fbe26904403837d93125fbcaf555c882e7113c78..33a69de0649515fedf4f627f8449ac12481df1fa 100644 --- a/packages/node-client/src/base/jsonql-cache-class.js +++ b/packages/node-client/src/base/jsonql-cache-class.js @@ -1,6 +1,9 @@ // using node-cache for storage // @2019-08-25 we use the hostname as the base key then store the // data associate with this particular object + +// @TODO we should take this class out and allow to use a third party cacher method + const NodeCache = require('node-cache') const merge = require('lodash.merge') @@ -14,22 +17,46 @@ class JsonqlCacheClass { this.nc = new NodeCache() this.ncBaseKey = config.hostname; debug('ncBaseKey', this.ncBaseKey) + // should init the base cache object + this.baseCacheObj = {}; // @TODO should we use a Set instead? } + /** + * base cache object getter + * @return {object} the base cache object + */ get baseCacheObj() { - const key = this.nc.get(this.ncBaseKey) - debug('baseCacheObj', key) - return key + const obj = this.nc.get(this.ncBaseKey) + // @BUG this is always undefined? + debug('get baseCacheObj', obj) + return obj; } + /** + * base cache object setter + * @param {object} values it should be an merge object + * @return {void} + */ set baseCacheObj(values) { + debug('set baseCacheObj', values) this.nc.set(this.ncBaseKey, values) } + /** + * the value getter + * @param {*} key any qualify object + * @return {*} false when not found + */ getter(key) { return getConfigValue(key, this.baseCacheObj) || false; } + /** + * store the value, id by key + * @param {*} key any qualify key + * @param {*} value any storable value + * @return {void} + */ setter(key, value) { debug('setter', key, value) let obj = this.baseCacheObj; @@ -37,5 +64,4 @@ class JsonqlCacheClass { } } - module.exports = JsonqlCacheClass diff --git a/packages/node-client/src/create-socket-client.js b/packages/node-client/src/create-socket-client.js new file mode 100644 index 0000000000000000000000000000000000000000..6547c5c1b20271ffebbcf2f13255229225692b4b --- /dev/null +++ b/packages/node-client/src/create-socket-client.js @@ -0,0 +1,58 @@ +// new method to include the socket client when pass the serverType config +const { JS_WS_NAME, JS_WS_SOCKET_IO_NAME, JS_PRIMUS_NAME, SOCKET_NAME } = require('jsonql-constants') +const { JsonqlError } = require('jsonql-errors') +const debug = require('debug')('jsonql-node-client:create-socket-client') + +/** + * get the socket client node version using serverType + * @param {string} serverType the socket server (client) type + * @return {object} the module + */ +function getSocketClient(serverType) { + try { + switch (serverType) { + case JS_WS_NAME: + const jsonqlWsClient = require('@jsonql/ws/node') + return jsonqlWsClient; + + case JS_WS_SOCKET_IO_NAME: + case JS_PRIMUS_NAME: + default: + throw new JsonqlError(`getSocketClient`, `Not support ${serverType} at the moment!`) + } + } catch(e) { + console.error(e) + throw new Error(e) + } +} + +/** + * This will hook into the last of the chain during init + * @param {object} client the init jsonql-node-client + * @param {object} config the checked configuration + * @param {object} contract the contract json + * @param {object} rawConfig the configuration pass by user + * @return {object} the modified client object if socketClientType presented + */ +function createSocketClient(client, config, contract, rawConfig) { + const { serverType } = config; + if (serverType) { + // need to pass the eventEmitter here to the config + rawConfig.eventEmitter = client.eventEmitter() + // also need to pass the contract + rawConfig.contract = contract; + const socketClient = getSocketClient(serverType) + // do our thing here + // @TODO need to check when we call the login method from + // the http client, is it triggering the same login event to the + // socket client + return socketClient(rawConfig) + .then(socketCalls => { + client[SOCKET_NAME] = socketCalls + return client; + }) + } + return client; +} + +module.exports = { createSocketClient } diff --git a/packages/node-client/src/generator.js b/packages/node-client/src/generator.js index 13d3d0d24350de5ec5b6b71f85bbcb241a332eaa..208c8a203c4ddec36724226cd8500f9a63bbbbaa 100755 --- a/packages/node-client/src/generator.js +++ b/packages/node-client/src/generator.js @@ -1,7 +1,7 @@ // the main interface generator const { validateAsync } = require('jsonql-params-validator') -const { JsonqlValidationError, finalCatch } = require('jsonql-errors') -const { getDebug, display } = require('./utils') +const { JsonqlValidationError, finalCatch } = require('jsonql-errors') +const { getDebug, display, injectToFn, chainFns } = require('./utils') const debug = getDebug('generator') /** @@ -34,10 +34,12 @@ const authMethodGenerator = (jsonqlInstance, name, opts, contract) => { .apply(jsonqlInstance, [name, values, header]) ) .catch(finalCatch) - }; + } } /** + * Actually generate the client + * @TODO make it getter of the obj instead of just a prop * @param {object} jsonqlInstance * @param {object} config options * @param {object} contract @@ -83,25 +85,32 @@ const generator = (jsonqlInstance, config, contract) => { // there is only one call `issuer` we want if (config.enableAuth && contract.auth) { const { loginHandlerName, logoutHandlerName } = config; + // login if (contract.auth[loginHandlerName]) { // changing to the name the config specify obj[loginHandlerName] = (...args) => { - const fn = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract) - return fn.apply(null, args) + const loginHandler = authMethodGenerator(jsonqlInstance, loginHandlerName, config, contract) + return Reflect.apply(loginHandler, null, args) + .then(jsonqlInstance.loginCallback.bind(jsonqlInstance)) } } + // logout if (contract.auth[logoutHandlerName]) { obj[logoutHandlerName] = (...args) => { // the logout will call after the http call completed - const fn = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract) - return fn.apply(null, args) + const logoutHandler = authMethodGenerator(jsonqlInstance, logoutHandlerName, config, contract) + return Reflect.apply(logoutHandler, null, args) + .then(jsonqlInstance.logoutCallback.bind(jsonqlInstance)) } } else { + // @TODO need to better figure out how to apply the user supplied method here obj[logoutHandlerName] = () => { - debug('call the built-in logout method') - jsonqlInstance.logout() + jsonqlInstance.logoutCallback() } } + // the eventEmitter getter + obj.eventEmitter = () => jsonqlInstance.eventEmitter + // we have to make this into a function if I want to // need to create a getter method for it otherwise // it's straight through pass to the instance property diff --git a/packages/node-client/src/index.js b/packages/node-client/src/index.js index f5136cef27deafa5bac123c593f1f12d087383a5..edd88eec71b5389d8c3ce4e0faa2e480a7f5d615 100644 --- a/packages/node-client/src/index.js +++ b/packages/node-client/src/index.js @@ -3,6 +3,7 @@ const JsonqlRequestClient = require('./base') const { getContract, generator } = require('./generator') const checkOptions = require('./options') const { getDebug } = require('./utils') +const { createSocketClient} = require('./create-socket-client') // export module.exports = { @@ -10,5 +11,6 @@ module.exports = { getContract, generator, checkOptions, - getDebug + getDebug, + createSocketClient } diff --git a/packages/node-client/src/options/index.js b/packages/node-client/src/options/index.js index 64ce7ab061dae7e76f54a9f74396267a2dac84d3..a5a8101705d65bffaadfe5b34912fc37154ad3a2 100755 --- a/packages/node-client/src/options/index.js +++ b/packages/node-client/src/options/index.js @@ -23,12 +23,17 @@ const { ARGS_KEY, TYPE_KEY, ENUM_KEY, + ALIAS_KEY, CHECKER_KEY, ACCEPTED_JS_TYPES, CJS_TYPE, ISSUER_NAME, LOGOUT_NAME, - VALIDATOR_NAME + VALIDATOR_NAME, + // for socket client + JS_WS_NAME, + JS_WS_SOCKET_IO_NAME, + JS_PRIMUS_NAME } = require('jsonql-constants') const BASE_DIR = process.cwd() @@ -65,7 +70,13 @@ const appProps = { // functions storeAuthToken: constructConfig(false, BOOLEAN_TYPE), getAuthToken: constructConfig(false, BOOLEAN_TYPE), - defaultHeader: constructConfig(DEFAULT_HEADER, STRING_TYPE) + defaultHeader: constructConfig(DEFAULT_HEADER, STRING_TYPE), + // new prop for socket client + serverType: createConfig(null, [STRING_TYPE], { + [ENUM_KEY]: [JS_WS_NAME, JS_WS_SOCKET_IO_NAME, JS_PRIMUS_NAME], + [ALIAS_KEY]: 'socketClientType' + }) + } // debug('appProps', appProps); // export just one method diff --git a/packages/node-client/src/utils.js b/packages/node-client/src/utils.js index d93a7e587cbe7526713757fab3c720874a10068f..197a5415057581e59f518536e1b8b2befdb76b72 100755 --- a/packages/node-client/src/utils.js +++ b/packages/node-client/src/utils.js @@ -1,8 +1,21 @@ const { inspect } = require('util') const debug = require('debug') -const { isObjectHasKey, resultHandler } = require('jsonql-utils') + +const { + isObjectHasKey, + resultHandler, + injectToFn, + chainFns +} = require('jsonql-utils') + const MODULE_NAME = 'jsonql-node-client' +/** + * Helper to display more of the debug info + * @param {*} data what to show + * @param {boolean} full or not + * @return {*} formatted data to display + */ const display = (data, full = false) => ( full ? inspect(data, false, null, true) : (data ? data.toString() : false) ) @@ -12,6 +25,8 @@ module.exports = { display, isObjectHasKey, resultHandler, + injectToFn, + chainFns, getDebug: function(name) { return debug(MODULE_NAME).extend(name) } diff --git a/packages/node-client/tests/fixtures/contract-api.js b/packages/node-client/tests/fixtures/contract-api.js index 0039d86c54a02ccd194268c715fc3ecf5c0e33a5..26ba433ba1b36583d75315e2484194e068e623ed 100644 --- a/packages/node-client/tests/fixtures/contract-api.js +++ b/packages/node-client/tests/fixtures/contract-api.js @@ -4,9 +4,16 @@ const { join } = require('path') module.exports = (clean = false) => { const outDir = join(__dirname, 'contract', 'tmp' , 'server') + const contractFile = join(outDir, 'contract.json') + if (fsx.existsSync(contractFile)) { + return Promise.resolve(fsx.readJsonSync(contractFile)) + } + /* + just keep the damn thing if (clean === true) { - return fsx.removeSync(join(ourDir, 'contract.json')) + return fsx.removeSync(join(outDir, 'contract.json')) } + */ return contractApi({ inDir: join(__dirname, 'resolvers'), outDir diff --git a/packages/node-client/tests/fixtures/jsonql-koa.js b/packages/node-client/tests/fixtures/jsonql-koa.js index c9ed0398bff7a82babf585fb01aee388d852a545..fcc96ec8647c59782b2e71dd5d7134e751e3300d 100644 --- a/packages/node-client/tests/fixtures/jsonql-koa.js +++ b/packages/node-client/tests/fixtures/jsonql-koa.js @@ -1,3 +1,3 @@ -const jsonqlKoa = require('../../../koa') +const { jsonqlKoa } = require('jsonql-koa') module.exports = jsonqlKoa; diff --git a/packages/node-client/tests/fixtures/resolvers/auth/custom-validator.js b/packages/node-client/tests/fixtures/resolvers/auth/custom-validator.js index d973a9322e7f80424e60a92dc69db061a1440c0c..3fd95958348c08bace79629d4cb1e585aff58454 100644 --- a/packages/node-client/tests/fixtures/resolvers/auth/custom-validator.js +++ b/packages/node-client/tests/fixtures/resolvers/auth/custom-validator.js @@ -1,4 +1,5 @@ const debug = require('debug')('jsonql-node-client:test:customValidator') + /** * result * @param {*} userdata from last processor diff --git a/packages/node-client/tests/fixtures/resolvers/socket/public/gateway.js b/packages/node-client/tests/fixtures/resolvers/socket/public/gateway.js new file mode 100644 index 0000000000000000000000000000000000000000..ddac9fd98a43b7895acb57cd8dcca6f8a1c62ab4 --- /dev/null +++ b/packages/node-client/tests/fixtures/resolvers/socket/public/gateway.js @@ -0,0 +1,12 @@ +// new public socket interface + +/** + * tell the gateway what you want and wait for the broadcast + * @param {string} msg a message + * @return {string} the first will just say, hang on + */ +module.exports = function gateway(msg) { + + + return `hang on ... got your message ${msg}`; +} diff --git a/packages/node-client/tests/fixtures/resolvers/socket/secret-chat.js b/packages/node-client/tests/fixtures/resolvers/socket/secret-chat.js new file mode 100644 index 0000000000000000000000000000000000000000..a1ab0532737a3f4cba99d88e3ce895ca481bc9c3 --- /dev/null +++ b/packages/node-client/tests/fixtures/resolvers/socket/secret-chat.js @@ -0,0 +1,12 @@ + +/** + * for testing the private socket interface + * @param {string} msg something you want to say + * @return {string} my reply + */ +module.exports = function secretChat(msg) { + + + + return 'got it' +} diff --git a/packages/node-client/tests/fixtures/server-with-auth.js b/packages/node-client/tests/fixtures/server-with-auth.js index 5830a50a801fee5a912299296eb738b00779e526..0f439d9c52da10e66fb32f53c15d85b8db0ee2c9 100755 --- a/packages/node-client/tests/fixtures/server-with-auth.js +++ b/packages/node-client/tests/fixtures/server-with-auth.js @@ -1,9 +1,9 @@ const server = require('server-io-core') -const { jsonqlKoa } = require('./jsonql-koa') +const jsonqlKoa = require('./jsonql-koa') const { contractKey } = require('./options') const { join } = require('path') -module.exports = function(port = 8889, extra = {}) { +module.exports = function serverWithAuth(port = 8889, extra = {}) { return server({ port: port, debug: false, @@ -18,5 +18,5 @@ module.exports = function(port = 8889, extra = {}) { enableAuth: true }, extra)) ] - }); + }) } diff --git a/packages/node-client/tests/fixtures/server-with-socket.js b/packages/node-client/tests/fixtures/server-with-socket.js new file mode 100644 index 0000000000000000000000000000000000000000..b29fcd6900dd6da898222d5bbe98a98c3e3352d3 --- /dev/null +++ b/packages/node-client/tests/fixtures/server-with-socket.js @@ -0,0 +1,33 @@ +// for testing the server with socket +const { join } = require('path') +const server = require('server-io-core') +const jsonqlKoa = require('./jsonql-koa') + +const jsonqlWsServer = require('jsonql-ws-server') + +// output +module.exports = function serverWithAuth(extra = {}) { + const config = Object.assign({ + resolverDir: join(__dirname,'resolvers'), + // resuse this contract if there is one + contractDir: join(__dirname,'contract','tmp','server-with-auth'), + keysDir: join(__dirname, 'keys'), + enableAuth: true + }, extra) + const port = 9001; + return Promise.resolve( + server({ + port: port, + debug: false, + open: false, + reload: false, + socket: false, + middlewares: [ + jsonqlKoa(config) + ] + }) + ).then(({webserver, stop}) => ( + jsonqlWsServer(config, webserver) + .then(() => ({stop, config, port})) + )) +} diff --git a/packages/node-client/tests/fixtures/server.js b/packages/node-client/tests/fixtures/server.js index 7964d77fbc3d0bcc6cfa2ddbfa49ca09b27d8a06..f6a26d31b7ee262221d311725e9a1bffe1f1c42a 100755 --- a/packages/node-client/tests/fixtures/server.js +++ b/packages/node-client/tests/fixtures/server.js @@ -1,5 +1,5 @@ const server = require('server-io-core') -const { jsonqlKoa } = require('./jsonql-koa') +const jsonqlKoa = require('./jsonql-koa') const options = require('./options') const { join } = require('path') module.exports = function(port = 8888) { diff --git a/packages/node-client/tests/fixtures/two/server-setup.js b/packages/node-client/tests/fixtures/two/server-setup.js index 2d834c747ff0fe88c3b5ed59dd92a8563ca67bb5..143c263d80dc6f137063f41e60f502fbcbea5f75 100644 --- a/packages/node-client/tests/fixtures/two/server-setup.js +++ b/packages/node-client/tests/fixtures/two/server-setup.js @@ -1,5 +1,5 @@ const server = require('server-io-core') -const { jsonqlKoa } = require('../jsonql-koa') +const jsonqlKoa = require('../jsonql-koa') const { join } = require('path') const dummy = join(__dirname, 'dummy') diff --git a/packages/node-client/tests/jwt.test.js b/packages/node-client/tests/jwt.test.js index b6d0f14e5670c20f305b26ad903335dfe46c2f2c..7f3f2c74db7c349c81660ec1dba6a56bcffb10ae 100644 --- a/packages/node-client/tests/jwt.test.js +++ b/packages/node-client/tests/jwt.test.js @@ -43,6 +43,8 @@ test.serial("It should able to login and received a token", async t => { let client = t.context.client; let result = await client.customLogin(username, '1234') + debug(result) + t.truthy(result) let userdata = client.userdata() @@ -57,15 +59,17 @@ test.serial("It should able to use the token to login and query private methods" t.is(user, users[1]) }) -test.serial('It should not be able to call the private method after we call logout', t => { - +test.serial.cb('It should not be able to call the private method after we call logout', t => { + t.plan(1) let client = t.context.client; - let r1 = client.logout() + + client.logout() client.query.getUser(2) .catch(err => { debug('catch error', err) t.truthy(err) + t.end() }) }) diff --git a/packages/node-client/tests/socket.test.js b/packages/node-client/tests/socket.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b97bca662a4c8b8502ba7e67d07621605caf6b3d --- /dev/null +++ b/packages/node-client/tests/socket.test.js @@ -0,0 +1,45 @@ +// testing the socket client +const test = require('ava') +const debug = require('debug')('jsonql-node-client:test:socket') +const serverWithSocket = require('./fixtures/server-with-socket') +const nodeClient = require('../index') + +test.before(async t => { + const { stop, config, port } = await serverWithSocket() + const opts = Object.assign({ + hostname: `http://localhost:${port}`, + serverType: 'ws' + }, config) + t.context.stop = stop; + t.context.client = await nodeClient(opts) +}) + +test.after(t => { + t.context.stop() +}) + +/* +test.skip(`Test if the server start at all`, t => { + t.pass() +}) +*/ + +test.skip(`It should able to connect the server via http`, async t => { + const result = await t.context.client.query.helloWorld() + t.is('Hello world!', result) +}) + +test.cb(`It should able to connect to the public socket interface`, t => { + t.plan(1) + const socket = t.context.client.socket + // debug(t.context.client.socket) + socket.gateway('yo') + socket.gateway.onResult = function(result) { + debug(result) + t.truthy(result) + t.end() + } + +}) + +test.todo(`It should able to connect to the private interface after login`) diff --git a/packages/validator/src/options/construct-config.js b/packages/validator/src/options/construct-config.js index 9fe5a0bd07d789c6692867f85faba5921dc919f0..3a7ca78b8045e298a931444a622d0cfa3802b81b 100644 --- a/packages/validator/src/options/construct-config.js +++ b/packages/validator/src/options/construct-config.js @@ -21,7 +21,7 @@ import checkIsBoolean from '../boolean' * @param {boolean|function} [checker=false] * @return {object} config entry */ -export default function(args, type, optional=false, enumv=false, checker=false, alias=false) { +export default function constructConfig(args, type, optional=false, enumv=false, checker=false, alias=false) { let base = { [ARGS_KEY]: args, [TYPE_KEY]: type diff --git a/packages/ws-client/src/core/setup-auth-methods.js b/packages/ws-client/src/core/setup-auth-methods.js index e15af8c65a879fc196d0596f6c74ed1fc4ceec6b..405683588375ad5cc6abe6070fd25228a733fa73 100644 --- a/packages/ws-client/src/core/setup-auth-methods.js +++ b/packages/ws-client/src/core/setup-auth-methods.js @@ -2,7 +2,10 @@ import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' import { JsonqlValidationError } from 'jsonql-errors' import { injectToFn, chainFns, isString } from '../utils' + /** + * @TODO this is now become unnecessary because the login is a slave to the + * http-client - but keep this for now and see what we want to do with it later * break out from createAuthMethods to allow chaining call * @param {object} obj the main client object * @param {object} ee event emitter diff --git a/packages/ws-server/index.js b/packages/ws-server/index.js index a87d7ae351555856d1043a7c2597184f8068edae..794fb0e50252d3ff21941fadb9a77f760202cf7f 100644 --- a/packages/ws-server/index.js +++ b/packages/ws-server/index.js @@ -1,13 +1,12 @@ // Not going to use the koa-socket-2 due to it's lack of support namespace // which is completely useless for us if there is no namespace -const { - checkOptions, - wsSetup, - wsCreateServer -} = require('./src') +const { checkOptions, wsSetup, wsCreateServer } = require('./src') const { getDebug } = require('./src/share/helpers') +const { JsonqlError } = require('jsonql-errors') const debug = getDebug('main') + /** + * @TODO this should export as a named export * @param {object} config this is now diverse from the middleware setup * @param {string} config.serverType socket.io or ws in the background * @param {object} config.options the actual options to pass to the underlying setups @@ -23,5 +22,6 @@ module.exports = function jsonqlWsServer(config, server) { }) .catch(err => { console.error('Init jsonql WebSocket server error', err) + throw new JsonqlError('jsonqlWsServer', err) }) }